2 * Copyright (c) 2015-2019 The Khronos Group Inc.
3 * Copyright (c) 2015-2019 Valve Corporation
4 * Copyright (c) 2015-2019 LunarG, Inc.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * Author: Jeremy Hayes <jeremy@lunarg.com>
19 * Author: Charles Giessen <charles@lunarg.com>
22 #if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
23 #include <X11/Xutil.h>
24 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
25 #include <linux/input.h>
26 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
27 #include "xdg-shell-client-header.h"
29 #ifdef TIZEN_SUPPPORT_XDG_DECORATION
30 #include "xdg-decoration-client-header.h"
33 #include <wayland-client.h>
46 #define VULKAN_HPP_NO_EXCEPTIONS
47 #define VULKAN_HPP_TYPESAFE_CONVERSION
48 #include <vulkan/vulkan.hpp>
53 #define VERIFY(x) assert(x)
55 #define VERIFY(x) ((void)(x))
58 #define APP_SHORT_NAME "vkcubepp"
60 // Allow a maximum of two outstanding presentation operations.
61 constexpr uint32_t FRAME_LAG = 2;
64 #define ERR_EXIT(err_msg, err_class) \
66 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
70 #define ERR_EXIT(err_msg, err_class) \
72 printf("%s\n", err_msg); \
78 // easier to use the C function for extension functions
79 PFN_vkCreateDebugUtilsMessengerEXT pfnVkCreateDebugUtilsMessengerEXT;
80 PFN_vkDestroyDebugUtilsMessengerEXT pfnVkDestroyDebugUtilsMessengerEXT;
81 VKAPI_ATTR VkResult VKAPI_CALL vkCreateDebugUtilsMessengerEXT(VkInstance instance,
82 const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo,
83 const VkAllocationCallbacks *pAllocator,
84 VkDebugUtilsMessengerEXT *pMessenger) {
85 return pfnVkCreateDebugUtilsMessengerEXT(instance, pCreateInfo, pAllocator, pMessenger);
88 VKAPI_ATTR void VKAPI_CALL vkDestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT messenger,
89 VkAllocationCallbacks const *pAllocator) {
90 return pfnVkDestroyDebugUtilsMessengerEXT(instance, messenger, pAllocator);
93 struct texture_object {
98 vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
100 vk::MemoryAllocateInfo mem_alloc;
101 vk::DeviceMemory mem;
104 uint32_t tex_width{0};
105 uint32_t tex_height{0};
108 static char const *const tex_files[] = {"lunarg.ppm"};
110 static int validation_error = 0;
112 struct vktexcube_vs_uniform {
113 // Must start with MVP
115 float position[12 * 3][4];
116 float attr[12 * 3][4];
119 //--------------------------------------------------------------------------------------
120 // Mesh and VertexFormat Data
121 //--------------------------------------------------------------------------------------
123 static const float g_vertex_buffer_data[] = {
124 -1.0f,-1.0f,-1.0f, // -X side
131 -1.0f,-1.0f,-1.0f, // -Z side
138 -1.0f,-1.0f,-1.0f, // -Y side
145 -1.0f, 1.0f,-1.0f, // +Y side
152 1.0f, 1.0f,-1.0f, // +X side
159 -1.0f, 1.0f, 1.0f, // +Z side
167 static const float g_uv_buffer_data[] = {
168 0.0f, 1.0f, // -X side
175 1.0f, 1.0f, // -Z side
182 1.0f, 0.0f, // -Y side
189 1.0f, 0.0f, // +Y side
196 1.0f, 0.0f, // +X side
203 0.0f, 0.0f, // +Z side
212 struct SwapchainImageResources {
214 vk::CommandBuffer cmd;
215 vk::CommandBuffer graphics_to_present_cmd;
217 vk::Buffer uniform_buffer;
218 vk::DeviceMemory uniform_memory;
219 void *uniform_memory_ptr = nullptr;
220 vk::Framebuffer framebuffer;
221 vk::DescriptorSet descriptor_set;
225 void build_image_ownership_cmd(const SwapchainImageResources &swapchain_image_resource);
226 vk::Bool32 check_layers(const std::vector<const char *> &check_names, const std::vector<vk::LayerProperties> &layers);
228 void destroy_swapchain_related_resources();
229 void create_device();
230 void destroy_texture(texture_object &tex_objs);
232 void draw_build_cmd(const SwapchainImageResources &swapchain_image_resource);
233 void prepare_init_cmd();
234 void flush_init_cmd();
235 void init(int argc, char **argv);
236 void init_connection();
238 void init_vk_swapchain();
240 void prepare_buffers();
241 void prepare_cube_data_buffers();
242 void prepare_depth();
243 void prepare_descriptor_layout();
244 void prepare_descriptor_pool();
245 void prepare_descriptor_set();
246 void prepare_framebuffers();
247 vk::ShaderModule prepare_shader_module(const uint32_t *code, size_t size);
248 vk::ShaderModule prepare_vs();
249 vk::ShaderModule prepare_fs();
250 void prepare_pipeline();
251 void prepare_render_pass();
252 void prepare_texture_image(const char *filename, texture_object &tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
253 vk::MemoryPropertyFlags required_props);
254 void prepare_texture_buffer(const char *filename, texture_object &tex_obj);
255 void prepare_textures();
258 void create_surface();
259 void set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
260 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages);
261 void update_data_buffer();
262 bool loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout &layout, uint32_t &width, uint32_t &height);
263 bool memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t &typeIndex);
264 vk::SurfaceFormatKHR pick_surface_format(const std::vector<vk::SurfaceFormatKHR> &surface_formats);
266 static VKAPI_ATTR VkBool32 VKAPI_CALL debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
267 VkDebugUtilsMessageTypeFlagsEXT messageType,
268 const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
271 #if defined(VK_USE_PLATFORM_WIN32_KHR)
273 void create_window();
274 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
275 void create_xlib_window();
276 void handle_xlib_event(const XEvent *event);
278 #elif defined(VK_USE_PLATFORM_XCB_KHR)
279 void handle_xcb_event(const xcb_generic_event_t *event);
281 void create_xcb_window();
282 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
284 void create_window();
285 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
286 void handle_directfb_event(const DFBInputEvent *event);
288 void create_directfb_window();
289 #elif defined(VK_USE_PLATFORM_METAL_EXT)
291 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
292 vk::Result create_display_surface();
296 std::string name = "vkcubepp"; // Name to put on the window/icon
297 #if defined(VK_USE_PLATFORM_WIN32_KHR)
298 HINSTANCE connection = nullptr; // hInstance - Windows Instance
299 HWND window = nullptr; // hWnd - window handle
300 POINT minsize = {0, 0}; // minimum window size
301 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
302 Window xlib_window = 0;
303 Atom xlib_wm_delete_window = 0;
304 Display *display = nullptr;
305 #elif defined(VK_USE_PLATFORM_XCB_KHR)
306 xcb_window_t xcb_window = 0;
307 xcb_screen_t *screen = nullptr;
308 xcb_connection_t *connection = nullptr;
309 xcb_intern_atom_reply_t *atom_wm_delete_window = nullptr;
310 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
311 wl_display *display = nullptr;
312 wl_registry *registry = nullptr;
313 wl_compositor *compositor = nullptr;
314 wl_surface *window = nullptr;
315 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
316 xdg_wm_base *wm_base = nullptr;
318 #ifdef TIZEN_SUPPPORT_XDG_DECORATION
319 zxdg_decoration_manager_v1 *xdg_decoration_mgr = nullptr;
320 zxdg_toplevel_decoration_v1 *toplevel_decoration = nullptr;
322 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
323 xdg_surface *window_surface = nullptr;
325 bool xdg_surface_has_been_configured = false;
326 //xdg_toplevel *window_toplevel = nullptr;
327 wl_seat *seat = nullptr;
328 wl_pointer *pointer = nullptr;
329 wl_keyboard *keyboard = nullptr;
331 wl_shell_surface *window_surface;
332 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
333 IDirectFB *dfb = nullptr;
334 IDirectFBSurface *window = nullptr;
335 IDirectFBEventBuffer *event_buffer = nullptr;
336 #elif defined(VK_USE_PLATFORM_METAL_EXT)
340 vk::SurfaceKHR surface;
341 bool prepared = false;
342 bool use_staging_buffer = false;
343 bool use_xlib = false;
344 bool separate_present_queue = false;
345 bool invalid_gpu_selection = false;
346 int32_t gpu_number = 0;
349 vk::DebugUtilsMessengerEXT debug_messenger;
350 vk::PhysicalDevice gpu;
352 vk::Queue graphics_queue;
353 vk::Queue present_queue;
354 uint32_t graphics_queue_family_index = 0;
355 uint32_t present_queue_family_index = 0;
356 std::array<vk::Semaphore, FRAME_LAG> image_acquired_semaphores;
357 std::array<vk::Semaphore, FRAME_LAG> draw_complete_semaphores;
358 std::array<vk::Semaphore, FRAME_LAG> image_ownership_semaphores;
359 vk::PhysicalDeviceProperties gpu_props;
360 std::vector<vk::QueueFamilyProperties> queue_props;
361 vk::PhysicalDeviceMemoryProperties memory_properties;
363 std::vector<const char *> enabled_instance_extensions;
364 std::vector<const char *> enabled_layers;
365 std::vector<const char *> enabled_device_extensions;
370 vk::ColorSpaceKHR color_space;
372 vk::SwapchainKHR swapchain;
373 std::vector<SwapchainImageResources> swapchain_image_resources;
374 vk::PresentModeKHR presentMode = vk::PresentModeKHR::eFifo;
375 std::array<vk::Fence, FRAME_LAG> fences;
376 uint32_t frame_index = 0;
378 vk::CommandPool cmd_pool;
379 vk::CommandPool present_cmd_pool;
384 vk::MemoryAllocateInfo mem_alloc;
385 vk::DeviceMemory mem;
389 static int32_t const texture_count = 1;
390 std::array<texture_object, texture_count> textures;
391 texture_object staging_texture;
395 vk::MemoryAllocateInfo mem_alloc;
396 vk::DeviceMemory mem;
397 vk::DescriptorBufferInfo buffer_info;
400 vk::CommandBuffer cmd; // Buffer for initialization commands
401 vk::PipelineLayout pipeline_layout;
402 vk::DescriptorSetLayout desc_layout;
403 vk::PipelineCache pipelineCache;
404 vk::RenderPass render_pass;
405 vk::Pipeline pipeline;
407 mat4x4 projection_matrix = {};
408 mat4x4 view_matrix = {};
409 mat4x4 model_matrix = {};
411 float spin_angle = 0.0f;
412 float spin_increment = 0.0f;
415 vk::ShaderModule vert_shader_module;
416 vk::ShaderModule frag_shader_module;
418 vk::DescriptorPool desc_pool;
419 vk::DescriptorSet desc_set;
421 std::vector<vk::Framebuffer> framebuffers;
424 uint32_t curFrame = 0;
425 uint32_t frameCount = 0;
426 bool validate = false;
427 bool in_callback = false;
428 bool use_debug_messenger = false;
429 bool use_break = false;
430 bool suppress_popups = false;
431 bool force_errors = false;
433 uint32_t current_buffer = 0;
437 // MS-Windows event handling function:
438 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
441 #if defined(VK_USE_PLATFORM_WAYLAND_KHR)
442 static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
445 static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
447 static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
449 static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
451 //Demo &demo = *static_cast<Demo *>(data);
452 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
453 //xdg_toplevel_move(demo.window_toplevel, demo.seat, serial);
457 static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
459 static const struct wl_pointer_listener pointer_listener = {
460 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
463 static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
465 static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
466 struct wl_array *keys) {}
468 static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
470 static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
472 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
473 Demo &demo = *static_cast<Demo *>(data);
475 case KEY_ESC: // Escape
478 case KEY_LEFT: // left arrow key
479 demo.spin_angle -= demo.spin_increment;
481 case KEY_RIGHT: // right arrow key
482 demo.spin_angle += demo.spin_increment;
484 case KEY_SPACE: // space bar
485 demo.pause = !demo.pause;
490 static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
491 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
493 static const struct wl_keyboard_listener keyboard_listener = {
494 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
497 static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
498 // Subscribe to pointer events
499 Demo &demo = *static_cast<Demo *>(data);
500 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo.pointer) {
501 demo.pointer = wl_seat_get_pointer(seat);
502 wl_pointer_add_listener(demo.pointer, &pointer_listener, &demo);
503 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo.pointer) {
504 wl_pointer_destroy(demo.pointer);
505 demo.pointer = nullptr;
507 // Subscribe to keyboard events
508 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
509 demo.keyboard = wl_seat_get_keyboard(seat);
510 wl_keyboard_add_listener(demo.keyboard, &keyboard_listener, &demo);
511 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && demo.keyboard) {
512 wl_keyboard_destroy(demo.keyboard);
513 demo.keyboard = nullptr;
517 static const wl_seat_listener seat_listener = {
518 seat_handle_capabilities,
521 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
522 static void wm_base_ping(void *data, xdg_wm_base *xdg_wm_base, uint32_t serial) { xdg_wm_base_pong(xdg_wm_base, serial); }
524 static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
527 static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
528 Demo &demo = *static_cast<Demo *>(data);
529 // pickup wayland objects when they appear
530 if (strcmp(interface, wl_compositor_interface.name) == 0) {
531 demo.compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
532 } else if (strcmp(interface, "wl_shell") == 0) {
533 demo.shell = (struct wl_shell *)wl_registry_bind(registry, id,
534 &wl_shell_interface, 1);
536 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
537 else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
538 demo.wm_base = (xdg_wm_base *)wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
539 xdg_wm_base_add_listener(demo.wm_base, &wm_base_listener, nullptr);
542 else if (strcmp(interface, wl_seat_interface.name) == 0) {
543 demo.seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
544 wl_seat_add_listener(demo.seat, &seat_listener, &demo);
546 #ifdef TIZEN_SUPPPORT_XDG_DECORATION
547 else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
548 demo.xdg_decoration_mgr =
549 (zxdg_decoration_manager_v1 *)wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
554 static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
556 static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
559 void Demo::build_image_ownership_cmd(const SwapchainImageResources &swapchain_image_resource) {
560 auto result = swapchain_image_resource.graphics_to_present_cmd.begin(
561 vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse));
562 VERIFY(result == vk::Result::eSuccess);
564 auto const image_ownership_barrier =
565 vk::ImageMemoryBarrier()
566 .setSrcAccessMask(vk::AccessFlags())
567 .setDstAccessMask(vk::AccessFlags())
568 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
569 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
570 .setSrcQueueFamilyIndex(graphics_queue_family_index)
571 .setDstQueueFamilyIndex(present_queue_family_index)
572 .setImage(swapchain_image_resource.image)
573 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
575 swapchain_image_resource.graphics_to_present_cmd.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe,
576 vk::PipelineStageFlagBits::eBottomOfPipe,
577 vk::DependencyFlagBits(), {}, {}, image_ownership_barrier);
579 result = swapchain_image_resource.graphics_to_present_cmd.end();
580 VERIFY(result == vk::Result::eSuccess);
583 vk::Bool32 Demo::check_layers(const std::vector<const char *> &check_names, const std::vector<vk::LayerProperties> &layers) {
584 for (const auto &name : check_names) {
585 vk::Bool32 found = VK_FALSE;
586 for (const auto &layer : layers) {
587 if (!strcmp(name, layer.layerName)) {
593 fprintf(stderr, "Cannot find layer: %s\n", name);
600 void Demo::cleanup() {
602 auto result = device.waitIdle();
603 VERIFY(result == vk::Result::eSuccess);
605 destroy_swapchain_related_resources();
606 // Wait for fences from present operations
607 for (uint32_t i = 0; i < FRAME_LAG; i++) {
608 device.destroyFence(fences[i]);
609 device.destroySemaphore(image_acquired_semaphores[i]);
610 device.destroySemaphore(draw_complete_semaphores[i]);
611 if (separate_present_queue) {
612 device.destroySemaphore(image_ownership_semaphores[i]);
616 device.destroySwapchainKHR(swapchain);
619 inst.destroySurfaceKHR(surface);
621 #if defined(VK_USE_PLATFORM_XLIB_KHR)
622 XDestroyWindow(display, xlib_window);
623 XCloseDisplay(display);
624 #elif defined(VK_USE_PLATFORM_XCB_KHR)
625 xcb_destroy_window(connection, xcb_window);
626 xcb_disconnect(connection);
627 free(atom_wm_delete_window);
628 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
629 if (keyboard) wl_keyboard_destroy(keyboard);
630 if (pointer) wl_pointer_destroy(pointer);
631 if (seat) wl_seat_destroy(seat);
632 //xdg_toplevel_destroy(window_toplevel);
633 //xdg_surface_destroy(window_surface);
634 wl_shell_surface_destroy(window_surface);
635 wl_surface_destroy(window);
636 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
637 xdg_wm_base_destroy(wm_base);
639 #ifdef TIZEN_SUPPPORT_XDG_DECORATION
640 if (xdg_decoration_mgr) {
641 zxdg_toplevel_decoration_v1_destroy(toplevel_decoration);
642 zxdg_decoration_manager_v1_destroy(xdg_decoration_mgr);
645 wl_compositor_destroy(compositor);
646 wl_registry_destroy(registry);
647 wl_display_disconnect(display);
648 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
649 event_buffer->Release(event_buffer);
650 window->Release(window);
653 if (use_debug_messenger) {
654 inst.destroyDebugUtilsMessengerEXT(debug_messenger);
659 void Demo::create_device() {
660 float priorities = 0.0;
662 std::vector<vk::DeviceQueueCreateInfo> queues;
663 queues.push_back(vk::DeviceQueueCreateInfo().setQueueFamilyIndex(graphics_queue_family_index).setQueuePriorities(priorities));
665 if (separate_present_queue) {
667 vk::DeviceQueueCreateInfo().setQueueFamilyIndex(present_queue_family_index).setQueuePriorities(priorities));
670 auto deviceInfo = vk::DeviceCreateInfo().setQueueCreateInfos(queues).setPEnabledExtensionNames(enabled_device_extensions);
671 auto device_return = gpu.createDevice(deviceInfo);
672 VERIFY(device_return.result == vk::Result::eSuccess);
673 device = device_return.value;
676 void Demo::destroy_texture(texture_object &tex_objs) {
677 // clean up staging resources
678 device.freeMemory(tex_objs.mem);
679 if (tex_objs.image) device.destroyImage(tex_objs.image);
680 if (tex_objs.buffer) device.destroyBuffer(tex_objs.buffer);
684 // Ensure no more than FRAME_LAG renderings are outstanding
685 device.waitForFences(fences[frame_index], VK_TRUE, UINT64_MAX);
686 device.resetFences({fences[frame_index]});
688 vk::Result acquire_result;
691 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), ¤t_buffer);
692 if (acquire_result == vk::Result::eErrorOutOfDateKHR) {
693 // demo.swapchain is out of date (e.g. the window was resized) and
694 // must be recreated:
696 } else if (acquire_result == vk::Result::eSuboptimalKHR) {
697 // swapchain is not as optimal as it could be, but the platform's
698 // presentation engine will still present the image correctly.
700 } else if (acquire_result == vk::Result::eErrorSurfaceLostKHR) {
701 inst.destroySurfaceKHR(surface);
705 VERIFY(acquire_result == vk::Result::eSuccess);
707 } while (acquire_result != vk::Result::eSuccess);
709 update_data_buffer();
711 // Wait for the image acquired semaphore to be signaled to ensure
712 // that the image won't be rendered to until the presentation
713 // engine has fully released ownership to the application, and it is
714 // okay to render to the image.
715 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
717 auto submit_result = graphics_queue.submit(vk::SubmitInfo()
718 .setWaitDstStageMask(pipe_stage_flags)
719 .setWaitSemaphores(image_acquired_semaphores[frame_index])
720 .setCommandBuffers(swapchain_image_resources[current_buffer].cmd)
721 .setSignalSemaphores(draw_complete_semaphores[frame_index]),
722 fences[frame_index]);
723 VERIFY(submit_result == vk::Result::eSuccess);
725 if (separate_present_queue) {
726 // If we are using separate queues, change image ownership to the
727 // present queue before presenting, waiting for the draw complete
728 // semaphore and signalling the ownership released semaphore when
730 auto change_owner_result =
731 present_queue.submit(vk::SubmitInfo()
732 .setWaitDstStageMask(pipe_stage_flags)
733 .setWaitSemaphores(draw_complete_semaphores[frame_index])
734 .setCommandBuffers(swapchain_image_resources[current_buffer].graphics_to_present_cmd)
735 .setSignalSemaphores(image_ownership_semaphores[frame_index]));
736 VERIFY(change_owner_result == vk::Result::eSuccess);
739 const auto presentInfo = vk::PresentInfoKHR()
740 .setWaitSemaphores(separate_present_queue ? image_ownership_semaphores[frame_index]
741 : draw_complete_semaphores[frame_index])
742 .setSwapchains(swapchain)
743 .setImageIndices(current_buffer);
745 // If we are using separate queues we have to wait for image ownership,
746 // otherwise wait for draw complete
747 auto present_result = present_queue.presentKHR(&presentInfo);
749 frame_index %= FRAME_LAG;
750 if (present_result == vk::Result::eErrorOutOfDateKHR) {
751 // swapchain is out of date (e.g. the window was resized) and
752 // must be recreated:
754 } else if (present_result == vk::Result::eSuboptimalKHR) {
755 // SUBOPTIMAL could be due to resize
756 vk::SurfaceCapabilitiesKHR surfCapabilities;
757 auto caps_result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
758 VERIFY(caps_result == vk::Result::eSuccess);
759 if (surfCapabilities.currentExtent.width != width || surfCapabilities.currentExtent.height != height) {
762 } else if (present_result == vk::Result::eErrorSurfaceLostKHR) {
763 inst.destroySurfaceKHR(surface);
767 VERIFY(present_result == vk::Result::eSuccess);
771 void Demo::draw_build_cmd(const SwapchainImageResources &swapchain_image_resource) {
772 const auto commandBuffer = swapchain_image_resource.cmd;
773 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
774 vk::ClearDepthStencilValue(1.0f, 0u)};
776 auto result = commandBuffer.begin(vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse));
777 VERIFY(result == vk::Result::eSuccess);
779 commandBuffer.beginRenderPass(vk::RenderPassBeginInfo()
780 .setRenderPass(render_pass)
781 .setFramebuffer(swapchain_image_resource.framebuffer)
782 .setRenderArea(vk::Rect2D(vk::Offset2D{}, vk::Extent2D(width, height)))
783 .setClearValueCount(2)
784 .setPClearValues(clearValues),
785 vk::SubpassContents::eInline);
787 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
788 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, swapchain_image_resource.descriptor_set,
790 float viewport_dimension;
791 float viewport_x = 0.0f;
792 float viewport_y = 0.0f;
793 if (width < height) {
794 viewport_dimension = static_cast<float>(width);
795 viewport_y = (height - width) / 2.0f;
797 viewport_dimension = static_cast<float>(height);
798 viewport_x = (width - height) / 2.0f;
801 commandBuffer.setViewport(0, vk::Viewport()
804 .setWidth(viewport_dimension)
805 .setHeight(viewport_dimension)
809 commandBuffer.setScissor(0, vk::Rect2D(vk::Offset2D{}, vk::Extent2D(width, height)));
810 commandBuffer.draw(12 * 3, 1, 0, 0);
811 // Note that ending the renderpass changes the image's layout from
812 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
813 commandBuffer.endRenderPass();
815 if (separate_present_queue) {
816 // We have to transfer ownership from the graphics queue family to
818 // present queue family to be able to present. Note that we don't
820 // to transfer from present queue family back to graphics queue
822 // the start of the next frame because we don't care about the
824 // contents at that point.
825 commandBuffer.pipelineBarrier(
826 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), {}, {},
827 vk::ImageMemoryBarrier()
828 .setSrcAccessMask(vk::AccessFlags())
829 .setDstAccessMask(vk::AccessFlags())
830 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
831 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
832 .setSrcQueueFamilyIndex(graphics_queue_family_index)
833 .setDstQueueFamilyIndex(present_queue_family_index)
834 .setImage(swapchain_image_resource.image)
835 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1)));
838 result = commandBuffer.end();
839 VERIFY(result == vk::Result::eSuccess);
842 void Demo::prepare_init_cmd() {
843 auto cmd_pool_return = device.createCommandPool(vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index));
844 VERIFY(cmd_pool_return.result == vk::Result::eSuccess);
845 cmd_pool = cmd_pool_return.value;
847 auto cmd_return = device.allocateCommandBuffers(vk::CommandBufferAllocateInfo()
848 .setCommandPool(cmd_pool)
849 .setLevel(vk::CommandBufferLevel::ePrimary)
850 .setCommandBufferCount(1));
851 VERIFY(cmd_return.result == vk::Result::eSuccess);
852 cmd = cmd_return.value[0];
854 auto result = cmd.begin(vk::CommandBufferBeginInfo());
855 VERIFY(result == vk::Result::eSuccess);
858 void Demo::flush_init_cmd() {
859 auto result = cmd.end();
860 VERIFY(result == vk::Result::eSuccess);
862 auto fenceInfo = vk::FenceCreateInfo();
864 // Remove sType to intentionally force validation layer errors.
865 fenceInfo.sType = vk::StructureType::eRenderPassBeginInfo;
867 auto fence_return = device.createFence(fenceInfo);
868 VERIFY(fence_return.result == vk::Result::eSuccess);
869 auto fence = fence_return.value;
871 result = graphics_queue.submit(vk::SubmitInfo().setCommandBuffers(cmd), fence);
872 VERIFY(result == vk::Result::eSuccess);
874 result = device.waitForFences(fence, VK_TRUE, UINT64_MAX);
875 VERIFY(result == vk::Result::eSuccess);
877 device.freeCommandBuffers(cmd_pool, cmd);
878 device.destroyFence(fence);
881 void Demo::init(int argc, char **argv) {
882 vec3 eye = {0.0f, 3.0f, 5.0f};
883 vec3 origin = {0, 0, 0};
884 vec3 up = {0.0f, 1.0f, 0.0};
886 presentMode = vk::PresentModeKHR::eFifo;
887 frameCount = UINT32_MAX;
891 /* Autodetect suitable / best GPU by default */
894 for (int i = 1; i < argc; i++) {
895 if (strcmp(argv[i], "--use_staging") == 0) {
896 use_staging_buffer = true;
899 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
900 presentMode = static_cast<vk::PresentModeKHR>(atoi(argv[i + 1]));
904 if (strcmp(argv[i], "--break") == 0) {
908 if (strcmp(argv[i], "--validate") == 0) {
912 if (strcmp(argv[i], "--xlib") == 0) {
913 fprintf(stderr, "--xlib is deprecated and no longer does anything");
916 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
917 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
921 if (strcmp(argv[i], "--width") == 0) {
922 int32_t in_width = 0;
923 if (i < argc - 1 && sscanf(argv[i + 1], "%d", &in_width) == 1) {
925 width = static_cast<uint32_t>(in_width);
929 ERR_EXIT("The --width parameter must be greater than 0", "User Error");
932 ERR_EXIT("The --width parameter must be followed by a number", "User Error");
934 if (strcmp(argv[i], "--height") == 0) {
935 int32_t in_height = 0;
936 if (i < argc - 1 && sscanf(argv[i + 1], "%d", &height) == 1) {
938 height = static_cast<uint32_t>(in_height);
942 ERR_EXIT("The --height parameter must be greater than 0", "User Error");
945 ERR_EXIT("The --height parameter must be followed by a number", "User Error");
947 if (strcmp(argv[i], "--suppress_popups") == 0) {
948 suppress_popups = true;
951 if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
952 gpu_number = atoi(argv[i + 1]);
953 if (gpu_number < 0) invalid_gpu_selection = true;
957 if (strcmp(argv[i], "--force_errors") == 0) {
961 std::stringstream usage;
962 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
963 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
964 << "\t[--gpu_number <index of physical device>]\n"
965 << "\t[--present_mode <present mode enum>]\n"
966 << "\t[--width <width>] [--height <height>]\n"
967 << "\t[--force_errors]\n"
968 << "\t<present_mode_enum>\n"
969 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
970 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
971 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
972 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR << "\n";
975 if (!suppress_popups) MessageBox(nullptr, usage.str().c_str(), "Usage Error", MB_OK);
977 std::cerr << usage.str();
990 spin_increment = 0.2f;
993 mat4x4_perspective(projection_matrix, static_cast<float>(degreesToRadians(45.0f)), 1.0f, 0.1f, 100.0f);
994 mat4x4_look_at(view_matrix, eye, origin, up);
995 mat4x4_identity(model_matrix);
997 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
1000 void Demo::init_connection() {
1001 #if defined(VK_USE_PLATFORM_XCB_KHR)
1002 const xcb_setup_t *setup;
1003 xcb_screen_iterator_t iter;
1006 const char *display_envar = getenv("DISPLAY");
1007 if (display_envar == nullptr || display_envar[0] == '\0') {
1008 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1013 connection = xcb_connect(nullptr, &scr);
1014 if (xcb_connection_has_error(connection) > 0) {
1015 printf("Cannot connect to XCB.\nExiting ...\n");
1020 setup = xcb_get_setup(connection);
1021 iter = xcb_setup_roots_iterator(setup);
1022 while (scr-- > 0) xcb_screen_next(&iter);
1025 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1026 display = wl_display_connect(nullptr);
1028 if (display == nullptr) {
1029 printf("Cannot connect to wayland.\nExiting ...\n");
1034 registry = wl_display_get_registry(display);
1035 wl_registry_add_listener(registry, ®istry_listener, this);
1036 wl_display_dispatch(display);
1039 #if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1040 int find_display_gpu(int gpu_number, const std::vector<vk::PhysicalDevice> &physical_devices) {
1041 uint32_t display_count = 0;
1042 int gpu_return = gpu_number;
1043 if (gpu_number >= 0) {
1044 auto display_props_return = physical_devices[gpu_number].getDisplayPropertiesKHR();
1045 VERIFY(display_props_return.result == vk::Result::eSuccess);
1046 display_count = display_props_return.value.size();
1048 for (uint32_t i = 0; i < physical_devices.size(); i++) {
1049 auto display_props_return = physical_devices[i].getDisplayPropertiesKHR();
1050 VERIFY(display_props_return.result == vk::Result::eSuccess);
1051 if (display_props_return.value.size() > 0) {
1052 display_count = display_props_return.value.size();
1058 if (display_count > 0)
1064 VKAPI_ATTR VkBool32 VKAPI_CALL Demo::debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
1065 VkDebugUtilsMessageTypeFlagsEXT messageType,
1066 const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
1068 std::ostringstream message;
1069 Demo &demo = *static_cast<Demo *>(pUserData);
1071 if (demo.use_break) {
1078 message << vk::to_string(vk::DebugUtilsMessageSeverityFlagBitsEXT(messageSeverity));
1079 message << " : " + vk::to_string(vk::DebugUtilsMessageTypeFlagsEXT(messageType));
1081 if (vk::DebugUtilsMessageTypeFlagsEXT(messageType) & vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation) {
1082 validation_error = 1;
1085 message << " - Message Id Number: " << std::to_string(pCallbackData->messageIdNumber);
1086 message << " | Message Id Name: " << pCallbackData->pMessageIdName << "\n\t" << pCallbackData->pMessage << "\n";
1088 if (pCallbackData->objectCount > 0) {
1089 message << "\n\tObjects - " << pCallbackData->objectCount << "\n";
1090 for (uint32_t object = 0; object < pCallbackData->objectCount; ++object) {
1091 message << "\t\tObject[" << object << "] - "
1092 << vk::to_string(vk::ObjectType(pCallbackData->pObjects[object].objectType)) << ", Handle ";
1094 // Print handle correctly if it is a dispatchable handle - aka a pointer
1095 VkObjectType t = pCallbackData->pObjects[object].objectType;
1096 if (t == VK_OBJECT_TYPE_INSTANCE || t == VK_OBJECT_TYPE_PHYSICAL_DEVICE || t == VK_OBJECT_TYPE_DEVICE ||
1097 t == VK_OBJECT_TYPE_COMMAND_BUFFER || t == VK_OBJECT_TYPE_QUEUE) {
1098 message << reinterpret_cast<void*>(static_cast<uintptr_t>(pCallbackData->pObjects[object].objectHandle));
1100 message << pCallbackData->pObjects[object].objectHandle;
1102 if (NULL != pCallbackData->pObjects[object].pObjectName && strlen(pCallbackData->pObjects[object].pObjectName) > 0) {
1103 message << ", Name \"" << pCallbackData->pObjects[object].pObjectName << "\"\n";
1109 if (pCallbackData->cmdBufLabelCount > 0) {
1110 message << "\n\tCommand Buffer Labels - " << pCallbackData->cmdBufLabelCount << "\n";
1111 for (uint32_t cmd_buf_label = 0; cmd_buf_label < pCallbackData->cmdBufLabelCount; ++cmd_buf_label) {
1112 message << "\t\tLabel[" << cmd_buf_label << "] - " << pCallbackData->pCmdBufLabels[cmd_buf_label].pLabelName << " { "
1113 << pCallbackData->pCmdBufLabels[cmd_buf_label].color[0] << ", "
1114 << pCallbackData->pCmdBufLabels[cmd_buf_label].color[1] << ", "
1115 << pCallbackData->pCmdBufLabels[cmd_buf_label].color[2] << ", "
1116 << pCallbackData->pCmdBufLabels[cmd_buf_label].color[2] << "}\n";
1122 if (!demo.suppress_popups) {
1123 demo.in_callback = true;
1124 auto message_string = message.str();
1125 MessageBox(NULL, message_string.c_str(), "Alert", MB_OK);
1126 demo.in_callback = false;
1129 #elif defined(ANDROID)
1131 if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
1132 __android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message.str());
1133 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
1134 __android_log_print(ANDROID_LOG_WARN, APP_SHORT_NAME, "%s", message.str());
1135 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
1136 __android_log_print(ANDROID_LOG_ERROR, APP_SHORT_NAME, "%s", message.str());
1137 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
1138 __android_log_print(ANDROID_LOG_VERBOSE, APP_SHORT_NAME, "%s", message.str());
1140 __android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message.str());
1144 std::cout << message.str() << std::endl; // use endl to force a flush
1146 return false; // Don't bail out, but keep going.
1149 void Demo::init_vk() {
1150 std::vector<char const *> instance_validation_layers = {"VK_LAYER_KHRONOS_validation"};
1152 // Look for validation layers
1153 vk::Bool32 validation_found = VK_FALSE;
1155 auto layers = vk::enumerateInstanceLayerProperties();
1156 VERIFY(layers.result == vk::Result::eSuccess);
1158 validation_found = check_layers(instance_validation_layers, layers.value);
1159 if (validation_found) {
1160 enabled_layers.push_back("VK_LAYER_KHRONOS_validation");
1165 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1166 "Please look at the Getting Started guide for additional information.\n",
1167 "vkCreateInstance Failure");
1171 /* Look for instance extensions */
1172 vk::Bool32 surfaceExtFound = VK_FALSE;
1173 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1174 bool portabilityEnumerationActive = false;
1176 auto instance_extensions_return = vk::enumerateInstanceExtensionProperties();
1177 VERIFY(instance_extensions_return.result == vk::Result::eSuccess);
1179 for (const auto &extension : instance_extensions_return.value) {
1180 if (!strcmp(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, extension.extensionName)) {
1181 enabled_instance_extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
1182 } else if (!strcmp(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, extension.extensionName)) {
1183 use_debug_messenger = true;
1184 enabled_instance_extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
1185 } else if (!strcmp(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME, extension.extensionName)) {
1186 // We want cube to be able to enumerate drivers that support the portability_subset extension, so we have to enable the
1187 // portability enumeration extension.
1188 portabilityEnumerationActive = true;
1189 enabled_instance_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
1190 } else if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1191 surfaceExtFound = 1;
1192 enabled_instance_extensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
1194 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1195 else if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1196 platformSurfaceExtFound = 1;
1197 enabled_instance_extensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
1199 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1200 else if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1201 platformSurfaceExtFound = 1;
1202 enabled_instance_extensions.push_back(VK_KHR_XLIB_SURFACE_EXTENSION_NAME);
1204 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1205 else if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1206 platformSurfaceExtFound = 1;
1207 enabled_instance_extensions.push_back(VK_KHR_XCB_SURFACE_EXTENSION_NAME);
1209 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1210 else if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1211 platformSurfaceExtFound = 1;
1212 enabled_instance_extensions.push_back(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME);
1214 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1215 else if (!strcmp(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1216 platformSurfaceExtFound = 1;
1217 enabled_instance_extensions.push_back(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME);
1219 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1220 else if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, extension.extensionName)) {
1221 platformSurfaceExtFound = 1;
1222 enabled_instance_extensions.push_back(VK_KHR_DISPLAY_EXTENSION_NAME);
1224 #elif defined(VK_USE_PLATFORM_METAL_EXT)
1225 else if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1226 platformSurfaceExtFound = 1;
1227 enabled_instance_extensions.push_back(VK_EXT_METAL_SURFACE_EXTENSION_NAME);
1232 if (!surfaceExtFound) {
1233 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1235 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1236 "Please look at the Getting Started guide for additional information.\n",
1237 "vkCreateInstance Failure");
1240 if (!platformSurfaceExtFound) {
1241 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1242 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1244 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1245 "Please look at the Getting Started guide for additional information.\n",
1246 "vkCreateInstance Failure");
1247 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1248 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1250 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1251 "Please look at the Getting Started guide for additional information.\n",
1252 "vkCreateInstance Failure");
1253 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1254 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1256 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1257 "Please look at the Getting Started guide for additional information.\n",
1258 "vkCreateInstance Failure");
1259 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1260 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1262 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1263 "Please look at the Getting Started guide for additional information.\n",
1264 "vkCreateInstance Failure");
1265 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1266 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME
1268 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1269 "Please look at the Getting Started guide for additional information.\n",
1270 "vkCreateInstance Failure");
1271 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1272 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1274 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1275 "Please look at the Getting Started guide for additional information.\n",
1276 "vkCreateInstance Failure");
1277 #elif defined(VK_USE_PLATFORM_METAL_EXT)
1278 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
1279 " extension.\n\nDo you have a compatible "
1280 "Vulkan installable client driver (ICD) installed?\nPlease "
1281 "look at the Getting Started guide for additional "
1283 "vkCreateInstance Failure");
1287 vk::DebugUtilsMessageSeverityFlagsEXT severityFlags(vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning |
1288 vk::DebugUtilsMessageSeverityFlagBitsEXT::eError);
1289 vk::DebugUtilsMessageTypeFlagsEXT messageTypeFlags(vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral |
1290 vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance |
1291 vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation);
1292 auto debug_utils_create_info = vk::DebugUtilsMessengerCreateInfoEXT({}, severityFlags, messageTypeFlags,
1293 &debug_messenger_callback, static_cast<void *>(this));
1295 auto const app = vk::ApplicationInfo()
1296 .setPApplicationName(APP_SHORT_NAME)
1297 .setApplicationVersion(0)
1298 .setPEngineName(APP_SHORT_NAME)
1299 .setEngineVersion(0)
1300 .setApiVersion(VK_API_VERSION_1_0);
1301 auto const inst_info = vk::InstanceCreateInfo()
1302 .setFlags(portabilityEnumerationActive ? vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR
1303 : static_cast<vk::InstanceCreateFlagBits>(0))
1304 .setPNext((use_debug_messenger && validate) ? &debug_utils_create_info : nullptr)
1305 .setPApplicationInfo(&app)
1306 .setPEnabledLayerNames(enabled_layers)
1307 .setPEnabledExtensionNames(enabled_instance_extensions);
1309 auto instance_result = vk::createInstance(inst_info);
1310 if (instance_result.result == vk::Result::eErrorIncompatibleDriver) {
1312 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1313 "Please look at the Getting Started guide for additional information.\n",
1314 "vkCreateInstance Failure");
1315 } else if (instance_result.result == vk::Result::eErrorExtensionNotPresent) {
1317 "Cannot find a specified extension library.\n"
1318 "Make sure your layers path is set appropriately.\n",
1319 "vkCreateInstance Failure");
1320 } else if (instance_result.result != vk::Result::eSuccess) {
1322 "vkCreateInstance failed.\n\n"
1323 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1324 "Please look at the Getting Started guide for additional information.\n",
1325 "vkCreateInstance Failure");
1327 inst = instance_result.value;
1329 if (use_debug_messenger) {
1330 pfnVkCreateDebugUtilsMessengerEXT =
1331 reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT>(inst.getProcAddr("vkCreateDebugUtilsMessengerEXT"));
1332 pfnVkDestroyDebugUtilsMessengerEXT =
1333 reinterpret_cast<PFN_vkDestroyDebugUtilsMessengerEXT>(inst.getProcAddr("vkDestroyDebugUtilsMessengerEXT"));
1334 VERIFY(pfnVkCreateDebugUtilsMessengerEXT != nullptr && pfnVkDestroyDebugUtilsMessengerEXT != nullptr);
1335 auto create_debug_messenger_return = inst.createDebugUtilsMessengerEXT(debug_utils_create_info);
1336 VERIFY(create_debug_messenger_return.result == vk::Result::eSuccess);
1337 debug_messenger = create_debug_messenger_return.value;
1340 auto physical_device_return = inst.enumeratePhysicalDevices();
1341 VERIFY(physical_device_return.result == vk::Result::eSuccess);
1342 auto physical_devices = physical_device_return.value;
1344 if (physical_devices.size() <= 0) {
1346 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1347 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1348 "Please look at the Getting Started guide for additional information.\n",
1349 "vkEnumeratePhysicalDevices Failure");
1352 if (invalid_gpu_selection || (gpu_number >= 0 && !(static_cast<uint32_t>(gpu_number) < physical_devices.size()))) {
1353 fprintf(stderr, "GPU %d specified is not present, GPU count = %zu\n", gpu_number, physical_devices.size());
1354 ERR_EXIT("Specified GPU number is not present", "User Error");
1356 #if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1357 gpu_number = find_display_gpu(gpu_number, physical_devices);
1358 if (gpu_number < 0) {
1359 printf("Cannot find any display!\n");
1364 /* Try to auto select most suitable device */
1365 if (gpu_number == -1) {
1366 constexpr uint32_t device_type_count = static_cast<uint32_t>(vk::PhysicalDeviceType::eCpu) + 1;
1367 std::array<uint32_t, device_type_count> count_device_type{};
1369 for (uint32_t i = 0; i < physical_devices.size(); i++) {
1370 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1371 assert(physicalDeviceProperties.deviceType <= vk::PhysicalDeviceType::eCpu);
1372 count_device_type[static_cast<int>(physicalDeviceProperties.deviceType)]++;
1375 std::array<vk::PhysicalDeviceType, device_type_count> const device_type_preference = {
1376 vk::PhysicalDeviceType::eDiscreteGpu, vk::PhysicalDeviceType::eIntegratedGpu, vk::PhysicalDeviceType::eVirtualGpu,
1377 vk::PhysicalDeviceType::eCpu, vk::PhysicalDeviceType::eOther};
1379 vk::PhysicalDeviceType search_for_device_type = vk::PhysicalDeviceType::eDiscreteGpu;
1380 for (uint32_t i = 0; i < sizeof(device_type_preference) / sizeof(vk::PhysicalDeviceType); i++) {
1381 if (count_device_type[static_cast<int>(device_type_preference[i])]) {
1382 search_for_device_type = device_type_preference[i];
1387 for (uint32_t i = 0; i < physical_devices.size(); i++) {
1388 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1389 if (physicalDeviceProperties.deviceType == search_for_device_type) {
1396 assert(gpu_number >= 0);
1397 gpu = physical_devices[gpu_number];
1399 auto physicalDeviceProperties = gpu.getProperties();
1400 fprintf(stderr, "Selected GPU %d: %s, type: %s\n", gpu_number, physicalDeviceProperties.deviceName.data(),
1401 to_string(physicalDeviceProperties.deviceType).c_str());
1404 /* Look for device extensions */
1405 vk::Bool32 swapchainExtFound = VK_FALSE;
1407 auto device_extension_return = gpu.enumerateDeviceExtensionProperties();
1408 VERIFY(device_extension_return.result == vk::Result::eSuccess);
1410 for (const auto &extension : device_extension_return.value) {
1411 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, extension.extensionName)) {
1412 swapchainExtFound = 1;
1413 enabled_device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
1414 } else if (!strcmp("VK_KHR_portability_subset", extension.extensionName)) {
1415 enabled_device_extensions.push_back("VK_KHR_portability_subset");
1419 if (!swapchainExtFound) {
1420 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1422 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1423 "Please look at the Getting Started guide for additional information.\n",
1424 "vkCreateInstance Failure");
1427 gpu.getProperties(&gpu_props);
1429 /* Call with nullptr data to get count */
1430 queue_props = gpu.getQueueFamilyProperties();
1431 assert(queue_props.size() >= 1);
1433 // Query fine-grained feature support for this device.
1434 // If app has specific feature requirements it should check supported
1435 // features based on this query
1436 vk::PhysicalDeviceFeatures physDevFeatures;
1437 gpu.getFeatures(&physDevFeatures);
1440 void Demo::create_surface() {
1441 // Create a WSI surface for the window:
1442 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1444 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1446 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1447 VERIFY(result == vk::Result::eSuccess);
1449 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1451 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1453 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1454 VERIFY(result == vk::Result::eSuccess);
1456 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1458 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1460 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1461 VERIFY(result == vk::Result::eSuccess);
1463 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1465 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1467 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1468 VERIFY(result == vk::Result::eSuccess);
1470 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1472 auto const createInfo = vk::DirectFBSurfaceCreateInfoEXT().setDfb(dfb).setSurface(window);
1474 auto result = inst.createDirectFBSurfaceEXT(&createInfo, nullptr, &surface);
1475 VERIFY(result == vk::Result::eSuccess);
1477 #elif defined(VK_USE_PLATFORM_METAL_EXT)
1479 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
1481 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
1482 VERIFY(result == vk::Result::eSuccess);
1484 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1486 auto result = create_display_surface();
1487 VERIFY(result == vk::Result::eSuccess);
1492 void Demo::init_vk_swapchain() {
1494 // Iterate over each queue to learn whether it supports presenting:
1495 std::vector<vk::Bool32> supportsPresent;
1496 for (uint32_t i = 0; i < static_cast<uint32_t>(queue_props.size()); i++) {
1497 auto supports = gpu.getSurfaceSupportKHR(i, surface);
1498 VERIFY(supports.result == vk::Result::eSuccess);
1499 supportsPresent.push_back(supports.value);
1502 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1503 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1504 for (uint32_t i = 0; i < static_cast<uint32_t>(queue_props.size()); i++) {
1505 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1506 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1507 graphicsQueueFamilyIndex = i;
1510 if (supportsPresent[i] == VK_TRUE) {
1511 graphicsQueueFamilyIndex = i;
1512 presentQueueFamilyIndex = i;
1518 if (presentQueueFamilyIndex == UINT32_MAX) {
1519 // If didn't find a queue that supports both graphics and present,
1521 // find a separate present queue.
1522 for (uint32_t i = 0; i < queue_props.size(); ++i) {
1523 if (supportsPresent[i] == VK_TRUE) {
1524 presentQueueFamilyIndex = i;
1530 // Generate error if could not find both a graphics and a present queue
1531 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1532 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1535 graphics_queue_family_index = graphicsQueueFamilyIndex;
1536 present_queue_family_index = presentQueueFamilyIndex;
1537 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
1541 graphics_queue = device.getQueue(graphics_queue_family_index, 0);
1542 if (!separate_present_queue) {
1543 present_queue = graphics_queue;
1545 present_queue = device.getQueue(present_queue_family_index, 0);
1548 // Get the list of VkFormat's that are supported:
1549 auto surface_formats_return = gpu.getSurfaceFormatsKHR(surface);
1550 VERIFY(surface_formats_return.result == vk::Result::eSuccess);
1552 vk::SurfaceFormatKHR surfaceFormat = pick_surface_format(surface_formats_return.value);
1553 format = surfaceFormat.format;
1554 color_space = surfaceFormat.colorSpace;
1559 // Create semaphores to synchronize acquiring presentable buffers before
1560 // rendering and waiting for drawing to be complete before presenting
1561 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
1563 // Create fences that we can use to throttle if we get too far
1564 // ahead of the image presents
1565 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1566 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1567 vk::Result result = device.createFence(&fence_ci, nullptr, &fences[i]);
1568 VERIFY(result == vk::Result::eSuccess);
1570 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1571 VERIFY(result == vk::Result::eSuccess);
1573 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1574 VERIFY(result == vk::Result::eSuccess);
1576 if (separate_present_queue) {
1577 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
1578 VERIFY(result == vk::Result::eSuccess);
1583 // Get Memory information and properties
1584 memory_properties = gpu.getMemoryProperties();
1587 void Demo::prepare() {
1593 prepare_cube_data_buffers();
1595 prepare_descriptor_layout();
1596 prepare_render_pass();
1599 for (auto &swapchain_image_resource : swapchain_image_resources) {
1600 auto alloc_return = device.allocateCommandBuffers(vk::CommandBufferAllocateInfo()
1601 .setCommandPool(cmd_pool)
1602 .setLevel(vk::CommandBufferLevel::ePrimary)
1603 .setCommandBufferCount(1));
1604 VERIFY(alloc_return.result == vk::Result::eSuccess);
1605 swapchain_image_resource.cmd = alloc_return.value[0];
1608 if (separate_present_queue) {
1609 auto present_cmd_pool_return =
1610 device.createCommandPool(vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index));
1611 VERIFY(present_cmd_pool_return.result == vk::Result::eSuccess);
1612 present_cmd_pool = present_cmd_pool_return.value;
1614 for (auto &swapchain_image_resource : swapchain_image_resources) {
1615 auto alloc_cmd_return = device.allocateCommandBuffers(vk::CommandBufferAllocateInfo()
1616 .setCommandPool(present_cmd_pool)
1617 .setLevel(vk::CommandBufferLevel::ePrimary)
1618 .setCommandBufferCount(1));
1619 VERIFY(alloc_cmd_return.result == vk::Result::eSuccess);
1620 swapchain_image_resource.graphics_to_present_cmd = alloc_cmd_return.value[0];
1621 build_image_ownership_cmd(swapchain_image_resource);
1625 prepare_descriptor_pool();
1626 prepare_descriptor_set();
1628 prepare_framebuffers();
1630 for (const auto &swapchain_image_resource : swapchain_image_resources) {
1631 draw_build_cmd(swapchain_image_resource);
1635 * Prepare functions above may generate pipeline commands
1636 * that need to be flushed before beginning the render loop.
1639 if (staging_texture.buffer) {
1640 destroy_texture(staging_texture);
1647 void Demo::prepare_buffers() {
1648 vk::SwapchainKHR oldSwapchain = swapchain;
1650 // Check the surface capabilities and formats
1651 auto surface_capabilities_return = gpu.getSurfaceCapabilitiesKHR(surface);
1652 VERIFY(surface_capabilities_return.result == vk::Result::eSuccess);
1653 auto surfCapabilities = surface_capabilities_return.value;
1655 auto present_modes_return = gpu.getSurfacePresentModesKHR(surface);
1656 VERIFY(present_modes_return.result == vk::Result::eSuccess);
1657 auto present_modes = present_modes_return.value;
1659 vk::Extent2D swapchainExtent;
1660 // width and height are either both -1, or both not -1.
1661 if (surfCapabilities.currentExtent.width == static_cast<uint32_t>(-1)) {
1662 // If the surface size is undefined, the size is set to
1663 // the size of the images requested.
1664 swapchainExtent.width = width;
1665 swapchainExtent.height = height;
1667 // If the surface size is defined, the swap chain size must match
1668 swapchainExtent = surfCapabilities.currentExtent;
1669 width = surfCapabilities.currentExtent.width;
1670 height = surfCapabilities.currentExtent.height;
1673 // The FIFO present mode is guaranteed by the spec to be supported
1674 // and to have no tearing. It's a great default present mode to use.
1675 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1677 // There are times when you may wish to use another present mode. The
1678 // following code shows how to select them, and the comments provide some
1679 // reasons you may wish to use them.
1681 // It should be noted that Vulkan 1.0 doesn't provide a method for
1682 // synchronizing rendering with the presentation engine's display. There
1683 // is a method provided for throttling rendering with the display, but
1684 // there are some presentation engines for which this method will not work.
1685 // If an application doesn't throttle its rendering, and if it renders much
1686 // faster than the refresh rate of the display, this can waste power on
1687 // mobile devices. That is because power is being spent rendering images
1688 // that may never be seen.
1690 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1692 // tearing, or have some way of synchronizing their rendering with the
1694 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1695 // generally render a new presentable image every refresh cycle, but are
1696 // occasionally early. In this case, the application wants the new
1698 // to be displayed instead of the previously-queued-for-presentation
1700 // that has not yet been displayed.
1701 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1702 // render a new presentable image every refresh cycle, but are
1704 // late. In this case (perhaps because of stuttering/latency concerns),
1705 // the application wants the late image to be immediately displayed,
1707 // though that may mean some tearing.
1709 if (presentMode != swapchainPresentMode) {
1710 for (const auto &mode : present_modes) {
1711 if (mode == presentMode) {
1712 swapchainPresentMode = mode;
1718 if (swapchainPresentMode != presentMode) {
1719 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1722 // Determine the number of VkImages to use in the swap chain.
1723 // Application desires to acquire 3 images at a time for triple
1725 uint32_t desiredNumOfSwapchainImages = 3;
1726 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1727 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1730 // If maxImageCount is 0, we can ask for as many images as we want,
1732 // we're limited to maxImageCount
1733 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1734 // Application must settle for fewer images than desired:
1735 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1738 vk::SurfaceTransformFlagBitsKHR preTransform;
1739 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1740 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1742 preTransform = surfCapabilities.currentTransform;
1745 // Find a supported composite alpha mode - one of these is guaranteed to be set
1746 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1747 std::array<vk::CompositeAlphaFlagBitsKHR, 4> compositeAlphaFlags = {
1748 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1749 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1750 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1751 vk::CompositeAlphaFlagBitsKHR::eInherit,
1753 for (const auto &compositeAlphaFlag : compositeAlphaFlags) {
1754 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlag) {
1755 compositeAlpha = compositeAlphaFlag;
1760 auto swapchain_return = device.createSwapchainKHR(vk::SwapchainCreateInfoKHR()
1761 .setSurface(surface)
1762 .setMinImageCount(desiredNumOfSwapchainImages)
1763 .setImageFormat(format)
1764 .setImageColorSpace(color_space)
1765 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1766 .setImageArrayLayers(1)
1767 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1768 .setImageSharingMode(vk::SharingMode::eExclusive)
1769 .setPreTransform(preTransform)
1770 .setCompositeAlpha(compositeAlpha)
1771 .setPresentMode(swapchainPresentMode)
1773 .setOldSwapchain(oldSwapchain));
1774 VERIFY(swapchain_return.result == vk::Result::eSuccess);
1775 swapchain = swapchain_return.value;
1777 // If we just re-created an existing swapchain, we should destroy the
1779 // swapchain at this point.
1780 // Note: destroying the swapchain also cleans up all its associated
1781 // presentable images once the platform is done with them.
1783 device.destroySwapchainKHR(oldSwapchain);
1786 auto swapchain_images_return = device.getSwapchainImagesKHR(swapchain);
1787 VERIFY(swapchain_images_return.result == vk::Result::eSuccess);
1788 swapchain_image_resources.resize(swapchain_images_return.value.size());
1790 for (uint32_t i = 0; i < swapchain_image_resources.size(); ++i) {
1791 auto color_image_view = vk::ImageViewCreateInfo()
1792 .setViewType(vk::ImageViewType::e2D)
1794 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1796 swapchain_image_resources[i].image = swapchain_images_return.value[i];
1798 color_image_view.image = swapchain_image_resources[i].image;
1800 auto image_view_return = device.createImageView(color_image_view);
1801 VERIFY(image_view_return.result == vk::Result::eSuccess);
1802 swapchain_image_resources[i].view = image_view_return.value;
1806 void Demo::prepare_cube_data_buffers() {
1808 mat4x4_mul(VP, projection_matrix, view_matrix);
1811 mat4x4_mul(MVP, VP, model_matrix);
1813 vktexcube_vs_uniform data;
1814 memcpy(data.mvp, MVP, sizeof(MVP));
1815 // dumpMatrix("MVP", MVP)
1817 for (int32_t i = 0; i < 12 * 3; i++) {
1818 data.position[i][0] = g_vertex_buffer_data[i * 3];
1819 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1820 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1821 data.position[i][3] = 1.0f;
1822 data.attr[i][0] = g_uv_buffer_data[2 * i];
1823 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1824 data.attr[i][2] = 0;
1825 data.attr[i][3] = 0;
1828 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1830 for (auto &swapchain_image_resource : swapchain_image_resources) {
1831 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resource.uniform_buffer);
1832 VERIFY(result == vk::Result::eSuccess);
1834 vk::MemoryRequirements mem_reqs;
1835 device.getBufferMemoryRequirements(swapchain_image_resource.uniform_buffer, &mem_reqs);
1837 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
1839 bool const pass = memory_type_from_properties(
1840 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1841 mem_alloc.memoryTypeIndex);
1844 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resource.uniform_memory);
1845 VERIFY(result == vk::Result::eSuccess);
1847 result = device.mapMemory(swapchain_image_resource.uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1848 &swapchain_image_resource.uniform_memory_ptr);
1849 VERIFY(result == vk::Result::eSuccess);
1851 memcpy(swapchain_image_resource.uniform_memory_ptr, &data, sizeof data);
1853 result = device.bindBufferMemory(swapchain_image_resource.uniform_buffer, swapchain_image_resource.uniform_memory, 0);
1854 VERIFY(result == vk::Result::eSuccess);
1858 void Demo::prepare_depth() {
1859 depth.format = vk::Format::eD16Unorm;
1861 auto const image = vk::ImageCreateInfo()
1862 .setImageType(vk::ImageType::e2D)
1863 .setFormat(depth.format)
1864 .setExtent({width, height, 1})
1867 .setSamples(vk::SampleCountFlagBits::e1)
1868 .setTiling(vk::ImageTiling::eOptimal)
1869 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1870 .setSharingMode(vk::SharingMode::eExclusive)
1871 .setInitialLayout(vk::ImageLayout::eUndefined);
1873 auto result = device.createImage(&image, nullptr, &depth.image);
1874 VERIFY(result == vk::Result::eSuccess);
1876 vk::MemoryRequirements mem_reqs;
1877 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1879 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1880 depth.mem_alloc.setMemoryTypeIndex(0);
1882 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1883 depth.mem_alloc.memoryTypeIndex);
1886 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1887 VERIFY(result == vk::Result::eSuccess);
1889 result = device.bindImageMemory(depth.image, depth.mem, 0);
1890 VERIFY(result == vk::Result::eSuccess);
1892 auto view = vk::ImageViewCreateInfo()
1893 .setImage(depth.image)
1894 .setViewType(vk::ImageViewType::e2D)
1895 .setFormat(depth.format)
1896 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1898 // Intentionally force a bad pNext value to generate a validation layer error
1899 view.pNext = ℑ
1901 result = device.createImageView(&view, nullptr, &depth.view);
1902 VERIFY(result == vk::Result::eSuccess);
1905 void Demo::prepare_descriptor_layout() {
1906 std::array<vk::DescriptorSetLayoutBinding, 2> const layout_bindings = {
1907 vk::DescriptorSetLayoutBinding()
1909 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1910 .setDescriptorCount(1)
1911 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1912 .setPImmutableSamplers(nullptr),
1913 vk::DescriptorSetLayoutBinding()
1915 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1916 .setDescriptorCount(texture_count)
1917 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1918 .setPImmutableSamplers(nullptr)};
1920 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindings(layout_bindings);
1922 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1923 VERIFY(result == vk::Result::eSuccess);
1925 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayouts(desc_layout);
1927 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1928 VERIFY(result == vk::Result::eSuccess);
1931 void Demo::prepare_descriptor_pool() {
1932 std::array<vk::DescriptorPoolSize, 2> const poolSizes = {
1933 vk::DescriptorPoolSize()
1934 .setType(vk::DescriptorType::eUniformBuffer)
1935 .setDescriptorCount(static_cast<uint32_t>(swapchain_image_resources.size())),
1936 vk::DescriptorPoolSize()
1937 .setType(vk::DescriptorType::eCombinedImageSampler)
1938 .setDescriptorCount(static_cast<uint32_t>(swapchain_image_resources.size()) * texture_count)};
1940 auto const descriptor_pool =
1941 vk::DescriptorPoolCreateInfo().setMaxSets(static_cast<uint32_t>(swapchain_image_resources.size())).setPoolSizes(poolSizes);
1943 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1944 VERIFY(result == vk::Result::eSuccess);
1947 void Demo::prepare_descriptor_set() {
1948 auto const alloc_info = vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setSetLayouts(desc_layout);
1950 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(vktexcube_vs_uniform));
1952 std::array<vk::DescriptorImageInfo, texture_count> tex_descs;
1953 for (uint32_t i = 0; i < texture_count; i++) {
1954 tex_descs[i].setSampler(textures[i].sampler);
1955 tex_descs[i].setImageView(textures[i].view);
1956 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
1959 std::array<vk::WriteDescriptorSet, 2> writes;
1960 writes[0].setDescriptorCount(1).setDescriptorType(vk::DescriptorType::eUniformBuffer).setPBufferInfo(&buffer_info);
1963 .setDescriptorCount(texture_count)
1964 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1965 .setImageInfo(tex_descs);
1967 for (auto &swapchain_image_resource : swapchain_image_resources) {
1968 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resource.descriptor_set);
1969 VERIFY(result == vk::Result::eSuccess);
1971 buffer_info.setBuffer(swapchain_image_resource.uniform_buffer);
1972 writes[0].setDstSet(swapchain_image_resource.descriptor_set);
1973 writes[1].setDstSet(swapchain_image_resource.descriptor_set);
1974 device.updateDescriptorSets(writes, {});
1978 void Demo::prepare_framebuffers() {
1979 std::array<vk::ImageView, 2> attachments;
1980 attachments[1] = depth.view;
1982 for (auto &swapchain_image_resource : swapchain_image_resources) {
1983 attachments[0] = swapchain_image_resource.view;
1984 auto const framebuffer_return = device.createFramebuffer(vk::FramebufferCreateInfo()
1985 .setRenderPass(render_pass)
1986 .setAttachments(attachments)
1990 VERIFY(framebuffer_return.result == vk::Result::eSuccess);
1991 swapchain_image_resource.framebuffer = framebuffer_return.value;
1995 vk::ShaderModule Demo::prepare_fs() {
1996 const uint32_t fragShaderCode[] = {
1997 #include "cube.frag.inc"
2000 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
2002 return frag_shader_module;
2005 void Demo::prepare_pipeline() {
2006 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
2007 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
2008 VERIFY(result == vk::Result::eSuccess);
2010 std::array<vk::PipelineShaderStageCreateInfo, 2> const shaderStageInfo = {
2011 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
2012 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
2014 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
2016 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
2018 // TODO: Where are pViewports and pScissors set?
2019 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
2021 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
2022 .setDepthClampEnable(VK_FALSE)
2023 .setRasterizerDiscardEnable(VK_FALSE)
2024 .setPolygonMode(vk::PolygonMode::eFill)
2025 .setCullMode(vk::CullModeFlagBits::eBack)
2026 .setFrontFace(vk::FrontFace::eCounterClockwise)
2027 .setDepthBiasEnable(VK_FALSE)
2028 .setLineWidth(1.0f);
2030 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
2032 auto const stencilOp =
2033 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
2035 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
2036 .setDepthTestEnable(VK_TRUE)
2037 .setDepthWriteEnable(VK_TRUE)
2038 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
2039 .setDepthBoundsTestEnable(VK_FALSE)
2040 .setStencilTestEnable(VK_FALSE)
2041 .setFront(stencilOp)
2042 .setBack(stencilOp);
2044 std::array<vk::PipelineColorBlendAttachmentState, 1> const colorBlendAttachments = {
2045 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
2046 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
2048 auto const colorBlendInfo = vk::PipelineColorBlendStateCreateInfo().setAttachments(colorBlendAttachments);
2050 std::array<vk::DynamicState, 2> const dynamicStates = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
2052 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setDynamicStates(dynamicStates);
2054 auto pipline_return = device.createGraphicsPipelines(pipelineCache, vk::GraphicsPipelineCreateInfo()
2055 .setStages(shaderStageInfo)
2056 .setPVertexInputState(&vertexInputInfo)
2057 .setPInputAssemblyState(&inputAssemblyInfo)
2058 .setPViewportState(&viewportInfo)
2059 .setPRasterizationState(&rasterizationInfo)
2060 .setPMultisampleState(&multisampleInfo)
2061 .setPDepthStencilState(&depthStencilInfo)
2062 .setPColorBlendState(&colorBlendInfo)
2063 .setPDynamicState(&dynamicStateInfo)
2064 .setLayout(pipeline_layout)
2065 .setRenderPass(render_pass));
2066 VERIFY(result == vk::Result::eSuccess);
2067 pipeline = pipline_return.value.at(0);
2069 device.destroyShaderModule(frag_shader_module);
2070 device.destroyShaderModule(vert_shader_module);
2073 void Demo::prepare_render_pass() {
2074 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
2075 // because at the start of the renderpass, we don't care about their contents.
2076 // At the start of the subpass, the color attachment's layout will be transitioned
2077 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
2078 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
2079 // the renderpass, the color attachment's layout will be transitioned to
2080 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
2081 // the renderpass, no barriers are necessary.
2082 std::array<vk::AttachmentDescription, 2> const attachments = {
2083 vk::AttachmentDescription()
2085 .setSamples(vk::SampleCountFlagBits::e1)
2086 .setLoadOp(vk::AttachmentLoadOp::eClear)
2087 .setStoreOp(vk::AttachmentStoreOp::eStore)
2088 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2089 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2090 .setInitialLayout(vk::ImageLayout::eUndefined)
2091 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
2092 vk::AttachmentDescription()
2093 .setFormat(depth.format)
2094 .setSamples(vk::SampleCountFlagBits::e1)
2095 .setLoadOp(vk::AttachmentLoadOp::eClear)
2096 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
2097 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2098 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2099 .setInitialLayout(vk::ImageLayout::eUndefined)
2100 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
2102 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
2104 auto const depth_reference =
2105 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
2107 auto const subpass = vk::SubpassDescription()
2108 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2109 .setColorAttachments(color_reference)
2110 .setPDepthStencilAttachment(&depth_reference);
2112 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2113 std::array<vk::SubpassDependency, 2> const dependencies = {
2114 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2115 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2117 .setSrcStageMask(stages)
2118 .setDstStageMask(stages)
2119 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2120 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2121 .setDependencyFlags(vk::DependencyFlags()),
2122 vk::SubpassDependency() // Image layout transition
2123 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2125 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2126 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2127 .setSrcAccessMask(vk::AccessFlagBits())
2128 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2129 .setDependencyFlags(vk::DependencyFlags()),
2132 const auto render_pass_result = device.createRenderPass(
2133 vk::RenderPassCreateInfo().setAttachments(attachments).setSubpasses(subpass).setDependencies(dependencies));
2134 VERIFY(render_pass_result.result == vk::Result::eSuccess);
2135 render_pass = render_pass_result.value;
2138 vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2139 const auto shader_module_return = device.createShaderModule(vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code));
2140 VERIFY(shader_module_return.result == vk::Result::eSuccess);
2142 return shader_module_return.value;
2145 void Demo::prepare_texture_buffer(const char *filename, texture_object &tex_obj) {
2146 vk::SubresourceLayout tex_layout;
2148 if (!loadTexture(filename, nullptr, tex_layout, tex_obj.tex_width, tex_obj.tex_height)) {
2149 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2152 auto const buffer_create_info = vk::BufferCreateInfo()
2153 .setSize(tex_obj.tex_width * tex_obj.tex_height * 4)
2154 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2155 .setSharingMode(vk::SharingMode::eExclusive);
2157 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj.buffer);
2158 VERIFY(result == vk::Result::eSuccess);
2160 vk::MemoryRequirements mem_reqs;
2161 device.getBufferMemoryRequirements(tex_obj.buffer, &mem_reqs);
2163 tex_obj.mem_alloc.setAllocationSize(mem_reqs.size);
2164 tex_obj.mem_alloc.setMemoryTypeIndex(0);
2166 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2167 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, tex_obj.mem_alloc.memoryTypeIndex);
2168 VERIFY(pass == true);
2170 result = device.allocateMemory(&tex_obj.mem_alloc, nullptr, &(tex_obj.mem));
2171 VERIFY(result == vk::Result::eSuccess);
2173 result = device.bindBufferMemory(tex_obj.buffer, tex_obj.mem, 0);
2174 VERIFY(result == vk::Result::eSuccess);
2176 vk::SubresourceLayout layout;
2177 layout.rowPitch = tex_obj.tex_width * 4;
2178 auto data = device.mapMemory(tex_obj.mem, 0, tex_obj.mem_alloc.allocationSize);
2179 VERIFY(data.result == vk::Result::eSuccess);
2181 if (!loadTexture(filename, (uint8_t *)data.value, layout, tex_obj.tex_width, tex_obj.tex_height)) {
2182 fprintf(stderr, "Error loading texture: %s\n", filename);
2185 device.unmapMemory(tex_obj.mem);
2188 void Demo::prepare_texture_image(const char *filename, texture_object &tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2189 vk::MemoryPropertyFlags required_props) {
2190 vk::SubresourceLayout tex_layout;
2191 if (!loadTexture(filename, nullptr, tex_layout, tex_obj.tex_width, tex_obj.tex_height)) {
2192 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2195 auto const image_create_info = vk::ImageCreateInfo()
2196 .setImageType(vk::ImageType::e2D)
2197 .setFormat(vk::Format::eR8G8B8A8Unorm)
2198 .setExtent({tex_obj.tex_width, tex_obj.tex_height, 1})
2201 .setSamples(vk::SampleCountFlagBits::e1)
2204 .setSharingMode(vk::SharingMode::eExclusive)
2205 .setInitialLayout(vk::ImageLayout::ePreinitialized);
2207 auto result = device.createImage(&image_create_info, nullptr, &tex_obj.image);
2208 VERIFY(result == vk::Result::eSuccess);
2210 vk::MemoryRequirements mem_reqs;
2211 device.getImageMemoryRequirements(tex_obj.image, &mem_reqs);
2213 tex_obj.mem_alloc.setAllocationSize(mem_reqs.size);
2214 tex_obj.mem_alloc.setMemoryTypeIndex(0);
2216 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, tex_obj.mem_alloc.memoryTypeIndex);
2217 VERIFY(pass == true);
2219 result = device.allocateMemory(&tex_obj.mem_alloc, nullptr, &tex_obj.mem);
2220 VERIFY(result == vk::Result::eSuccess);
2222 result = device.bindImageMemory(tex_obj.image, tex_obj.mem, 0);
2223 VERIFY(result == vk::Result::eSuccess);
2225 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2226 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2227 vk::SubresourceLayout layout;
2228 device.getImageSubresourceLayout(tex_obj.image, &subres, &layout);
2230 auto data = device.mapMemory(tex_obj.mem, 0, tex_obj.mem_alloc.allocationSize);
2231 VERIFY(data.result == vk::Result::eSuccess);
2233 if (!loadTexture(filename, (uint8_t *)data.value, layout, tex_obj.tex_width, tex_obj.tex_height)) {
2234 fprintf(stderr, "Error loading texture: %s\n", filename);
2237 device.unmapMemory(tex_obj.mem);
2240 tex_obj.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2243 void Demo::prepare_textures() {
2244 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2245 vk::FormatProperties props;
2246 gpu.getFormatProperties(tex_format, &props);
2248 for (uint32_t i = 0; i < texture_count; i++) {
2249 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2250 /* Device can texture using linear textures */
2251 prepare_texture_image(tex_files[i], textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2252 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2253 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2254 // shader to run until layout transition completes
2255 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2256 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2257 vk::PipelineStageFlagBits::eFragmentShader);
2258 staging_texture.image = vk::Image();
2259 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2260 /* Must use staging buffer to copy linear texture to optimized */
2262 prepare_texture_buffer(tex_files[i], staging_texture);
2264 prepare_texture_image(tex_files[i], textures[i], vk::ImageTiling::eOptimal,
2265 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2266 vk::MemoryPropertyFlagBits::eDeviceLocal);
2268 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2269 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2270 vk::PipelineStageFlagBits::eTransfer);
2272 auto const subresource = vk::ImageSubresourceLayers()
2273 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2275 .setBaseArrayLayer(0)
2278 auto const copy_region = vk::BufferImageCopy()
2280 .setBufferRowLength(staging_texture.tex_width)
2281 .setBufferImageHeight(staging_texture.tex_height)
2282 .setImageSubresource(subresource)
2283 .setImageOffset({0, 0, 0})
2284 .setImageExtent({staging_texture.tex_width, staging_texture.tex_height, 1});
2286 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, ©_region);
2288 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2289 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2290 vk::PipelineStageFlagBits::eFragmentShader);
2292 assert(!"No support for R8G8B8A8_UNORM as texture image format");
2295 auto const samplerInfo = vk::SamplerCreateInfo()
2296 .setMagFilter(vk::Filter::eNearest)
2297 .setMinFilter(vk::Filter::eNearest)
2298 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2299 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2300 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2301 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2302 .setMipLodBias(0.0f)
2303 .setAnisotropyEnable(VK_FALSE)
2304 .setMaxAnisotropy(1)
2305 .setCompareEnable(VK_FALSE)
2306 .setCompareOp(vk::CompareOp::eNever)
2309 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2310 .setUnnormalizedCoordinates(VK_FALSE);
2312 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2313 VERIFY(result == vk::Result::eSuccess);
2315 auto const viewInfo = vk::ImageViewCreateInfo()
2316 .setImage(textures[i].image)
2317 .setViewType(vk::ImageViewType::e2D)
2318 .setFormat(tex_format)
2319 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2321 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2322 VERIFY(result == vk::Result::eSuccess);
2326 vk::ShaderModule Demo::prepare_vs() {
2327 const uint32_t vertShaderCode[] = {
2328 #include "cube.vert.inc"
2331 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2333 return vert_shader_module;
2336 void Demo::destroy_swapchain_related_resources() {
2337 device.destroyDescriptorPool(desc_pool);
2339 device.destroyPipeline(pipeline);
2340 device.destroyPipelineCache(pipelineCache);
2341 device.destroyRenderPass(render_pass);
2342 device.destroyPipelineLayout(pipeline_layout);
2343 device.destroyDescriptorSetLayout(desc_layout);
2345 for (const auto &tex : textures) {
2346 device.destroyImageView(tex.view);
2347 device.destroyImage(tex.image);
2348 device.freeMemory(tex.mem);
2349 device.destroySampler(tex.sampler);
2352 device.destroyImageView(depth.view);
2353 device.destroyImage(depth.image);
2354 device.freeMemory(depth.mem);
2356 for (const auto &resource : swapchain_image_resources) {
2357 device.destroyFramebuffer(resource.framebuffer);
2358 device.destroyImageView(resource.view);
2359 device.freeCommandBuffers(cmd_pool, {resource.cmd});
2360 device.destroyBuffer(resource.uniform_buffer);
2361 device.unmapMemory(resource.uniform_memory);
2362 device.freeMemory(resource.uniform_memory);
2365 device.destroyCommandPool(cmd_pool);
2366 if (separate_present_queue) {
2367 device.destroyCommandPool(present_cmd_pool);
2371 void Demo::resize() {
2372 // Don't react to resize until after first initialization.
2377 // In order to properly resize the window, we must re-create the
2379 // AND redo the command buffers, etc.
2381 // First, perform part of the cleanup() function:
2383 auto result = device.waitIdle();
2384 VERIFY(result == vk::Result::eSuccess);
2385 destroy_swapchain_related_resources();
2387 // Second, re-perform the prepare() function, which will re-create the
2392 void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2393 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2396 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2397 vk::AccessFlags flags;
2400 case vk::ImageLayout::eTransferDstOptimal:
2401 // Make sure anything that was copying from this image has
2403 flags = vk::AccessFlagBits::eTransferWrite;
2405 case vk::ImageLayout::eColorAttachmentOptimal:
2406 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2408 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2409 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2411 case vk::ImageLayout::eShaderReadOnlyOptimal:
2412 // Make sure any Copy or CPU writes to image are flushed
2413 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2415 case vk::ImageLayout::eTransferSrcOptimal:
2416 flags = vk::AccessFlagBits::eTransferRead;
2418 case vk::ImageLayout::ePresentSrcKHR:
2419 flags = vk::AccessFlagBits::eMemoryRead;
2428 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), {}, {},
2429 vk::ImageMemoryBarrier()
2430 .setSrcAccessMask(srcAccessMask)
2431 .setDstAccessMask(DstAccessMask(newLayout))
2432 .setOldLayout(oldLayout)
2433 .setNewLayout(newLayout)
2434 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2435 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2437 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1)));
2440 void Demo::update_data_buffer() {
2442 mat4x4_mul(VP, projection_matrix, view_matrix);
2444 // Rotate around the Y axis
2446 mat4x4_dup(Model, model_matrix);
2447 mat4x4_rotate_Y(model_matrix, Model, static_cast<float>(degreesToRadians(spin_angle)));
2448 mat4x4_orthonormalize(model_matrix, model_matrix);
2451 mat4x4_mul(MVP, VP, model_matrix);
2453 memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
2456 /* Convert ppm image data from header file into RGBA texture image */
2457 #include "lunarg.ppm.h"
2458 bool Demo::loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout &layout, uint32_t &w, uint32_t &h) {
2461 cPtr = (char *)lunarg_ppm;
2462 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
2465 while (strncmp(cPtr++, "\n", 1))
2467 sscanf(cPtr, "%u %u", &w, &h);
2468 if (rgba_data == nullptr) {
2471 while (strncmp(cPtr++, "\n", 1))
2473 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
2476 while (strncmp(cPtr++, "\n", 1))
2478 for (uint32_t y = 0; y < h; y++) {
2479 uint8_t *rowPtr = rgba_data;
2480 for (uint32_t x = 0; x < w; x++) {
2481 memcpy(rowPtr, cPtr, 3);
2482 rowPtr[3] = 255; /* Alpha of 1 */
2486 rgba_data += layout.rowPitch;
2491 bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t &typeIndex) {
2492 // Search memtypes to find first index with those properties
2493 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2494 if ((typeBits & 1) == 1) {
2495 // Type is available, does it match user properties?
2496 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2504 // No memory types matched, return failure
2508 vk::SurfaceFormatKHR Demo::pick_surface_format(const std::vector<vk::SurfaceFormatKHR> &surface_formats) {
2509 // Prefer non-SRGB formats...
2510 for (const auto &surface_format : surface_formats) {
2511 const vk::Format format = surface_format.format;
2513 if (format == vk::Format::eR8G8B8A8Unorm || format == vk::Format::eB8G8R8A8Unorm ||
2514 format == vk::Format::eA2B10G10R10UnormPack32 || format == vk::Format::eA2R10G10B10UnormPack32 ||
2515 format == vk::Format::eR16G16B16A16Sfloat) {
2516 return surface_format;
2520 printf("Can't find our preferred formats... Falling back to first exposed format. Rendering may be incorrect.\n");
2522 assert(surface_formats.size() >= 1);
2523 return surface_formats[0];
2526 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2535 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2536 PostQuitMessage(validation_error);
2540 void Demo::create_window() {
2541 WNDCLASSEX win_class;
2543 // Initialize the window class structure:
2544 win_class.cbSize = sizeof(WNDCLASSEX);
2545 win_class.style = CS_HREDRAW | CS_VREDRAW;
2546 win_class.lpfnWndProc = WndProc;
2547 win_class.cbClsExtra = 0;
2548 win_class.cbWndExtra = 0;
2549 win_class.hInstance = connection; // hInstance
2550 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2551 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2552 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2553 win_class.lpszMenuName = nullptr;
2554 win_class.lpszClassName = name.c_str();
2555 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2557 // Register window class:
2558 if (!RegisterClassEx(&win_class)) {
2559 // It didn't work, so try to give a useful error:
2560 printf("Unexpected error trying to start the application!\n");
2565 // Create window with the registered class:
2566 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2567 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2568 window = CreateWindowEx(0,
2569 name.c_str(), // class name
2570 name.c_str(), // app name
2571 WS_OVERLAPPEDWINDOW | // window style
2572 WS_VISIBLE | WS_SYSMENU,
2573 100, 100, // x/y coords
2574 wr.right - wr.left, // width
2575 wr.bottom - wr.top, // height
2576 nullptr, // handle to parent
2577 nullptr, // handle to menu
2578 connection, // hInstance
2579 nullptr); // no extra parameters
2582 // It didn't work, so try to give a useful error:
2583 printf("Cannot create a window in which to draw!\n");
2588 // Window client area size must be at least 1 pixel high, to prevent
2590 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2591 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2593 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2595 void Demo::create_xlib_window() {
2596 const char *display_envar = getenv("DISPLAY");
2597 if (display_envar == nullptr || display_envar[0] == '\0') {
2598 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2604 display = XOpenDisplay(nullptr);
2605 long visualMask = VisualScreenMask;
2606 int numberOfVisuals;
2607 XVisualInfo vInfoTemplate = {};
2608 vInfoTemplate.screen = DefaultScreen(display);
2609 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2611 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2613 XSetWindowAttributes windowAttributes = {};
2614 windowAttributes.colormap = colormap;
2615 windowAttributes.background_pixel = 0xFFFFFFFF;
2616 windowAttributes.border_pixel = 0;
2617 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2620 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2621 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2623 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2624 XMapWindow(display, xlib_window);
2626 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2629 void Demo::handle_xlib_event(const XEvent *event) {
2630 switch (event->type) {
2632 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2637 switch (event->xkey.keycode) {
2641 case 0x71: // left arrow key
2642 spin_angle -= spin_increment;
2644 case 0x72: // right arrow key
2645 spin_angle += spin_increment;
2647 case 0x41: // space bar
2652 case ConfigureNotify:
2653 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2654 width = event->xconfigure.width;
2655 height = event->xconfigure.height;
2664 void Demo::run_xlib() {
2669 XNextEvent(display, &event);
2670 handle_xlib_event(&event);
2672 while (XPending(display) > 0) {
2673 XNextEvent(display, &event);
2674 handle_xlib_event(&event);
2680 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2685 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2687 void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2688 uint8_t event_code = event->response_type & 0x7f;
2689 switch (event_code) {
2691 // TODO: Resize window
2693 case XCB_CLIENT_MESSAGE:
2694 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2698 case XCB_KEY_RELEASE: {
2699 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
2701 switch (key->detail) {
2705 case 0x71: // left arrow key
2706 spin_angle -= spin_increment;
2708 case 0x72: // right arrow key
2709 spin_angle += spin_increment;
2711 case 0x41: // space bar
2716 case XCB_CONFIGURE_NOTIFY: {
2717 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2718 if ((width != cfg->width) || (height != cfg->height)) {
2720 height = cfg->height;
2729 void Demo::run_xcb() {
2730 xcb_flush(connection);
2733 xcb_generic_event_t *event;
2736 event = xcb_wait_for_event(connection);
2738 event = xcb_poll_for_event(connection);
2741 handle_xcb_event(event);
2743 event = xcb_poll_for_event(connection);
2748 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2754 void Demo::create_xcb_window() {
2755 uint32_t value_mask, value_list[32];
2757 xcb_window = xcb_generate_id(connection);
2759 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2760 value_list[0] = screen->black_pixel;
2761 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
2763 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2764 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2766 /* Magic code that will send notification when window is destroyed */
2767 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2768 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2770 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2771 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2773 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2777 xcb_map_window(connection, xcb_window);
2779 // Force the x/y coordinates to 100,100 results are identical in
2782 std::array<uint32_t, 2> const coords = {100, 100};
2783 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords.data());
2785 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2790 wl_display_dispatch(display);
2792 wl_display_dispatch_pending(display);
2795 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2802 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
2803 static void handle_surface_configure(void *data, xdg_surface *xdg_surface, uint32_t serial) {
2804 Demo &demo = *static_cast<Demo *>(data);
2805 xdg_surface_ack_configure(xdg_surface, serial);
2806 if (demo.xdg_surface_has_been_configured) {
2809 demo.xdg_surface_has_been_configured = true;
2812 static const xdg_surface_listener surface_listener = {handle_surface_configure};
2814 static void handle_toplevel_configure(void *data, xdg_toplevel *xdg_toplevel, int32_t width, int32_t height,
2815 struct wl_array *states) {
2816 Demo &demo = *static_cast<Demo *>(data);
2817 /* zero values imply the program may choose its own size, so in that case
2818 * stay with the existing value (which on startup is the default) */
2820 demo.width = static_cast<uint32_t>(width);
2823 demo.height = static_cast<uint32_t>(height);
2825 // This will be followed by a surface configure
2828 static void handle_toplevel_close(void *data, xdg_toplevel *xdg_toplevel) {
2829 Demo &demo = *static_cast<Demo *>(data);
2833 static const xdg_toplevel_listener toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
2836 static void PingCb(void *data, struct wl_shell_surface *shell_surface,
2839 wl_shell_surface_pong(shell_surface, serial);
2842 static void ConfigureCb(void *data, struct wl_shell_surface *shell_surface,
2843 uint32_t edges, int32_t width, int32_t height)
2848 static void PopupDoneCb(void *data, struct wl_shell_surface *shell_surface)
2853 void Demo::create_window() {
2855 printf("Compositor did not provide the standard protocol\n");
2860 window = wl_compositor_create_surface(compositor);
2862 printf("Can not create wayland_surface from compositor!\n");
2867 window_surface = wl_shell_get_shell_surface(shell, window);
2868 static const struct wl_shell_surface_listener shell_surface_listener =
2869 {PingCb, ConfigureCb, PopupDoneCb};
2870 wl_shell_surface_add_listener(window_surface, &shell_surface_listener, this);
2871 wl_shell_surface_set_toplevel(window_surface);
2872 wl_shell_surface_set_title(window_surface, APP_SHORT_NAME);
2874 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
2875 window_surface = xdg_wm_base_get_xdg_surface(wm_base, window);
2876 if (!window_surface) {
2877 printf("Can not get xdg_surface from wayland_surface!\n");
2881 window_toplevel = xdg_surface_get_toplevel(window_surface);
2882 if (!window_toplevel) {
2883 printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2887 xdg_surface_add_listener(window_surface, &surface_listener, this);
2888 xdg_toplevel_add_listener(window_toplevel, &toplevel_listener, this);
2889 xdg_toplevel_set_title(window_toplevel, APP_SHORT_NAME);
2891 #ifdef TIZEN_SUPPPORT_XDG_DECORATION
2892 if (xdg_decoration_mgr) {
2893 // if supported, let the compositor render titlebars for us
2894 toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(xdg_decoration_mgr, window_toplevel);
2895 zxdg_toplevel_decoration_v1_set_mode(toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2899 wl_surface_commit(window);
2901 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2903 void Demo::handle_directfb_event(const DFBInputEvent *event) {
2904 if (event->type != DIET_KEYPRESS) return;
2905 switch (event->key_symbol) {
2906 case DIKS_ESCAPE: // Escape
2909 case DIKS_CURSOR_LEFT: // left arrow key
2910 spin_angle -= spin_increment;
2912 case DIKS_CURSOR_RIGHT: // right arrow key
2913 spin_angle += spin_increment;
2915 case DIKS_SPACE: // space bar
2923 void Demo::run_directfb() {
2925 DFBInputEvent event;
2928 event_buffer->WaitForEvent(event_buffer);
2929 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
2931 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
2935 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2942 void Demo::create_directfb_window() {
2945 ret = DirectFBInit(nullptr, nullptr);
2947 printf("DirectFBInit failed to initialize DirectFB!\n");
2952 ret = DirectFBCreate(&dfb);
2954 printf("DirectFBCreate failed to create main interface of DirectFB!\n");
2959 DFBSurfaceDescription desc;
2960 desc.flags = (DFBSurfaceDescriptionFlags)(DSDESC_CAPS | DSDESC_WIDTH | DSDESC_HEIGHT);
2961 desc.caps = DSCAPS_PRIMARY;
2963 desc.height = height;
2964 ret = dfb->CreateSurface(dfb, &desc, &window);
2966 printf("CreateSurface failed to create DirectFB surface interface!\n");
2971 ret = dfb->CreateInputEventBuffer(dfb, DICAPS_KEYS, DFB_FALSE, &event_buffer);
2973 printf("CreateInputEventBuffer failed to create DirectFB event buffer interface!\n");
2978 #elif defined(VK_USE_PLATFORM_METAL_EXT)
2982 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2986 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2988 vk::Result Demo::create_display_surface() {
2989 auto display_properties_return = gpu.getDisplayPropertiesKHR();
2990 VERIFY((display_properties_return.result == vk::Result::eSuccess) ||
2991 (display_properties_return.result == vk::Result::eIncomplete));
2993 auto display = display_properties_return.value.at(0).display;
2995 auto display_mode_props_return = gpu.getDisplayModePropertiesKHR(display);
2996 VERIFY(display_mode_props_return.result == vk::Result::eSuccess);
2998 if (display_mode_props_return.value.size() == 0) {
2999 printf("Cannot find any mode for the display!\n");
3003 auto display_mode_prop = display_mode_props_return.value.at(0);
3005 // Get the list of planes
3006 auto display_plane_props_return = gpu.getDisplayPlanePropertiesKHR();
3007 VERIFY(display_plane_props_return.result == vk::Result::eSuccess);
3009 if (display_plane_props_return.value.size() == 0) {
3010 printf("Cannot find any plane!\n");
3014 auto display_plane_props = display_plane_props_return.value;
3016 vk::Bool32 found_plane = VK_FALSE;
3017 uint32_t plane_found = 0;
3018 // Find a plane compatible with the display
3019 for (uint32_t plane_index = 0; plane_index < display_plane_props.size(); plane_index++) {
3020 // Disqualify planes that are bound to a different display
3021 if (display_plane_props[plane_index].currentDisplay && (display_plane_props[plane_index].currentDisplay != display)) {
3025 auto display_plane_supported_displays_return = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index);
3026 VERIFY(display_plane_supported_displays_return.result == vk::Result::eSuccess);
3028 if (display_plane_supported_displays_return.value.size() == 0) {
3032 for (const auto &supported_display : display_plane_supported_displays_return.value) {
3033 if (supported_display == display) {
3034 found_plane = VK_TRUE;
3035 plane_found = plane_index;
3046 printf("Cannot find a plane compatible with the display!\n");
3051 vk::DisplayPlaneCapabilitiesKHR planeCaps =
3052 gpu.getDisplayPlaneCapabilitiesKHR(display_mode_prop.displayMode, plane_found).value;
3053 // Find a supported alpha mode
3054 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
3055 std::array<vk::DisplayPlaneAlphaFlagBitsKHR, 4> alphaModes = {
3056 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
3057 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
3058 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
3059 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
3061 for (const auto &alpha_mode : alphaModes) {
3062 if (planeCaps.supportedAlpha & alpha_mode) {
3063 alphaMode = alpha_mode;
3068 vk::Extent2D image_extent{};
3069 image_extent.setWidth(display_mode_prop.parameters.visibleRegion.width)
3070 .setHeight(display_mode_prop.parameters.visibleRegion.height);
3072 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
3073 .setDisplayMode(display_mode_prop.displayMode)
3074 .setPlaneIndex(plane_found)
3075 .setPlaneStackIndex(display_plane_props[plane_found].currentStackIndex)
3076 .setGlobalAlpha(1.0f)
3077 .setAlphaMode(alphaMode)
3078 .setImageExtent(image_extent);
3080 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
3083 void Demo::run_display() {
3088 if (frameCount != UINT32_MAX && curFrame == frameCount) {
3096 // Include header required for parsing the command line options.
3097 #include <shellapi.h>
3101 // MS-Windows event handling function:
3102 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
3105 PostQuitMessage(validation_error);
3108 if (!demo.in_callback) {
3112 case WM_GETMINMAXINFO: // set window's minimum size
3113 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
3118 // Resize the application to the new window size, except when
3119 // it was minimized. Vulkan doesn't support images or swapchains
3120 // with width=0 and height=0.
3121 if (wParam != SIZE_MINIMIZED) {
3122 demo.width = lParam & 0xffff;
3123 demo.height = (lParam & 0xffff0000) >> 16;
3130 PostQuitMessage(validation_error);
3133 demo.spin_angle -= demo.spin_increment;
3136 demo.spin_angle += demo.spin_increment;
3139 demo.pause = !demo.pause;
3147 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
3150 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
3151 // TODO: Gah.. refactor. This isn't 1989.
3153 bool done; // flag saying when app is complete
3157 // Ensure wParam is initialized.
3160 // Use the CommandLine functions to get the command line arguments.
3161 // Unfortunately, Microsoft outputs
3162 // this information as wide characters for Unicode, and we simply want the
3163 // Ascii version to be compatible
3164 // with the non-Windows side. So, we have to convert the information to
3165 // Ascii character strings.
3166 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
3167 if (nullptr == commandLineArgs) {
3172 argv = (char **)malloc(sizeof(char *) * argc);
3173 if (argv == nullptr) {
3176 for (int iii = 0; iii < argc; iii++) {
3177 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3178 size_t numConverted = 0;
3180 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
3181 if (argv[iii] != nullptr) {
3182 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
3190 demo.init(argc, argv);
3192 // Free up the items we had to allocate for the command line arguments.
3193 if (argc > 0 && argv != nullptr) {
3194 for (int iii = 0; iii < argc; iii++) {
3195 if (argv[iii] != nullptr) {
3202 demo.connection = hInstance;
3203 demo.name = "Vulkan Cube";
3204 demo.create_window();
3205 demo.init_vk_swapchain();
3209 done = false; // initialize loop condition variable
3211 // main message loop
3214 const BOOL succ = WaitMessage();
3217 const auto &suppress_popups = demo.suppress_popups;
3218 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3222 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
3223 if (msg.message == WM_QUIT) // check for a quit message
3225 done = true; // if found, quit app
3227 /* Translate and dispatch to event queue*/
3228 TranslateMessage(&msg);
3229 DispatchMessage(&msg);
3231 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3236 return static_cast<int>(msg.wParam);
3239 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__)
3241 int main(int argc, char **argv) {
3244 demo.init(argc, argv);
3246 #if defined(VK_USE_PLATFORM_XCB_KHR)
3247 demo.create_xcb_window();
3248 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3249 demo.use_xlib = true;
3250 demo.create_xlib_window();
3251 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3252 demo.create_window();
3253 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3254 demo.create_directfb_window();
3257 demo.init_vk_swapchain();
3261 #if defined(VK_USE_PLATFORM_XCB_KHR)
3263 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3265 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3267 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3268 demo.run_directfb();
3269 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3275 return validation_error;
3278 #elif defined(VK_USE_PLATFORM_METAL_EXT)
3280 // Global function invoked from NS or UI views and controllers to create demo
3281 static void demo_main(Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
3282 demo.init(argc, (char **)argv);
3283 demo.caMetalLayer = caMetalLayer;
3284 demo.init_vk_swapchain();
3286 demo.spin_angle = 0.4f;
3290 #error "Platform not supported"