From 5459b8ff69176eb77d70e9178755be28728f4dec Mon Sep 17 00:00:00 2001 From: Ivan Avdeev Date: Sat, 7 Nov 2020 13:43:54 -0800 Subject: [PATCH 01/18] get first wayland+vulkan triangle --- 3p/wl-xdg-proto.c | 181 ++++ 3p/wl-xdg-proto.h | 1970 +++++++++++++++++++++++++++++++++++++ CMakeLists.txt | 28 +- examples/CMakeLists.txt | 30 +- examples/shader.frag | 10 + examples/shader.vert | 18 + examples/vk_tri.c | 354 +++++++ include/atto/app.h | 49 +- include/atto/worobushek.h | 53 + src/app_vulkan.c | 236 +++++ src/app_wayland.c | 136 +++ 11 files changed, 3047 insertions(+), 18 deletions(-) create mode 100644 3p/wl-xdg-proto.c create mode 100644 3p/wl-xdg-proto.h create mode 100644 examples/shader.frag create mode 100644 examples/shader.vert create mode 100644 examples/vk_tri.c create mode 100644 include/atto/worobushek.h create mode 100644 src/app_vulkan.c create mode 100644 src/app_wayland.c diff --git a/3p/wl-xdg-proto.c b/3p/wl-xdg-proto.c new file mode 100644 index 0000000..6bcc9fd --- /dev/null +++ b/3p/wl-xdg-proto.c @@ -0,0 +1,181 @@ +/* Generated by wayland-scanner 1.18.0 */ + +/* + * Copyright © 2008-2013 Kristian Høgsberg + * Copyright © 2013 Rafael Antognolli + * Copyright © 2013 Jasper St. Pierre + * Copyright © 2010-2013 Intel Corporation + * Copyright © 2015-2017 Samsung Electronics Co., Ltd + * Copyright © 2015-2017 Red Hat Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#include +#include +#include "wayland-util.h" + +#ifndef __has_attribute +# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */ +#endif + +#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4) +#define WL_PRIVATE __attribute__ ((visibility("hidden"))) +#else +#define WL_PRIVATE +#endif + +extern const struct wl_interface wl_output_interface; +extern const struct wl_interface wl_seat_interface; +extern const struct wl_interface wl_surface_interface; +extern const struct wl_interface xdg_popup_interface; +extern const struct wl_interface xdg_positioner_interface; +extern const struct wl_interface xdg_surface_interface; +extern const struct wl_interface xdg_toplevel_interface; + +static const struct wl_interface *xdg_shell_types[] = { + NULL, + NULL, + NULL, + NULL, + &xdg_positioner_interface, + &xdg_surface_interface, + &wl_surface_interface, + &xdg_toplevel_interface, + &xdg_popup_interface, + &xdg_surface_interface, + &xdg_positioner_interface, + &xdg_toplevel_interface, + &wl_seat_interface, + NULL, + NULL, + NULL, + &wl_seat_interface, + NULL, + &wl_seat_interface, + NULL, + NULL, + &wl_output_interface, + &wl_seat_interface, + NULL, + &xdg_positioner_interface, + NULL, +}; + +static const struct wl_message xdg_wm_base_requests[] = { + { "destroy", "", xdg_shell_types + 0 }, + { "create_positioner", "n", xdg_shell_types + 4 }, + { "get_xdg_surface", "no", xdg_shell_types + 5 }, + { "pong", "u", xdg_shell_types + 0 }, +}; + +static const struct wl_message xdg_wm_base_events[] = { + { "ping", "u", xdg_shell_types + 0 }, +}; + +WL_PRIVATE const struct wl_interface xdg_wm_base_interface = { + "xdg_wm_base", 3, + 4, xdg_wm_base_requests, + 1, xdg_wm_base_events, +}; + +static const struct wl_message xdg_positioner_requests[] = { + { "destroy", "", xdg_shell_types + 0 }, + { "set_size", "ii", xdg_shell_types + 0 }, + { "set_anchor_rect", "iiii", xdg_shell_types + 0 }, + { "set_anchor", "u", xdg_shell_types + 0 }, + { "set_gravity", "u", xdg_shell_types + 0 }, + { "set_constraint_adjustment", "u", xdg_shell_types + 0 }, + { "set_offset", "ii", xdg_shell_types + 0 }, + { "set_reactive", "3", xdg_shell_types + 0 }, + { "set_parent_size", "3ii", xdg_shell_types + 0 }, + { "set_parent_configure", "3u", xdg_shell_types + 0 }, +}; + +WL_PRIVATE const struct wl_interface xdg_positioner_interface = { + "xdg_positioner", 3, + 10, xdg_positioner_requests, + 0, NULL, +}; + +static const struct wl_message xdg_surface_requests[] = { + { "destroy", "", xdg_shell_types + 0 }, + { "get_toplevel", "n", xdg_shell_types + 7 }, + { "get_popup", "n?oo", xdg_shell_types + 8 }, + { "set_window_geometry", "iiii", xdg_shell_types + 0 }, + { "ack_configure", "u", xdg_shell_types + 0 }, +}; + +static const struct wl_message xdg_surface_events[] = { + { "configure", "u", xdg_shell_types + 0 }, +}; + +WL_PRIVATE const struct wl_interface xdg_surface_interface = { + "xdg_surface", 3, + 5, xdg_surface_requests, + 1, xdg_surface_events, +}; + +static const struct wl_message xdg_toplevel_requests[] = { + { "destroy", "", xdg_shell_types + 0 }, + { "set_parent", "?o", xdg_shell_types + 11 }, + { "set_title", "s", xdg_shell_types + 0 }, + { "set_app_id", "s", xdg_shell_types + 0 }, + { "show_window_menu", "ouii", xdg_shell_types + 12 }, + { "move", "ou", xdg_shell_types + 16 }, + { "resize", "ouu", xdg_shell_types + 18 }, + { "set_max_size", "ii", xdg_shell_types + 0 }, + { "set_min_size", "ii", xdg_shell_types + 0 }, + { "set_maximized", "", xdg_shell_types + 0 }, + { "unset_maximized", "", xdg_shell_types + 0 }, + { "set_fullscreen", "?o", xdg_shell_types + 21 }, + { "unset_fullscreen", "", xdg_shell_types + 0 }, + { "set_minimized", "", xdg_shell_types + 0 }, +}; + +static const struct wl_message xdg_toplevel_events[] = { + { "configure", "iia", xdg_shell_types + 0 }, + { "close", "", xdg_shell_types + 0 }, +}; + +WL_PRIVATE const struct wl_interface xdg_toplevel_interface = { + "xdg_toplevel", 3, + 14, xdg_toplevel_requests, + 2, xdg_toplevel_events, +}; + +static const struct wl_message xdg_popup_requests[] = { + { "destroy", "", xdg_shell_types + 0 }, + { "grab", "ou", xdg_shell_types + 22 }, + { "reposition", "3ou", xdg_shell_types + 24 }, +}; + +static const struct wl_message xdg_popup_events[] = { + { "configure", "iiii", xdg_shell_types + 0 }, + { "popup_done", "", xdg_shell_types + 0 }, + { "repositioned", "3u", xdg_shell_types + 0 }, +}; + +WL_PRIVATE const struct wl_interface xdg_popup_interface = { + "xdg_popup", 3, + 3, xdg_popup_requests, + 3, xdg_popup_events, +}; + diff --git a/3p/wl-xdg-proto.h b/3p/wl-xdg-proto.h new file mode 100644 index 0000000..6e80367 --- /dev/null +++ b/3p/wl-xdg-proto.h @@ -0,0 +1,1970 @@ +/* Generated by wayland-scanner 1.18.0 */ + +#ifndef XDG_SHELL_CLIENT_PROTOCOL_H +#define XDG_SHELL_CLIENT_PROTOCOL_H + +#include +#include +#include "wayland-client.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @page page_xdg_shell The xdg_shell protocol + * @section page_ifaces_xdg_shell Interfaces + * - @subpage page_iface_xdg_wm_base - create desktop-style surfaces + * - @subpage page_iface_xdg_positioner - child surface positioner + * - @subpage page_iface_xdg_surface - desktop user interface surface base interface + * - @subpage page_iface_xdg_toplevel - toplevel surface + * - @subpage page_iface_xdg_popup - short-lived, popup surfaces for menus + * @section page_copyright_xdg_shell Copyright + *
+ *
+ * Copyright © 2008-2013 Kristian Høgsberg
+ * Copyright © 2013      Rafael Antognolli
+ * Copyright © 2013      Jasper St. Pierre
+ * Copyright © 2010-2013 Intel Corporation
+ * Copyright © 2015-2017 Samsung Electronics Co., Ltd
+ * Copyright © 2015-2017 Red Hat Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ * 
+ */ +struct wl_output; +struct wl_seat; +struct wl_surface; +struct xdg_popup; +struct xdg_positioner; +struct xdg_surface; +struct xdg_toplevel; +struct xdg_wm_base; + +/** + * @page page_iface_xdg_wm_base xdg_wm_base + * @section page_iface_xdg_wm_base_desc Description + * + * The xdg_wm_base interface is exposed as a global object enabling clients + * to turn their wl_surfaces into windows in a desktop environment. It + * defines the basic functionality needed for clients and the compositor to + * create windows that can be dragged, resized, maximized, etc, as well as + * creating transient windows such as popup menus. + * @section page_iface_xdg_wm_base_api API + * See @ref iface_xdg_wm_base. + */ +/** + * @defgroup iface_xdg_wm_base The xdg_wm_base interface + * + * The xdg_wm_base interface is exposed as a global object enabling clients + * to turn their wl_surfaces into windows in a desktop environment. It + * defines the basic functionality needed for clients and the compositor to + * create windows that can be dragged, resized, maximized, etc, as well as + * creating transient windows such as popup menus. + */ +extern const struct wl_interface xdg_wm_base_interface; +/** + * @page page_iface_xdg_positioner xdg_positioner + * @section page_iface_xdg_positioner_desc Description + * + * The xdg_positioner provides a collection of rules for the placement of a + * child surface relative to a parent surface. Rules can be defined to ensure + * the child surface remains within the visible area's borders, and to + * specify how the child surface changes its position, such as sliding along + * an axis, or flipping around a rectangle. These positioner-created rules are + * constrained by the requirement that a child surface must intersect with or + * be at least partially adjacent to its parent surface. + * + * See the various requests for details about possible rules. + * + * At the time of the request, the compositor makes a copy of the rules + * specified by the xdg_positioner. Thus, after the request is complete the + * xdg_positioner object can be destroyed or reused; further changes to the + * object will have no effect on previous usages. + * + * For an xdg_positioner object to be considered complete, it must have a + * non-zero size set by set_size, and a non-zero anchor rectangle set by + * set_anchor_rect. Passing an incomplete xdg_positioner object when + * positioning a surface raises an error. + * @section page_iface_xdg_positioner_api API + * See @ref iface_xdg_positioner. + */ +/** + * @defgroup iface_xdg_positioner The xdg_positioner interface + * + * The xdg_positioner provides a collection of rules for the placement of a + * child surface relative to a parent surface. Rules can be defined to ensure + * the child surface remains within the visible area's borders, and to + * specify how the child surface changes its position, such as sliding along + * an axis, or flipping around a rectangle. These positioner-created rules are + * constrained by the requirement that a child surface must intersect with or + * be at least partially adjacent to its parent surface. + * + * See the various requests for details about possible rules. + * + * At the time of the request, the compositor makes a copy of the rules + * specified by the xdg_positioner. Thus, after the request is complete the + * xdg_positioner object can be destroyed or reused; further changes to the + * object will have no effect on previous usages. + * + * For an xdg_positioner object to be considered complete, it must have a + * non-zero size set by set_size, and a non-zero anchor rectangle set by + * set_anchor_rect. Passing an incomplete xdg_positioner object when + * positioning a surface raises an error. + */ +extern const struct wl_interface xdg_positioner_interface; +/** + * @page page_iface_xdg_surface xdg_surface + * @section page_iface_xdg_surface_desc Description + * + * An interface that may be implemented by a wl_surface, for + * implementations that provide a desktop-style user interface. + * + * It provides a base set of functionality required to construct user + * interface elements requiring management by the compositor, such as + * toplevel windows, menus, etc. The types of functionality are split into + * xdg_surface roles. + * + * Creating an xdg_surface does not set the role for a wl_surface. In order + * to map an xdg_surface, the client must create a role-specific object + * using, e.g., get_toplevel, get_popup. The wl_surface for any given + * xdg_surface can have at most one role, and may not be assigned any role + * not based on xdg_surface. + * + * A role must be assigned before any other requests are made to the + * xdg_surface object. + * + * The client must call wl_surface.commit on the corresponding wl_surface + * for the xdg_surface state to take effect. + * + * Creating an xdg_surface from a wl_surface which has a buffer attached or + * committed is a client error, and any attempts by a client to attach or + * manipulate a buffer prior to the first xdg_surface.configure call must + * also be treated as errors. + * + * Mapping an xdg_surface-based role surface is defined as making it + * possible for the surface to be shown by the compositor. Note that + * a mapped surface is not guaranteed to be visible once it is mapped. + * + * For an xdg_surface to be mapped by the compositor, the following + * conditions must be met: + * (1) the client has assigned an xdg_surface-based role to the surface + * (2) the client has set and committed the xdg_surface state and the + * role-dependent state to the surface + * (3) the client has committed a buffer to the surface + * + * A newly-unmapped surface is considered to have met condition (1) out + * of the 3 required conditions for mapping a surface if its role surface + * has not been destroyed. + * @section page_iface_xdg_surface_api API + * See @ref iface_xdg_surface. + */ +/** + * @defgroup iface_xdg_surface The xdg_surface interface + * + * An interface that may be implemented by a wl_surface, for + * implementations that provide a desktop-style user interface. + * + * It provides a base set of functionality required to construct user + * interface elements requiring management by the compositor, such as + * toplevel windows, menus, etc. The types of functionality are split into + * xdg_surface roles. + * + * Creating an xdg_surface does not set the role for a wl_surface. In order + * to map an xdg_surface, the client must create a role-specific object + * using, e.g., get_toplevel, get_popup. The wl_surface for any given + * xdg_surface can have at most one role, and may not be assigned any role + * not based on xdg_surface. + * + * A role must be assigned before any other requests are made to the + * xdg_surface object. + * + * The client must call wl_surface.commit on the corresponding wl_surface + * for the xdg_surface state to take effect. + * + * Creating an xdg_surface from a wl_surface which has a buffer attached or + * committed is a client error, and any attempts by a client to attach or + * manipulate a buffer prior to the first xdg_surface.configure call must + * also be treated as errors. + * + * Mapping an xdg_surface-based role surface is defined as making it + * possible for the surface to be shown by the compositor. Note that + * a mapped surface is not guaranteed to be visible once it is mapped. + * + * For an xdg_surface to be mapped by the compositor, the following + * conditions must be met: + * (1) the client has assigned an xdg_surface-based role to the surface + * (2) the client has set and committed the xdg_surface state and the + * role-dependent state to the surface + * (3) the client has committed a buffer to the surface + * + * A newly-unmapped surface is considered to have met condition (1) out + * of the 3 required conditions for mapping a surface if its role surface + * has not been destroyed. + */ +extern const struct wl_interface xdg_surface_interface; +/** + * @page page_iface_xdg_toplevel xdg_toplevel + * @section page_iface_xdg_toplevel_desc Description + * + * This interface defines an xdg_surface role which allows a surface to, + * among other things, set window-like properties such as maximize, + * fullscreen, and minimize, set application-specific metadata like title and + * id, and well as trigger user interactive operations such as interactive + * resize and move. + * + * Unmapping an xdg_toplevel means that the surface cannot be shown + * by the compositor until it is explicitly mapped again. + * All active operations (e.g., move, resize) are canceled and all + * attributes (e.g. title, state, stacking, ...) are discarded for + * an xdg_toplevel surface when it is unmapped. + * + * Attaching a null buffer to a toplevel unmaps the surface. + * @section page_iface_xdg_toplevel_api API + * See @ref iface_xdg_toplevel. + */ +/** + * @defgroup iface_xdg_toplevel The xdg_toplevel interface + * + * This interface defines an xdg_surface role which allows a surface to, + * among other things, set window-like properties such as maximize, + * fullscreen, and minimize, set application-specific metadata like title and + * id, and well as trigger user interactive operations such as interactive + * resize and move. + * + * Unmapping an xdg_toplevel means that the surface cannot be shown + * by the compositor until it is explicitly mapped again. + * All active operations (e.g., move, resize) are canceled and all + * attributes (e.g. title, state, stacking, ...) are discarded for + * an xdg_toplevel surface when it is unmapped. + * + * Attaching a null buffer to a toplevel unmaps the surface. + */ +extern const struct wl_interface xdg_toplevel_interface; +/** + * @page page_iface_xdg_popup xdg_popup + * @section page_iface_xdg_popup_desc Description + * + * A popup surface is a short-lived, temporary surface. It can be used to + * implement for example menus, popovers, tooltips and other similar user + * interface concepts. + * + * A popup can be made to take an explicit grab. See xdg_popup.grab for + * details. + * + * When the popup is dismissed, a popup_done event will be sent out, and at + * the same time the surface will be unmapped. See the xdg_popup.popup_done + * event for details. + * + * Explicitly destroying the xdg_popup object will also dismiss the popup and + * unmap the surface. Clients that want to dismiss the popup when another + * surface of their own is clicked should dismiss the popup using the destroy + * request. + * + * A newly created xdg_popup will be stacked on top of all previously created + * xdg_popup surfaces associated with the same xdg_toplevel. + * + * The parent of an xdg_popup must be mapped (see the xdg_surface + * description) before the xdg_popup itself. + * + * The client must call wl_surface.commit on the corresponding wl_surface + * for the xdg_popup state to take effect. + * @section page_iface_xdg_popup_api API + * See @ref iface_xdg_popup. + */ +/** + * @defgroup iface_xdg_popup The xdg_popup interface + * + * A popup surface is a short-lived, temporary surface. It can be used to + * implement for example menus, popovers, tooltips and other similar user + * interface concepts. + * + * A popup can be made to take an explicit grab. See xdg_popup.grab for + * details. + * + * When the popup is dismissed, a popup_done event will be sent out, and at + * the same time the surface will be unmapped. See the xdg_popup.popup_done + * event for details. + * + * Explicitly destroying the xdg_popup object will also dismiss the popup and + * unmap the surface. Clients that want to dismiss the popup when another + * surface of their own is clicked should dismiss the popup using the destroy + * request. + * + * A newly created xdg_popup will be stacked on top of all previously created + * xdg_popup surfaces associated with the same xdg_toplevel. + * + * The parent of an xdg_popup must be mapped (see the xdg_surface + * description) before the xdg_popup itself. + * + * The client must call wl_surface.commit on the corresponding wl_surface + * for the xdg_popup state to take effect. + */ +extern const struct wl_interface xdg_popup_interface; + +#ifndef XDG_WM_BASE_ERROR_ENUM +#define XDG_WM_BASE_ERROR_ENUM +enum xdg_wm_base_error { + /** + * given wl_surface has another role + */ + XDG_WM_BASE_ERROR_ROLE = 0, + /** + * xdg_wm_base was destroyed before children + */ + XDG_WM_BASE_ERROR_DEFUNCT_SURFACES = 1, + /** + * the client tried to map or destroy a non-topmost popup + */ + XDG_WM_BASE_ERROR_NOT_THE_TOPMOST_POPUP = 2, + /** + * the client specified an invalid popup parent surface + */ + XDG_WM_BASE_ERROR_INVALID_POPUP_PARENT = 3, + /** + * the client provided an invalid surface state + */ + XDG_WM_BASE_ERROR_INVALID_SURFACE_STATE = 4, + /** + * the client provided an invalid positioner + */ + XDG_WM_BASE_ERROR_INVALID_POSITIONER = 5, +}; +#endif /* XDG_WM_BASE_ERROR_ENUM */ + +/** + * @ingroup iface_xdg_wm_base + * @struct xdg_wm_base_listener + */ +struct xdg_wm_base_listener { + /** + * check if the client is alive + * + * The ping event asks the client if it's still alive. Pass the + * serial specified in the event back to the compositor by sending + * a "pong" request back with the specified serial. See + * xdg_wm_base.pong. + * + * Compositors can use this to determine if the client is still + * alive. It's unspecified what will happen if the client doesn't + * respond to the ping request, or in what timeframe. Clients + * should try to respond in a reasonable amount of time. + * + * A compositor is free to ping in any way it wants, but a client + * must always respond to any xdg_wm_base object it created. + * @param serial pass this to the pong request + */ + void (*ping)(void *data, + struct xdg_wm_base *xdg_wm_base, + uint32_t serial); +}; + +/** + * @ingroup iface_xdg_wm_base + */ +static inline int +xdg_wm_base_add_listener(struct xdg_wm_base *xdg_wm_base, + const struct xdg_wm_base_listener *listener, void *data) +{ + return wl_proxy_add_listener((struct wl_proxy *) xdg_wm_base, + (void (**)(void)) listener, data); +} + +#define XDG_WM_BASE_DESTROY 0 +#define XDG_WM_BASE_CREATE_POSITIONER 1 +#define XDG_WM_BASE_GET_XDG_SURFACE 2 +#define XDG_WM_BASE_PONG 3 + +/** + * @ingroup iface_xdg_wm_base + */ +#define XDG_WM_BASE_PING_SINCE_VERSION 1 + +/** + * @ingroup iface_xdg_wm_base + */ +#define XDG_WM_BASE_DESTROY_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_wm_base + */ +#define XDG_WM_BASE_CREATE_POSITIONER_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_wm_base + */ +#define XDG_WM_BASE_GET_XDG_SURFACE_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_wm_base + */ +#define XDG_WM_BASE_PONG_SINCE_VERSION 1 + +/** @ingroup iface_xdg_wm_base */ +static inline void +xdg_wm_base_set_user_data(struct xdg_wm_base *xdg_wm_base, void *user_data) +{ + wl_proxy_set_user_data((struct wl_proxy *) xdg_wm_base, user_data); +} + +/** @ingroup iface_xdg_wm_base */ +static inline void * +xdg_wm_base_get_user_data(struct xdg_wm_base *xdg_wm_base) +{ + return wl_proxy_get_user_data((struct wl_proxy *) xdg_wm_base); +} + +static inline uint32_t +xdg_wm_base_get_version(struct xdg_wm_base *xdg_wm_base) +{ + return wl_proxy_get_version((struct wl_proxy *) xdg_wm_base); +} + +/** + * @ingroup iface_xdg_wm_base + * + * Destroy this xdg_wm_base object. + * + * Destroying a bound xdg_wm_base object while there are surfaces + * still alive created by this xdg_wm_base object instance is illegal + * and will result in a protocol error. + */ +static inline void +xdg_wm_base_destroy(struct xdg_wm_base *xdg_wm_base) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_wm_base, + XDG_WM_BASE_DESTROY); + + wl_proxy_destroy((struct wl_proxy *) xdg_wm_base); +} + +/** + * @ingroup iface_xdg_wm_base + * + * Create a positioner object. A positioner object is used to position + * surfaces relative to some parent surface. See the interface description + * and xdg_surface.get_popup for details. + */ +static inline struct xdg_positioner * +xdg_wm_base_create_positioner(struct xdg_wm_base *xdg_wm_base) +{ + struct wl_proxy *id; + + id = wl_proxy_marshal_constructor((struct wl_proxy *) xdg_wm_base, + XDG_WM_BASE_CREATE_POSITIONER, &xdg_positioner_interface, NULL); + + return (struct xdg_positioner *) id; +} + +/** + * @ingroup iface_xdg_wm_base + * + * This creates an xdg_surface for the given surface. While xdg_surface + * itself is not a role, the corresponding surface may only be assigned + * a role extending xdg_surface, such as xdg_toplevel or xdg_popup. + * + * This creates an xdg_surface for the given surface. An xdg_surface is + * used as basis to define a role to a given surface, such as xdg_toplevel + * or xdg_popup. It also manages functionality shared between xdg_surface + * based surface roles. + * + * See the documentation of xdg_surface for more details about what an + * xdg_surface is and how it is used. + */ +static inline struct xdg_surface * +xdg_wm_base_get_xdg_surface(struct xdg_wm_base *xdg_wm_base, struct wl_surface *surface) +{ + struct wl_proxy *id; + + id = wl_proxy_marshal_constructor((struct wl_proxy *) xdg_wm_base, + XDG_WM_BASE_GET_XDG_SURFACE, &xdg_surface_interface, NULL, surface); + + return (struct xdg_surface *) id; +} + +/** + * @ingroup iface_xdg_wm_base + * + * A client must respond to a ping event with a pong request or + * the client may be deemed unresponsive. See xdg_wm_base.ping. + */ +static inline void +xdg_wm_base_pong(struct xdg_wm_base *xdg_wm_base, uint32_t serial) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_wm_base, + XDG_WM_BASE_PONG, serial); +} + +#ifndef XDG_POSITIONER_ERROR_ENUM +#define XDG_POSITIONER_ERROR_ENUM +enum xdg_positioner_error { + /** + * invalid input provided + */ + XDG_POSITIONER_ERROR_INVALID_INPUT = 0, +}; +#endif /* XDG_POSITIONER_ERROR_ENUM */ + +#ifndef XDG_POSITIONER_ANCHOR_ENUM +#define XDG_POSITIONER_ANCHOR_ENUM +enum xdg_positioner_anchor { + XDG_POSITIONER_ANCHOR_NONE = 0, + XDG_POSITIONER_ANCHOR_TOP = 1, + XDG_POSITIONER_ANCHOR_BOTTOM = 2, + XDG_POSITIONER_ANCHOR_LEFT = 3, + XDG_POSITIONER_ANCHOR_RIGHT = 4, + XDG_POSITIONER_ANCHOR_TOP_LEFT = 5, + XDG_POSITIONER_ANCHOR_BOTTOM_LEFT = 6, + XDG_POSITIONER_ANCHOR_TOP_RIGHT = 7, + XDG_POSITIONER_ANCHOR_BOTTOM_RIGHT = 8, +}; +#endif /* XDG_POSITIONER_ANCHOR_ENUM */ + +#ifndef XDG_POSITIONER_GRAVITY_ENUM +#define XDG_POSITIONER_GRAVITY_ENUM +enum xdg_positioner_gravity { + XDG_POSITIONER_GRAVITY_NONE = 0, + XDG_POSITIONER_GRAVITY_TOP = 1, + XDG_POSITIONER_GRAVITY_BOTTOM = 2, + XDG_POSITIONER_GRAVITY_LEFT = 3, + XDG_POSITIONER_GRAVITY_RIGHT = 4, + XDG_POSITIONER_GRAVITY_TOP_LEFT = 5, + XDG_POSITIONER_GRAVITY_BOTTOM_LEFT = 6, + XDG_POSITIONER_GRAVITY_TOP_RIGHT = 7, + XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT = 8, +}; +#endif /* XDG_POSITIONER_GRAVITY_ENUM */ + +#ifndef XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_ENUM +#define XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_ENUM +/** + * @ingroup iface_xdg_positioner + * vertically resize the surface + * + * Resize the surface vertically so that it is completely unconstrained. + */ +enum xdg_positioner_constraint_adjustment { + XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_NONE = 0, + XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_X = 1, + XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_Y = 2, + XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_X = 4, + XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_Y = 8, + XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_X = 16, + XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_Y = 32, +}; +#endif /* XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_ENUM */ + +#define XDG_POSITIONER_DESTROY 0 +#define XDG_POSITIONER_SET_SIZE 1 +#define XDG_POSITIONER_SET_ANCHOR_RECT 2 +#define XDG_POSITIONER_SET_ANCHOR 3 +#define XDG_POSITIONER_SET_GRAVITY 4 +#define XDG_POSITIONER_SET_CONSTRAINT_ADJUSTMENT 5 +#define XDG_POSITIONER_SET_OFFSET 6 +#define XDG_POSITIONER_SET_REACTIVE 7 +#define XDG_POSITIONER_SET_PARENT_SIZE 8 +#define XDG_POSITIONER_SET_PARENT_CONFIGURE 9 + + +/** + * @ingroup iface_xdg_positioner + */ +#define XDG_POSITIONER_DESTROY_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_positioner + */ +#define XDG_POSITIONER_SET_SIZE_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_positioner + */ +#define XDG_POSITIONER_SET_ANCHOR_RECT_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_positioner + */ +#define XDG_POSITIONER_SET_ANCHOR_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_positioner + */ +#define XDG_POSITIONER_SET_GRAVITY_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_positioner + */ +#define XDG_POSITIONER_SET_CONSTRAINT_ADJUSTMENT_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_positioner + */ +#define XDG_POSITIONER_SET_OFFSET_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_positioner + */ +#define XDG_POSITIONER_SET_REACTIVE_SINCE_VERSION 3 +/** + * @ingroup iface_xdg_positioner + */ +#define XDG_POSITIONER_SET_PARENT_SIZE_SINCE_VERSION 3 +/** + * @ingroup iface_xdg_positioner + */ +#define XDG_POSITIONER_SET_PARENT_CONFIGURE_SINCE_VERSION 3 + +/** @ingroup iface_xdg_positioner */ +static inline void +xdg_positioner_set_user_data(struct xdg_positioner *xdg_positioner, void *user_data) +{ + wl_proxy_set_user_data((struct wl_proxy *) xdg_positioner, user_data); +} + +/** @ingroup iface_xdg_positioner */ +static inline void * +xdg_positioner_get_user_data(struct xdg_positioner *xdg_positioner) +{ + return wl_proxy_get_user_data((struct wl_proxy *) xdg_positioner); +} + +static inline uint32_t +xdg_positioner_get_version(struct xdg_positioner *xdg_positioner) +{ + return wl_proxy_get_version((struct wl_proxy *) xdg_positioner); +} + +/** + * @ingroup iface_xdg_positioner + * + * Notify the compositor that the xdg_positioner will no longer be used. + */ +static inline void +xdg_positioner_destroy(struct xdg_positioner *xdg_positioner) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_positioner, + XDG_POSITIONER_DESTROY); + + wl_proxy_destroy((struct wl_proxy *) xdg_positioner); +} + +/** + * @ingroup iface_xdg_positioner + * + * Set the size of the surface that is to be positioned with the positioner + * object. The size is in surface-local coordinates and corresponds to the + * window geometry. See xdg_surface.set_window_geometry. + * + * If a zero or negative size is set the invalid_input error is raised. + */ +static inline void +xdg_positioner_set_size(struct xdg_positioner *xdg_positioner, int32_t width, int32_t height) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_positioner, + XDG_POSITIONER_SET_SIZE, width, height); +} + +/** + * @ingroup iface_xdg_positioner + * + * Specify the anchor rectangle within the parent surface that the child + * surface will be placed relative to. The rectangle is relative to the + * window geometry as defined by xdg_surface.set_window_geometry of the + * parent surface. + * + * When the xdg_positioner object is used to position a child surface, the + * anchor rectangle may not extend outside the window geometry of the + * positioned child's parent surface. + * + * If a negative size is set the invalid_input error is raised. + */ +static inline void +xdg_positioner_set_anchor_rect(struct xdg_positioner *xdg_positioner, int32_t x, int32_t y, int32_t width, int32_t height) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_positioner, + XDG_POSITIONER_SET_ANCHOR_RECT, x, y, width, height); +} + +/** + * @ingroup iface_xdg_positioner + * + * Defines the anchor point for the anchor rectangle. The specified anchor + * is used derive an anchor point that the child surface will be + * positioned relative to. If a corner anchor is set (e.g. 'top_left' or + * 'bottom_right'), the anchor point will be at the specified corner; + * otherwise, the derived anchor point will be centered on the specified + * edge, or in the center of the anchor rectangle if no edge is specified. + */ +static inline void +xdg_positioner_set_anchor(struct xdg_positioner *xdg_positioner, uint32_t anchor) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_positioner, + XDG_POSITIONER_SET_ANCHOR, anchor); +} + +/** + * @ingroup iface_xdg_positioner + * + * Defines in what direction a surface should be positioned, relative to + * the anchor point of the parent surface. If a corner gravity is + * specified (e.g. 'bottom_right' or 'top_left'), then the child surface + * will be placed towards the specified gravity; otherwise, the child + * surface will be centered over the anchor point on any axis that had no + * gravity specified. + */ +static inline void +xdg_positioner_set_gravity(struct xdg_positioner *xdg_positioner, uint32_t gravity) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_positioner, + XDG_POSITIONER_SET_GRAVITY, gravity); +} + +/** + * @ingroup iface_xdg_positioner + * + * Specify how the window should be positioned if the originally intended + * position caused the surface to be constrained, meaning at least + * partially outside positioning boundaries set by the compositor. The + * adjustment is set by constructing a bitmask describing the adjustment to + * be made when the surface is constrained on that axis. + * + * If no bit for one axis is set, the compositor will assume that the child + * surface should not change its position on that axis when constrained. + * + * If more than one bit for one axis is set, the order of how adjustments + * are applied is specified in the corresponding adjustment descriptions. + * + * The default adjustment is none. + */ +static inline void +xdg_positioner_set_constraint_adjustment(struct xdg_positioner *xdg_positioner, uint32_t constraint_adjustment) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_positioner, + XDG_POSITIONER_SET_CONSTRAINT_ADJUSTMENT, constraint_adjustment); +} + +/** + * @ingroup iface_xdg_positioner + * + * Specify the surface position offset relative to the position of the + * anchor on the anchor rectangle and the anchor on the surface. For + * example if the anchor of the anchor rectangle is at (x, y), the surface + * has the gravity bottom|right, and the offset is (ox, oy), the calculated + * surface position will be (x + ox, y + oy). The offset position of the + * surface is the one used for constraint testing. See + * set_constraint_adjustment. + * + * An example use case is placing a popup menu on top of a user interface + * element, while aligning the user interface element of the parent surface + * with some user interface element placed somewhere in the popup surface. + */ +static inline void +xdg_positioner_set_offset(struct xdg_positioner *xdg_positioner, int32_t x, int32_t y) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_positioner, + XDG_POSITIONER_SET_OFFSET, x, y); +} + +/** + * @ingroup iface_xdg_positioner + * + * When set reactive, the surface is reconstrained if the conditions used + * for constraining changed, e.g. the parent window moved. + * + * If the conditions changed and the popup was reconstrained, an + * xdg_popup.configure event is sent with updated geometry, followed by an + * xdg_surface.configure event. + */ +static inline void +xdg_positioner_set_reactive(struct xdg_positioner *xdg_positioner) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_positioner, + XDG_POSITIONER_SET_REACTIVE); +} + +/** + * @ingroup iface_xdg_positioner + * + * Set the parent window geometry the compositor should use when + * positioning the popup. The compositor may use this information to + * determine the future state the popup should be constrained using. If + * this doesn't match the dimension of the parent the popup is eventually + * positioned against, the behavior is undefined. + * + * The arguments are given in the surface-local coordinate space. + */ +static inline void +xdg_positioner_set_parent_size(struct xdg_positioner *xdg_positioner, int32_t parent_width, int32_t parent_height) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_positioner, + XDG_POSITIONER_SET_PARENT_SIZE, parent_width, parent_height); +} + +/** + * @ingroup iface_xdg_positioner + * + * Set the serial of a xdg_surface.configure event this positioner will be + * used in response to. The compositor may use this information together + * with set_parent_size to determine what future state the popup should be + * constrained using. + */ +static inline void +xdg_positioner_set_parent_configure(struct xdg_positioner *xdg_positioner, uint32_t serial) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_positioner, + XDG_POSITIONER_SET_PARENT_CONFIGURE, serial); +} + +#ifndef XDG_SURFACE_ERROR_ENUM +#define XDG_SURFACE_ERROR_ENUM +enum xdg_surface_error { + XDG_SURFACE_ERROR_NOT_CONSTRUCTED = 1, + XDG_SURFACE_ERROR_ALREADY_CONSTRUCTED = 2, + XDG_SURFACE_ERROR_UNCONFIGURED_BUFFER = 3, +}; +#endif /* XDG_SURFACE_ERROR_ENUM */ + +/** + * @ingroup iface_xdg_surface + * @struct xdg_surface_listener + */ +struct xdg_surface_listener { + /** + * suggest a surface change + * + * The configure event marks the end of a configure sequence. A + * configure sequence is a set of one or more events configuring + * the state of the xdg_surface, including the final + * xdg_surface.configure event. + * + * Where applicable, xdg_surface surface roles will during a + * configure sequence extend this event as a latched state sent as + * events before the xdg_surface.configure event. Such events + * should be considered to make up a set of atomically applied + * configuration states, where the xdg_surface.configure commits + * the accumulated state. + * + * Clients should arrange their surface for the new states, and + * then send an ack_configure request with the serial sent in this + * configure event at some point before committing the new surface. + * + * If the client receives multiple configure events before it can + * respond to one, it is free to discard all but the last event it + * received. + * @param serial serial of the configure event + */ + void (*configure)(void *data, + struct xdg_surface *xdg_surface, + uint32_t serial); +}; + +/** + * @ingroup iface_xdg_surface + */ +static inline int +xdg_surface_add_listener(struct xdg_surface *xdg_surface, + const struct xdg_surface_listener *listener, void *data) +{ + return wl_proxy_add_listener((struct wl_proxy *) xdg_surface, + (void (**)(void)) listener, data); +} + +#define XDG_SURFACE_DESTROY 0 +#define XDG_SURFACE_GET_TOPLEVEL 1 +#define XDG_SURFACE_GET_POPUP 2 +#define XDG_SURFACE_SET_WINDOW_GEOMETRY 3 +#define XDG_SURFACE_ACK_CONFIGURE 4 + +/** + * @ingroup iface_xdg_surface + */ +#define XDG_SURFACE_CONFIGURE_SINCE_VERSION 1 + +/** + * @ingroup iface_xdg_surface + */ +#define XDG_SURFACE_DESTROY_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_surface + */ +#define XDG_SURFACE_GET_TOPLEVEL_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_surface + */ +#define XDG_SURFACE_GET_POPUP_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_surface + */ +#define XDG_SURFACE_SET_WINDOW_GEOMETRY_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_surface + */ +#define XDG_SURFACE_ACK_CONFIGURE_SINCE_VERSION 1 + +/** @ingroup iface_xdg_surface */ +static inline void +xdg_surface_set_user_data(struct xdg_surface *xdg_surface, void *user_data) +{ + wl_proxy_set_user_data((struct wl_proxy *) xdg_surface, user_data); +} + +/** @ingroup iface_xdg_surface */ +static inline void * +xdg_surface_get_user_data(struct xdg_surface *xdg_surface) +{ + return wl_proxy_get_user_data((struct wl_proxy *) xdg_surface); +} + +static inline uint32_t +xdg_surface_get_version(struct xdg_surface *xdg_surface) +{ + return wl_proxy_get_version((struct wl_proxy *) xdg_surface); +} + +/** + * @ingroup iface_xdg_surface + * + * Destroy the xdg_surface object. An xdg_surface must only be destroyed + * after its role object has been destroyed. + */ +static inline void +xdg_surface_destroy(struct xdg_surface *xdg_surface) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_surface, + XDG_SURFACE_DESTROY); + + wl_proxy_destroy((struct wl_proxy *) xdg_surface); +} + +/** + * @ingroup iface_xdg_surface + * + * This creates an xdg_toplevel object for the given xdg_surface and gives + * the associated wl_surface the xdg_toplevel role. + * + * See the documentation of xdg_toplevel for more details about what an + * xdg_toplevel is and how it is used. + */ +static inline struct xdg_toplevel * +xdg_surface_get_toplevel(struct xdg_surface *xdg_surface) +{ + struct wl_proxy *id; + + id = wl_proxy_marshal_constructor((struct wl_proxy *) xdg_surface, + XDG_SURFACE_GET_TOPLEVEL, &xdg_toplevel_interface, NULL); + + return (struct xdg_toplevel *) id; +} + +/** + * @ingroup iface_xdg_surface + * + * This creates an xdg_popup object for the given xdg_surface and gives + * the associated wl_surface the xdg_popup role. + * + * If null is passed as a parent, a parent surface must be specified using + * some other protocol, before committing the initial state. + * + * See the documentation of xdg_popup for more details about what an + * xdg_popup is and how it is used. + */ +static inline struct xdg_popup * +xdg_surface_get_popup(struct xdg_surface *xdg_surface, struct xdg_surface *parent, struct xdg_positioner *positioner) +{ + struct wl_proxy *id; + + id = wl_proxy_marshal_constructor((struct wl_proxy *) xdg_surface, + XDG_SURFACE_GET_POPUP, &xdg_popup_interface, NULL, parent, positioner); + + return (struct xdg_popup *) id; +} + +/** + * @ingroup iface_xdg_surface + * + * The window geometry of a surface is its "visible bounds" from the + * user's perspective. Client-side decorations often have invisible + * portions like drop-shadows which should be ignored for the + * purposes of aligning, placing and constraining windows. + * + * The window geometry is double buffered, and will be applied at the + * time wl_surface.commit of the corresponding wl_surface is called. + * + * When maintaining a position, the compositor should treat the (x, y) + * coordinate of the window geometry as the top left corner of the window. + * A client changing the (x, y) window geometry coordinate should in + * general not alter the position of the window. + * + * Once the window geometry of the surface is set, it is not possible to + * unset it, and it will remain the same until set_window_geometry is + * called again, even if a new subsurface or buffer is attached. + * + * If never set, the value is the full bounds of the surface, + * including any subsurfaces. This updates dynamically on every + * commit. This unset is meant for extremely simple clients. + * + * The arguments are given in the surface-local coordinate space of + * the wl_surface associated with this xdg_surface. + * + * The width and height must be greater than zero. Setting an invalid size + * will raise an error. When applied, the effective window geometry will be + * the set window geometry clamped to the bounding rectangle of the + * combined geometry of the surface of the xdg_surface and the associated + * subsurfaces. + */ +static inline void +xdg_surface_set_window_geometry(struct xdg_surface *xdg_surface, int32_t x, int32_t y, int32_t width, int32_t height) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_surface, + XDG_SURFACE_SET_WINDOW_GEOMETRY, x, y, width, height); +} + +/** + * @ingroup iface_xdg_surface + * + * When a configure event is received, if a client commits the + * surface in response to the configure event, then the client + * must make an ack_configure request sometime before the commit + * request, passing along the serial of the configure event. + * + * For instance, for toplevel surfaces the compositor might use this + * information to move a surface to the top left only when the client has + * drawn itself for the maximized or fullscreen state. + * + * If the client receives multiple configure events before it + * can respond to one, it only has to ack the last configure event. + * + * A client is not required to commit immediately after sending + * an ack_configure request - it may even ack_configure several times + * before its next surface commit. + * + * A client may send multiple ack_configure requests before committing, but + * only the last request sent before a commit indicates which configure + * event the client really is responding to. + */ +static inline void +xdg_surface_ack_configure(struct xdg_surface *xdg_surface, uint32_t serial) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_surface, + XDG_SURFACE_ACK_CONFIGURE, serial); +} + +#ifndef XDG_TOPLEVEL_RESIZE_EDGE_ENUM +#define XDG_TOPLEVEL_RESIZE_EDGE_ENUM +/** + * @ingroup iface_xdg_toplevel + * edge values for resizing + * + * These values are used to indicate which edge of a surface + * is being dragged in a resize operation. + */ +enum xdg_toplevel_resize_edge { + XDG_TOPLEVEL_RESIZE_EDGE_NONE = 0, + XDG_TOPLEVEL_RESIZE_EDGE_TOP = 1, + XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM = 2, + XDG_TOPLEVEL_RESIZE_EDGE_LEFT = 4, + XDG_TOPLEVEL_RESIZE_EDGE_TOP_LEFT = 5, + XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_LEFT = 6, + XDG_TOPLEVEL_RESIZE_EDGE_RIGHT = 8, + XDG_TOPLEVEL_RESIZE_EDGE_TOP_RIGHT = 9, + XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_RIGHT = 10, +}; +#endif /* XDG_TOPLEVEL_RESIZE_EDGE_ENUM */ + +#ifndef XDG_TOPLEVEL_STATE_ENUM +#define XDG_TOPLEVEL_STATE_ENUM +/** + * @ingroup iface_xdg_toplevel + * the surface is tiled + * + * The window is currently in a tiled layout and the bottom edge is + * considered to be adjacent to another part of the tiling grid. + */ +enum xdg_toplevel_state { + /** + * the surface is maximized + */ + XDG_TOPLEVEL_STATE_MAXIMIZED = 1, + /** + * the surface is fullscreen + */ + XDG_TOPLEVEL_STATE_FULLSCREEN = 2, + /** + * the surface is being resized + */ + XDG_TOPLEVEL_STATE_RESIZING = 3, + /** + * the surface is now activated + */ + XDG_TOPLEVEL_STATE_ACTIVATED = 4, + /** + * @since 2 + */ + XDG_TOPLEVEL_STATE_TILED_LEFT = 5, + /** + * @since 2 + */ + XDG_TOPLEVEL_STATE_TILED_RIGHT = 6, + /** + * @since 2 + */ + XDG_TOPLEVEL_STATE_TILED_TOP = 7, + /** + * @since 2 + */ + XDG_TOPLEVEL_STATE_TILED_BOTTOM = 8, +}; +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_STATE_TILED_LEFT_SINCE_VERSION 2 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_STATE_TILED_RIGHT_SINCE_VERSION 2 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_STATE_TILED_TOP_SINCE_VERSION 2 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_STATE_TILED_BOTTOM_SINCE_VERSION 2 +#endif /* XDG_TOPLEVEL_STATE_ENUM */ + +/** + * @ingroup iface_xdg_toplevel + * @struct xdg_toplevel_listener + */ +struct xdg_toplevel_listener { + /** + * suggest a surface change + * + * This configure event asks the client to resize its toplevel + * surface or to change its state. The configured state should not + * be applied immediately. See xdg_surface.configure for details. + * + * The width and height arguments specify a hint to the window + * about how its surface should be resized in window geometry + * coordinates. See set_window_geometry. + * + * If the width or height arguments are zero, it means the client + * should decide its own window dimension. This may happen when the + * compositor needs to configure the state of the surface but + * doesn't have any information about any previous or expected + * dimension. + * + * The states listed in the event specify how the width/height + * arguments should be interpreted, and possibly how it should be + * drawn. + * + * Clients must send an ack_configure in response to this event. + * See xdg_surface.configure and xdg_surface.ack_configure for + * details. + */ + void (*configure)(void *data, + struct xdg_toplevel *xdg_toplevel, + int32_t width, + int32_t height, + struct wl_array *states); + /** + * surface wants to be closed + * + * The close event is sent by the compositor when the user wants + * the surface to be closed. This should be equivalent to the user + * clicking the close button in client-side decorations, if your + * application has any. + * + * This is only a request that the user intends to close the + * window. The client may choose to ignore this request, or show a + * dialog to ask the user to save their data, etc. + */ + void (*close)(void *data, + struct xdg_toplevel *xdg_toplevel); +}; + +/** + * @ingroup iface_xdg_toplevel + */ +static inline int +xdg_toplevel_add_listener(struct xdg_toplevel *xdg_toplevel, + const struct xdg_toplevel_listener *listener, void *data) +{ + return wl_proxy_add_listener((struct wl_proxy *) xdg_toplevel, + (void (**)(void)) listener, data); +} + +#define XDG_TOPLEVEL_DESTROY 0 +#define XDG_TOPLEVEL_SET_PARENT 1 +#define XDG_TOPLEVEL_SET_TITLE 2 +#define XDG_TOPLEVEL_SET_APP_ID 3 +#define XDG_TOPLEVEL_SHOW_WINDOW_MENU 4 +#define XDG_TOPLEVEL_MOVE 5 +#define XDG_TOPLEVEL_RESIZE 6 +#define XDG_TOPLEVEL_SET_MAX_SIZE 7 +#define XDG_TOPLEVEL_SET_MIN_SIZE 8 +#define XDG_TOPLEVEL_SET_MAXIMIZED 9 +#define XDG_TOPLEVEL_UNSET_MAXIMIZED 10 +#define XDG_TOPLEVEL_SET_FULLSCREEN 11 +#define XDG_TOPLEVEL_UNSET_FULLSCREEN 12 +#define XDG_TOPLEVEL_SET_MINIMIZED 13 + +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_CONFIGURE_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_CLOSE_SINCE_VERSION 1 + +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_DESTROY_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_SET_PARENT_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_SET_TITLE_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_SET_APP_ID_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_SHOW_WINDOW_MENU_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_MOVE_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_RESIZE_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_SET_MAX_SIZE_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_SET_MIN_SIZE_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_SET_MAXIMIZED_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_UNSET_MAXIMIZED_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_SET_FULLSCREEN_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_UNSET_FULLSCREEN_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_toplevel + */ +#define XDG_TOPLEVEL_SET_MINIMIZED_SINCE_VERSION 1 + +/** @ingroup iface_xdg_toplevel */ +static inline void +xdg_toplevel_set_user_data(struct xdg_toplevel *xdg_toplevel, void *user_data) +{ + wl_proxy_set_user_data((struct wl_proxy *) xdg_toplevel, user_data); +} + +/** @ingroup iface_xdg_toplevel */ +static inline void * +xdg_toplevel_get_user_data(struct xdg_toplevel *xdg_toplevel) +{ + return wl_proxy_get_user_data((struct wl_proxy *) xdg_toplevel); +} + +static inline uint32_t +xdg_toplevel_get_version(struct xdg_toplevel *xdg_toplevel) +{ + return wl_proxy_get_version((struct wl_proxy *) xdg_toplevel); +} + +/** + * @ingroup iface_xdg_toplevel + * + * This request destroys the role surface and unmaps the surface; + * see "Unmapping" behavior in interface section for details. + */ +static inline void +xdg_toplevel_destroy(struct xdg_toplevel *xdg_toplevel) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_DESTROY); + + wl_proxy_destroy((struct wl_proxy *) xdg_toplevel); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Set the "parent" of this surface. This surface should be stacked + * above the parent surface and all other ancestor surfaces. + * + * Parent windows should be set on dialogs, toolboxes, or other + * "auxiliary" surfaces, so that the parent is raised when the dialog + * is raised. + * + * Setting a null parent for a child window removes any parent-child + * relationship for the child. Setting a null parent for a window which + * currently has no parent is a no-op. + * + * If the parent is unmapped then its children are managed as + * though the parent of the now-unmapped parent has become the + * parent of this surface. If no parent exists for the now-unmapped + * parent then the children are managed as though they have no + * parent surface. + */ +static inline void +xdg_toplevel_set_parent(struct xdg_toplevel *xdg_toplevel, struct xdg_toplevel *parent) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_SET_PARENT, parent); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Set a short title for the surface. + * + * This string may be used to identify the surface in a task bar, + * window list, or other user interface elements provided by the + * compositor. + * + * The string must be encoded in UTF-8. + */ +static inline void +xdg_toplevel_set_title(struct xdg_toplevel *xdg_toplevel, const char *title) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_SET_TITLE, title); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Set an application identifier for the surface. + * + * The app ID identifies the general class of applications to which + * the surface belongs. The compositor can use this to group multiple + * surfaces together, or to determine how to launch a new application. + * + * For D-Bus activatable applications, the app ID is used as the D-Bus + * service name. + * + * The compositor shell will try to group application surfaces together + * by their app ID. As a best practice, it is suggested to select app + * ID's that match the basename of the application's .desktop file. + * For example, "org.freedesktop.FooViewer" where the .desktop file is + * "org.freedesktop.FooViewer.desktop". + * + * Like other properties, a set_app_id request can be sent after the + * xdg_toplevel has been mapped to update the property. + * + * See the desktop-entry specification [0] for more details on + * application identifiers and how they relate to well-known D-Bus + * names and .desktop files. + * + * [0] http://standards.freedesktop.org/desktop-entry-spec/ + */ +static inline void +xdg_toplevel_set_app_id(struct xdg_toplevel *xdg_toplevel, const char *app_id) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_SET_APP_ID, app_id); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Clients implementing client-side decorations might want to show + * a context menu when right-clicking on the decorations, giving the + * user a menu that they can use to maximize or minimize the window. + * + * This request asks the compositor to pop up such a window menu at + * the given position, relative to the local surface coordinates of + * the parent surface. There are no guarantees as to what menu items + * the window menu contains. + * + * This request must be used in response to some sort of user action + * like a button press, key press, or touch down event. + */ +static inline void +xdg_toplevel_show_window_menu(struct xdg_toplevel *xdg_toplevel, struct wl_seat *seat, uint32_t serial, int32_t x, int32_t y) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_SHOW_WINDOW_MENU, seat, serial, x, y); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Start an interactive, user-driven move of the surface. + * + * This request must be used in response to some sort of user action + * like a button press, key press, or touch down event. The passed + * serial is used to determine the type of interactive move (touch, + * pointer, etc). + * + * The server may ignore move requests depending on the state of + * the surface (e.g. fullscreen or maximized), or if the passed serial + * is no longer valid. + * + * If triggered, the surface will lose the focus of the device + * (wl_pointer, wl_touch, etc) used for the move. It is up to the + * compositor to visually indicate that the move is taking place, such as + * updating a pointer cursor, during the move. There is no guarantee + * that the device focus will return when the move is completed. + */ +static inline void +xdg_toplevel_move(struct xdg_toplevel *xdg_toplevel, struct wl_seat *seat, uint32_t serial) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_MOVE, seat, serial); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Start a user-driven, interactive resize of the surface. + * + * This request must be used in response to some sort of user action + * like a button press, key press, or touch down event. The passed + * serial is used to determine the type of interactive resize (touch, + * pointer, etc). + * + * The server may ignore resize requests depending on the state of + * the surface (e.g. fullscreen or maximized). + * + * If triggered, the client will receive configure events with the + * "resize" state enum value and the expected sizes. See the "resize" + * enum value for more details about what is required. The client + * must also acknowledge configure events using "ack_configure". After + * the resize is completed, the client will receive another "configure" + * event without the resize state. + * + * If triggered, the surface also will lose the focus of the device + * (wl_pointer, wl_touch, etc) used for the resize. It is up to the + * compositor to visually indicate that the resize is taking place, + * such as updating a pointer cursor, during the resize. There is no + * guarantee that the device focus will return when the resize is + * completed. + * + * The edges parameter specifies how the surface should be resized, + * and is one of the values of the resize_edge enum. The compositor + * may use this information to update the surface position for + * example when dragging the top left corner. The compositor may also + * use this information to adapt its behavior, e.g. choose an + * appropriate cursor image. + */ +static inline void +xdg_toplevel_resize(struct xdg_toplevel *xdg_toplevel, struct wl_seat *seat, uint32_t serial, uint32_t edges) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_RESIZE, seat, serial, edges); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Set a maximum size for the window. + * + * The client can specify a maximum size so that the compositor does + * not try to configure the window beyond this size. + * + * The width and height arguments are in window geometry coordinates. + * See xdg_surface.set_window_geometry. + * + * Values set in this way are double-buffered. They will get applied + * on the next commit. + * + * The compositor can use this information to allow or disallow + * different states like maximize or fullscreen and draw accurate + * animations. + * + * Similarly, a tiling window manager may use this information to + * place and resize client windows in a more effective way. + * + * The client should not rely on the compositor to obey the maximum + * size. The compositor may decide to ignore the values set by the + * client and request a larger size. + * + * If never set, or a value of zero in the request, means that the + * client has no expected maximum size in the given dimension. + * As a result, a client wishing to reset the maximum size + * to an unspecified state can use zero for width and height in the + * request. + * + * Requesting a maximum size to be smaller than the minimum size of + * a surface is illegal and will result in a protocol error. + * + * The width and height must be greater than or equal to zero. Using + * strictly negative values for width and height will result in a + * protocol error. + */ +static inline void +xdg_toplevel_set_max_size(struct xdg_toplevel *xdg_toplevel, int32_t width, int32_t height) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_SET_MAX_SIZE, width, height); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Set a minimum size for the window. + * + * The client can specify a minimum size so that the compositor does + * not try to configure the window below this size. + * + * The width and height arguments are in window geometry coordinates. + * See xdg_surface.set_window_geometry. + * + * Values set in this way are double-buffered. They will get applied + * on the next commit. + * + * The compositor can use this information to allow or disallow + * different states like maximize or fullscreen and draw accurate + * animations. + * + * Similarly, a tiling window manager may use this information to + * place and resize client windows in a more effective way. + * + * The client should not rely on the compositor to obey the minimum + * size. The compositor may decide to ignore the values set by the + * client and request a smaller size. + * + * If never set, or a value of zero in the request, means that the + * client has no expected minimum size in the given dimension. + * As a result, a client wishing to reset the minimum size + * to an unspecified state can use zero for width and height in the + * request. + * + * Requesting a minimum size to be larger than the maximum size of + * a surface is illegal and will result in a protocol error. + * + * The width and height must be greater than or equal to zero. Using + * strictly negative values for width and height will result in a + * protocol error. + */ +static inline void +xdg_toplevel_set_min_size(struct xdg_toplevel *xdg_toplevel, int32_t width, int32_t height) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_SET_MIN_SIZE, width, height); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Maximize the surface. + * + * After requesting that the surface should be maximized, the compositor + * will respond by emitting a configure event. Whether this configure + * actually sets the window maximized is subject to compositor policies. + * The client must then update its content, drawing in the configured + * state. The client must also acknowledge the configure when committing + * the new content (see ack_configure). + * + * It is up to the compositor to decide how and where to maximize the + * surface, for example which output and what region of the screen should + * be used. + * + * If the surface was already maximized, the compositor will still emit + * a configure event with the "maximized" state. + * + * If the surface is in a fullscreen state, this request has no direct + * effect. It may alter the state the surface is returned to when + * unmaximized unless overridden by the compositor. + */ +static inline void +xdg_toplevel_set_maximized(struct xdg_toplevel *xdg_toplevel) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_SET_MAXIMIZED); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Unmaximize the surface. + * + * After requesting that the surface should be unmaximized, the compositor + * will respond by emitting a configure event. Whether this actually + * un-maximizes the window is subject to compositor policies. + * If available and applicable, the compositor will include the window + * geometry dimensions the window had prior to being maximized in the + * configure event. The client must then update its content, drawing it in + * the configured state. The client must also acknowledge the configure + * when committing the new content (see ack_configure). + * + * It is up to the compositor to position the surface after it was + * unmaximized; usually the position the surface had before maximizing, if + * applicable. + * + * If the surface was already not maximized, the compositor will still + * emit a configure event without the "maximized" state. + * + * If the surface is in a fullscreen state, this request has no direct + * effect. It may alter the state the surface is returned to when + * unmaximized unless overridden by the compositor. + */ +static inline void +xdg_toplevel_unset_maximized(struct xdg_toplevel *xdg_toplevel) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_UNSET_MAXIMIZED); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Make the surface fullscreen. + * + * After requesting that the surface should be fullscreened, the + * compositor will respond by emitting a configure event. Whether the + * client is actually put into a fullscreen state is subject to compositor + * policies. The client must also acknowledge the configure when + * committing the new content (see ack_configure). + * + * The output passed by the request indicates the client's preference as + * to which display it should be set fullscreen on. If this value is NULL, + * it's up to the compositor to choose which display will be used to map + * this surface. + * + * If the surface doesn't cover the whole output, the compositor will + * position the surface in the center of the output and compensate with + * with border fill covering the rest of the output. The content of the + * border fill is undefined, but should be assumed to be in some way that + * attempts to blend into the surrounding area (e.g. solid black). + * + * If the fullscreened surface is not opaque, the compositor must make + * sure that other screen content not part of the same surface tree (made + * up of subsurfaces, popups or similarly coupled surfaces) are not + * visible below the fullscreened surface. + */ +static inline void +xdg_toplevel_set_fullscreen(struct xdg_toplevel *xdg_toplevel, struct wl_output *output) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_SET_FULLSCREEN, output); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Make the surface no longer fullscreen. + * + * After requesting that the surface should be unfullscreened, the + * compositor will respond by emitting a configure event. + * Whether this actually removes the fullscreen state of the client is + * subject to compositor policies. + * + * Making a surface unfullscreen sets states for the surface based on the following: + * * the state(s) it may have had before becoming fullscreen + * * any state(s) decided by the compositor + * * any state(s) requested by the client while the surface was fullscreen + * + * The compositor may include the previous window geometry dimensions in + * the configure event, if applicable. + * + * The client must also acknowledge the configure when committing the new + * content (see ack_configure). + */ +static inline void +xdg_toplevel_unset_fullscreen(struct xdg_toplevel *xdg_toplevel) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_UNSET_FULLSCREEN); +} + +/** + * @ingroup iface_xdg_toplevel + * + * Request that the compositor minimize your surface. There is no + * way to know if the surface is currently minimized, nor is there + * any way to unset minimization on this surface. + * + * If you are looking to throttle redrawing when minimized, please + * instead use the wl_surface.frame event for this, as this will + * also work with live previews on windows in Alt-Tab, Expose or + * similar compositor features. + */ +static inline void +xdg_toplevel_set_minimized(struct xdg_toplevel *xdg_toplevel) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_toplevel, + XDG_TOPLEVEL_SET_MINIMIZED); +} + +#ifndef XDG_POPUP_ERROR_ENUM +#define XDG_POPUP_ERROR_ENUM +enum xdg_popup_error { + /** + * tried to grab after being mapped + */ + XDG_POPUP_ERROR_INVALID_GRAB = 0, +}; +#endif /* XDG_POPUP_ERROR_ENUM */ + +/** + * @ingroup iface_xdg_popup + * @struct xdg_popup_listener + */ +struct xdg_popup_listener { + /** + * configure the popup surface + * + * This event asks the popup surface to configure itself given + * the configuration. The configured state should not be applied + * immediately. See xdg_surface.configure for details. + * + * The x and y arguments represent the position the popup was + * placed at given the xdg_positioner rule, relative to the upper + * left corner of the window geometry of the parent surface. + * + * For version 2 or older, the configure event for an xdg_popup is + * only ever sent once for the initial configuration. Starting with + * version 3, it may be sent again if the popup is setup with an + * xdg_positioner with set_reactive requested, or in response to + * xdg_popup.reposition requests. + * @param x x position relative to parent surface window geometry + * @param y y position relative to parent surface window geometry + * @param width window geometry width + * @param height window geometry height + */ + void (*configure)(void *data, + struct xdg_popup *xdg_popup, + int32_t x, + int32_t y, + int32_t width, + int32_t height); + /** + * popup interaction is done + * + * The popup_done event is sent out when a popup is dismissed by + * the compositor. The client should destroy the xdg_popup object + * at this point. + */ + void (*popup_done)(void *data, + struct xdg_popup *xdg_popup); + /** + * signal the completion of a repositioned request + * + * The repositioned event is sent as part of a popup + * configuration sequence, together with xdg_popup.configure and + * lastly xdg_surface.configure to notify the completion of a + * reposition request. + * + * The repositioned event is to notify about the completion of a + * xdg_popup.reposition request. The token argument is the token + * passed in the xdg_popup.reposition request. + * + * Immediately after this event is emitted, xdg_popup.configure and + * xdg_surface.configure will be sent with the updated size and + * position, as well as a new configure serial. + * + * The client should optionally update the content of the popup, + * but must acknowledge the new popup configuration for the new + * position to take effect. See xdg_surface.ack_configure for + * details. + * @param token reposition request token + * @since 3 + */ + void (*repositioned)(void *data, + struct xdg_popup *xdg_popup, + uint32_t token); +}; + +/** + * @ingroup iface_xdg_popup + */ +static inline int +xdg_popup_add_listener(struct xdg_popup *xdg_popup, + const struct xdg_popup_listener *listener, void *data) +{ + return wl_proxy_add_listener((struct wl_proxy *) xdg_popup, + (void (**)(void)) listener, data); +} + +#define XDG_POPUP_DESTROY 0 +#define XDG_POPUP_GRAB 1 +#define XDG_POPUP_REPOSITION 2 + +/** + * @ingroup iface_xdg_popup + */ +#define XDG_POPUP_CONFIGURE_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_popup + */ +#define XDG_POPUP_POPUP_DONE_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_popup + */ +#define XDG_POPUP_REPOSITIONED_SINCE_VERSION 3 + +/** + * @ingroup iface_xdg_popup + */ +#define XDG_POPUP_DESTROY_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_popup + */ +#define XDG_POPUP_GRAB_SINCE_VERSION 1 +/** + * @ingroup iface_xdg_popup + */ +#define XDG_POPUP_REPOSITION_SINCE_VERSION 3 + +/** @ingroup iface_xdg_popup */ +static inline void +xdg_popup_set_user_data(struct xdg_popup *xdg_popup, void *user_data) +{ + wl_proxy_set_user_data((struct wl_proxy *) xdg_popup, user_data); +} + +/** @ingroup iface_xdg_popup */ +static inline void * +xdg_popup_get_user_data(struct xdg_popup *xdg_popup) +{ + return wl_proxy_get_user_data((struct wl_proxy *) xdg_popup); +} + +static inline uint32_t +xdg_popup_get_version(struct xdg_popup *xdg_popup) +{ + return wl_proxy_get_version((struct wl_proxy *) xdg_popup); +} + +/** + * @ingroup iface_xdg_popup + * + * This destroys the popup. Explicitly destroying the xdg_popup + * object will also dismiss the popup, and unmap the surface. + * + * If this xdg_popup is not the "topmost" popup, a protocol error + * will be sent. + */ +static inline void +xdg_popup_destroy(struct xdg_popup *xdg_popup) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_popup, + XDG_POPUP_DESTROY); + + wl_proxy_destroy((struct wl_proxy *) xdg_popup); +} + +/** + * @ingroup iface_xdg_popup + * + * This request makes the created popup take an explicit grab. An explicit + * grab will be dismissed when the user dismisses the popup, or when the + * client destroys the xdg_popup. This can be done by the user clicking + * outside the surface, using the keyboard, or even locking the screen + * through closing the lid or a timeout. + * + * If the compositor denies the grab, the popup will be immediately + * dismissed. + * + * This request must be used in response to some sort of user action like a + * button press, key press, or touch down event. The serial number of the + * event should be passed as 'serial'. + * + * The parent of a grabbing popup must either be an xdg_toplevel surface or + * another xdg_popup with an explicit grab. If the parent is another + * xdg_popup it means that the popups are nested, with this popup now being + * the topmost popup. + * + * Nested popups must be destroyed in the reverse order they were created + * in, e.g. the only popup you are allowed to destroy at all times is the + * topmost one. + * + * When compositors choose to dismiss a popup, they may dismiss every + * nested grabbing popup as well. When a compositor dismisses popups, it + * will follow the same dismissing order as required from the client. + * + * The parent of a grabbing popup must either be another xdg_popup with an + * active explicit grab, or an xdg_popup or xdg_toplevel, if there are no + * explicit grabs already taken. + * + * If the topmost grabbing popup is destroyed, the grab will be returned to + * the parent of the popup, if that parent previously had an explicit grab. + * + * If the parent is a grabbing popup which has already been dismissed, this + * popup will be immediately dismissed. If the parent is a popup that did + * not take an explicit grab, an error will be raised. + * + * During a popup grab, the client owning the grab will receive pointer + * and touch events for all their surfaces as normal (similar to an + * "owner-events" grab in X11 parlance), while the top most grabbing popup + * will always have keyboard focus. + */ +static inline void +xdg_popup_grab(struct xdg_popup *xdg_popup, struct wl_seat *seat, uint32_t serial) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_popup, + XDG_POPUP_GRAB, seat, serial); +} + +/** + * @ingroup iface_xdg_popup + * + * Reposition an already-mapped popup. The popup will be placed given the + * details in the passed xdg_positioner object, and a + * xdg_popup.repositioned followed by xdg_popup.configure and + * xdg_surface.configure will be emitted in response. Any parameters set + * by the previous positioner will be discarded. + * + * The passed token will be sent in the corresponding + * xdg_popup.repositioned event. The new popup position will not take + * effect until the corresponding configure event is acknowledged by the + * client. See xdg_popup.repositioned for details. The token itself is + * opaque, and has no other special meaning. + * + * If multiple reposition requests are sent, the compositor may skip all + * but the last one. + * + * If the popup is repositioned in response to a configure event for its + * parent, the client should send an xdg_positioner.set_parent_configure + * and possibly a xdg_positioner.set_parent_size request to allow the + * compositor to properly constrain the popup. + * + * If the popup is repositioned together with a parent that is being + * resized, but not in response to a configure event, the client should + * send a xdg_positioner.set_parent_size request. + */ +static inline void +xdg_popup_reposition(struct xdg_popup *xdg_popup, struct xdg_positioner *positioner, uint32_t token) +{ + wl_proxy_marshal((struct wl_proxy *) xdg_popup, + XDG_POPUP_REPOSITION, positioner, token); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/CMakeLists.txt b/CMakeLists.txt index bb74e1e..e1dcb8a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,23 +8,33 @@ if(WIN32) set(ATTO_SRC ${CMAKE_CURRENT_SOURCE_DIR}/src/app_windows.c) elseif(CMAKE_SYSTEM_NAME MATCHES ".*Linux") - find_package(X11 REQUIRED) - set(ATTO_LIBS - ${X11_LIBRARIES} - ${X11_Xext_LIB} - ${X11_Xfixes_LIB} - m) + # find_package(X11 REQUIRED) + # set(ATTO_LIBS + # ${X11_LIBRARIES} + # ${X11_Xext_LIB} + # ${X11_Xfixes_LIB} + # m) + # set(ATTO_SRC + # ${CMAKE_CURRENT_SOURCE_DIR}/src/app_linux.c + # # ${CMAKE_CURRENT_SOURCE_DIR}/src/app_x11.c) + # ${CMAKE_CURRENT_SOURCE_DIR}/src/app_wayland.c) set(ATTO_SRC - ${CMAKE_CURRENT_SOURCE_DIR}/src/app_linux.c - ${CMAKE_CURRENT_SOURCE_DIR}/src/app_x11.c) + ${CMAKE_CURRENT_SOURCE_DIR}/src/app_linux.c + # # ${CMAKE_CURRENT_SOURCE_DIR}/src/app_x11.c) + ${CMAKE_CURRENT_SOURCE_DIR}/src/app_wayland.c + ${CMAKE_CURRENT_SOURCE_DIR}/src/app_vulkan.c + ${CMAKE_CURRENT_SOURCE_DIR}/3p/wl-xdg-proto.c + ) else() message(FATAL_ERROR "Not ported") endif() add_library(atto STATIC ${ATTO_SRC}) target_include_directories(atto PUBLIC include) +target_include_directories(atto PRIVATE 3p) target_link_libraries(atto - PUBLIC OpenGL::GL + #PUBLIC OpenGL::GL + PUBLIC wayland-client vulkan PRIVATE ${ATTO_LIBS}) set_target_properties(atto PROPERTIES C_STANDARD 99 diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 1f1c091..1fa9ff1 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -10,15 +10,33 @@ function(add_example EXAMPLE_NAME) project(${EXAMPLE_NAME}) add_executable(${EXAMPLE_NAME} ${ATTO_EXE_SUBSYSTEM} ${CMAKE_CURRENT_SOURCE_DIR}/${EXAMPLE_NAME}.c) - target_link_libraries(${EXAMPLE_NAME} atto) + target_link_libraries(${EXAMPLE_NAME} atto m) set_target_properties(${EXAMPLE_NAME} PROPERTIES C_STANDARD 99 C_STANDARD_REQUIRED TRUE C_EXTENSIONS OFF) endfunction() -add_example(app) -add_example(cube) -add_example(fb) -add_example(tri) -add_example(tribench) +# add_example(app) +# add_example(cube) +# add_example(fb) +# add_example(tri) +# add_example(tribench) +add_example(vk_tri) + +function(add_shaders) + cmake_parse_arguments(PARSE_ARGV 0 SHADERS "" "TARGET" "FILES") + foreach(SHADER ${SHADERS_FILES}) + add_custom_command( + OUTPUT ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}${SHADER}.spv + COMMAND glslc + ${CMAKE_SOURCE_DIR}/examples/${SHADER} -o ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}${SHADER}.spv + MAIN_DEPENDENCY ${CMAKE_SOURCE_DIR}/examples/${SHADER} + COMMENT "Building ${SHADER}" + ) + list(APPEND SHADERS_DEPS "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}${SHADER}.spv") + endforeach() + add_custom_target(${SHADERS_TARGET} ALL DEPENDS ${SHADERS_DEPS}) +endfunction() + +add_shaders(TARGET vk_tri_shaders FILES shader.frag shader.vert) diff --git a/examples/shader.frag b/examples/shader.frag new file mode 100644 index 0000000..4118056 --- /dev/null +++ b/examples/shader.frag @@ -0,0 +1,10 @@ +#version 450 +// WHY? +#extension GL_ARB_separate_shader_objects : enable + +layout(location = 0) in vec3 fragColor; +layout(location = 0) out vec4 outColor; + +void main() { + outColor = vec4(fragColor, 1.0); +} diff --git a/examples/shader.vert b/examples/shader.vert new file mode 100644 index 0000000..15c828e --- /dev/null +++ b/examples/shader.vert @@ -0,0 +1,18 @@ +#version 450 + +layout(location=0) in vec2 aPos; +layout(location=1) in vec2 aColorRG; +layout(location=2) in float aColorB; + +layout(push_constant) uniform G { + float t; +}; + +layout(location = 0) out vec3 fragColor; + +#define rm(a) mat2(cos(a),sin(a),-sin(a),cos(a)) + +void main() { + gl_Position = vec4(vec2(600./800., 1.) * (rm(t)*aPos), 0.0, 1.0); + fragColor = vec3(aColorRG, aColorB); +} diff --git a/examples/vk_tri.c b/examples/vk_tri.c new file mode 100644 index 0000000..c4b3d6b --- /dev/null +++ b/examples/vk_tri.c @@ -0,0 +1,354 @@ +#include "atto/app.h" +#include "atto/worobushek.h" + +#include +#include +#include + +struct Vertex { + float x, y; + uint8_t r, g, b; +}; + +static struct { + VkFence fence; + VkSemaphore done; + VkRenderPass render_pass; + + VkPipelineLayout pipeline_layout; + VkShaderModule module_vertex; + VkShaderModule module_fragment; + + VkImageView *image_views; + VkFramebuffer *framebuffers; + VkPipeline pipeline; + + VkDeviceMemory devmem; + VkBuffer vertex_buf; + + VkCommandPool cmdpool; + VkCommandBuffer cmdbuf; +} g; + +static void createRenderPass() { + VkAttachmentDescription attachment = {0}; + attachment.format = VK_FORMAT_B8G8R8A8_SRGB;// FIXME too early a_vk.swapchain.info.imageFormat; + attachment.samples = VK_SAMPLE_COUNT_1_BIT; + //attachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + //attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + + VkAttachmentReference color_attachment = {0}; + color_attachment.attachment = 0; + color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + VkSubpassDescription subdesc = {0}; + subdesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subdesc.colorAttachmentCount = 1; + subdesc.pColorAttachments = &color_attachment; + + VkRenderPassCreateInfo rpci = {0}; + rpci.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + rpci.attachmentCount = 1; + rpci.pAttachments = &attachment; + rpci.subpassCount = 1; + rpci.pSubpasses = &subdesc; + AVK_CHECK_RESULT(vkCreateRenderPass(a_vk.dev, &rpci, NULL, &g.render_pass)); +} + +static void createShaders() { + VkPushConstantRange push_const = {0}; + push_const.offset = 0; + push_const.size = sizeof(float); + push_const.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + + VkPipelineLayoutCreateInfo plci = {0}; + plci.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + plci.setLayoutCount = 0; + plci.pushConstantRangeCount = 1; + plci.pPushConstantRanges = &push_const; + AVK_CHECK_RESULT(vkCreatePipelineLayout(a_vk.dev, &plci, NULL, &g.pipeline_layout)); + + g.module_vertex = loadShaderFromFile("shader.vert.spv"); + g.module_fragment = loadShaderFromFile("shader.frag.spv"); +} + +static const struct Vertex vertices[] = { + {1.f, 0.f, 255, 0, 0}, + {-.5f, .866f, 255, 255, 0}, + {-.5f, -.866f, 255, 0, 255}, +}; + +static void createBuffer() { + VkBufferCreateInfo bci = {0}; + bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + bci.size = sizeof(vertices); + bci.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; + bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + AVK_CHECK_RESULT(vkCreateBuffer(a_vk.dev, &bci, NULL, &g.vertex_buf)); + + VkMemoryRequirements memreq; + vkGetBufferMemoryRequirements(a_vk.dev, g.vertex_buf, &memreq); + aAppDebugPrintf("memreq: memoryTypeBits=0x%x alignment=%zu size=%zu", memreq.memoryTypeBits, memreq.alignment, memreq.size); + + VkMemoryAllocateInfo mai={0}; + mai.allocationSize = memreq.size; + mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mai.memoryTypeIndex = aVkFindMemoryWithType(memreq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + AVK_CHECK_RESULT(vkAllocateMemory(a_vk.dev, &mai, NULL, &g.devmem)); + AVK_CHECK_RESULT(vkBindBufferMemory(a_vk.dev, g.vertex_buf, g.devmem, 0)); + + void *ptr = NULL; + AVK_CHECK_RESULT(vkMapMemory(a_vk.dev, g.devmem, 0, bci.size, 0, &ptr)); + memcpy(ptr, vertices, sizeof(vertices)); + vkUnmapMemory(a_vk.dev, g.devmem); +} + +static void createCommandPool() { + VkCommandPoolCreateInfo cpci = {0}; + cpci.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + cpci.queueFamilyIndex = 0; + cpci.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + AVK_CHECK_RESULT(vkCreateCommandPool(a_vk.dev, &cpci, NULL, &g.cmdpool)); + + VkCommandBufferAllocateInfo cbai = {0}; + cbai.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + cbai.commandBufferCount = 1; + cbai.commandPool = g.cmdpool; + cbai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + AVK_CHECK_RESULT(vkAllocateCommandBuffers(a_vk.dev, &cbai, &g.cmdbuf)); +} + +static void createPipeline() { + VkPipelineShaderStageCreateInfo shader_stages[2] = {0}; + shader_stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shader_stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + + shader_stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + shader_stages[0].module = g.module_vertex; + shader_stages[0].pName = "main"; + + shader_stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + shader_stages[1].module = g.module_fragment; + shader_stages[1].pName = "main"; + + VkVertexInputBindingDescription vibd = {0}; + vibd.binding = 0; + vibd.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; + vibd.stride = sizeof(struct Vertex); + + VkVertexInputAttributeDescription attribs[] = { + {.binding = 0, .location = 0, .format = VK_FORMAT_R32G32_SFLOAT, .offset = offsetof(struct Vertex, x)}, + {.binding = 0, .location = 1, .format = VK_FORMAT_R8G8_UNORM, .offset = offsetof(struct Vertex, r)}, + {.binding = 0, .location = 2, .format = VK_FORMAT_R8_UNORM, .offset = offsetof(struct Vertex, b)}, + }; + + VkPipelineVertexInputStateCreateInfo vertex_input = {0}; + vertex_input.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertex_input.vertexBindingDescriptionCount = 1; + vertex_input.pVertexBindingDescriptions = &vibd; + vertex_input.vertexAttributeDescriptionCount = COUNTOF(attribs); + vertex_input.pVertexAttributeDescriptions = attribs; + + VkPipelineInputAssemblyStateCreateInfo input_assembly = {0}; + input_assembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + + VkViewport viewport = { + .x = 0, .y = 0, + .width = a_app_state->width, .height = a_app_state->height, + .minDepth = 0.f, .maxDepth = 1.f + }; + VkRect2D scissor = { + .offset = {0}, + .extent = {a_app_state->width, a_app_state->height} + }; + VkPipelineViewportStateCreateInfo viewport_state = {0}; + viewport_state.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport_state.viewportCount = 1; + viewport_state.scissorCount = 1; + viewport_state.pViewports = &viewport; + viewport_state.pScissors = &scissor; + + VkPipelineRasterizationStateCreateInfo raster_state = {0}; + raster_state.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + raster_state.polygonMode = VK_POLYGON_MODE_FILL; + raster_state.cullMode = VK_CULL_MODE_NONE; + raster_state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + raster_state.lineWidth = 1.f; + + VkPipelineMultisampleStateCreateInfo multi_state = {0}; + multi_state.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multi_state.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + VkPipelineColorBlendAttachmentState blend_attachment = {0}; + blend_attachment.blendEnable = VK_FALSE; + blend_attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + + VkPipelineColorBlendStateCreateInfo color_blend = {0}; + color_blend.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + color_blend.attachmentCount = 1; + color_blend.pAttachments = &blend_attachment; + + VkGraphicsPipelineCreateInfo gpci = {0}; + gpci.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + gpci.stageCount = COUNTOF(shader_stages); + gpci.pStages = shader_stages; + gpci.pVertexInputState = &vertex_input; + gpci.pInputAssemblyState = &input_assembly; + gpci.pViewportState = &viewport_state; + gpci.pRasterizationState = &raster_state; + gpci.pMultisampleState = &multi_state; + gpci.pColorBlendState = &color_blend; + gpci.layout = g.pipeline_layout; + gpci.renderPass = g.render_pass; + gpci.subpass = 0; + AVK_CHECK_RESULT(vkCreateGraphicsPipelines(a_vk.dev, NULL, 1, &gpci, NULL, &g.pipeline)); +} + +static void swapchainWillDestroy() { + vkDestroyPipeline(a_vk.dev, g.pipeline, NULL); + for (uint32_t i = 0; i < a_vk.swapchain.num_images; ++i) { + vkDestroyFramebuffer(a_vk.dev, g.framebuffers[i], NULL); + vkDestroyImageView(a_vk.dev, g.image_views[i], NULL); + } +} + +static void swapchainCreated() { + const uint32_t num_images = a_vk.swapchain.num_images; + g.image_views = malloc(num_images * sizeof(VkImageView)); + g.framebuffers = malloc(num_images * sizeof(VkFramebuffer)); + for (uint32_t i = 0; i < num_images; ++i) { + VkImageViewCreateInfo ivci = {}; + ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + ivci.viewType = VK_IMAGE_VIEW_TYPE_2D; + ivci.format = a_vk.swapchain.info.imageFormat; + ivci.image = a_vk.swapchain.images[i]; + ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + ivci.subresourceRange.levelCount = 1; + ivci.subresourceRange.layerCount = 1; + AVK_CHECK_RESULT(vkCreateImageView(a_vk.dev, &ivci, NULL, g.image_views + i)); + + VkFramebufferCreateInfo fbci = {}; + fbci.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + fbci.renderPass = g.render_pass; + fbci.attachmentCount = 1; + fbci.pAttachments = g.image_views + i; + fbci.width = a_app_state->width; + fbci.height = a_app_state->height; + fbci.layers = 1; + AVK_CHECK_RESULT(vkCreateFramebuffer(a_vk.dev, &fbci, NULL, g.framebuffers + i)); + } + + createPipeline(); +} + +static void paint(ATimeUs timestamp, float dt) { + const float t = timestamp / 1e6; + + VkCommandBufferBeginInfo beginfo = {}; + beginfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + beginfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + AVK_CHECK_RESULT(vkBeginCommandBuffer(g.cmdbuf, &beginfo)); + + VkClearValue clear_value = {}; + clear_value.color.float32[0] = .5f + .5f * sinf(t); + clear_value.color.float32[1] = .5f + .5f * sinf(t*3); + clear_value.color.float32[2] = .5f + .5f * sinf(t*5); + clear_value.color.float32[3] = 1.f; + /* clear_value.color.uint32[0] = 0xffffffff; */ + /* clear_value.color.uint32[3] = 0xffffffff; */ + VkRenderPassBeginInfo rpbi = {}; + rpbi.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + rpbi.renderPass = g.render_pass; + rpbi.framebuffer = g.framebuffers[a_vk.swapchain.current_frame_image_index]; + rpbi.renderArea.offset.x = rpbi.renderArea.offset.y = 0; + rpbi.renderArea.extent.width = a_app_state->width; + rpbi.renderArea.extent.height = a_app_state->height; + rpbi.clearValueCount = 1; + rpbi.pClearValues = &clear_value; + vkCmdBeginRenderPass(g.cmdbuf, &rpbi, VK_SUBPASS_CONTENTS_INLINE); + + vkCmdBindPipeline(g.cmdbuf, VK_PIPELINE_BIND_POINT_GRAPHICS, g.pipeline); + + VkDeviceSize offset = {0}; + vkCmdBindVertexBuffers(g.cmdbuf, 0, 1, &g.vertex_buf, &offset); + vkCmdPushConstants(g.cmdbuf, g.pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(float), &t); + vkCmdDraw(g.cmdbuf, 3, 1, 0, 0); + /* const int N = 32; */ + /* for (int i = 0; i < N; ++i) { */ + /* const float it = i / (float)N; */ + /* const float tt = t*(.8+it*.2) + it * ((1. + sin(t*.3))*.15 + .7) * 20.; */ + /* vkCmdPushConstants(cmdbuf, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(float), &tt); */ + /* vkCmdDraw(cmdbuf, 3, 1, 0, 0); */ + /* } */ + vkCmdEndRenderPass(g.cmdbuf); + + AVK_CHECK_RESULT(vkEndCommandBuffer(g.cmdbuf)); + + VkPipelineStageFlags stageflags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkSubmitInfo subinfo = {0}; + subinfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + subinfo.pNext = NULL; + subinfo.commandBufferCount = 1; + subinfo.pCommandBuffers = &g.cmdbuf; + subinfo.waitSemaphoreCount = 1; + subinfo.pWaitSemaphores = &a_vk.swapchain.image_available; + subinfo.signalSemaphoreCount = 1; + subinfo.pSignalSemaphores = &g.done, + subinfo.pWaitDstStageMask = &stageflags; + AVK_CHECK_RESULT(vkQueueSubmit(a_vk.main_queue, 1, &subinfo, g.fence)); + + VkPresentInfoKHR presinfo = {0}; + presinfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + presinfo.pSwapchains = &a_vk.swapchain.handle; + presinfo.pImageIndices = &a_vk.swapchain.current_frame_image_index; + presinfo.swapchainCount = 1; + presinfo.pWaitSemaphores = &g.done; + presinfo.waitSemaphoreCount = 1; + AVK_CHECK_RESULT(vkQueuePresentKHR(a_vk.main_queue, &presinfo)); + + // FIXME bad sync + AVK_CHECK_RESULT(vkWaitForFences(a_vk.dev, 1, &g.fence, VK_TRUE, INT64_MAX)); + AVK_CHECK_RESULT(vkResetFences(a_vk.dev, 1, &g.fence)); +} + +static void close() { + vkFreeCommandBuffers(a_vk.dev, g.cmdpool, 1, &g.cmdbuf); + vkDestroyCommandPool(a_vk.dev, g.cmdpool, NULL); + + vkDestroyPipelineLayout(a_vk.dev, g.pipeline_layout, NULL); + + vkDestroyShaderModule(a_vk.dev, g.module_fragment, NULL); + vkDestroyShaderModule(a_vk.dev, g.module_vertex, NULL); + + vkFreeMemory(a_vk.dev, g.devmem, NULL); + vkDestroyBuffer(a_vk.dev, g.vertex_buf, NULL); + + vkDestroyRenderPass(a_vk.dev, g.render_pass, NULL); + aVkDestroySemaphore(g.done); + vkDestroyFence(a_vk.dev, g.fence, NULL); +} + +void attoAppInit(struct AAppProctable *proctable) { + proctable->paint = paint; + proctable->swapchain_created = swapchainCreated; + proctable->swapchain_will_destroy = swapchainWillDestroy; + proctable->close = close; + + g.done = aVkCreateSemaphore(); + createRenderPass(); + createShaders(); + createBuffer(); + createCommandPool(); + + VkFenceCreateInfo fci = {0}; + fci.flags = 0; + fci.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + AVK_CHECK_RESULT(vkCreateFence(a_vk.dev, &fci, NULL, &g.fence)); +} diff --git a/include/atto/app.h b/include/atto/app.h index ae31f7a..232819c 100644 --- a/include/atto/app.h +++ b/include/atto/app.h @@ -18,6 +18,9 @@ void aAppDebugPrintf(const char *fmt, ...) PRINTF_ARGS(1, 2); /* Immediately terminate current process */ void aAppTerminate(int code); +/* Gracefully close the app */ +void aAppClose(); + #define ATTO_ASSERT(cond) \ if (!(cond)) { \ aAppDebugPrintf("ERROR @ %s:%d: (%s) failed", __FILE__, __LINE__, #cond); \ @@ -122,12 +125,12 @@ typedef enum { AB_WheelDown = 1 << 4 } AButton; -typedef enum { AOGLV_21, AOGLV_ES_20 } AOpenGLVersion; +typedef enum { AOGLV_21, AOGLV_ES_20, AOVK10 } AGraphicsVersion; struct AAppState { int argc; const char *const *argv; - AOpenGLVersion gl_version; + AGraphicsVersion graphics_version; unsigned int width, height; int keys[AK_Max]; struct { @@ -142,12 +145,52 @@ void aAppGrabInput(int grab); extern const struct AAppState *a_app_state; +// struct AVkPaintArgs { +// ATimeUs pts; +// float dt; +// uint32_t image_index; +// VkSemaphore image_ready; +// uint32_t out_num_semaphores; +// VkSemaphore *out_semaphores; +// } + struct AAppProctable { - void (*resize)(ATimeUs ts, unsigned int old_width, unsigned int old_height); + // FIXME #ifndef ATTO_VK + //void (*resize)(ATimeUs ts, unsigned int old_width, unsigned int old_height); void (*paint)(ATimeUs ts, float dt); void (*key)(ATimeUs ts, AKey key, int down); void (*pointer)(ATimeUs ts, int dx, int dy, unsigned int buttons_changed_bits); void (*close)(); + +// FIXME #idfef ATTO_VK + void (*swapchain_will_destroy)(); + void (*swapchain_created)(); + //void (*paint_vk)(); +}; + +/* + * 1. Instance extensions (at compile time) + * 2. (atto) main(...) + * 3. (atto) VkInstance init + * 4. (atto) enum vk devices (? I: hide in atto, II: give to app) + * 5. attoAppInit: - procs, - handle args, - picks device? dev extensions? + * 6. (atto) creates window, surface, ... + * 7. app->resize(w,h, dev, surface) + * app creates swapchain using helper funcs + * app creates framebuffers, ... + * 8. (atto) paint( +*/ + + +struct AVkAppProctable { + + + + // void (*swapDestroy)(); + // void (*swapCreate)(); // ~= resize + void (*paint)(); + /// + void (*close)(); }; #ifndef ATTO_APP_INIT_FUNC diff --git a/include/atto/worobushek.h b/include/atto/worobushek.h new file mode 100644 index 0000000..fff675e --- /dev/null +++ b/include/atto/worobushek.h @@ -0,0 +1,53 @@ +#pragma once + +// FIXME atto platform +#define VK_USE_PLATFORM_WAYLAND_KHR +#include + +#define COUNTOF(a) (sizeof(a)/sizeof(*(a))) + +#define AVK_VERSION(v) \ + VK_VERSION_MAJOR(v), \ + VK_VERSION_MINOR(v), \ + VK_VERSION_PATCH(v) + +#define AVK_CHECK_RESULT(res) { \ + const VkResult result = res; \ + if (result != VK_SUCCESS) { \ + aAppDebugPrintf("VK ERROR @ %s:%d: %s failed with result %d", __FILE__, __LINE__, #res, result); \ + aAppTerminate(-1); \ + } \ +} + +#define MAX_SWAPCHAIN_IMAGES 8 + +struct AVkSwapchain { + VkSwapchainCreateInfoKHR info; + VkSwapchainKHR handle; + uint32_t num_images; + VkImage images[MAX_SWAPCHAIN_IMAGES]; + uint32_t current_frame_image_index; + VkSemaphore image_available; +}; + +struct AVkState { + VkInstance inst; + VkSurfaceKHR surf; + + VkPhysicalDevice phys_dev; + VkPhysicalDeviceMemoryProperties mem_props; + //VkSurfaceCapabilitiesKHR surf_caps; + VkDevice dev; + + VkQueue main_queue; + + struct AVkSwapchain swapchain; +}; + +extern struct AVkState a_vk; + +VkSemaphore aVkCreateSemaphore(); +void aVkDestroySemaphore(VkSemaphore sema); + +VkShaderModule loadShaderFromFile(const char *filename); +uint32_t aVkFindMemoryWithType(uint32_t type_index_bits, VkMemoryPropertyFlags flags); diff --git a/src/app_vulkan.c b/src/app_vulkan.c new file mode 100644 index 0000000..ebc8bbd --- /dev/null +++ b/src/app_vulkan.c @@ -0,0 +1,236 @@ +#include "atto/worobushek.h" +#include "atto/app.h" + +#include +#include + +static const char *instance_exts[] = { + VK_KHR_SURFACE_EXTENSION_NAME, + VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME +}; + +struct AVkState a_vk; + +void a_vkInitInstance() { + uint32_t version = 0; + AVK_CHECK_RESULT(vkEnumerateInstanceVersion(&version)); + aAppDebugPrintf("InstanceVersion: %u.%u.%u", AVK_VERSION(version)); + + VkApplicationInfo ai; + ai.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; + ai.pNext = NULL; + ai.apiVersion = VK_MAKE_VERSION(1, 0, 0); + ai.applicationVersion = 0; + ai.engineVersion = 0; + ai.pApplicationName = "LOL"; + ai.pEngineName = "KEK"; + + VkInstanceCreateInfo vici; + vici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + vici.pNext = NULL; + vici.enabledLayerCount = 0; + vici.flags = 0; + vici.ppEnabledLayerNames = NULL; + vici.enabledExtensionCount = COUNTOF(instance_exts); + vici.ppEnabledExtensionNames = instance_exts; + vici.pApplicationInfo = &ai; + + AVK_CHECK_RESULT(vkCreateInstance(&vici, NULL, &a_vk.inst)); +} + +void a_vkInitDevice() { + // Get only the first device + uint32_t num_devices = 1; + vkEnumeratePhysicalDevices(a_vk.inst, &num_devices, &a_vk.phys_dev); + + uint32_t queue_index = UINT32_MAX; + VkPhysicalDeviceProperties pd; + vkGetPhysicalDeviceProperties(a_vk.phys_dev, &pd); + +#define MAX_QUEUE_FAMILIES 8 + uint32_t num_queue_families = MAX_QUEUE_FAMILIES; + VkQueueFamilyProperties queue_families[MAX_QUEUE_FAMILIES]; + vkGetPhysicalDeviceQueueFamilyProperties(a_vk.phys_dev, &num_queue_families, queue_families); + + for (uint32_t i = 0; i < num_queue_families; ++i) { + if (!(queue_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) + continue; + + VkBool32 present = 0; + vkGetPhysicalDeviceSurfaceSupportKHR(a_vk.phys_dev, i, a_vk.surf, &present); + + if (!present) + continue; + + queue_index = i; + break; + } + + ATTO_ASSERT(queue_index < num_queue_families); + + vkGetPhysicalDeviceMemoryProperties(a_vk.phys_dev, &a_vk.mem_props); + + float prio = 1.f; + VkDeviceQueueCreateInfo queue_info = { + .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, + .pNext = NULL, + .flags = 0, + .queueFamilyIndex = queue_index, + .queueCount = 1, + .pQueuePriorities = &prio, + }; + + const char* devex[] = { + VK_KHR_SWAPCHAIN_EXTENSION_NAME + }; + VkDeviceCreateInfo create_info = { + .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, + .pNext = NULL, + .flags = 0, + .queueCreateInfoCount = 1, + .pQueueCreateInfos = &queue_info, + .enabledLayerCount = 0, + .ppEnabledLayerNames = NULL, + .enabledExtensionCount = COUNTOF(devex), + .ppEnabledExtensionNames = devex, + .pEnabledFeatures = NULL + }; + + AVK_CHECK_RESULT(vkCreateDevice(a_vk.phys_dev, &create_info, NULL, &a_vk.dev)); + + vkGetDeviceQueue(a_vk.dev, 0, 0, &a_vk.main_queue); + + a_vk.swapchain.image_available = aVkCreateSemaphore(); +} + +void a_vkCreateSwapchain(int w, int h) { + struct AVkSwapchain* sw = &a_vk.swapchain; + sw->info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + sw->info.pNext = NULL; + sw->info.surface = a_vk.surf; + sw->info.minImageCount = 5; // TODO get from caps + sw->info.imageFormat = VK_FORMAT_B8G8R8A8_SRGB; // TODO get from caps + sw->info.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; // TODO get from caps + sw->info.imageExtent.width = w; + sw->info.imageExtent.height = h; + sw->info.imageArrayLayers = 1; + sw->info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + sw->info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; + sw->info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; // TODO get from caps + sw->info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + sw->info.presentMode = VK_PRESENT_MODE_FIFO_KHR; // TODO caps, MAILBOX is better + //sw->info.presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; // TODO caps, MAILBOX is better + sw->info.clipped = VK_TRUE; + + AVK_CHECK_RESULT(vkCreateSwapchainKHR(a_vk.dev, &sw->info, NULL, &sw->handle)); + + sw->num_images = 0; + AVK_CHECK_RESULT(vkGetSwapchainImagesKHR(a_vk.dev, sw->handle, &sw->num_images, NULL)); + + sw->num_images = sw->num_images > MAX_SWAPCHAIN_IMAGES ? MAX_SWAPCHAIN_IMAGES : sw->num_images; + AVK_CHECK_RESULT(vkGetSwapchainImagesKHR(a_vk.dev, sw->handle, &sw->num_images, sw->images)); +} + +void a_vkDestroySwapchain() { + vkDestroySwapchainKHR(a_vk.dev, a_vk.swapchain.handle, NULL); + a_vk.swapchain.handle = NULL; +} + +void a_vkInitWithWayland(struct wl_display *disp, struct wl_surface *surf) { + a_vkInitInstance(); + + VkWaylandSurfaceCreateInfoKHR wsci = {0}; + wsci.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR; + wsci.surface = surf; + wsci.display = disp; + AVK_CHECK_RESULT(vkCreateWaylandSurfaceKHR(a_vk.inst, &wsci, NULL, &a_vk.surf)); + + a_vkInitDevice(); + +#define MAX_PRESENT_MODES 8 + uint32_t num_present_modes = MAX_PRESENT_MODES; + VkPresentModeKHR present_modes[MAX_PRESENT_MODES]; + vkGetPhysicalDeviceSurfacePresentModesKHR(a_vk.phys_dev, a_vk.surf, &num_present_modes, present_modes); + // TODO use the best mode +} + +void a_vkDestroy() { + vkDestroySurfaceKHR(a_vk.inst, a_vk.surf, NULL); + aVkDestroySemaphore(a_vk.swapchain.image_available); + vkDestroyDevice(a_vk.dev, NULL); + vkDestroyInstance(a_vk.inst, NULL); +} + +void a_vkPaint(struct AAppProctable *ptbl, ATimeUs t, float dt) { + AVK_CHECK_RESULT(vkAcquireNextImageKHR(a_vk.dev, a_vk.swapchain.handle, UINT64_MAX, a_vk.swapchain.image_available, NULL, &a_vk.swapchain.current_frame_image_index)); + + ptbl->paint(t, dt); + + /* VkPresentInfoKHR presinfo = {0}; */ + /* presinfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; */ + /* presinfo.pSwapchains = &a_vk.swapchain.handle; */ + /* presinfo.pImageIndices = &a_vk.swapchain.current_frame_image_index; */ + /* presinfo.swapchainCount = 1; */ + /* presinfo.pWaitSemaphores = &semaDone; */ + /* presinfo.waitSemaphoreCount = 1; */ + /* AVK_CHECK_RESULT(vkQueuePresentKHR(a_vk.main_queue, &presinfo)); */ +} + +VkSemaphore aVkCreateSemaphore() { + VkSemaphore sema; + VkSemaphoreCreateInfo sci = {0}; + sci.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + sci.flags = 0; + AVK_CHECK_RESULT(vkCreateSemaphore(a_vk.dev, &sci, NULL, &sema)); + return sema; +} + +void aVkDestroySemaphore(VkSemaphore sema) { + vkDestroySemaphore(a_vk.dev, sema, NULL); +} + +VkShaderModule loadShaderFromFile(const char *filename) { + FILE *f = fopen(filename, "rb"); + if (!f) { + perror(filename); + exit(1); + } + fseek(f, 0, SEEK_END); + const size_t size = ftell(f); + if (size % 4 != 0) { + aAppDebugPrintf("size %zu is not aligned to 4 bytes as required by SPIR-V/Vulkan spec", size); + } + + fseek(f, 0, SEEK_SET); + uint32_t *buf = malloc(4 * ((size+3)/4)); + if (size != fread(buf, 1, size, f)) { + fprintf(stderr, "Cannot read the entire file %s\n", filename); + exit(1); + } + + VkShaderModuleCreateInfo smci = {0}; + smci.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + smci.codeSize = size; + smci.pCode = buf; + VkShaderModule shader; + const VkResult res = vkCreateShaderModule(a_vk.dev, &smci, NULL, &shader); + if (VK_SUCCESS != res) { \ + aAppDebugPrintf("%s:%d: failed w/ %d\n", __FILE__, __LINE__, res); \ + exit(1); + } + fclose(f); + free(buf); + return shader; +} + +uint32_t aVkFindMemoryWithType(uint32_t type_index_bits, VkMemoryPropertyFlags flags) { + for (uint32_t i = 0; i < a_vk.mem_props.memoryTypeCount; ++i) { + if (!(type_index_bits & (1 << i))) + continue; + + if ((a_vk.mem_props.memoryTypes[i].propertyFlags & flags) == flags) + return i; + } + + return UINT32_MAX; +} diff --git a/src/app_wayland.c b/src/app_wayland.c new file mode 100644 index 0000000..7b4eec9 --- /dev/null +++ b/src/app_wayland.c @@ -0,0 +1,136 @@ +#ifndef ATTO_APP_WIDTH + #define ATTO_APP_WIDTH 1280 +#endif + +#ifndef ATTO_APP_HEIGHT + #define ATTO_APP_HEIGHT 720 +#endif + +#ifndef ATTO_APP_NAME + #define ATTO_APP_NAME "atto app" +#endif + +#include "atto/platform.h" +#include "atto/app.h" +#include "wl-xdg-proto.h" +#include +#include +#include /* exit() */ + +// FIXME declare this somewhere properly +void a_vkInitWithWayland(struct wl_display *disp, struct wl_surface *surf); +void a_vkCreateSwapchain(int w, int h); +void a_vkPaint(struct AAppProctable *ptbl, ATimeUs t, float dt); +void a_vkDestroy(); +void a_vkDestroySwapchain(); + +static struct AAppState a__app_state; +const struct AAppState *a_app_state = &a__app_state; +static struct AAppProctable a__app_proctable; + +void aAppTerminate(int code) { + exit(code); +} + +static int running = 1; +void aAppClose() { + running = 0; +} + +static struct { + struct wl_display *disp; + struct wl_compositor *comp; + struct xdg_wm_base *xdg_wm; +} a__wl = {0}; + +static void reg_global(void *data, struct wl_registry *reg, uint32_t name, const char *interface, uint32_t version) { + //printf("%s: %s name=%u ver=%u\n", __FUNCTION__, interface, name, version); + if (strcmp(interface, wl_compositor_interface.name) == 0) { + a__wl.comp = wl_registry_bind(reg, name, &wl_compositor_interface, 1); + } else + if (strcmp(interface, xdg_wm_base_interface.name) == 0) { + a__wl.xdg_wm = wl_registry_bind(reg, name, &xdg_wm_base_interface, 1); + } +} + +static void reg_global_remove(void *data, struct wl_registry *reg, uint32_t name) { + //printf("%s: name=%u\n", __FUNCTION__, name); +} + +static struct wl_registry_listener reg_listen = { + .global = reg_global, + .global_remove = reg_global_remove, +}; + +static void xsurf_configure(void *data, + struct xdg_surface *xdg_surface, + uint32_t serial) { + xdg_surface_ack_configure(xdg_surface, serial); + wl_surface_commit(data); +} + +static struct xdg_surface_listener xsurf_listener = { + .configure = xsurf_configure +}; + +static void noop() {} +static void xtop_close(void *data, + struct xdg_toplevel *xdg_toplevel) { + //printf("%s\n", __FUNCTION__); + *(int*)data = 0; +} + +static struct xdg_toplevel_listener xtop_listener = { + .configure = noop, + .close = xtop_close +}; + +int main(int argc, char *argv[]) { + ATimeUs timestamp = aAppTime(); + + ATTO_ASSERT(a__wl.disp = wl_display_connect(NULL)); + + struct wl_registry *reg = wl_display_get_registry(a__wl.disp); + wl_registry_add_listener(reg, ®_listen, NULL); + wl_display_roundtrip(a__wl.disp); + + struct wl_surface *surf = wl_compositor_create_surface(a__wl.comp); + struct xdg_surface *xsurf = xdg_wm_base_get_xdg_surface(a__wl.xdg_wm, surf); + struct xdg_toplevel *xtop = xdg_surface_get_toplevel(xsurf); + xdg_surface_add_listener(xsurf, &xsurf_listener, surf); + xdg_toplevel_add_listener(xtop, &xtop_listener, &running); + + wl_surface_commit(surf); + wl_display_roundtrip(a__wl.disp); + + a_vkInitWithWayland(a__wl.disp, surf); + ATTO_APP_INIT_FUNC(&a__app_proctable); + + a__app_state.width = 1280; + a__app_state.height = 720; + a_vkCreateSwapchain(a__app_state.width, a__app_state.height); + a__app_proctable.swapchain_created(); + + ATimeUs last_paint = 0; + while (running) { + ATimeUs now = aAppTime(); + float dt; + if (!last_paint) + last_paint = now; + dt = (now - last_paint) * 1e-6f; + + a_vkPaint(&a__app_proctable, now, dt); + + ATTO_ASSERT(wl_display_dispatch(a__wl.disp) != -1); + } + + a__app_proctable.swapchain_will_destroy(); + if (a__app_proctable.close) + a__app_proctable.close(); + a_vkDestroySwapchain(); + a_vkDestroy(); + xdg_toplevel_destroy(xtop); + xdg_surface_destroy(xsurf); + wl_surface_destroy(surf); + wl_display_disconnect(a__wl.disp); +} From cfc97df7d8046dbd9a5e04b9c0e2159b62a2ffbd Mon Sep 17 00:00:00 2001 From: Ivan Avdeev Date: Wed, 11 Nov 2020 12:07:14 -0800 Subject: [PATCH 02/18] fix bits of missing functionality for wayland --- include/atto/worobushek.h | 2 ++ src/app_wayland.c | 10 +++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/include/atto/worobushek.h b/include/atto/worobushek.h index fff675e..ecb445e 100644 --- a/include/atto/worobushek.h +++ b/include/atto/worobushek.h @@ -4,7 +4,9 @@ #define VK_USE_PLATFORM_WAYLAND_KHR #include +#ifndef COUNTOF #define COUNTOF(a) (sizeof(a)/sizeof(*(a))) +#endif #define AVK_VERSION(v) \ VK_VERSION_MAJOR(v), \ diff --git a/src/app_wayland.c b/src/app_wayland.c index 7b4eec9..865c3d2 100644 --- a/src/app_wayland.c +++ b/src/app_wayland.c @@ -32,6 +32,10 @@ void aAppTerminate(int code) { exit(code); } +void aAppGrabInput(int grab) { + (void)(grab); +} + static int running = 1; void aAppClose() { running = 0; @@ -104,10 +108,14 @@ int main(int argc, char *argv[]) { wl_display_roundtrip(a__wl.disp); a_vkInitWithWayland(a__wl.disp, surf); - ATTO_APP_INIT_FUNC(&a__app_proctable); + a__app_state.argc = argc; + a__app_state.argv = (const char *const *)argv; + a__app_state.graphics_version = AOVK10; a__app_state.width = 1280; a__app_state.height = 720; + ATTO_APP_INIT_FUNC(&a__app_proctable); + a_vkCreateSwapchain(a__app_state.width, a__app_state.height); a__app_proctable.swapchain_created(); From 29c6d1b3652395b3c5bead511124254f793d55db Mon Sep 17 00:00:00 2001 From: Ivan Avdeev Date: Sat, 14 Nov 2020 14:05:54 -0800 Subject: [PATCH 03/18] wayland: add rudimentary wsad keyboard input; fix dt --- include/atto/worobushek.h | 4 +-- src/app_wayland.c | 71 +++++++++++++++++++++++++++++++++++---- 2 files changed, 67 insertions(+), 8 deletions(-) diff --git a/include/atto/worobushek.h b/include/atto/worobushek.h index ecb445e..c541a85 100644 --- a/include/atto/worobushek.h +++ b/include/atto/worobushek.h @@ -13,13 +13,13 @@ VK_VERSION_MINOR(v), \ VK_VERSION_PATCH(v) -#define AVK_CHECK_RESULT(res) { \ +#define AVK_CHECK_RESULT(res) do { \ const VkResult result = res; \ if (result != VK_SUCCESS) { \ aAppDebugPrintf("VK ERROR @ %s:%d: %s failed with result %d", __FILE__, __LINE__, #res, result); \ aAppTerminate(-1); \ } \ -} +} while(0) #define MAX_SWAPCHAIN_IMAGES 8 diff --git a/src/app_wayland.c b/src/app_wayland.c index 865c3d2..685986a 100644 --- a/src/app_wayland.c +++ b/src/app_wayland.c @@ -45,8 +45,65 @@ static struct { struct wl_display *disp; struct wl_compositor *comp; struct xdg_wm_base *xdg_wm; + struct wl_seat *seat; } a__wl = {0}; +static void noop() {} + +static struct wl_pointer_listener pointer_listener = { + .enter = noop, + .leave = noop, + .motion = noop, + .button = noop, + .axis = noop, +}; + +static void key(void *data, + struct wl_keyboard *wl_keyboard, + uint32_t serial, + uint32_t time, + uint32_t key, + uint32_t state) { + aAppDebugPrintf("key: %u state: %u", key, state); + + // KEK + int akey = 0; + switch (key) { + case 17: akey = AK_W; break; + case 30: akey = AK_A; break; + case 31: akey = AK_S; break; + case 32: akey = AK_D; break; + case 42: akey = AK_LeftShift; break; + default: return; + } + if (a__app_proctable.key) + a__app_proctable.key(aAppTime(), akey, state); +} + +static struct wl_keyboard_listener keyboard_listener = { + .keymap = noop, + .enter = noop, + .leave = noop, + .modifiers = noop, + .repeat_info = noop, + .key = key, +}; + +static void seat_capabilities(void *data, struct wl_seat *seat, uint32_t capabilities) { + if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) { + struct wl_keyboard *const keyboard = wl_seat_get_keyboard(seat); + wl_keyboard_add_listener(keyboard, &keyboard_listener, NULL); + } + if (capabilities & WL_SEAT_CAPABILITY_POINTER) { + struct wl_pointer *const pointer = wl_seat_get_pointer(seat); + wl_pointer_add_listener(pointer, &pointer_listener, NULL); + } +} + +static struct wl_seat_listener seat_listener = { + .capabilities = seat_capabilities, +}; + static void reg_global(void *data, struct wl_registry *reg, uint32_t name, const char *interface, uint32_t version) { //printf("%s: %s name=%u ver=%u\n", __FUNCTION__, interface, name, version); if (strcmp(interface, wl_compositor_interface.name) == 0) { @@ -54,6 +111,10 @@ static void reg_global(void *data, struct wl_registry *reg, uint32_t name, const } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) { a__wl.xdg_wm = wl_registry_bind(reg, name, &xdg_wm_base_interface, 1); + } else + if (strcmp(interface, wl_seat_interface.name) == 0) { + a__wl.seat = wl_registry_bind(reg, name, &wl_seat_interface, 1); + wl_seat_add_listener(a__wl.seat, &seat_listener, NULL); } } @@ -77,7 +138,6 @@ static struct xdg_surface_listener xsurf_listener = { .configure = xsurf_configure }; -static void noop() {} static void xtop_close(void *data, struct xdg_toplevel *xdg_toplevel) { //printf("%s\n", __FUNCTION__); @@ -121,11 +181,10 @@ int main(int argc, char *argv[]) { ATimeUs last_paint = 0; while (running) { - ATimeUs now = aAppTime(); - float dt; - if (!last_paint) - last_paint = now; - dt = (now - last_paint) * 1e-6f; + ATimeUs now = aAppTime(); + float dt; + dt = (now - last_paint) * 1e-6f; + last_paint = now; a_vkPaint(&a__app_proctable, now, dt); From 81fb87b57c1b88420ce7533de77477e8421ac957 Mon Sep 17 00:00:00 2001 From: Ivan Avdeev Date: Mon, 16 Nov 2020 10:13:16 -0800 Subject: [PATCH 04/18] add rudimentary pointer input --- src/app_wayland.c | 67 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 3 deletions(-) diff --git a/src/app_wayland.c b/src/app_wayland.c index 685986a..4310ed9 100644 --- a/src/app_wayland.c +++ b/src/app_wayland.c @@ -16,6 +16,7 @@ #include #include #include /* exit() */ +#include // FIXME declare this somewhere properly void a_vkInitWithWayland(struct wl_display *disp, struct wl_surface *surf); @@ -34,6 +35,10 @@ void aAppTerminate(int code) { void aAppGrabInput(int grab) { (void)(grab); + // FIXME: + // https://gitlab.freedesktop.org/wayland/wayland-protocols/-/blob/master/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml + // https://gitlab.freedesktop.org/wayland/wayland-protocols/-/blob/master/unstable/relative-pointer/relative-pointer-unstable-v1.xml + a__app_state.grabbed = grab; } static int running = 1; @@ -50,11 +55,56 @@ static struct { static void noop() {} +static void motion(void *data, + struct wl_pointer *wl_pointer, + uint32_t time, + wl_fixed_t surface_x, + wl_fixed_t surface_y) { + const int x = wl_fixed_to_int(surface_x); + const int y = wl_fixed_to_int(surface_y); + + // TODO track enter/leave + const int dx = x - a__app_state.pointer.x; + const int dy = y - a__app_state.pointer.y; + + a__app_state.pointer.x = x; + a__app_state.pointer.y = y; + + if (!a__app_proctable.pointer) + return; + + const ATimeUs now = aAppTime(); // FIXME convert wl time + a__app_proctable.pointer(now, dx, dy, 0); +} + +static void button(void *data, + struct wl_pointer *wl_pointer, + uint32_t serial, + uint32_t time, + uint32_t button, + uint32_t state) { + const uint32_t button_bit = 1 << (button-1); + switch (state) { + case WL_POINTER_BUTTON_STATE_PRESSED: + a__app_state.pointer.buttons |= button_bit; + break; + case WL_POINTER_BUTTON_STATE_RELEASED: + a__app_state.pointer.buttons &= ~button_bit; + break; + } + + if (!a__app_proctable.pointer) + return; + + const ATimeUs now = aAppTime(); // FIXME convert wl time + a__app_proctable.pointer(now, 0, 0, button_bit); +} + static struct wl_pointer_listener pointer_listener = { .enter = noop, .leave = noop, - .motion = noop, - .button = noop, + .motion = motion, + .button = button, .axis = noop, }; @@ -66,9 +116,10 @@ static void key(void *data, uint32_t state) { aAppDebugPrintf("key: %u state: %u", key, state); - // KEK + // FIXME do this properly w/ xkb and all that jazz int akey = 0; switch (key) { + case 1: akey = AK_Esc; break; case 17: akey = AK_W; break; case 30: akey = AK_A; break; case 31: akey = AK_S; break; @@ -80,6 +131,16 @@ static void key(void *data, a__app_proctable.key(aAppTime(), akey, state); } +static void keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int32_t fd, uint32_t size) { + /* char *keymap_string = mmap (NULL, size, PROT_READ, MAP_SHARED, fd, 0); */ + /* xkb_keymap_unref (keymap); */ + /* keymap = xkb_keymap_new_from_string (xkb_context, keymap_string, XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS); */ + /* munmap (keymap_string, size); */ + close (fd); + /* xkb_state_unref (xkb_state); */ + /* xkb_state = xkb_state_new (keymap); */ +} + static struct wl_keyboard_listener keyboard_listener = { .keymap = noop, .enter = noop, From 8ec3179990af2400c7c035295ec74cd6b47277fd Mon Sep 17 00:00:00 2001 From: Ivan Avdeev Date: Mon, 16 Nov 2020 10:52:18 -0800 Subject: [PATCH 05/18] implement swapchain resize for wayland+vk --- include/atto/app.h | 2 ++ src/app_vulkan.c | 2 ++ src/app_wayland.c | 32 +++++++++++++++++++++++++++++--- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/include/atto/app.h b/include/atto/app.h index 232819c..caf87ab 100644 --- a/include/atto/app.h +++ b/include/atto/app.h @@ -154,6 +154,8 @@ extern const struct AAppState *a_app_state; // VkSemaphore *out_semaphores; // } +// TODO add explicit leave/enter focus handling + struct AAppProctable { // FIXME #ifndef ATTO_VK //void (*resize)(ATimeUs ts, unsigned int old_width, unsigned int old_height); diff --git a/src/app_vulkan.c b/src/app_vulkan.c index ebc8bbd..317cd28 100644 --- a/src/app_vulkan.c +++ b/src/app_vulkan.c @@ -129,6 +129,8 @@ void a_vkCreateSwapchain(int w, int h) { sw->num_images = sw->num_images > MAX_SWAPCHAIN_IMAGES ? MAX_SWAPCHAIN_IMAGES : sw->num_images; AVK_CHECK_RESULT(vkGetSwapchainImagesKHR(a_vk.dev, sw->handle, &sw->num_images, sw->images)); + + aAppDebugPrintf("swapchain created: %d %d", w, h); } void a_vkDestroySwapchain() { diff --git a/src/app_wayland.c b/src/app_wayland.c index 4310ed9..8ad6ab1 100644 --- a/src/app_wayland.c +++ b/src/app_wayland.c @@ -83,7 +83,7 @@ static void button(void *data, uint32_t time, uint32_t button, uint32_t state) { - const uint32_t button_bit = 1 << (button-1); + const uint32_t button_bit = 1 << (button-0x110); switch (state) { case WL_POINTER_BUTTON_STATE_PRESSED: a__app_state.pointer.buttons |= button_bit; @@ -193,6 +193,7 @@ static void xsurf_configure(void *data, uint32_t serial) { xdg_surface_ack_configure(xdg_surface, serial); wl_surface_commit(data); + aAppDebugPrintf("%s", __FUNCTION__); } static struct xdg_surface_listener xsurf_listener = { @@ -201,12 +202,32 @@ static struct xdg_surface_listener xsurf_listener = { static void xtop_close(void *data, struct xdg_toplevel *xdg_toplevel) { - //printf("%s\n", __FUNCTION__); *(int*)data = 0; } +static void xtop_configure(void *data, + struct xdg_toplevel *xdg_toplevel, + int32_t width, + int32_t height, + struct wl_array *states) { + aAppDebugPrintf("%s %d %d", __FUNCTION__, width, height); + if (width == 0 || height == 0) + return; + + if (a__app_proctable.swapchain_will_destroy) + a__app_proctable.swapchain_will_destroy(); + a_vkDestroySwapchain(); + + a__app_state.width = width; + a__app_state.height = height; + + a_vkCreateSwapchain(width, height); + if (a__app_proctable.swapchain_created) + a__app_proctable.swapchain_created(); +} + static struct xdg_toplevel_listener xtop_listener = { - .configure = noop, + .configure = xtop_configure, .close = xtop_close }; @@ -237,9 +258,13 @@ int main(int argc, char *argv[]) { a__app_state.height = 720; ATTO_APP_INIT_FUNC(&a__app_proctable); + aAppDebugPrintf("post-init"); + a_vkCreateSwapchain(a__app_state.width, a__app_state.height); a__app_proctable.swapchain_created(); + aAppDebugPrintf("post-swapchain"); + ATimeUs last_paint = 0; while (running) { ATimeUs now = aAppTime(); @@ -247,6 +272,7 @@ int main(int argc, char *argv[]) { dt = (now - last_paint) * 1e-6f; last_paint = now; + //aAppDebugPrintf("DRAW"); a_vkPaint(&a__app_proctable, now, dt); ATTO_ASSERT(wl_display_dispatch(a__wl.disp) != -1); From c51216dcc2f33dc9bba5853fbd0eb4ef053547e0 Mon Sep 17 00:00:00 2001 From: Ivan Avdeev Date: Sat, 28 Nov 2020 10:53:10 -0800 Subject: [PATCH 06/18] improve window resize - do not destroy swapchain, pass old as oldSwapchain instead - do not recreate anything if dimensions haven't changed --- src/app_vulkan.c | 1 + src/app_wayland.c | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/app_vulkan.c b/src/app_vulkan.c index 317cd28..09315be 100644 --- a/src/app_vulkan.c +++ b/src/app_vulkan.c @@ -121,6 +121,7 @@ void a_vkCreateSwapchain(int w, int h) { sw->info.presentMode = VK_PRESENT_MODE_FIFO_KHR; // TODO caps, MAILBOX is better //sw->info.presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; // TODO caps, MAILBOX is better sw->info.clipped = VK_TRUE; + sw->info.oldSwapchain = sw->handle; AVK_CHECK_RESULT(vkCreateSwapchainKHR(a_vk.dev, &sw->info, NULL, &sw->handle)); diff --git a/src/app_wayland.c b/src/app_wayland.c index 8ad6ab1..a4abbc0 100644 --- a/src/app_wayland.c +++ b/src/app_wayland.c @@ -214,9 +214,11 @@ static void xtop_configure(void *data, if (width == 0 || height == 0) return; + if (width == a__app_state.width && height == a__app_state.height) + return; + if (a__app_proctable.swapchain_will_destroy) a__app_proctable.swapchain_will_destroy(); - a_vkDestroySwapchain(); a__app_state.width = width; a__app_state.height = height; From 3331105b2e87c07f28a3dbd02af6e9f084c2c1a5 Mon Sep 17 00:00:00 2001 From: Ivan 'provod' Avdeev Date: Sat, 5 Dec 2020 14:21:37 -0800 Subject: [PATCH 07/18] make vulkan work (somewhat) on windows --- CMakeLists.txt | 15 +++++++++++---- examples/vk_tri.c | 18 +++++++----------- include/atto/worobushek.h | 22 ++++++++++++++++++++++ src/app_vulkan.c | 26 ++++++++++++++++++++++++++ src/app_wayland.c | 7 ------- src/app_windows.c | 38 +++++++++++++++++++++++++++++++++++++- 6 files changed, 103 insertions(+), 23 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e1dcb8a..a6a6919 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,12 +1,18 @@ cmake_minimum_required(VERSION 3.10) project(atto C) -set(OpenGL_GL_PREFERENCE GLVND) -find_package(OpenGL REQUIRED) +# set(OpenGL_GL_PREFERENCE GLVND) +# find_package(OpenGL REQUIRED) +find_package(Vulkan REQUIRED) + if(WIN32) set(ATTO_SRC - ${CMAKE_CURRENT_SOURCE_DIR}/src/app_windows.c) + ${CMAKE_CURRENT_SOURCE_DIR}/src/app_windows.c + ${CMAKE_CURRENT_SOURCE_DIR}/src/app_vulkan.c + ${CMAKE_CURRENT_SOURCE_DIR}/include/atto/app.h + ${CMAKE_CURRENT_SOURCE_DIR}/include/atto/worobushek.h + ) elseif(CMAKE_SYSTEM_NAME MATCHES ".*Linux") # find_package(X11 REQUIRED) # set(ATTO_LIBS @@ -34,7 +40,8 @@ target_include_directories(atto PUBLIC include) target_include_directories(atto PRIVATE 3p) target_link_libraries(atto #PUBLIC OpenGL::GL - PUBLIC wayland-client vulkan + #PUBLIC wayland-client + PUBLIC Vulkan::Vulkan PRIVATE ${ATTO_LIBS}) set_target_properties(atto PROPERTIES C_STANDARD 99 diff --git a/examples/vk_tri.c b/examples/vk_tri.c index c4b3d6b..db99d65 100644 --- a/examples/vk_tri.c +++ b/examples/vk_tri.c @@ -160,8 +160,8 @@ static void createPipeline() { input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; VkViewport viewport = { - .x = 0, .y = 0, - .width = a_app_state->width, .height = a_app_state->height, + .x = 0.f, .y = 0.f, + .width = (float)a_app_state->width, .height = (float)a_app_state->height, .minDepth = 0.f, .maxDepth = 1.f }; VkRect2D scissor = { @@ -224,8 +224,7 @@ static void swapchainCreated() { g.image_views = malloc(num_images * sizeof(VkImageView)); g.framebuffers = malloc(num_images * sizeof(VkFramebuffer)); for (uint32_t i = 0; i < num_images; ++i) { - VkImageViewCreateInfo ivci = {}; - ivci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + VkImageViewCreateInfo ivci = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO }; ivci.viewType = VK_IMAGE_VIEW_TYPE_2D; ivci.format = a_vk.swapchain.info.imageFormat; ivci.image = a_vk.swapchain.images[i]; @@ -234,8 +233,7 @@ static void swapchainCreated() { ivci.subresourceRange.layerCount = 1; AVK_CHECK_RESULT(vkCreateImageView(a_vk.dev, &ivci, NULL, g.image_views + i)); - VkFramebufferCreateInfo fbci = {}; - fbci.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + VkFramebufferCreateInfo fbci = {.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; fbci.renderPass = g.render_pass; fbci.attachmentCount = 1; fbci.pAttachments = g.image_views + i; @@ -251,20 +249,18 @@ static void swapchainCreated() { static void paint(ATimeUs timestamp, float dt) { const float t = timestamp / 1e6; - VkCommandBufferBeginInfo beginfo = {}; - beginfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + VkCommandBufferBeginInfo beginfo = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; beginfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; AVK_CHECK_RESULT(vkBeginCommandBuffer(g.cmdbuf, &beginfo)); - VkClearValue clear_value = {}; + VkClearValue clear_value = {0}; clear_value.color.float32[0] = .5f + .5f * sinf(t); clear_value.color.float32[1] = .5f + .5f * sinf(t*3); clear_value.color.float32[2] = .5f + .5f * sinf(t*5); clear_value.color.float32[3] = 1.f; /* clear_value.color.uint32[0] = 0xffffffff; */ /* clear_value.color.uint32[3] = 0xffffffff; */ - VkRenderPassBeginInfo rpbi = {}; - rpbi.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + VkRenderPassBeginInfo rpbi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; rpbi.renderPass = g.render_pass; rpbi.framebuffer = g.framebuffers[a_vk.swapchain.current_frame_image_index]; rpbi.renderArea.offset.x = rpbi.renderArea.offset.y = 0; diff --git a/include/atto/worobushek.h b/include/atto/worobushek.h index c541a85..6bf2830 100644 --- a/include/atto/worobushek.h +++ b/include/atto/worobushek.h @@ -1,7 +1,17 @@ #pragma once +#include "atto/platform.h" + +#ifdef ATTO_PLATFORM_WINDOWS +#define LEAN_AND_MEAN +#define NOMINMAX +#include +#define VK_USE_PLATFORM_WIN32_KHR +#else // FIXME atto platform #define VK_USE_PLATFORM_WAYLAND_KHR +#endif + #include #ifndef COUNTOF @@ -53,3 +63,15 @@ void aVkDestroySemaphore(VkSemaphore sema); VkShaderModule loadShaderFromFile(const char *filename); uint32_t aVkFindMemoryWithType(uint32_t type_index_bits, VkMemoryPropertyFlags flags); + +// FIXME declare this somewhere properly +#include "atto/app.h" +#if defined(ATTO_PLATFORM_WINDOWS) +void a_vkInitWithWindows(HINSTANCE hInst, HWND hWnd); +#else +void a_vkInitWithWayland(struct wl_display *disp, struct wl_surface *surf); +#endif +void a_vkCreateSwapchain(int w, int h); +void a_vkPaint(struct AAppProctable *ptbl, ATimeUs t, float dt); +void a_vkDestroy(); +void a_vkDestroySwapchain(); diff --git a/src/app_vulkan.c b/src/app_vulkan.c index 09315be..89527d8 100644 --- a/src/app_vulkan.c +++ b/src/app_vulkan.c @@ -6,7 +6,11 @@ static const char *instance_exts[] = { VK_KHR_SURFACE_EXTENSION_NAME, +#ifdef ATTO_PLATFORM_WINDOWS + VK_KHR_WIN32_SURFACE_EXTENSION_NAME, +#else VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME +#endif }; struct AVkState a_vk; @@ -139,6 +143,26 @@ void a_vkDestroySwapchain() { a_vk.swapchain.handle = NULL; } +#if defined(ATTO_PLATFORM_WINDOWS) +void a_vkInitWithWindows(HINSTANCE hInst, HWND hWnd) { + a_vkInitInstance(); + + VkWin32SurfaceCreateInfoKHR wsci = {0}; + wsci.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; + wsci.hinstance = hInst; + wsci.hwnd = hWnd; + AVK_CHECK_RESULT(vkCreateWin32SurfaceKHR(a_vk.inst, &wsci, NULL, &a_vk.surf)); + + a_vkInitDevice(); + +#define MAX_PRESENT_MODES 8 + uint32_t num_present_modes = MAX_PRESENT_MODES; + VkPresentModeKHR present_modes[MAX_PRESENT_MODES]; + vkGetPhysicalDeviceSurfacePresentModesKHR(a_vk.phys_dev, a_vk.surf, &num_present_modes, present_modes); + // TODO use the best mode +} +#else + void a_vkInitWithWayland(struct wl_display *disp, struct wl_surface *surf) { a_vkInitInstance(); @@ -157,6 +181,8 @@ void a_vkInitWithWayland(struct wl_display *disp, struct wl_surface *surf) { // TODO use the best mode } +#endif + void a_vkDestroy() { vkDestroySurfaceKHR(a_vk.inst, a_vk.surf, NULL); aVkDestroySemaphore(a_vk.swapchain.image_available); diff --git a/src/app_wayland.c b/src/app_wayland.c index a4abbc0..e2521cc 100644 --- a/src/app_wayland.c +++ b/src/app_wayland.c @@ -18,13 +18,6 @@ #include /* exit() */ #include -// FIXME declare this somewhere properly -void a_vkInitWithWayland(struct wl_display *disp, struct wl_surface *surf); -void a_vkCreateSwapchain(int w, int h); -void a_vkPaint(struct AAppProctable *ptbl, ATimeUs t, float dt); -void a_vkDestroy(); -void a_vkDestroySwapchain(); - static struct AAppState a__app_state; const struct AAppState *a_app_state = &a__app_state; static struct AAppProctable a__app_proctable; diff --git a/src/app_windows.c b/src/app_windows.c index acd725b..558ff6d 100644 --- a/src/app_windows.c +++ b/src/app_windows.c @@ -10,6 +10,9 @@ #define ATTO_APP_NAME "atto app" #endif +// FIXME +#define ATTO_VK 1 + #include #include #include @@ -19,7 +22,8 @@ #include /* #include "wglext.h" #include */ -#include +#include "atto/app.h" +#include "atto/worobushek.h" /* static WCHAR *utf8_to_wchar(const char *string, int length, int *out_length); */ static char *wchar_to_utf8(const WCHAR *string, int length, int *out_length); @@ -97,6 +101,8 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine g.hwnd = CreateWindow(TEXT("atto"), TEXT(ATTO_APP_NAME), WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, ATTO_APP_WIDTH, ATTO_APP_HEIGHT, NULL, NULL, hInstance, NULL); ATTO_ASSERT(0 != g.hwnd); + +#if defined(ATTO_GL) g.hdc = GetDC(g.hwnd); ATTO_ASSERT(0 != g.hdc); @@ -104,6 +110,7 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine g.hglrc = wglCreateContext(g.hdc); ATTO_ASSERT(0 != g.hglrc); wglMakeCurrent(g.hdc, g.hglrc); +#endif { int i; @@ -114,13 +121,27 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine a__app_state.argv = (const char **)argv; } +#if defined(ATTO_GL) a__app_state.gl_version = AOGLV_21; +//#elif defined(ATTO_VK) +// a__app_state.gl_version = AOGLV_21; +#endif + + a_vkInitWithWindows(hInstance, g.hwnd); + a__app_state.width = ATTO_APP_WIDTH; a__app_state.height = ATTO_APP_HEIGHT; ATTO_APP_INIT_FUNC(&a__app_proctable); + + a_vkCreateSwapchain(a__app_state.width, a__app_state.height); +if (a__app_proctable.swapchain_created) + a__app_proctable.swapchain_created(); + +#if defined(ATTO_GL) if (a__app_proctable.resize) a__app_proctable.resize(aAppTime(), 0, 0); +#endif ShowWindow(g.hwnd, nCmdShow); @@ -153,9 +174,11 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine } static void a__AppCleanup(void) { +#ifdef ATTO_GL wglMakeCurrent(g.hdc, NULL); wglDeleteContext(g.hglrc); ReleaseDC(g.hwnd, g.hdc); +#endif DestroyWindow(g.hwnd); } @@ -264,10 +287,23 @@ static LRESULT CALLBACK a__AppWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM const int width = (int)(lparam & 0xffff), height = (int)(lparam >> 16); if (a__app_state.width == width && a__app_state.height == height) break; + +#if defined(ATTO_VK) + if (a__app_proctable.swapchain_will_destroy) + a__app_proctable.swapchain_will_destroy(); +#endif + a__app_state.width = width; a__app_state.height = height; + +#if defined(ATTO_GL) if (a__app_proctable.resize) a__app_proctable.resize(aAppTime(), oldw, oldh); +#elif defined(ATTO_VK) + a_vkCreateSwapchain(width, height); + if (a__app_proctable.swapchain_created) + a__app_proctable.swapchain_created(); +#endif } break; case WM_KEYDOWN: down = 1; From 0a33e96117179f97f759a3f570bf2e5aadac7f5f Mon Sep 17 00:00:00 2001 From: Ivan 'provod' Avdeev Date: Mon, 7 Dec 2020 11:36:19 -0800 Subject: [PATCH 08/18] refactor vulkan to enable custom init functions --- CMakeLists.txt | 7 +- examples/CMakeLists.txt | 5 +- examples/vk_ray.c | 371 ++++++++++++++++++++++++++++++++++++++ include/atto/app.h | 39 +--- include/atto/platform.h | 23 --- include/atto/worobushek.h | 263 +++++++++++++++++++++++++-- src/app_vulkan.c | 265 --------------------------- src/app_windows.c | 39 ++-- 8 files changed, 654 insertions(+), 358 deletions(-) create mode 100644 examples/vk_ray.c delete mode 100644 include/atto/platform.h delete mode 100644 src/app_vulkan.c diff --git a/CMakeLists.txt b/CMakeLists.txt index a6a6919..55c05ab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,14 +5,13 @@ project(atto C) # find_package(OpenGL REQUIRED) find_package(Vulkan REQUIRED) - if(WIN32) set(ATTO_SRC ${CMAKE_CURRENT_SOURCE_DIR}/src/app_windows.c - ${CMAKE_CURRENT_SOURCE_DIR}/src/app_vulkan.c ${CMAKE_CURRENT_SOURCE_DIR}/include/atto/app.h ${CMAKE_CURRENT_SOURCE_DIR}/include/atto/worobushek.h ) + set(ATTO_DEFINES ATTO_PLATFORM_WINDOWS ATTO_VK) elseif(CMAKE_SYSTEM_NAME MATCHES ".*Linux") # find_package(X11 REQUIRED) # set(ATTO_LIBS @@ -28,9 +27,10 @@ elseif(CMAKE_SYSTEM_NAME MATCHES ".*Linux") ${CMAKE_CURRENT_SOURCE_DIR}/src/app_linux.c # # ${CMAKE_CURRENT_SOURCE_DIR}/src/app_x11.c) ${CMAKE_CURRENT_SOURCE_DIR}/src/app_wayland.c - ${CMAKE_CURRENT_SOURCE_DIR}/src/app_vulkan.c ${CMAKE_CURRENT_SOURCE_DIR}/3p/wl-xdg-proto.c + ${CMAKE_CURRENT_SOURCE_DIR}/include/atto/worobushek.h ) + set(ATTO_DEFINES ATTO_PLATFORM_POSIX ATTO_PLATFORM_LINUX ATTO_VK) else() message(FATAL_ERROR "Not ported") endif() @@ -38,6 +38,7 @@ endif() add_library(atto STATIC ${ATTO_SRC}) target_include_directories(atto PUBLIC include) target_include_directories(atto PRIVATE 3p) +target_compile_definitions(atto PUBLIC ${ATTO_DEFINES}) target_link_libraries(atto #PUBLIC OpenGL::GL #PUBLIC wayland-client diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 1fa9ff1..137bf26 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -22,7 +22,8 @@ endfunction() # add_example(fb) # add_example(tri) # add_example(tribench) -add_example(vk_tri) +#add_example(vk_tri) +add_example(vk_ray) function(add_shaders) cmake_parse_arguments(PARSE_ARGV 0 SHADERS "" "TARGET" "FILES") @@ -39,4 +40,4 @@ function(add_shaders) add_custom_target(${SHADERS_TARGET} ALL DEPENDS ${SHADERS_DEPS}) endfunction() -add_shaders(TARGET vk_tri_shaders FILES shader.frag shader.vert) +add_shaders(TARGET vk_shaders FILES shader.frag shader.vert) diff --git a/examples/vk_ray.c b/examples/vk_ray.c new file mode 100644 index 0000000..2c26fb0 --- /dev/null +++ b/examples/vk_ray.c @@ -0,0 +1,371 @@ +#include "atto/app.h" + +#include +#include +#include + +#define ATTO_VK_IMPLEMENT +#include "atto/worobushek.h" + +struct Vertex { + float x, y; + uint8_t r, g, b; +}; + +static struct { + VkFence fence; + VkSemaphore done; + VkRenderPass render_pass; + + VkPipelineLayout pipeline_layout; + VkShaderModule module_vertex; + VkShaderModule module_fragment; + + VkImageView *image_views; + VkFramebuffer *framebuffers; + VkPipeline pipeline; + + VkDeviceMemory devmem; + VkBuffer vertex_buf; + + VkCommandPool cmdpool; + VkCommandBuffer cmdbuf; +} g; + +static void createRenderPass() { + VkAttachmentDescription attachment = {0}; + attachment.format = VK_FORMAT_B8G8R8A8_SRGB;// FIXME too early a_vk.swapchain.info.imageFormat; + attachment.samples = VK_SAMPLE_COUNT_1_BIT; + //attachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + //attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + + VkAttachmentReference color_attachment = {0}; + color_attachment.attachment = 0; + color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + VkSubpassDescription subdesc = {0}; + subdesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subdesc.colorAttachmentCount = 1; + subdesc.pColorAttachments = &color_attachment; + + VkRenderPassCreateInfo rpci = {0}; + rpci.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + rpci.attachmentCount = 1; + rpci.pAttachments = &attachment; + rpci.subpassCount = 1; + rpci.pSubpasses = &subdesc; + AVK_CHECK_RESULT(vkCreateRenderPass(a_vk.dev, &rpci, NULL, &g.render_pass)); +} + +static void createShaders() { + VkPushConstantRange push_const = {0}; + push_const.offset = 0; + push_const.size = sizeof(float); + push_const.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + + VkPipelineLayoutCreateInfo plci = {0}; + plci.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + plci.setLayoutCount = 0; + plci.pushConstantRangeCount = 1; + plci.pPushConstantRanges = &push_const; + AVK_CHECK_RESULT(vkCreatePipelineLayout(a_vk.dev, &plci, NULL, &g.pipeline_layout)); + + g.module_vertex = loadShaderFromFile("shader.vert.spv"); + g.module_fragment = loadShaderFromFile("shader.frag.spv"); +} + +static const struct Vertex vertices[] = { + {1.f, 0.f, 255, 0, 0}, + {-.5f, .866f, 255, 255, 0}, + {-.5f, -.866f, 255, 0, 255}, +}; + +static void createBuffer() { + VkBufferCreateInfo bci = {0}; + bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + bci.size = sizeof(vertices); + bci.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; + bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + AVK_CHECK_RESULT(vkCreateBuffer(a_vk.dev, &bci, NULL, &g.vertex_buf)); + + VkMemoryRequirements memreq; + vkGetBufferMemoryRequirements(a_vk.dev, g.vertex_buf, &memreq); + aAppDebugPrintf("memreq: memoryTypeBits=0x%x alignment=%zu size=%zu", memreq.memoryTypeBits, memreq.alignment, memreq.size); + + VkMemoryAllocateInfo mai={0}; + mai.allocationSize = memreq.size; + mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mai.memoryTypeIndex = aVkFindMemoryWithType(memreq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + AVK_CHECK_RESULT(vkAllocateMemory(a_vk.dev, &mai, NULL, &g.devmem)); + AVK_CHECK_RESULT(vkBindBufferMemory(a_vk.dev, g.vertex_buf, g.devmem, 0)); + + void *ptr = NULL; + AVK_CHECK_RESULT(vkMapMemory(a_vk.dev, g.devmem, 0, bci.size, 0, &ptr)); + memcpy(ptr, vertices, sizeof(vertices)); + vkUnmapMemory(a_vk.dev, g.devmem); +} + +static void createCommandPool() { + VkCommandPoolCreateInfo cpci = {0}; + cpci.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + cpci.queueFamilyIndex = 0; + cpci.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + AVK_CHECK_RESULT(vkCreateCommandPool(a_vk.dev, &cpci, NULL, &g.cmdpool)); + + VkCommandBufferAllocateInfo cbai = {0}; + cbai.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + cbai.commandBufferCount = 1; + cbai.commandPool = g.cmdpool; + cbai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + AVK_CHECK_RESULT(vkAllocateCommandBuffers(a_vk.dev, &cbai, &g.cmdbuf)); +} + +static void createPipeline() { + VkPipelineShaderStageCreateInfo shader_stages[2] = {0}; + shader_stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shader_stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + + shader_stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + shader_stages[0].module = g.module_vertex; + shader_stages[0].pName = "main"; + + shader_stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + shader_stages[1].module = g.module_fragment; + shader_stages[1].pName = "main"; + + VkVertexInputBindingDescription vibd = {0}; + vibd.binding = 0; + vibd.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; + vibd.stride = sizeof(struct Vertex); + + VkVertexInputAttributeDescription attribs[] = { + {.binding = 0, .location = 0, .format = VK_FORMAT_R32G32_SFLOAT, .offset = offsetof(struct Vertex, x)}, + {.binding = 0, .location = 1, .format = VK_FORMAT_R8G8_UNORM, .offset = offsetof(struct Vertex, r)}, + {.binding = 0, .location = 2, .format = VK_FORMAT_R8_UNORM, .offset = offsetof(struct Vertex, b)}, + }; + + VkPipelineVertexInputStateCreateInfo vertex_input = {0}; + vertex_input.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertex_input.vertexBindingDescriptionCount = 1; + vertex_input.pVertexBindingDescriptions = &vibd; + vertex_input.vertexAttributeDescriptionCount = COUNTOF(attribs); + vertex_input.pVertexAttributeDescriptions = attribs; + + VkPipelineInputAssemblyStateCreateInfo input_assembly = {0}; + input_assembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + + VkViewport viewport = { + .x = 0.f, .y = 0.f, + .width = (float)a_app_state->width, .height = (float)a_app_state->height, + .minDepth = 0.f, .maxDepth = 1.f + }; + VkRect2D scissor = { + .offset = {0}, + .extent = {a_app_state->width, a_app_state->height} + }; + VkPipelineViewportStateCreateInfo viewport_state = {0}; + viewport_state.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport_state.viewportCount = 1; + viewport_state.scissorCount = 1; + viewport_state.pViewports = &viewport; + viewport_state.pScissors = &scissor; + + VkPipelineRasterizationStateCreateInfo raster_state = {0}; + raster_state.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + raster_state.polygonMode = VK_POLYGON_MODE_FILL; + raster_state.cullMode = VK_CULL_MODE_NONE; + raster_state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + raster_state.lineWidth = 1.f; + + VkPipelineMultisampleStateCreateInfo multi_state = {0}; + multi_state.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multi_state.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + VkPipelineColorBlendAttachmentState blend_attachment = {0}; + blend_attachment.blendEnable = VK_FALSE; + blend_attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + + VkPipelineColorBlendStateCreateInfo color_blend = {0}; + color_blend.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + color_blend.attachmentCount = 1; + color_blend.pAttachments = &blend_attachment; + + VkGraphicsPipelineCreateInfo gpci = {0}; + gpci.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + gpci.stageCount = COUNTOF(shader_stages); + gpci.pStages = shader_stages; + gpci.pVertexInputState = &vertex_input; + gpci.pInputAssemblyState = &input_assembly; + gpci.pViewportState = &viewport_state; + gpci.pRasterizationState = &raster_state; + gpci.pMultisampleState = &multi_state; + gpci.pColorBlendState = &color_blend; + gpci.layout = g.pipeline_layout; + gpci.renderPass = g.render_pass; + gpci.subpass = 0; + AVK_CHECK_RESULT(vkCreateGraphicsPipelines(a_vk.dev, NULL, 1, &gpci, NULL, &g.pipeline)); +} + +static void swapchainWillDestroy() { + vkDestroyPipeline(a_vk.dev, g.pipeline, NULL); + for (uint32_t i = 0; i < a_vk.swapchain.num_images; ++i) { + vkDestroyFramebuffer(a_vk.dev, g.framebuffers[i], NULL); + vkDestroyImageView(a_vk.dev, g.image_views[i], NULL); + } +} + +static void swapchainCreated() { + const uint32_t num_images = a_vk.swapchain.num_images; + g.image_views = malloc(num_images * sizeof(VkImageView)); + g.framebuffers = malloc(num_images * sizeof(VkFramebuffer)); + for (uint32_t i = 0; i < num_images; ++i) { + VkImageViewCreateInfo ivci = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO }; + ivci.viewType = VK_IMAGE_VIEW_TYPE_2D; + ivci.format = a_vk.swapchain.info.imageFormat; + ivci.image = a_vk.swapchain.images[i]; + ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + ivci.subresourceRange.levelCount = 1; + ivci.subresourceRange.layerCount = 1; + AVK_CHECK_RESULT(vkCreateImageView(a_vk.dev, &ivci, NULL, g.image_views + i)); + + VkFramebufferCreateInfo fbci = {.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; + fbci.renderPass = g.render_pass; + fbci.attachmentCount = 1; + fbci.pAttachments = g.image_views + i; + fbci.width = a_app_state->width; + fbci.height = a_app_state->height; + fbci.layers = 1; + AVK_CHECK_RESULT(vkCreateFramebuffer(a_vk.dev, &fbci, NULL, g.framebuffers + i)); + } + + createPipeline(); +} + +static void paint(ATimeUs timestamp, float dt) { + const float t = timestamp / 1e6; + + aVkAcquireNextImage(); + + VkCommandBufferBeginInfo beginfo = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + beginfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + AVK_CHECK_RESULT(vkBeginCommandBuffer(g.cmdbuf, &beginfo)); + + VkClearValue clear_value = {0}; + clear_value.color.float32[0] = .5f + .5f * sinf(t); + clear_value.color.float32[1] = .5f + .5f * sinf(t*3); + clear_value.color.float32[2] = .5f + .5f * sinf(t*5); + clear_value.color.float32[3] = 1.f; + /* clear_value.color.uint32[0] = 0xffffffff; */ + /* clear_value.color.uint32[3] = 0xffffffff; */ + VkRenderPassBeginInfo rpbi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; + rpbi.renderPass = g.render_pass; + rpbi.framebuffer = g.framebuffers[a_vk.swapchain.current_frame_image_index]; + rpbi.renderArea.offset.x = rpbi.renderArea.offset.y = 0; + rpbi.renderArea.extent.width = a_app_state->width; + rpbi.renderArea.extent.height = a_app_state->height; + rpbi.clearValueCount = 1; + rpbi.pClearValues = &clear_value; + vkCmdBeginRenderPass(g.cmdbuf, &rpbi, VK_SUBPASS_CONTENTS_INLINE); + + vkCmdBindPipeline(g.cmdbuf, VK_PIPELINE_BIND_POINT_GRAPHICS, g.pipeline); + + VkDeviceSize offset = {0}; + vkCmdBindVertexBuffers(g.cmdbuf, 0, 1, &g.vertex_buf, &offset); + vkCmdPushConstants(g.cmdbuf, g.pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(float), &t); + vkCmdDraw(g.cmdbuf, 3, 1, 0, 0); + /* const int N = 32; */ + /* for (int i = 0; i < N; ++i) { */ + /* const float it = i / (float)N; */ + /* const float tt = t*(.8+it*.2) + it * ((1. + sin(t*.3))*.15 + .7) * 20.; */ + /* vkCmdPushConstants(cmdbuf, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(float), &tt); */ + /* vkCmdDraw(cmdbuf, 3, 1, 0, 0); */ + /* } */ + vkCmdEndRenderPass(g.cmdbuf); + + AVK_CHECK_RESULT(vkEndCommandBuffer(g.cmdbuf)); + + VkPipelineStageFlags stageflags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkSubmitInfo subinfo = {0}; + subinfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + subinfo.pNext = NULL; + subinfo.commandBufferCount = 1; + subinfo.pCommandBuffers = &g.cmdbuf; + subinfo.waitSemaphoreCount = 1; + subinfo.pWaitSemaphores = &a_vk.swapchain.image_available; + subinfo.signalSemaphoreCount = 1; + subinfo.pSignalSemaphores = &g.done, + subinfo.pWaitDstStageMask = &stageflags; + AVK_CHECK_RESULT(vkQueueSubmit(a_vk.main_queue, 1, &subinfo, g.fence)); + + VkPresentInfoKHR presinfo = {0}; + presinfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + presinfo.pSwapchains = &a_vk.swapchain.handle; + presinfo.pImageIndices = &a_vk.swapchain.current_frame_image_index; + presinfo.swapchainCount = 1; + presinfo.pWaitSemaphores = &g.done; + presinfo.waitSemaphoreCount = 1; + AVK_CHECK_RESULT(vkQueuePresentKHR(a_vk.main_queue, &presinfo)); + + // FIXME bad sync + AVK_CHECK_RESULT(vkWaitForFences(a_vk.dev, 1, &g.fence, VK_TRUE, INT64_MAX)); + AVK_CHECK_RESULT(vkResetFences(a_vk.dev, 1, &g.fence)); +} + +static void close() { + vkFreeCommandBuffers(a_vk.dev, g.cmdpool, 1, &g.cmdbuf); + vkDestroyCommandPool(a_vk.dev, g.cmdpool, NULL); + + vkDestroyPipelineLayout(a_vk.dev, g.pipeline_layout, NULL); + + vkDestroyShaderModule(a_vk.dev, g.module_fragment, NULL); + vkDestroyShaderModule(a_vk.dev, g.module_vertex, NULL); + + vkFreeMemory(a_vk.dev, g.devmem, NULL); + vkDestroyBuffer(a_vk.dev, g.vertex_buf, NULL); + + vkDestroyRenderPass(a_vk.dev, g.render_pass, NULL); + aVkDestroySemaphore(g.done); + vkDestroyFence(a_vk.dev, g.fence, NULL); + + aVkDestroy(); +} + +static void resize(ATimeUs ts, unsigned int old_width, unsigned int old_height) { + swapchainWillDestroy(); + aVkCreateSwapchain(a_app_state->width, a_app_state->height); + swapchainCreated(); + paint(ts, 0); +} + +void attoAppInit(struct AAppProctable *proctable) { + proctable->paint = paint; + proctable->resize = resize; + proctable->close = close; + + // TODO FIXME VK INIT + aVkInitInstance(); + aVkCreateSurface(); + aVkInitDevice(); + aVkPokePresentModes(); + + g.done = aVkCreateSemaphore(); + createRenderPass(); + createShaders(); + createBuffer(); + createCommandPool(); + + aVkCreateSwapchain(a_app_state->width, a_app_state->height); + swapchainCreated(); + + VkFenceCreateInfo fci = {0}; + fci.flags = 0; + fci.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + AVK_CHECK_RESULT(vkCreateFence(a_vk.dev, &fci, NULL, &g.fence)); +} diff --git a/include/atto/app.h b/include/atto/app.h index caf87ab..4080366 100644 --- a/include/atto/app.h +++ b/include/atto/app.h @@ -125,12 +125,20 @@ typedef enum { AB_WheelDown = 1 << 4 } AButton; -typedef enum { AOGLV_21, AOGLV_ES_20, AOVK10 } AGraphicsVersion; +typedef enum { AOGLV_21, AOGLV_ES_20 } AGraphicsVersion; struct AAppState { int argc; const char *const *argv; +#ifdef ATTO_GL AGraphicsVersion graphics_version; +#endif +#ifdef ATTO_VK +#if defined(ATTO_PLATFORM_WINDOWS) + void* hInstance; + void* hWnd; +#endif +#endif unsigned int width, height; int keys[AK_Max]; struct { @@ -145,29 +153,14 @@ void aAppGrabInput(int grab); extern const struct AAppState *a_app_state; -// struct AVkPaintArgs { -// ATimeUs pts; -// float dt; -// uint32_t image_index; -// VkSemaphore image_ready; -// uint32_t out_num_semaphores; -// VkSemaphore *out_semaphores; -// } - // TODO add explicit leave/enter focus handling struct AAppProctable { - // FIXME #ifndef ATTO_VK - //void (*resize)(ATimeUs ts, unsigned int old_width, unsigned int old_height); + void (*resize)(ATimeUs ts, unsigned int old_width, unsigned int old_height); void (*paint)(ATimeUs ts, float dt); void (*key)(ATimeUs ts, AKey key, int down); void (*pointer)(ATimeUs ts, int dx, int dy, unsigned int buttons_changed_bits); void (*close)(); - -// FIXME #idfef ATTO_VK - void (*swapchain_will_destroy)(); - void (*swapchain_created)(); - //void (*paint_vk)(); }; /* @@ -183,18 +176,6 @@ struct AAppProctable { * 8. (atto) paint( */ - -struct AVkAppProctable { - - - - // void (*swapDestroy)(); - // void (*swapCreate)(); // ~= resize - void (*paint)(); - /// - void (*close)(); -}; - #ifndef ATTO_APP_INIT_FUNC #define ATTO_APP_INIT_FUNC attoAppInit #endif /* ATTO_APP_INIT */ diff --git a/include/atto/platform.h b/include/atto/platform.h deleted file mode 100644 index 74d0a5d..0000000 --- a/include/atto/platform.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef ATTO_PLATFORM -#define ATTO_PLATFORM - -#ifdef __linux__ - #define ATTO_PLATFORM_POSIX - #define ATTO_PLATFORM_LINUX - #ifndef ATTO_PLATFORM_RPI - #define ATTO_PLATFORM_X11 - #else - #define ATTO_PLATFORM_EGL - #define ATTO_PLATFORM_EVDEV - #endif /* ifndef ATTO_PLATFORM_RPI */ -#elif defined(_WIN32) - #define ATTO_PLATFORM_WINDOWS -#elif defined(__MACH__) && defined(__APPLE__) - #define ATTO_PLATFORM_POSIX - #define ATTO_PLATFORM_MACH - #define ATTO_PLATFORM_OSX -#else - #error Not ported -#endif - -#endif /* ifndef ATTO_PLATFORM */ diff --git a/include/atto/worobushek.h b/include/atto/worobushek.h index 6bf2830..546c403 100644 --- a/include/atto/worobushek.h +++ b/include/atto/worobushek.h @@ -1,19 +1,19 @@ #pragma once -#include "atto/platform.h" - #ifdef ATTO_PLATFORM_WINDOWS -#define LEAN_AND_MEAN -#define NOMINMAX -#include #define VK_USE_PLATFORM_WIN32_KHR #else // FIXME atto platform #define VK_USE_PLATFORM_WAYLAND_KHR #endif +#include "atto/app.h" + #include +#include +#include + #ifndef COUNTOF #define COUNTOF(a) (sizeof(a)/sizeof(*(a))) #endif @@ -64,14 +64,251 @@ void aVkDestroySemaphore(VkSemaphore sema); VkShaderModule loadShaderFromFile(const char *filename); uint32_t aVkFindMemoryWithType(uint32_t type_index_bits, VkMemoryPropertyFlags flags); -// FIXME declare this somewhere properly -#include "atto/app.h" +void aVkCreateSurface(); +void aVkPokePresentModes(); +void aVkCreateSwapchain(int w, int h); +void aVkAcquireNextImage(); +void aVkDestroy(); +void aVkDestroySwapchain(); + +#if defined(ATTO_VK_IMPLEMENT) +static const char *instance_exts[] = { + VK_KHR_SURFACE_EXTENSION_NAME, +#ifdef ATTO_PLATFORM_WINDOWS + VK_KHR_WIN32_SURFACE_EXTENSION_NAME, +#else + VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, +#endif +}; + +struct AVkState a_vk; + +void aVkInitInstance() { + uint32_t version = 0; + AVK_CHECK_RESULT(vkEnumerateInstanceVersion(&version)); + aAppDebugPrintf("InstanceVersion: %u.%u.%u", AVK_VERSION(version)); + + VkApplicationInfo ai; + ai.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; + ai.pNext = NULL; + ai.apiVersion = VK_MAKE_VERSION(1, 0, 0); + ai.applicationVersion = 0; + ai.engineVersion = 0; + ai.pApplicationName = "LOL"; + ai.pEngineName = "KEK"; + + const char *layers[] = { + #ifdef _DEBUG + "VK_LAYER_KHRONOS_validation", + #endif + }; + + VkInstanceCreateInfo vici; + vici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + vici.pNext = NULL; + vici.enabledLayerCount = COUNTOF(layers); + vici.flags = 0; + vici.ppEnabledLayerNames = layers; + vici.enabledExtensionCount = COUNTOF(instance_exts); + vici.ppEnabledExtensionNames = instance_exts; + vici.pApplicationInfo = &ai; + + AVK_CHECK_RESULT(vkCreateInstance(&vici, NULL, &a_vk.inst)); +} + +void aVkInitDevice() { + // Get only the first device + uint32_t num_devices = 1; + vkEnumeratePhysicalDevices(a_vk.inst, &num_devices, &a_vk.phys_dev); + + uint32_t queue_index = UINT32_MAX; + VkPhysicalDeviceProperties pd; + vkGetPhysicalDeviceProperties(a_vk.phys_dev, &pd); + +#define MAX_QUEUE_FAMILIES 8 + uint32_t num_queue_families = MAX_QUEUE_FAMILIES; + VkQueueFamilyProperties queue_families[MAX_QUEUE_FAMILIES]; + vkGetPhysicalDeviceQueueFamilyProperties(a_vk.phys_dev, &num_queue_families, queue_families); + + for (uint32_t i = 0; i < num_queue_families; ++i) { + if (!(queue_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) + continue; + + VkBool32 present = 0; + vkGetPhysicalDeviceSurfaceSupportKHR(a_vk.phys_dev, i, a_vk.surf, &present); + + if (!present) + continue; + + queue_index = i; + break; + } + + ATTO_ASSERT(queue_index < num_queue_families); + + vkGetPhysicalDeviceMemoryProperties(a_vk.phys_dev, &a_vk.mem_props); + + float prio = 1.f; + VkDeviceQueueCreateInfo queue_info = { + .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, + .pNext = NULL, + .flags = 0, + .queueFamilyIndex = queue_index, + .queueCount = 1, + .pQueuePriorities = &prio, + }; + + const char* devex[] = { + VK_KHR_SWAPCHAIN_EXTENSION_NAME + }; + VkDeviceCreateInfo create_info = { + .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, + .pNext = NULL, + .flags = 0, + .queueCreateInfoCount = 1, + .pQueueCreateInfos = &queue_info, + .enabledLayerCount = 0, + .ppEnabledLayerNames = NULL, + .enabledExtensionCount = COUNTOF(devex), + .ppEnabledExtensionNames = devex, + .pEnabledFeatures = NULL + }; + + AVK_CHECK_RESULT(vkCreateDevice(a_vk.phys_dev, &create_info, NULL, &a_vk.dev)); + + vkGetDeviceQueue(a_vk.dev, 0, 0, &a_vk.main_queue); + + a_vk.swapchain.image_available = aVkCreateSemaphore(); +} + +void aVkCreateSwapchain(int w, int h) { + struct AVkSwapchain* sw = &a_vk.swapchain; + sw->info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + sw->info.pNext = NULL; + sw->info.surface = a_vk.surf; + sw->info.minImageCount = 5; // TODO get from caps + sw->info.imageFormat = VK_FORMAT_B8G8R8A8_SRGB; // TODO get from caps + sw->info.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; // TODO get from caps + sw->info.imageExtent.width = w; + sw->info.imageExtent.height = h; + sw->info.imageArrayLayers = 1; + sw->info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + sw->info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; + sw->info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; // TODO get from caps + sw->info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + sw->info.presentMode = VK_PRESENT_MODE_FIFO_KHR; // TODO caps, MAILBOX is better + //sw->info.presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; // TODO caps, MAILBOX is better + sw->info.clipped = VK_TRUE; + sw->info.oldSwapchain = sw->handle; + + AVK_CHECK_RESULT(vkCreateSwapchainKHR(a_vk.dev, &sw->info, NULL, &sw->handle)); + + sw->num_images = 0; + AVK_CHECK_RESULT(vkGetSwapchainImagesKHR(a_vk.dev, sw->handle, &sw->num_images, NULL)); + + sw->num_images = sw->num_images > MAX_SWAPCHAIN_IMAGES ? MAX_SWAPCHAIN_IMAGES : sw->num_images; + AVK_CHECK_RESULT(vkGetSwapchainImagesKHR(a_vk.dev, sw->handle, &sw->num_images, sw->images)); + + aAppDebugPrintf("swapchain created: %d %d", w, h); +} + +void aVkDestroySwapchain() { + vkDestroySwapchainKHR(a_vk.dev, a_vk.swapchain.handle, NULL); + a_vk.swapchain.handle = NULL; +} + +void aVkCreateSurface() { #if defined(ATTO_PLATFORM_WINDOWS) -void a_vkInitWithWindows(HINSTANCE hInst, HWND hWnd); + VkWin32SurfaceCreateInfoKHR wsci = {0}; + wsci.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; + wsci.hinstance = a_app_state->hInstance; + wsci.hwnd = a_app_state->hWnd; + AVK_CHECK_RESULT(vkCreateWin32SurfaceKHR(a_vk.inst, &wsci, NULL, &a_vk.surf)); #else -void a_vkInitWithWayland(struct wl_display *disp, struct wl_surface *surf); + VkWaylandSurfaceCreateInfoKHR wsci = {0}; + wsci.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR; + wsci.surface = surf; + wsci.display = disp; + AVK_CHECK_RESULT(vkCreateWaylandSurfaceKHR(a_vk.inst, &wsci, NULL, &a_vk.surf)); +#endif +} + +void aVkPokePresentModes() { +#define MAX_PRESENT_MODES 8 + uint32_t num_present_modes = MAX_PRESENT_MODES; + VkPresentModeKHR present_modes[MAX_PRESENT_MODES]; + vkGetPhysicalDeviceSurfacePresentModesKHR(a_vk.phys_dev, a_vk.surf, &num_present_modes, present_modes); + // TODO use the best mode +} + +void aVkDestroy() { + vkDestroySurfaceKHR(a_vk.inst, a_vk.surf, NULL); + aVkDestroySemaphore(a_vk.swapchain.image_available); + vkDestroyDevice(a_vk.dev, NULL); + vkDestroyInstance(a_vk.inst, NULL); +} + +void aVkAcquireNextImage() { + AVK_CHECK_RESULT(vkAcquireNextImageKHR(a_vk.dev, a_vk.swapchain.handle, UINT64_MAX, a_vk.swapchain.image_available, + NULL, &a_vk.swapchain.current_frame_image_index)); +} + +VkSemaphore aVkCreateSemaphore() { + VkSemaphore sema; + VkSemaphoreCreateInfo sci = {0}; + sci.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + sci.flags = 0; + AVK_CHECK_RESULT(vkCreateSemaphore(a_vk.dev, &sci, NULL, &sema)); + return sema; +} + +void aVkDestroySemaphore(VkSemaphore sema) { + vkDestroySemaphore(a_vk.dev, sema, NULL); +} + +VkShaderModule loadShaderFromFile(const char *filename) { + FILE *f = fopen(filename, "rb"); + if (!f) { + perror(filename); + exit(1); + } + fseek(f, 0, SEEK_END); + const size_t size = ftell(f); + if (size % 4 != 0) { + aAppDebugPrintf("size %zu is not aligned to 4 bytes as required by SPIR-V/Vulkan spec", size); + } + + fseek(f, 0, SEEK_SET); + uint32_t *buf = malloc(4 * ((size+3)/4)); + if (size != fread(buf, 1, size, f)) { + fprintf(stderr, "Cannot read the entire file %s\n", filename); + exit(1); + } + + VkShaderModuleCreateInfo smci = {0}; + smci.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + smci.codeSize = size; + smci.pCode = buf; + VkShaderModule shader; + const VkResult res = vkCreateShaderModule(a_vk.dev, &smci, NULL, &shader); + if (VK_SUCCESS != res) { \ + aAppDebugPrintf("%s:%d: failed w/ %d\n", __FILE__, __LINE__, res); \ + exit(1); + } + fclose(f); + free(buf); + return shader; +} + +uint32_t aVkFindMemoryWithType(uint32_t type_index_bits, VkMemoryPropertyFlags flags) { + for (uint32_t i = 0; i < a_vk.mem_props.memoryTypeCount; ++i) { + if (!(type_index_bits & (1 << i))) + continue; + + if ((a_vk.mem_props.memoryTypes[i].propertyFlags & flags) == flags) + return i; + } + + return UINT32_MAX; +} #endif -void a_vkCreateSwapchain(int w, int h); -void a_vkPaint(struct AAppProctable *ptbl, ATimeUs t, float dt); -void a_vkDestroy(); -void a_vkDestroySwapchain(); diff --git a/src/app_vulkan.c b/src/app_vulkan.c deleted file mode 100644 index 89527d8..0000000 --- a/src/app_vulkan.c +++ /dev/null @@ -1,265 +0,0 @@ -#include "atto/worobushek.h" -#include "atto/app.h" - -#include -#include - -static const char *instance_exts[] = { - VK_KHR_SURFACE_EXTENSION_NAME, -#ifdef ATTO_PLATFORM_WINDOWS - VK_KHR_WIN32_SURFACE_EXTENSION_NAME, -#else - VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME -#endif -}; - -struct AVkState a_vk; - -void a_vkInitInstance() { - uint32_t version = 0; - AVK_CHECK_RESULT(vkEnumerateInstanceVersion(&version)); - aAppDebugPrintf("InstanceVersion: %u.%u.%u", AVK_VERSION(version)); - - VkApplicationInfo ai; - ai.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; - ai.pNext = NULL; - ai.apiVersion = VK_MAKE_VERSION(1, 0, 0); - ai.applicationVersion = 0; - ai.engineVersion = 0; - ai.pApplicationName = "LOL"; - ai.pEngineName = "KEK"; - - VkInstanceCreateInfo vici; - vici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; - vici.pNext = NULL; - vici.enabledLayerCount = 0; - vici.flags = 0; - vici.ppEnabledLayerNames = NULL; - vici.enabledExtensionCount = COUNTOF(instance_exts); - vici.ppEnabledExtensionNames = instance_exts; - vici.pApplicationInfo = &ai; - - AVK_CHECK_RESULT(vkCreateInstance(&vici, NULL, &a_vk.inst)); -} - -void a_vkInitDevice() { - // Get only the first device - uint32_t num_devices = 1; - vkEnumeratePhysicalDevices(a_vk.inst, &num_devices, &a_vk.phys_dev); - - uint32_t queue_index = UINT32_MAX; - VkPhysicalDeviceProperties pd; - vkGetPhysicalDeviceProperties(a_vk.phys_dev, &pd); - -#define MAX_QUEUE_FAMILIES 8 - uint32_t num_queue_families = MAX_QUEUE_FAMILIES; - VkQueueFamilyProperties queue_families[MAX_QUEUE_FAMILIES]; - vkGetPhysicalDeviceQueueFamilyProperties(a_vk.phys_dev, &num_queue_families, queue_families); - - for (uint32_t i = 0; i < num_queue_families; ++i) { - if (!(queue_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) - continue; - - VkBool32 present = 0; - vkGetPhysicalDeviceSurfaceSupportKHR(a_vk.phys_dev, i, a_vk.surf, &present); - - if (!present) - continue; - - queue_index = i; - break; - } - - ATTO_ASSERT(queue_index < num_queue_families); - - vkGetPhysicalDeviceMemoryProperties(a_vk.phys_dev, &a_vk.mem_props); - - float prio = 1.f; - VkDeviceQueueCreateInfo queue_info = { - .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, - .pNext = NULL, - .flags = 0, - .queueFamilyIndex = queue_index, - .queueCount = 1, - .pQueuePriorities = &prio, - }; - - const char* devex[] = { - VK_KHR_SWAPCHAIN_EXTENSION_NAME - }; - VkDeviceCreateInfo create_info = { - .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, - .pNext = NULL, - .flags = 0, - .queueCreateInfoCount = 1, - .pQueueCreateInfos = &queue_info, - .enabledLayerCount = 0, - .ppEnabledLayerNames = NULL, - .enabledExtensionCount = COUNTOF(devex), - .ppEnabledExtensionNames = devex, - .pEnabledFeatures = NULL - }; - - AVK_CHECK_RESULT(vkCreateDevice(a_vk.phys_dev, &create_info, NULL, &a_vk.dev)); - - vkGetDeviceQueue(a_vk.dev, 0, 0, &a_vk.main_queue); - - a_vk.swapchain.image_available = aVkCreateSemaphore(); -} - -void a_vkCreateSwapchain(int w, int h) { - struct AVkSwapchain* sw = &a_vk.swapchain; - sw->info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; - sw->info.pNext = NULL; - sw->info.surface = a_vk.surf; - sw->info.minImageCount = 5; // TODO get from caps - sw->info.imageFormat = VK_FORMAT_B8G8R8A8_SRGB; // TODO get from caps - sw->info.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; // TODO get from caps - sw->info.imageExtent.width = w; - sw->info.imageExtent.height = h; - sw->info.imageArrayLayers = 1; - sw->info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - sw->info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; - sw->info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; // TODO get from caps - sw->info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; - sw->info.presentMode = VK_PRESENT_MODE_FIFO_KHR; // TODO caps, MAILBOX is better - //sw->info.presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; // TODO caps, MAILBOX is better - sw->info.clipped = VK_TRUE; - sw->info.oldSwapchain = sw->handle; - - AVK_CHECK_RESULT(vkCreateSwapchainKHR(a_vk.dev, &sw->info, NULL, &sw->handle)); - - sw->num_images = 0; - AVK_CHECK_RESULT(vkGetSwapchainImagesKHR(a_vk.dev, sw->handle, &sw->num_images, NULL)); - - sw->num_images = sw->num_images > MAX_SWAPCHAIN_IMAGES ? MAX_SWAPCHAIN_IMAGES : sw->num_images; - AVK_CHECK_RESULT(vkGetSwapchainImagesKHR(a_vk.dev, sw->handle, &sw->num_images, sw->images)); - - aAppDebugPrintf("swapchain created: %d %d", w, h); -} - -void a_vkDestroySwapchain() { - vkDestroySwapchainKHR(a_vk.dev, a_vk.swapchain.handle, NULL); - a_vk.swapchain.handle = NULL; -} - -#if defined(ATTO_PLATFORM_WINDOWS) -void a_vkInitWithWindows(HINSTANCE hInst, HWND hWnd) { - a_vkInitInstance(); - - VkWin32SurfaceCreateInfoKHR wsci = {0}; - wsci.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; - wsci.hinstance = hInst; - wsci.hwnd = hWnd; - AVK_CHECK_RESULT(vkCreateWin32SurfaceKHR(a_vk.inst, &wsci, NULL, &a_vk.surf)); - - a_vkInitDevice(); - -#define MAX_PRESENT_MODES 8 - uint32_t num_present_modes = MAX_PRESENT_MODES; - VkPresentModeKHR present_modes[MAX_PRESENT_MODES]; - vkGetPhysicalDeviceSurfacePresentModesKHR(a_vk.phys_dev, a_vk.surf, &num_present_modes, present_modes); - // TODO use the best mode -} -#else - -void a_vkInitWithWayland(struct wl_display *disp, struct wl_surface *surf) { - a_vkInitInstance(); - - VkWaylandSurfaceCreateInfoKHR wsci = {0}; - wsci.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR; - wsci.surface = surf; - wsci.display = disp; - AVK_CHECK_RESULT(vkCreateWaylandSurfaceKHR(a_vk.inst, &wsci, NULL, &a_vk.surf)); - - a_vkInitDevice(); - -#define MAX_PRESENT_MODES 8 - uint32_t num_present_modes = MAX_PRESENT_MODES; - VkPresentModeKHR present_modes[MAX_PRESENT_MODES]; - vkGetPhysicalDeviceSurfacePresentModesKHR(a_vk.phys_dev, a_vk.surf, &num_present_modes, present_modes); - // TODO use the best mode -} - -#endif - -void a_vkDestroy() { - vkDestroySurfaceKHR(a_vk.inst, a_vk.surf, NULL); - aVkDestroySemaphore(a_vk.swapchain.image_available); - vkDestroyDevice(a_vk.dev, NULL); - vkDestroyInstance(a_vk.inst, NULL); -} - -void a_vkPaint(struct AAppProctable *ptbl, ATimeUs t, float dt) { - AVK_CHECK_RESULT(vkAcquireNextImageKHR(a_vk.dev, a_vk.swapchain.handle, UINT64_MAX, a_vk.swapchain.image_available, NULL, &a_vk.swapchain.current_frame_image_index)); - - ptbl->paint(t, dt); - - /* VkPresentInfoKHR presinfo = {0}; */ - /* presinfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; */ - /* presinfo.pSwapchains = &a_vk.swapchain.handle; */ - /* presinfo.pImageIndices = &a_vk.swapchain.current_frame_image_index; */ - /* presinfo.swapchainCount = 1; */ - /* presinfo.pWaitSemaphores = &semaDone; */ - /* presinfo.waitSemaphoreCount = 1; */ - /* AVK_CHECK_RESULT(vkQueuePresentKHR(a_vk.main_queue, &presinfo)); */ -} - -VkSemaphore aVkCreateSemaphore() { - VkSemaphore sema; - VkSemaphoreCreateInfo sci = {0}; - sci.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; - sci.flags = 0; - AVK_CHECK_RESULT(vkCreateSemaphore(a_vk.dev, &sci, NULL, &sema)); - return sema; -} - -void aVkDestroySemaphore(VkSemaphore sema) { - vkDestroySemaphore(a_vk.dev, sema, NULL); -} - -VkShaderModule loadShaderFromFile(const char *filename) { - FILE *f = fopen(filename, "rb"); - if (!f) { - perror(filename); - exit(1); - } - fseek(f, 0, SEEK_END); - const size_t size = ftell(f); - if (size % 4 != 0) { - aAppDebugPrintf("size %zu is not aligned to 4 bytes as required by SPIR-V/Vulkan spec", size); - } - - fseek(f, 0, SEEK_SET); - uint32_t *buf = malloc(4 * ((size+3)/4)); - if (size != fread(buf, 1, size, f)) { - fprintf(stderr, "Cannot read the entire file %s\n", filename); - exit(1); - } - - VkShaderModuleCreateInfo smci = {0}; - smci.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - smci.codeSize = size; - smci.pCode = buf; - VkShaderModule shader; - const VkResult res = vkCreateShaderModule(a_vk.dev, &smci, NULL, &shader); - if (VK_SUCCESS != res) { \ - aAppDebugPrintf("%s:%d: failed w/ %d\n", __FILE__, __LINE__, res); \ - exit(1); - } - fclose(f); - free(buf); - return shader; -} - -uint32_t aVkFindMemoryWithType(uint32_t type_index_bits, VkMemoryPropertyFlags flags) { - for (uint32_t i = 0; i < a_vk.mem_props.memoryTypeCount; ++i) { - if (!(type_index_bits & (1 << i))) - continue; - - if ((a_vk.mem_props.memoryTypes[i].propertyFlags & flags) == flags) - return i; - } - - return UINT32_MAX; -} diff --git a/src/app_windows.c b/src/app_windows.c index 558ff6d..fd31dd2 100644 --- a/src/app_windows.c +++ b/src/app_windows.c @@ -10,20 +10,23 @@ #define ATTO_APP_NAME "atto app" #endif -// FIXME -#define ATTO_VK 1 - #include #include #include #include + +#define LEAN_AND_MEAN +#define NOMINMAX +#define EXTRALEAN #include #include /* GET_X/Y_LPARAM */ + +#ifdef ATTO_GL #include -/* #include "wglext.h" -#include */ +//#include "wglext.h" +#endif + #include "atto/app.h" -#include "atto/worobushek.h" /* static WCHAR *utf8_to_wchar(const char *string, int length, int *out_length); */ static char *wchar_to_utf8(const WCHAR *string, int length, int *out_length); @@ -127,16 +130,14 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine // a__app_state.gl_version = AOGLV_21; #endif - a_vkInitWithWindows(hInstance, g.hwnd); - a__app_state.width = ATTO_APP_WIDTH; a__app_state.height = ATTO_APP_HEIGHT; + a__app_state.hInstance = hInstance; + a__app_state.hWnd = g.hwnd; +#ifdef ATTO_VK ATTO_APP_INIT_FUNC(&a__app_proctable); - - a_vkCreateSwapchain(a__app_state.width, a__app_state.height); -if (a__app_proctable.swapchain_created) - a__app_proctable.swapchain_created(); +#endif #if defined(ATTO_GL) if (a__app_proctable.resize) @@ -161,7 +162,9 @@ if (a__app_proctable.swapchain_created) float dt = (now - last_paint) * 1e-6f; if (a__app_proctable.paint) a__app_proctable.paint(now, dt); +#ifdef ATTO_GL SwapBuffers(g.hdc); +#endif last_paint = now; } } @@ -288,22 +291,12 @@ static LRESULT CALLBACK a__AppWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM if (a__app_state.width == width && a__app_state.height == height) break; -#if defined(ATTO_VK) - if (a__app_proctable.swapchain_will_destroy) - a__app_proctable.swapchain_will_destroy(); -#endif - a__app_state.width = width; a__app_state.height = height; -#if defined(ATTO_GL) if (a__app_proctable.resize) a__app_proctable.resize(aAppTime(), oldw, oldh); -#elif defined(ATTO_VK) - a_vkCreateSwapchain(width, height); - if (a__app_proctable.swapchain_created) - a__app_proctable.swapchain_created(); -#endif + } break; case WM_KEYDOWN: down = 1; From 1e36e85833a78ae1571dbc0d4b7a8d44abae7165 Mon Sep 17 00:00:00 2001 From: Ivan 'provod' Avdeev Date: Mon, 14 Dec 2020 10:13:49 -0800 Subject: [PATCH 09/18] get ray tracing pipeline to draw something --- examples/CMakeLists.txt | 9 +- examples/ray.rgen | 14 + examples/vk_ray.c | 525 ++++++++++++++++++++++++++++---------- include/atto/worobushek.h | 98 ++++++- src/app_windows.c | 4 + 5 files changed, 495 insertions(+), 155 deletions(-) create mode 100644 examples/ray.rgen diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 137bf26..b05feed 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -10,7 +10,7 @@ function(add_example EXAMPLE_NAME) project(${EXAMPLE_NAME}) add_executable(${EXAMPLE_NAME} ${ATTO_EXE_SUBSYSTEM} ${CMAKE_CURRENT_SOURCE_DIR}/${EXAMPLE_NAME}.c) - target_link_libraries(${EXAMPLE_NAME} atto m) + target_link_libraries(${EXAMPLE_NAME} atto) # m) set_target_properties(${EXAMPLE_NAME} PROPERTIES C_STANDARD 99 C_STANDARD_REQUIRED TRUE @@ -30,8 +30,9 @@ function(add_shaders) foreach(SHADER ${SHADERS_FILES}) add_custom_command( OUTPUT ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}${SHADER}.spv - COMMAND glslc - ${CMAKE_SOURCE_DIR}/examples/${SHADER} -o ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}${SHADER}.spv + #COMMAND glslc + COMMAND glslangValidator + ${CMAKE_SOURCE_DIR}/examples/${SHADER} --target-env vulkan1.2 -o ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}${SHADER}.spv MAIN_DEPENDENCY ${CMAKE_SOURCE_DIR}/examples/${SHADER} COMMENT "Building ${SHADER}" ) @@ -40,4 +41,4 @@ function(add_shaders) add_custom_target(${SHADERS_TARGET} ALL DEPENDS ${SHADERS_DEPS}) endfunction() -add_shaders(TARGET vk_shaders FILES shader.frag shader.vert) +add_shaders(TARGET vk_shaders FILES shader.frag shader.vert ray.rgen) diff --git a/examples/ray.rgen b/examples/ray.rgen new file mode 100644 index 0000000..3eea0f1 --- /dev/null +++ b/examples/ray.rgen @@ -0,0 +1,14 @@ +#version 460 +#extension GL_EXT_ray_tracing : require + +//layout(binding = 0, set = 0, rgba32f) uniform image2D image; +layout(binding = 0, set = 0, rgba8) uniform image2D image; + +void main() { +//const vec2 pixelCenter = vec2(gl_LaunchIDEXT.xy) + vec2(0.5); + //const vec2 inUV = pixelCenter / vec2(gl_LaunchSizeEXT.xy); + + vec3 c = vec3(fract(gl_LaunchIDEXT.xy / 10.), 1.); + imageStore(image, ivec2(gl_LaunchIDEXT.xy), vec4(c, 1.0)); +} + diff --git a/examples/vk_ray.c b/examples/vk_ray.c index 2c26fb0..38ab4d3 100644 --- a/examples/vk_ray.c +++ b/examples/vk_ray.c @@ -4,29 +4,96 @@ #include #include +#define ATTO_VK_INSTANCE_EXTENSIONS \ + VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, \ + +#define ATTO_VK_DEVICE_EXTENSIONS \ + VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME, \ + VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME, \ + VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME, \ + +#define AVK_VK_VERSION VK_MAKE_VERSION(1, 2, 0) + #define ATTO_VK_IMPLEMENT #include "atto/worobushek.h" -struct Vertex { - float x, y; - uint8_t r, g, b; +//struct Vertex { +// float x, y; +// uint8_t r, g, b; +//}; + +struct Image { + VkDeviceMemory devmem; + VkImage image; + VkImageView view; }; +static struct Image createImage(uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage) { + VkImageCreateInfo ici = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; + ici.imageType = VK_IMAGE_TYPE_2D; + ici.extent.width = width; + ici.extent.height = height; + ici.extent.depth = 1; + ici.mipLevels = 1; + ici.arrayLayers = 1; + ici.format = format; + ici.tiling = tiling; + ici.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + ici.usage = usage; + ici.samples = VK_SAMPLE_COUNT_1_BIT; + ici.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + struct Image image; + AVK_CHECK_RESULT(vkCreateImage(a_vk.dev, &ici, NULL, &image.image)); + + VkMemoryRequirements memreq; + vkGetImageMemoryRequirements(a_vk.dev, image.image, &memreq); + + VkMemoryAllocateInfo mai={.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + mai.allocationSize = memreq.size; + mai.memoryTypeIndex = aVkFindMemoryWithType(memreq.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + AVK_CHECK_RESULT(vkAllocateMemory(a_vk.dev, &mai, NULL, &image.devmem)); + AVK_CHECK_RESULT(vkBindImageMemory(a_vk.dev, image.image, image.devmem, 0)); + + VkImageViewCreateInfo ivci = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO }; + ivci.viewType = VK_IMAGE_VIEW_TYPE_2D; + ivci.format = ici.format; + ivci.image = image.image; + ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + ivci.subresourceRange.levelCount = 1; + ivci.subresourceRange.layerCount = 1; + AVK_CHECK_RESULT(vkCreateImageView(a_vk.dev, &ivci, NULL, &image.view)); + + return image; +} + static struct { + struct { + VkPhysicalDeviceProperties2 prop2; + VkPhysicalDeviceRayTracingPipelinePropertiesKHR rt; + } prop; + uint32_t shader_group_size; + VkFence fence; VkSemaphore done; VkRenderPass render_pass; VkPipelineLayout pipeline_layout; - VkShaderModule module_vertex; - VkShaderModule module_fragment; + struct { + VkShaderModule raygen; + } modules; + VkDescriptorSetLayout desc_layout; + VkDescriptorPool desc_pool; + VkDescriptorSet desc_set; VkImageView *image_views; VkFramebuffer *framebuffers; VkPipeline pipeline; + struct Image rt_image; VkDeviceMemory devmem; - VkBuffer vertex_buf; + VkBuffer sbt_buf; + //VkBuffer vertex_buf; VkCommandPool cmdpool; VkCommandBuffer cmdbuf; @@ -63,54 +130,91 @@ static void createRenderPass() { AVK_CHECK_RESULT(vkCreateRenderPass(a_vk.dev, &rpci, NULL, &g.render_pass)); } -static void createShaders() { +static void createLayouts() { + + VkDescriptorSetLayoutBinding bindings[] = { + { + .binding = 0, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR, + }, + /*{.binding = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR, + },*/ + }; + + VkDescriptorSetLayoutCreateInfo dslci = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .bindingCount = COUNTOF(bindings), .pBindings = bindings, }; + + AVK_CHECK_RESULT(vkCreateDescriptorSetLayout(a_vk.dev, &dslci, NULL, &g.desc_layout)); + + /* VkPushConstantRange push_const = {0}; push_const.offset = 0; push_const.size = sizeof(float); push_const.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + */ VkPipelineLayoutCreateInfo plci = {0}; plci.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; - plci.setLayoutCount = 0; - plci.pushConstantRangeCount = 1; - plci.pPushConstantRanges = &push_const; + plci.setLayoutCount = 1; + plci.pSetLayouts = &g.desc_layout; + // plci.pushConstantRangeCount = 1; + // plci.pPushConstantRanges = &push_const; AVK_CHECK_RESULT(vkCreatePipelineLayout(a_vk.dev, &plci, NULL, &g.pipeline_layout)); - g.module_vertex = loadShaderFromFile("shader.vert.spv"); - g.module_fragment = loadShaderFromFile("shader.frag.spv"); -} - -static const struct Vertex vertices[] = { - {1.f, 0.f, 255, 0, 0}, - {-.5f, .866f, 255, 255, 0}, - {-.5f, -.866f, 255, 0, 255}, -}; - -static void createBuffer() { - VkBufferCreateInfo bci = {0}; - bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - bci.size = sizeof(vertices); - bci.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; - bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - AVK_CHECK_RESULT(vkCreateBuffer(a_vk.dev, &bci, NULL, &g.vertex_buf)); + VkDescriptorPoolSize pools[] = { {.type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .descriptorCount = 1},}; - VkMemoryRequirements memreq; - vkGetBufferMemoryRequirements(a_vk.dev, g.vertex_buf, &memreq); - aAppDebugPrintf("memreq: memoryTypeBits=0x%x alignment=%zu size=%zu", memreq.memoryTypeBits, memreq.alignment, memreq.size); + VkDescriptorPoolCreateInfo dpci = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, + .maxSets = 1, .poolSizeCount = COUNTOF(pools), .pPoolSizes = pools, + }; + AVK_CHECK_RESULT(vkCreateDescriptorPool(a_vk.dev, &dpci, NULL, &g.desc_pool)); - VkMemoryAllocateInfo mai={0}; - mai.allocationSize = memreq.size; - mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - mai.memoryTypeIndex = aVkFindMemoryWithType(memreq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - AVK_CHECK_RESULT(vkAllocateMemory(a_vk.dev, &mai, NULL, &g.devmem)); - AVK_CHECK_RESULT(vkBindBufferMemory(a_vk.dev, g.vertex_buf, g.devmem, 0)); + VkDescriptorSetAllocateInfo dsai = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, + .descriptorPool = g.desc_pool, + .descriptorSetCount = 1, + .pSetLayouts = &g.desc_layout, + }; + AVK_CHECK_RESULT(vkAllocateDescriptorSets(a_vk.dev, &dsai, &g.desc_set)); - void *ptr = NULL; - AVK_CHECK_RESULT(vkMapMemory(a_vk.dev, g.devmem, 0, bci.size, 0, &ptr)); - memcpy(ptr, vertices, sizeof(vertices)); - vkUnmapMemory(a_vk.dev, g.devmem); + g.modules.raygen = loadShaderFromFile("ray.rgen.spv"); } +//static const struct Vertex vertices[] = { +// {1.f, 0.f, 255, 0, 0}, +// {-.5f, .866f, 255, 255, 0}, +// {-.5f, -.866f, 255, 0, 255}, +//}; +// +//static void createBuffer() { +// VkBufferCreateInfo bci = {0}; +// bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; +// bci.size = sizeof(vertices); +// bci.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; +// bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE; +// AVK_CHECK_RESULT(vkCreateBuffer(a_vk.dev, &bci, NULL, &g.vertex_buf)); +// +// VkMemoryRequirements memreq; +// vkGetBufferMemoryRequirements(a_vk.dev, g.vertex_buf, &memreq); +// aAppDebugPrintf("memreq: memoryTypeBits=0x%x alignment=%zu size=%zu", memreq.memoryTypeBits, memreq.alignment, memreq.size); +// +// VkMemoryAllocateInfo mai={0}; +// mai.allocationSize = memreq.size; +// mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; +// mai.memoryTypeIndex = aVkFindMemoryWithType(memreq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); +// AVK_CHECK_RESULT(vkAllocateMemory(a_vk.dev, &mai, NULL, &g.devmem)); +// AVK_CHECK_RESULT(vkBindBufferMemory(a_vk.dev, g.vertex_buf, g.devmem, 0)); +// +// void *ptr = NULL; +// AVK_CHECK_RESULT(vkMapMemory(a_vk.dev, g.devmem, 0, bci.size, 0, &ptr)); +// memcpy(ptr, vertices, sizeof(vertices)); +// vkUnmapMemory(a_vk.dev, g.devmem); +//} + static void createCommandPool() { VkCommandPoolCreateInfo cpci = {0}; cpci.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; @@ -127,94 +231,73 @@ static void createCommandPool() { } static void createPipeline() { - VkPipelineShaderStageCreateInfo shader_stages[2] = {0}; - shader_stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - shader_stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - - shader_stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; - shader_stages[0].module = g.module_vertex; - shader_stages[0].pName = "main"; - - shader_stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; - shader_stages[1].module = g.module_fragment; - shader_stages[1].pName = "main"; - - VkVertexInputBindingDescription vibd = {0}; - vibd.binding = 0; - vibd.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; - vibd.stride = sizeof(struct Vertex); - - VkVertexInputAttributeDescription attribs[] = { - {.binding = 0, .location = 0, .format = VK_FORMAT_R32G32_SFLOAT, .offset = offsetof(struct Vertex, x)}, - {.binding = 0, .location = 1, .format = VK_FORMAT_R8G8_UNORM, .offset = offsetof(struct Vertex, r)}, - {.binding = 0, .location = 2, .format = VK_FORMAT_R8_UNORM, .offset = offsetof(struct Vertex, b)}, + VkDynamicState dynstate[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; + + VkPipelineDynamicStateCreateInfo pdsci = {.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; + pdsci.dynamicStateCount = COUNTOF(dynstate); + pdsci.pDynamicStates = dynstate; + + VkPipelineShaderStageCreateInfo shader_stages[] = {{ + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_RAYGEN_BIT_KHR, + .module = g.modules.raygen, + .pName = "main", + }, }; + + VkRayTracingShaderGroupCreateInfoKHR groups[] = {{ + .sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR, + .type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR, + .generalShader = 0, + .closestHitShader = VK_SHADER_UNUSED_KHR, + .anyHitShader = VK_SHADER_UNUSED_KHR, + .intersectionShader = VK_SHADER_UNUSED_KHR, + }, }; - VkPipelineVertexInputStateCreateInfo vertex_input = {0}; - vertex_input.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; - vertex_input.vertexBindingDescriptionCount = 1; - vertex_input.pVertexBindingDescriptions = &vibd; - vertex_input.vertexAttributeDescriptionCount = COUNTOF(attribs); - vertex_input.pVertexAttributeDescriptions = attribs; - - VkPipelineInputAssemblyStateCreateInfo input_assembly = {0}; - input_assembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; - input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - - VkViewport viewport = { - .x = 0.f, .y = 0.f, - .width = (float)a_app_state->width, .height = (float)a_app_state->height, - .minDepth = 0.f, .maxDepth = 1.f - }; - VkRect2D scissor = { - .offset = {0}, - .extent = {a_app_state->width, a_app_state->height} - }; - VkPipelineViewportStateCreateInfo viewport_state = {0}; - viewport_state.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; - viewport_state.viewportCount = 1; - viewport_state.scissorCount = 1; - viewport_state.pViewports = &viewport; - viewport_state.pScissors = &scissor; - - VkPipelineRasterizationStateCreateInfo raster_state = {0}; - raster_state.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; - raster_state.polygonMode = VK_POLYGON_MODE_FILL; - raster_state.cullMode = VK_CULL_MODE_NONE; - raster_state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; - raster_state.lineWidth = 1.f; - - VkPipelineMultisampleStateCreateInfo multi_state = {0}; - multi_state.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; - multi_state.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - - VkPipelineColorBlendAttachmentState blend_attachment = {0}; - blend_attachment.blendEnable = VK_FALSE; - blend_attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; - - VkPipelineColorBlendStateCreateInfo color_blend = {0}; - color_blend.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; - color_blend.attachmentCount = 1; - color_blend.pAttachments = &blend_attachment; - - VkGraphicsPipelineCreateInfo gpci = {0}; - gpci.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; - gpci.stageCount = COUNTOF(shader_stages); - gpci.pStages = shader_stages; - gpci.pVertexInputState = &vertex_input; - gpci.pInputAssemblyState = &input_assembly; - gpci.pViewportState = &viewport_state; - gpci.pRasterizationState = &raster_state; - gpci.pMultisampleState = &multi_state; - gpci.pColorBlendState = &color_blend; - gpci.layout = g.pipeline_layout; - gpci.renderPass = g.render_pass; - gpci.subpass = 0; - AVK_CHECK_RESULT(vkCreateGraphicsPipelines(a_vk.dev, NULL, 1, &gpci, NULL, &g.pipeline)); + VkRayTracingPipelineCreateInfoKHR rtci = {.sType = VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR}; + rtci.flags = 0; //VK_PIPELINE_CREATE_RAY_TRACING_SKIP_TRIANGLES_BIT_KHR + rtci.stageCount = COUNTOF(shader_stages); + rtci.pStages = shader_stages; + rtci.groupCount = COUNTOF(groups); + rtci.pGroups = groups; + //rtci.pDynamicState = &pdsci; + rtci.layout = g.pipeline_layout; + rtci.maxPipelineRayRecursionDepth = 1; + + AVK_CHECK_RESULT( + AVK_DEV_FUNC(vkCreateRayTracingPipelinesKHR)(a_vk.dev, VK_NULL_HANDLE, VK_NULL_HANDLE, 1, &rtci, NULL, &g.pipeline)); + ATTO_ASSERT(g.pipeline); + + //FIXME static_assert(COUNTOF(groups) == 1, ""); + //FIXME max(shaderGroupHandleSize, alignment) + const uint32_t sbt_size = g.shader_group_size * rtci.groupCount; + VkBufferCreateInfo bci = {0}; + bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + bci.size = sbt_size; + bci.usage = VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + AVK_CHECK_RESULT(vkCreateBuffer(a_vk.dev, &bci, NULL, &g.sbt_buf)); + + VkMemoryRequirements memreq; + vkGetBufferMemoryRequirements(a_vk.dev, g.sbt_buf, &memreq); + aAppDebugPrintf("memreq: memoryTypeBits=0x%x alignment=%zu size=%zu", memreq.memoryTypeBits, memreq.alignment, memreq.size); + + VkMemoryAllocateInfo mai={0}; + mai.allocationSize = memreq.size; + mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mai.memoryTypeIndex = aVkFindMemoryWithType(memreq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + AVK_CHECK_RESULT(vkAllocateMemory(a_vk.dev, &mai, NULL, &g.devmem)); + AVK_CHECK_RESULT(vkBindBufferMemory(a_vk.dev, g.sbt_buf, g.devmem, 0)); + + void *ptr = NULL; + AVK_CHECK_RESULT(vkMapMemory(a_vk.dev, g.devmem, 0, bci.size, 0, &ptr)); + AVK_CHECK_RESULT( + AVK_DEV_FUNC(vkGetRayTracingShaderGroupHandlesKHR)(a_vk.dev, g.pipeline, 0, rtci.groupCount, sbt_size, ptr)); + vkUnmapMemory(a_vk.dev, g.devmem); } static void swapchainWillDestroy() { - vkDestroyPipeline(a_vk.dev, g.pipeline, NULL); + //vkDestroyPipeline(a_vk.dev, g.pipeline, NULL); for (uint32_t i = 0; i < a_vk.swapchain.num_images; ++i) { vkDestroyFramebuffer(a_vk.dev, g.framebuffers[i], NULL); vkDestroyImageView(a_vk.dev, g.image_views[i], NULL); @@ -239,20 +322,27 @@ static void swapchainCreated() { fbci.renderPass = g.render_pass; fbci.attachmentCount = 1; fbci.pAttachments = g.image_views + i; - fbci.width = a_app_state->width; - fbci.height = a_app_state->height; + fbci.width = a_vk.surface_width; + fbci.height = a_vk.surface_height; fbci.layers = 1; AVK_CHECK_RESULT(vkCreateFramebuffer(a_vk.dev, &fbci, NULL, g.framebuffers + i)); } - - createPipeline(); } +static PFN_vkCmdTraceRaysKHR vkCmdTraceRaysKHR_; static void paint(ATimeUs timestamp, float dt) { - const float t = timestamp / 1e6; + const float t = timestamp / 1e6f; aVkAcquireNextImage(); + const VkImageSubresourceRange subrange = { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }; + VkCommandBufferBeginInfo beginfo = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; beginfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; AVK_CHECK_RESULT(vkBeginCommandBuffer(g.cmdbuf, &beginfo)); @@ -272,8 +362,9 @@ static void paint(ATimeUs timestamp, float dt) { rpbi.renderArea.extent.height = a_app_state->height; rpbi.clearValueCount = 1; rpbi.pClearValues = &clear_value; - vkCmdBeginRenderPass(g.cmdbuf, &rpbi, VK_SUBPASS_CONTENTS_INLINE); + //vkCmdBeginRenderPass(g.cmdbuf, &rpbi, VK_SUBPASS_CONTENTS_INLINE); + #if 0 vkCmdBindPipeline(g.cmdbuf, VK_PIPELINE_BIND_POINT_GRAPHICS, g.pipeline); VkDeviceSize offset = {0}; @@ -287,7 +378,133 @@ static void paint(ATimeUs timestamp, float dt) { /* vkCmdPushConstants(cmdbuf, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(float), &tt); */ /* vkCmdDraw(cmdbuf, 3, 1, 0, 0); */ /* } */ - vkCmdEndRenderPass(g.cmdbuf); + #endif + //vkCmdEndRenderPass(g.cmdbuf); + + { + VkImageMemoryBarrier image_barriers[] = { + { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .image = g.rt_image.image, + .srcAccessMask = 0, + .dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT, + //.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, // VK_ACCESS_SHADER_WRITE_BIT, + .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .subresourceRange = + (VkImageSubresourceRange){ + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }}; + vkCmdPipelineBarrier(g.cmdbuf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR, 0, 0, + //vkCmdPipelineBarrier(g.cmdbuf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, + NULL, 0, NULL, COUNTOF(image_barriers), image_barriers); + } + + //vkCmdClearColorImage(g.cmdbuf, g.rt_image.image, VK_IMAGE_LAYOUT_GENERAL, &clear_value.color, 1, &subrange); + vkCmdBindPipeline(g.cmdbuf, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, g.pipeline); + + VkDescriptorImageInfo dii = { + .sampler = VK_NULL_HANDLE, + .imageView = g.rt_image.view, + .imageLayout = VK_IMAGE_LAYOUT_GENERAL, + }; + VkWriteDescriptorSet wds[] = { + { + .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, + .dstSet = g.desc_set, + .dstBinding = 0, + .dstArrayElement = 0, + .pImageInfo = &dii, + }, + }; + vkUpdateDescriptorSets(a_vk.dev, COUNTOF(wds), wds, 0, NULL); + vkCmdBindDescriptorSets(g.cmdbuf, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, g.pipeline_layout, 0, 1, &g.desc_set, 0, NULL); + + const VkStridedDeviceAddressRegionKHR sbt_null = {0}; + const VkBufferDeviceAddressInfo bdai = {.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, .buffer = g.sbt_buf}; + const VkDeviceAddress sbt_addr = vkGetBufferDeviceAddress(a_vk.dev, &bdai); + const VkStridedDeviceAddressRegionKHR sbt_raygen = {.deviceAddress = sbt_addr, .size = g.shader_group_size, .stride = g.shader_group_size}; + vkCmdTraceRaysKHR_(g.cmdbuf, &sbt_raygen, &sbt_null, &sbt_null, &sbt_null, 1280, 720, 1); + + VkImageMemoryBarrier image_barriers[] = { + { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .image = g.rt_image.image, + .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, + .oldLayout = VK_IMAGE_LAYOUT_GENERAL, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .subresourceRange = + (VkImageSubresourceRange){ + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }, + { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .image = a_vk.swapchain.images[a_vk.swapchain.current_frame_image_index], + .srcAccessMask = 0, + .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .subresourceRange = + (VkImageSubresourceRange){ + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }}; + vkCmdPipelineBarrier(g.cmdbuf, + VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, NULL, 0, NULL, COUNTOF(image_barriers), image_barriers); + + VkImageBlit region = {0}; + region.srcOffsets[1].x = 1280; + region.srcOffsets[1].y = 720; + region.srcOffsets[1].z = 1; + region.dstOffsets[1].x = 1280 < a_app_state->width ? 1280 : a_app_state->width; + region.dstOffsets[1].y = 720 < a_app_state->height ? 720 : a_app_state->height; + region.dstOffsets[1].z = 1; + region.srcSubresource.aspectMask = region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + region.srcSubresource.layerCount = region.dstSubresource.layerCount = 1; + vkCmdBlitImage(g.cmdbuf, g.rt_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + a_vk.swapchain.images[a_vk.swapchain.current_frame_image_index], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion, + VK_FILTER_NEAREST); + + { + VkImageMemoryBarrier image_barriers[] = { + { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .image = a_vk.swapchain.images[a_vk.swapchain.current_frame_image_index], + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + .subresourceRange = + (VkImageSubresourceRange){ + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }}; + vkCmdPipelineBarrier(g.cmdbuf, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, + NULL, 0, NULL, COUNTOF(image_barriers), image_barriers); + } AVK_CHECK_RESULT(vkEndCommandBuffer(g.cmdbuf)); @@ -324,11 +541,10 @@ static void close() { vkDestroyPipelineLayout(a_vk.dev, g.pipeline_layout, NULL); - vkDestroyShaderModule(a_vk.dev, g.module_fragment, NULL); - vkDestroyShaderModule(a_vk.dev, g.module_vertex, NULL); + vkDestroyShaderModule(a_vk.dev, g.modules.raygen, NULL); + vkDestroyBuffer(a_vk.dev, g.sbt_buf, NULL); vkFreeMemory(a_vk.dev, g.devmem, NULL); - vkDestroyBuffer(a_vk.dev, g.vertex_buf, NULL); vkDestroyRenderPass(a_vk.dev, g.render_pass, NULL); aVkDestroySemaphore(g.done); @@ -344,26 +560,61 @@ static void resize(ATimeUs ts, unsigned int old_width, unsigned int old_height) paint(ts, 0); } +void key(ATimeUs ts, AKey key, int down) { + if (key == AK_Esc) + aAppClose(); +} + void attoAppInit(struct AAppProctable *proctable) { proctable->paint = paint; proctable->resize = resize; proctable->close = close; + proctable->key = key; // TODO FIXME VK INIT aVkInitInstance(); aVkCreateSurface(); - aVkInitDevice(); - aVkPokePresentModes(); + + VkPhysicalDeviceBufferDeviceAddressFeaturesEXT pdbdaf = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT, + .bufferDeviceAddress = VK_TRUE, + }; + VkPhysicalDeviceAccelerationStructureFeaturesKHR pdasf = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR, + .accelerationStructure = VK_TRUE, + .pNext = &pdbdaf, + }; + VkPhysicalDeviceRayTracingPipelineFeaturesKHR pdrtf = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR, + .rayTracingPipeline = VK_TRUE, + .pNext = &pdasf, + }; + + aVkInitDevice(&pdrtf); + + g.prop.rt = (VkPhysicalDeviceRayTracingPipelinePropertiesKHR){.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR}; + g.prop.prop2 = (VkPhysicalDeviceProperties2){.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &g.prop.rt}; + vkGetPhysicalDeviceProperties2(a_vk.phys_dev, &g.prop.prop2); + g.shader_group_size = g.prop.rt.shaderGroupHandleSize < g.prop.rt.shaderGroupHandleAlignment + ? g.prop.rt.shaderGroupHandleAlignment + : g.prop.rt.shaderGroupHandleSize; g.done = aVkCreateSemaphore(); createRenderPass(); - createShaders(); - createBuffer(); + createLayouts(); + //createBuffer(); createCommandPool(); + aVkPokePresentModes(); aVkCreateSwapchain(a_app_state->width, a_app_state->height); swapchainCreated(); + vkCmdTraceRaysKHR_ = AVK_DEV_FUNC(vkCmdTraceRaysKHR); + g.rt_image = createImage(1280, 720, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL, + VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT); + + createPipeline(); + VkFenceCreateInfo fci = {0}; fci.flags = 0; fci.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; diff --git a/include/atto/worobushek.h b/include/atto/worobushek.h index 546c403..d9652cf 100644 --- a/include/atto/worobushek.h +++ b/include/atto/worobushek.h @@ -9,6 +9,7 @@ #include "atto/app.h" +//TODO #define VK_NO_PROTOTYPES #include #include @@ -22,6 +23,10 @@ VK_VERSION_MAJOR(v), \ VK_VERSION_MINOR(v), \ VK_VERSION_PATCH(v) + +#ifndef AVK_VK_VERSION +#define AVK_VK_VERSION VK_MAKE_VERSION(1, 0, 0); +#endif #define AVK_CHECK_RESULT(res) do { \ const VkResult result = res; \ @@ -45,6 +50,7 @@ struct AVkSwapchain { struct AVkState { VkInstance inst; VkSurfaceKHR surf; + int surface_width, surface_height; VkPhysicalDevice phys_dev; VkPhysicalDeviceMemoryProperties mem_props; @@ -71,8 +77,19 @@ void aVkAcquireNextImage(); void aVkDestroy(); void aVkDestroySwapchain(); +void* aVkLoadDeviceFunction(const char *name); +void* aVkLoadInstanceFunction(const char *name); +#define AVK_DEV_FUNC(name) ((PFN_##name)aVkLoadDeviceFunction(#name)) +#define AVK_INST_FUNC(name) ((PFN_##name)aVkLoadInstanceFunction(#name)) + #if defined(ATTO_VK_IMPLEMENT) static const char *instance_exts[] = { +#ifdef _DEBUG + VK_EXT_DEBUG_UTILS_EXTENSION_NAME, +#endif +#ifdef ATTO_VK_INSTANCE_EXTENSIONS + ATTO_VK_INSTANCE_EXTENSIONS +#endif VK_KHR_SURFACE_EXTENSION_NAME, #ifdef ATTO_PLATFORM_WINDOWS VK_KHR_WIN32_SURFACE_EXTENSION_NAME, @@ -83,6 +100,40 @@ static const char *instance_exts[] = { struct AVkState a_vk; +void *aVkLoadDeviceFunction(const char *name) { + void *ret = vkGetDeviceProcAddr(a_vk.dev, name); + aAppDebugPrintf("%s = %p", name, ret); + if (!ret) { + aAppDebugPrintf("Cannot load device function %s", name); + aAppTerminate(-1); + } + return ret; +} + +void *aVkLoadInstanceFunction(const char *name) { + void *ret = vkGetInstanceProcAddr(a_vk.inst, name); + aAppDebugPrintf("%s = %p", name, ret); + if (!ret) { + aAppDebugPrintf("Cannot load instance function %s", name); + aAppTerminate(-1); + } + return ret; +} + +#ifdef _DEBUG +VkBool32 debugCallback( + VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, + VkDebugUtilsMessageTypeFlagsEXT messageTypes, + const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, + void *pUserData) { + if (messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) { + aAppDebugPrintf("%s", pCallbackData->pMessage); + __debugbreak(); + } + return VK_FALSE; +} +#endif + void aVkInitInstance() { uint32_t version = 0; AVK_CHECK_RESULT(vkEnumerateInstanceVersion(&version)); @@ -91,7 +142,7 @@ void aVkInitInstance() { VkApplicationInfo ai; ai.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; ai.pNext = NULL; - ai.apiVersion = VK_MAKE_VERSION(1, 0, 0); + ai.apiVersion = AVK_VK_VERSION; ai.applicationVersion = 0; ai.engineVersion = 0; ai.pApplicationName = "LOL"; @@ -103,20 +154,30 @@ void aVkInitInstance() { #endif }; - VkInstanceCreateInfo vici; - vici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; - vici.pNext = NULL; + VkInstanceCreateInfo vici = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; vici.enabledLayerCount = COUNTOF(layers); - vici.flags = 0; vici.ppEnabledLayerNames = layers; vici.enabledExtensionCount = COUNTOF(instance_exts); vici.ppEnabledExtensionNames = instance_exts; vici.pApplicationInfo = &ai; AVK_CHECK_RESULT(vkCreateInstance(&vici, NULL, &a_vk.inst)); + //PFN_vkCreateRayTracingPipelinesKHR fn = AVK_INST_FUNC(vkCreateRayTracingPipelinesKHR); + //fn(NULL, VK_NULL_HANDLE, VK_NULL_HANDLE, 0, NULL, NULL, NULL); + +#ifdef _DEBUG + VkDebugUtilsMessengerCreateInfoEXT dumcie = { + .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, + .messageSeverity = 0x1111, //:vovka: VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT, + .messageType = 0x07, + .pfnUserCallback = debugCallback, + }; + VkDebugUtilsMessengerEXT msg; + AVK_CHECK_RESULT(AVK_INST_FUNC(vkCreateDebugUtilsMessengerEXT)(a_vk.inst, &dumcie, NULL, &msg)); +#endif } -void aVkInitDevice() { +void aVkInitDevice(const void* device_create_info_chain) { // Get only the first device uint32_t num_devices = 1; vkEnumeratePhysicalDevices(a_vk.inst, &num_devices, &a_vk.phys_dev); @@ -159,11 +220,14 @@ void aVkInitDevice() { }; const char* devex[] = { - VK_KHR_SWAPCHAIN_EXTENSION_NAME + VK_KHR_SWAPCHAIN_EXTENSION_NAME, + #ifdef ATTO_VK_DEVICE_EXTENSIONS + ATTO_VK_DEVICE_EXTENSIONS + #endif }; VkDeviceCreateInfo create_info = { .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, - .pNext = NULL, + .pNext = device_create_info_chain, .flags = 0, .queueCreateInfoCount = 1, .pQueueCreateInfos = &queue_info, @@ -182,6 +246,12 @@ void aVkInitDevice() { } void aVkCreateSwapchain(int w, int h) { + VkSurfaceCapabilitiesKHR scap; + AVK_CHECK_RESULT(AVK_INST_FUNC(vkGetPhysicalDeviceSurfaceCapabilitiesKHR)(a_vk.phys_dev, a_vk.surf, &scap)); + //AVK_CHECK_RESULT(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(a_vk.phys_dev, a_vk.surf, &scap)); + a_vk.surface_width = scap.currentExtent.width; + a_vk.surface_height = scap.currentExtent.height; + struct AVkSwapchain* sw = &a_vk.swapchain; sw->info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; sw->info.pNext = NULL; @@ -189,10 +259,10 @@ void aVkCreateSwapchain(int w, int h) { sw->info.minImageCount = 5; // TODO get from caps sw->info.imageFormat = VK_FORMAT_B8G8R8A8_SRGB; // TODO get from caps sw->info.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; // TODO get from caps - sw->info.imageExtent.width = w; - sw->info.imageExtent.height = h; + sw->info.imageExtent.width = scap.currentExtent.width; + sw->info.imageExtent.height = scap.currentExtent.height; sw->info.imageArrayLayers = 1; - sw->info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + sw->info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT /* FIXME FOR RT */ | VK_IMAGE_USAGE_TRANSFER_DST_BIT; sw->info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; sw->info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; // TODO get from caps sw->info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; @@ -270,7 +340,7 @@ VkShaderModule loadShaderFromFile(const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) { perror(filename); - exit(1); + aAppTerminate(1); } fseek(f, 0, SEEK_END); const size_t size = ftell(f); @@ -282,7 +352,7 @@ VkShaderModule loadShaderFromFile(const char *filename) { uint32_t *buf = malloc(4 * ((size+3)/4)); if (size != fread(buf, 1, size, f)) { fprintf(stderr, "Cannot read the entire file %s\n", filename); - exit(1); + aAppTerminate(1); } VkShaderModuleCreateInfo smci = {0}; @@ -293,7 +363,7 @@ VkShaderModule loadShaderFromFile(const char *filename) { const VkResult res = vkCreateShaderModule(a_vk.dev, &smci, NULL, &shader); if (VK_SUCCESS != res) { \ aAppDebugPrintf("%s:%d: failed w/ %d\n", __FILE__, __LINE__, res); \ - exit(1); + aAppTerminate(1); } fclose(f); free(buf); diff --git a/src/app_windows.c b/src/app_windows.c index fd31dd2..6c4aaa8 100644 --- a/src/app_windows.c +++ b/src/app_windows.c @@ -82,6 +82,10 @@ void aAppTerminate(int code) { ExitProcess(code); } +void aAppClose() { + PostQuitMessage(0); +} + int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wndclass; ATimeUs last_paint = 0; From d43d0c44301bca5fe0d98df6be7d23965ac0d8c7 Mon Sep 17 00:00:00 2001 From: Ivan 'provod' Avdeev Date: Wed, 16 Dec 2020 10:20:12 -0800 Subject: [PATCH 10/18] please validation --- examples/CMakeLists.txt | 1 + examples/vk_ray.c | 18 +++++++++++++++++- include/atto/worobushek.h | 10 ++++++++-- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index b05feed..e1e534f 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -42,3 +42,4 @@ function(add_shaders) endfunction() add_shaders(TARGET vk_shaders FILES shader.frag shader.vert ray.rgen) +add_dependencies(vk_ray vk_shaders) diff --git a/examples/vk_ray.c b/examples/vk_ray.c index 38ab4d3..b8d06c8 100644 --- a/examples/vk_ray.c +++ b/examples/vk_ray.c @@ -67,6 +67,13 @@ static struct Image createImage(uint32_t width, uint32_t height, VkFormat format return image; } +void destroyImage(struct Image *img) { + vkDestroyImageView(a_vk.dev, img->view, NULL); + vkDestroyImage(a_vk.dev, img->image, NULL); + vkFreeMemory(a_vk.dev, img->devmem, NULL); + *img = (struct Image){0}; +} + static struct { struct { VkPhysicalDeviceProperties2 prop2; @@ -536,11 +543,18 @@ static void paint(ATimeUs timestamp, float dt) { } static void close() { + vkDeviceWaitIdle(a_vk.dev); + + swapchainWillDestroy(); + destroyImage(&g.rt_image); + vkFreeCommandBuffers(a_vk.dev, g.cmdpool, 1, &g.cmdbuf); vkDestroyCommandPool(a_vk.dev, g.cmdpool, NULL); + vkDestroyPipeline(a_vk.dev, g.pipeline, NULL); + vkDestroyDescriptorSetLayout(a_vk.dev, g.desc_layout, NULL); + vkDestroyDescriptorPool(a_vk.dev, g.desc_pool, NULL); vkDestroyPipelineLayout(a_vk.dev, g.pipeline_layout, NULL); - vkDestroyShaderModule(a_vk.dev, g.modules.raygen, NULL); vkDestroyBuffer(a_vk.dev, g.sbt_buf, NULL); @@ -550,6 +564,8 @@ static void close() { aVkDestroySemaphore(g.done); vkDestroyFence(a_vk.dev, g.fence, NULL); + aVkDestroySwapchain(); + aVkDestroy(); } diff --git a/include/atto/worobushek.h b/include/atto/worobushek.h index d9652cf..e0c97ee 100644 --- a/include/atto/worobushek.h +++ b/include/atto/worobushek.h @@ -60,6 +60,10 @@ struct AVkState { VkQueue main_queue; struct AVkSwapchain swapchain; + +#ifdef _DEBUG + VkDebugUtilsMessengerEXT debug_messenger; +#endif }; extern struct AVkState a_vk; @@ -172,8 +176,7 @@ void aVkInitInstance() { .messageType = 0x07, .pfnUserCallback = debugCallback, }; - VkDebugUtilsMessengerEXT msg; - AVK_CHECK_RESULT(AVK_INST_FUNC(vkCreateDebugUtilsMessengerEXT)(a_vk.inst, &dumcie, NULL, &msg)); + AVK_CHECK_RESULT(AVK_INST_FUNC(vkCreateDebugUtilsMessengerEXT)(a_vk.inst, &dumcie, NULL, &a_vk.debug_messenger)); #endif } @@ -315,6 +318,9 @@ void aVkDestroy() { vkDestroySurfaceKHR(a_vk.inst, a_vk.surf, NULL); aVkDestroySemaphore(a_vk.swapchain.image_available); vkDestroyDevice(a_vk.dev, NULL); +#ifdef _DEBUG + AVK_INST_FUNC(vkDestroyDebugUtilsMessengerEXT)(a_vk.inst, a_vk.debug_messenger, NULL); +#endif vkDestroyInstance(a_vk.inst, NULL); } From b919839668d5522413dbeb1b176c30f686acaaf0 Mon Sep 17 00:00:00 2001 From: Ivan 'provod' Avdeev Date: Mon, 21 Dec 2020 10:08:01 -0800 Subject: [PATCH 11/18] build acceleration structures; but don't use them yet --- examples/ray.rgen | 90 ++++++++++- examples/vk_ray.c | 331 +++++++++++++++++++++++++------------- include/atto/worobushek.h | 68 +++++++- 3 files changed, 374 insertions(+), 115 deletions(-) diff --git a/examples/ray.rgen b/examples/ray.rgen index 3eea0f1..4847271 100644 --- a/examples/ray.rgen +++ b/examples/ray.rgen @@ -1,14 +1,98 @@ #version 460 #extension GL_EXT_ray_tracing : require -//layout(binding = 0, set = 0, rgba32f) uniform image2D image; layout(binding = 0, set = 0, rgba8) uniform image2D image; +layout(binding = 1, set = 0) uniform accelerationStructureEXT tlas; + +struct RayResult { + vec4 pl; + vec3 n; +}; + +layout(location = 0) rayPayloadEXT RayResult ray_result; + +float h(float f){return fract(sin(f)*38572.5432);} +float h(vec2 f){return h(dot(f,vec2(37.,17.)));} +float n(vec2 f){vec2 F=floor(f);f=f-F;f*=f*(3.-2.*f); +return mix( + mix(h(F),h(F+vec2(1.,0.)),f.x), + mix(h(F+vec2(0.,1.)),h(F+vec2(1.,1.)),f.x), +f.y); +} + +float kappa(vec3 p) { + float d = p.y - .3 * n(p.xz*2.); + p.y -= 1.; + d = min(d, length(p) - 1.); + return d; +} + +vec3 wn(vec3 p) { + return normalize(vec3( + kappa(p+vec3(.01,0.,0.)), + kappa(p+vec3(0.,.01,0.)), + kappa(p+vec3(0.,0.,.01)) + )-kappa(p)); +} + +float tr(vec3 O, vec3 D, float l, float L) { + for(int i=0;i<200;++i){ + float d=kappa(O+D*l); + l+=d; + if(d<.001*l||l>L)break; + } + return l; +} void main() { //const vec2 pixelCenter = vec2(gl_LaunchIDEXT.xy) + vec2(0.5); //const vec2 inUV = pixelCenter / vec2(gl_LaunchSizeEXT.xy); + + vec2 uv = gl_LaunchIDEXT.xy / vec2(1280., 720.) * 2. - 1.; + uv.x *= 1280. / 720.; + uv.y=-uv.y; + + vec3 C = vec3(0.); + + vec3 ld=normalize(vec3(1.)); + vec3 O=vec3(0., 1., 3.), D=normalize(vec3(uv, -1.)); + + vec3 kc = vec3(1.); + for(float r=0.;r<4.;++r) { + float L=20.,l=tr(O,D,0.,L); + + /* + traceRayEXT(tlas, gl_RayFlagsOpaqueEXT, 0., 0xff, 0, 0, 0, + O, 0., D, L, 0 + ); + + float rl = ray_result.pl.w; + + if (rl < L && rl < l) { + C += kc * fract(abs(ray_result.pl.xyz)); + break; + } + */ + + if (ldevmem); + vkDestroyBuffer(a_vk.dev, buf->buffer, NULL); + vkFreeMemory(a_vk.dev, buf->devmem, NULL); + *buf = (struct Buffer){0}; +} + +VkDeviceAddress getBufferDeviceAddress(VkBuffer buffer) { + const VkBufferDeviceAddressInfo bdai = {.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, .buffer = buffer}; + return vkGetBufferDeviceAddress(a_vk.dev, &bdai); +} + +struct Accel { + struct Buffer buffer; + VkAccelerationStructureKHR handle; +}; + static struct { struct { VkPhysicalDeviceProperties2 prop2; @@ -94,49 +138,70 @@ static struct { VkDescriptorSet desc_set; VkImageView *image_views; - VkFramebuffer *framebuffers; VkPipeline pipeline; struct Image rt_image; - VkDeviceMemory devmem; - VkBuffer sbt_buf; - //VkBuffer vertex_buf; + struct Buffer sbt_buf; + struct Accel blas, tlas; VkCommandPool cmdpool; VkCommandBuffer cmdbuf; } g; -static void createRenderPass() { - VkAttachmentDescription attachment = {0}; - attachment.format = VK_FORMAT_B8G8R8A8_SRGB;// FIXME too early a_vk.swapchain.info.imageFormat; - attachment.samples = VK_SAMPLE_COUNT_1_BIT; - //attachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - //attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; - - VkAttachmentReference color_attachment = {0}; - color_attachment.attachment = 0; - color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - - VkSubpassDescription subdesc = {0}; - subdesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - subdesc.colorAttachmentCount = 1; - subdesc.pColorAttachments = &color_attachment; - - VkRenderPassCreateInfo rpci = {0}; - rpci.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; - rpci.attachmentCount = 1; - rpci.pAttachments = &attachment; - rpci.subpassCount = 1; - rpci.pSubpasses = &subdesc; - AVK_CHECK_RESULT(vkCreateRenderPass(a_vk.dev, &rpci, NULL, &g.render_pass)); +struct Accel createAccelerationStructure(const VkAccelerationStructureGeometryKHR *geoms, const uint32_t *max_prim_counts, const VkAccelerationStructureBuildRangeInfoKHR **build_ranges, uint32_t n_geoms, VkAccelerationStructureTypeKHR type) { + struct Accel accel; + VkAccelerationStructureBuildGeometryInfoKHR build_info = { + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR, + .type = type, + .flags = VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR, + .mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR, + .geometryCount = n_geoms, + .pGeometries = geoms, + }; + + VkAccelerationStructureBuildSizesInfoKHR build_size = { + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR}; + AVK_DEV_FUNC(vkGetAccelerationStructureBuildSizesKHR)( + a_vk.dev, VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, &build_info, max_prim_counts, &build_size); + + aAppDebugPrintf( + "AS build size: %d, scratch size: %d", build_size.accelerationStructureSize, build_size.buildScratchSize); + + accel.buffer = createBuffer(build_size.accelerationStructureSize, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); + struct Buffer scratch_buffer = createBuffer(build_size.buildScratchSize, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); + + const VkAccelerationStructureCreateInfoKHR asci = { + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR, + .buffer = accel.buffer.buffer, + .size = accel.buffer.size, + .type = type, + }; + AVK_CHECK_RESULT(AVK_DEV_FUNC(vkCreateAccelerationStructureKHR)(a_vk.dev, &asci, NULL, &accel.handle)); + + build_info.dstAccelerationStructure = accel.handle; + build_info.scratchData.deviceAddress = getBufferDeviceAddress(scratch_buffer.buffer); + + VkCommandBufferBeginInfo beginfo = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + beginfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + AVK_CHECK_RESULT(vkBeginCommandBuffer(g.cmdbuf, &beginfo)); + AVK_DEV_FUNC(vkCmdBuildAccelerationStructuresKHR)(g.cmdbuf, 1, &build_info, build_ranges); + AVK_CHECK_RESULT(vkEndCommandBuffer(g.cmdbuf)); + + VkSubmitInfo subinfo = { + .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, + .commandBufferCount = 1, + .pCommandBuffers = &g.cmdbuf, + }; + AVK_CHECK_RESULT(vkQueueSubmit(a_vk.main_queue, 1, &subinfo, NULL)); + AVK_CHECK_RESULT(vkQueueWaitIdle(a_vk.main_queue)); + + return accel; } +//void destroyAccelerationStructure() {} + static void createLayouts() { VkDescriptorSetLayoutBinding bindings[] = { @@ -146,11 +211,12 @@ static void createLayouts() { .descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR, }, - /*{.binding = 1, + { + .binding = 1, .descriptorType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, .descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR, - },*/ + }, }; VkDescriptorSetLayoutCreateInfo dslci = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .bindingCount = COUNTOF(bindings), .pBindings = bindings, }; @@ -172,7 +238,10 @@ static void createLayouts() { // plci.pPushConstantRanges = &push_const; AVK_CHECK_RESULT(vkCreatePipelineLayout(a_vk.dev, &plci, NULL, &g.pipeline_layout)); - VkDescriptorPoolSize pools[] = { {.type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .descriptorCount = 1},}; + VkDescriptorPoolSize pools[] = { + {.type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .descriptorCount = 1}, + {.type = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, .descriptorCount = 1}, + }; VkDescriptorPoolCreateInfo dpci = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, @@ -191,37 +260,6 @@ static void createLayouts() { g.modules.raygen = loadShaderFromFile("ray.rgen.spv"); } -//static const struct Vertex vertices[] = { -// {1.f, 0.f, 255, 0, 0}, -// {-.5f, .866f, 255, 255, 0}, -// {-.5f, -.866f, 255, 0, 255}, -//}; -// -//static void createBuffer() { -// VkBufferCreateInfo bci = {0}; -// bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; -// bci.size = sizeof(vertices); -// bci.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; -// bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE; -// AVK_CHECK_RESULT(vkCreateBuffer(a_vk.dev, &bci, NULL, &g.vertex_buf)); -// -// VkMemoryRequirements memreq; -// vkGetBufferMemoryRequirements(a_vk.dev, g.vertex_buf, &memreq); -// aAppDebugPrintf("memreq: memoryTypeBits=0x%x alignment=%zu size=%zu", memreq.memoryTypeBits, memreq.alignment, memreq.size); -// -// VkMemoryAllocateInfo mai={0}; -// mai.allocationSize = memreq.size; -// mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; -// mai.memoryTypeIndex = aVkFindMemoryWithType(memreq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); -// AVK_CHECK_RESULT(vkAllocateMemory(a_vk.dev, &mai, NULL, &g.devmem)); -// AVK_CHECK_RESULT(vkBindBufferMemory(a_vk.dev, g.vertex_buf, g.devmem, 0)); -// -// void *ptr = NULL; -// AVK_CHECK_RESULT(vkMapMemory(a_vk.dev, g.devmem, 0, bci.size, 0, &ptr)); -// memcpy(ptr, vertices, sizeof(vertices)); -// vkUnmapMemory(a_vk.dev, g.devmem); -//} - static void createCommandPool() { VkCommandPoolCreateInfo cpci = {0}; cpci.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; @@ -278,35 +316,94 @@ static void createPipeline() { //FIXME static_assert(COUNTOF(groups) == 1, ""); //FIXME max(shaderGroupHandleSize, alignment) const uint32_t sbt_size = g.shader_group_size * rtci.groupCount; - VkBufferCreateInfo bci = {0}; - bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - bci.size = sbt_size; - bci.usage = VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - AVK_CHECK_RESULT(vkCreateBuffer(a_vk.dev, &bci, NULL, &g.sbt_buf)); + g.sbt_buf = + createBuffer(sbt_size, VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); + AVK_CHECK_RESULT( + AVK_DEV_FUNC(vkGetRayTracingShaderGroupHandlesKHR)(a_vk.dev, g.pipeline, 0, rtci.groupCount, sbt_size, g.sbt_buf.data)); +} - VkMemoryRequirements memreq; - vkGetBufferMemoryRequirements(a_vk.dev, g.sbt_buf, &memreq); - aAppDebugPrintf("memreq: memoryTypeBits=0x%x alignment=%zu size=%zu", memreq.memoryTypeBits, memreq.alignment, memreq.size); +VkDeviceAddress getASAddress(VkAccelerationStructureKHR as) { + VkAccelerationStructureDeviceAddressInfoKHR asdai = { + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR, + .accelerationStructure = as, + }; + return AVK_DEV_FUNC(vkGetAccelerationStructureDeviceAddressKHR)(a_vk.dev, &asdai); +} - VkMemoryAllocateInfo mai={0}; - mai.allocationSize = memreq.size; - mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - mai.memoryTypeIndex = aVkFindMemoryWithType(memreq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - AVK_CHECK_RESULT(vkAllocateMemory(a_vk.dev, &mai, NULL, &g.devmem)); - AVK_CHECK_RESULT(vkBindBufferMemory(a_vk.dev, g.sbt_buf, g.devmem, 0)); +void createAccelerationStructures() { + const VkAabbPositionsKHR aabbox= { + -1, -1, -1, + 1, 1, 1, + }; - void *ptr = NULL; - AVK_CHECK_RESULT(vkMapMemory(a_vk.dev, g.devmem, 0, bci.size, 0, &ptr)); - AVK_CHECK_RESULT( - AVK_DEV_FUNC(vkGetRayTracingShaderGroupHandlesKHR)(a_vk.dev, g.pipeline, 0, rtci.groupCount, sbt_size, ptr)); - vkUnmapMemory(a_vk.dev, g.devmem); + struct Buffer geom_buffer = createBuffer(sizeof(aabbox), + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR); + memcpy(geom_buffer.data, &aabbox, sizeof(aabbox)); + + const VkAccelerationStructureGeometryKHR geom[] = { + { + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR, + //.flags = VK_GEOMETRY_OPAQUE_BIT, + .geometryType = VK_GEOMETRY_TYPE_AABBS_KHR, + .geometry.aabbs = + (VkAccelerationStructureGeometryAabbsDataKHR){ + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_AABBS_DATA_KHR, + .data.deviceAddress = getBufferDeviceAddress(geom_buffer.buffer), + .stride = sizeof(VkAabbPositionsKHR), + }, + }, + }; + + const uint32_t max_prim_counts[COUNTOF(geom)] = {1}; + const VkAccelerationStructureBuildRangeInfoKHR build_range = { + .primitiveCount = 1, + }; + const VkAccelerationStructureBuildRangeInfoKHR *build_ranges[] = {&build_range}; + g.blas = createAccelerationStructure( + geom, max_prim_counts, build_ranges, COUNTOF(geom), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); + + const VkAccelerationStructureInstanceKHR inst = { + .transform = (VkTransformMatrixKHR){1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}, + .instanceCustomIndex = 0, + .mask = 0xff, + .instanceShaderBindingTableRecordOffset = 0, + .flags = 0, + .accelerationStructureReference = getASAddress(g.blas.handle), + }; + + struct Buffer tl_geom_buffer = createBuffer(sizeof(inst), + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR); + memcpy(tl_geom_buffer.data, &inst, sizeof(inst)); + + const VkAccelerationStructureGeometryKHR tl_geom[] = { + { + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR, + //.flags = VK_GEOMETRY_OPAQUE_BIT, + .geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR, + .geometry.instances = + (VkAccelerationStructureGeometryInstancesDataKHR){ + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR, + .data.deviceAddress = getBufferDeviceAddress(tl_geom_buffer.buffer), + .arrayOfPointers = VK_FALSE, + }, + }, + }; + + const uint32_t tl_max_prim_counts[COUNTOF(tl_geom)] = {1}; + const VkAccelerationStructureBuildRangeInfoKHR tl_build_range = { + .primitiveCount = 1, + }; + const VkAccelerationStructureBuildRangeInfoKHR *tl_build_ranges[] = {&tl_build_range}; + g.tlas = createAccelerationStructure( + tl_geom, tl_max_prim_counts, tl_build_ranges, COUNTOF(tl_geom), VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR); } static void swapchainWillDestroy() { //vkDestroyPipeline(a_vk.dev, g.pipeline, NULL); for (uint32_t i = 0; i < a_vk.swapchain.num_images; ++i) { - vkDestroyFramebuffer(a_vk.dev, g.framebuffers[i], NULL); + //vkDestroyFramebuffer(a_vk.dev, g.framebuffers[i], NULL); vkDestroyImageView(a_vk.dev, g.image_views[i], NULL); } } @@ -314,7 +411,7 @@ static void swapchainWillDestroy() { static void swapchainCreated() { const uint32_t num_images = a_vk.swapchain.num_images; g.image_views = malloc(num_images * sizeof(VkImageView)); - g.framebuffers = malloc(num_images * sizeof(VkFramebuffer)); + //g.framebuffers = malloc(num_images * sizeof(VkFramebuffer)); for (uint32_t i = 0; i < num_images; ++i) { VkImageViewCreateInfo ivci = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO }; ivci.viewType = VK_IMAGE_VIEW_TYPE_2D; @@ -325,14 +422,14 @@ static void swapchainCreated() { ivci.subresourceRange.layerCount = 1; AVK_CHECK_RESULT(vkCreateImageView(a_vk.dev, &ivci, NULL, g.image_views + i)); - VkFramebufferCreateInfo fbci = {.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; - fbci.renderPass = g.render_pass; - fbci.attachmentCount = 1; - fbci.pAttachments = g.image_views + i; - fbci.width = a_vk.surface_width; - fbci.height = a_vk.surface_height; - fbci.layers = 1; - AVK_CHECK_RESULT(vkCreateFramebuffer(a_vk.dev, &fbci, NULL, g.framebuffers + i)); + //VkFramebufferCreateInfo fbci = {.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; + //fbci.renderPass = g.render_pass; + //fbci.attachmentCount = 1; + //fbci.pAttachments = g.image_views + i; + //fbci.width = a_vk.surface_width; + //fbci.height = a_vk.surface_height; + //fbci.layers = 1; + //AVK_CHECK_RESULT(vkCreateFramebuffer(a_vk.dev, &fbci, NULL, g.framebuffers + i)); } } @@ -354,6 +451,7 @@ static void paint(ATimeUs timestamp, float dt) { beginfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; AVK_CHECK_RESULT(vkBeginCommandBuffer(g.cmdbuf, &beginfo)); + #if 0 VkClearValue clear_value = {0}; clear_value.color.float32[0] = .5f + .5f * sinf(t); clear_value.color.float32[1] = .5f + .5f * sinf(t*3); @@ -371,7 +469,6 @@ static void paint(ATimeUs timestamp, float dt) { rpbi.pClearValues = &clear_value; //vkCmdBeginRenderPass(g.cmdbuf, &rpbi, VK_SUBPASS_CONTENTS_INLINE); - #if 0 vkCmdBindPipeline(g.cmdbuf, VK_PIPELINE_BIND_POINT_GRAPHICS, g.pipeline); VkDeviceSize offset = {0}; @@ -415,11 +512,16 @@ static void paint(ATimeUs timestamp, float dt) { //vkCmdClearColorImage(g.cmdbuf, g.rt_image.image, VK_IMAGE_LAYOUT_GENERAL, &clear_value.color, 1, &subrange); vkCmdBindPipeline(g.cmdbuf, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, g.pipeline); - VkDescriptorImageInfo dii = { + const VkDescriptorImageInfo dii = { .sampler = VK_NULL_HANDLE, .imageView = g.rt_image.view, .imageLayout = VK_IMAGE_LAYOUT_GENERAL, }; + const VkWriteDescriptorSetAccelerationStructureKHR wdsas = { + .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR, + .accelerationStructureCount = 1, + .pAccelerationStructures = &g.tlas.handle, + }; VkWriteDescriptorSet wds[] = { { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, @@ -430,13 +532,22 @@ static void paint(ATimeUs timestamp, float dt) { .dstArrayElement = 0, .pImageInfo = &dii, }, + { + .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, + .dstSet = g.desc_set, + .dstBinding = 1, + .dstArrayElement = 0, + .pNext = &wdsas, + }, }; + vkUpdateDescriptorSets(a_vk.dev, COUNTOF(wds), wds, 0, NULL); vkCmdBindDescriptorSets(g.cmdbuf, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, g.pipeline_layout, 0, 1, &g.desc_set, 0, NULL); const VkStridedDeviceAddressRegionKHR sbt_null = {0}; - const VkBufferDeviceAddressInfo bdai = {.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, .buffer = g.sbt_buf}; - const VkDeviceAddress sbt_addr = vkGetBufferDeviceAddress(a_vk.dev, &bdai); + const VkDeviceAddress sbt_addr = getBufferDeviceAddress(g.sbt_buf.buffer); const VkStridedDeviceAddressRegionKHR sbt_raygen = {.deviceAddress = sbt_addr, .size = g.shader_group_size, .stride = g.shader_group_size}; vkCmdTraceRaysKHR_(g.cmdbuf, &sbt_raygen, &sbt_null, &sbt_null, &sbt_null, 1280, 720, 1); @@ -557,8 +668,8 @@ static void close() { vkDestroyPipelineLayout(a_vk.dev, g.pipeline_layout, NULL); vkDestroyShaderModule(a_vk.dev, g.modules.raygen, NULL); - vkDestroyBuffer(a_vk.dev, g.sbt_buf, NULL); - vkFreeMemory(a_vk.dev, g.devmem, NULL); + destroyBuffer(&g.sbt_buf); + //destroyBuffer(&g.blas); vkDestroyRenderPass(a_vk.dev, g.render_pass, NULL); aVkDestroySemaphore(g.done); @@ -598,6 +709,7 @@ void attoAppInit(struct AAppProctable *proctable) { VkPhysicalDeviceAccelerationStructureFeaturesKHR pdasf = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR, .accelerationStructure = VK_TRUE, + // not supported by nv .accelerationStructureHostCommands = VK_TRUE, .pNext = &pdbdaf, }; VkPhysicalDeviceRayTracingPipelineFeaturesKHR pdrtf = { @@ -616,7 +728,7 @@ void attoAppInit(struct AAppProctable *proctable) { : g.prop.rt.shaderGroupHandleSize; g.done = aVkCreateSemaphore(); - createRenderPass(); + //createRenderPass(); createLayouts(); //createBuffer(); createCommandPool(); @@ -630,6 +742,7 @@ void attoAppInit(struct AAppProctable *proctable) { VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT); createPipeline(); + createAccelerationStructures(); VkFenceCreateInfo fci = {0}; fci.flags = 0; diff --git a/include/atto/worobushek.h b/include/atto/worobushek.h index e0c97ee..091c1a5 100644 --- a/include/atto/worobushek.h +++ b/include/atto/worobushek.h @@ -28,10 +28,12 @@ #define AVK_VK_VERSION VK_MAKE_VERSION(1, 0, 0); #endif +const char *aVkResultName(VkResult result); + #define AVK_CHECK_RESULT(res) do { \ const VkResult result = res; \ if (result != VK_SUCCESS) { \ - aAppDebugPrintf("VK ERROR @ %s:%d: %s failed with result %d", __FILE__, __LINE__, #res, result); \ + aAppDebugPrintf("VK ERROR @ %s:%d: %s failed with result %s (%d)", __FILE__, __LINE__, #res, aVkResultName(result), result); \ aAppTerminate(-1); \ } \ } while(0) @@ -87,6 +89,51 @@ void* aVkLoadInstanceFunction(const char *name); #define AVK_INST_FUNC(name) ((PFN_##name)aVkLoadInstanceFunction(#name)) #if defined(ATTO_VK_IMPLEMENT) +const char *aVkResultName(VkResult result) { + switch (result) { + case VK_SUCCESS: return "VK_SUCCESS"; + case VK_NOT_READY: return "VK_NOT_READY"; + case VK_TIMEOUT: return "VK_TIMEOUT"; + case VK_EVENT_SET: return "VK_EVENT_SET"; + case VK_EVENT_RESET: return "VK_EVENT_RESET"; + case VK_INCOMPLETE: return "VK_INCOMPLETE"; + case VK_ERROR_OUT_OF_HOST_MEMORY: return "VK_ERROR_OUT_OF_HOST_MEMORY"; + case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "VK_ERROR_OUT_OF_DEVICE_MEMORY"; + case VK_ERROR_INITIALIZATION_FAILED: return "VK_ERROR_INITIALIZATION_FAILED"; + case VK_ERROR_DEVICE_LOST: return "VK_ERROR_DEVICE_LOST"; + case VK_ERROR_MEMORY_MAP_FAILED: return "VK_ERROR_MEMORY_MAP_FAILED"; + case VK_ERROR_LAYER_NOT_PRESENT: return "VK_ERROR_LAYER_NOT_PRESENT"; + case VK_ERROR_EXTENSION_NOT_PRESENT: return "VK_ERROR_EXTENSION_NOT_PRESENT"; + case VK_ERROR_FEATURE_NOT_PRESENT: return "VK_ERROR_FEATURE_NOT_PRESENT"; + case VK_ERROR_INCOMPATIBLE_DRIVER: return "VK_ERROR_INCOMPATIBLE_DRIVER"; + case VK_ERROR_TOO_MANY_OBJECTS: return "VK_ERROR_TOO_MANY_OBJECTS"; + case VK_ERROR_FORMAT_NOT_SUPPORTED: return "VK_ERROR_FORMAT_NOT_SUPPORTED"; + case VK_ERROR_FRAGMENTED_POOL: return "VK_ERROR_FRAGMENTED_POOL"; + case VK_ERROR_UNKNOWN: return "VK_ERROR_UNKNOWN"; + case VK_ERROR_OUT_OF_POOL_MEMORY: return "VK_ERROR_OUT_OF_POOL_MEMORY"; + case VK_ERROR_INVALID_EXTERNAL_HANDLE: return "VK_ERROR_INVALID_EXTERNAL_HANDLE"; + case VK_ERROR_FRAGMENTATION: return "VK_ERROR_FRAGMENTATION"; + case VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS: return "VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS"; + case VK_ERROR_SURFACE_LOST_KHR: return "VK_ERROR_SURFACE_LOST_KHR"; + case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR"; + case VK_SUBOPTIMAL_KHR: return "VK_SUBOPTIMAL_KHR"; + case VK_ERROR_OUT_OF_DATE_KHR: return "VK_ERROR_OUT_OF_DATE_KHR"; + case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR"; + case VK_ERROR_VALIDATION_FAILED_EXT: return "VK_ERROR_VALIDATION_FAILED_EXT"; + case VK_ERROR_INVALID_SHADER_NV: return "VK_ERROR_INVALID_SHADER_NV"; + case VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT: + return "VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT"; + case VK_ERROR_NOT_PERMITTED_EXT: return "VK_ERROR_NOT_PERMITTED_EXT"; + case VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT: return "VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT"; + case VK_THREAD_IDLE_KHR: return "VK_THREAD_IDLE_KHR"; + case VK_THREAD_DONE_KHR: return "VK_THREAD_DONE_KHR"; + case VK_OPERATION_DEFERRED_KHR: return "VK_OPERATION_DEFERRED_KHR"; + case VK_OPERATION_NOT_DEFERRED_KHR: return "VK_OPERATION_NOT_DEFERRED_KHR"; + case VK_PIPELINE_COMPILE_REQUIRED_EXT: return "VK_PIPELINE_COMPILE_REQUIRED_EXT"; + default: return "UNKNOWN"; + } +} + static const char *instance_exts[] = { #ifdef _DEBUG VK_EXT_DEBUG_UTILS_EXTENSION_NAME, @@ -186,8 +233,23 @@ void aVkInitDevice(const void* device_create_info_chain) { vkEnumeratePhysicalDevices(a_vk.inst, &num_devices, &a_vk.phys_dev); uint32_t queue_index = UINT32_MAX; - VkPhysicalDeviceProperties pd; - vkGetPhysicalDeviceProperties(a_vk.phys_dev, &pd); + + VkPhysicalDeviceProperties2 prop2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,}; + vkGetPhysicalDeviceProperties2(a_vk.phys_dev, &prop2); + + VkPhysicalDeviceBufferDeviceAddressFeaturesEXT pdbdaf = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT, + }; + VkPhysicalDeviceAccelerationStructureFeaturesKHR pdasf = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR, + .pNext = &pdbdaf, + }; + VkPhysicalDeviceRayTracingPipelineFeaturesKHR pdrtf = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR, + .pNext = &pdasf, + }; + VkPhysicalDeviceFeatures2 features2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, .pNext = &pdrtf}; + vkGetPhysicalDeviceFeatures2(a_vk.phys_dev, &features2); #define MAX_QUEUE_FAMILIES 8 uint32_t num_queue_families = MAX_QUEUE_FAMILIES; From e28c59d3977c3c6ae233edb5db89b7d74c5b1a74 Mon Sep 17 00:00:00 2001 From: Ivan 'provod' Avdeev Date: Wed, 23 Dec 2020 10:56:54 -0800 Subject: [PATCH 12/18] make RTX actually work yay --- examples/CMakeLists.txt | 2 +- examples/ray.glsl | 7 +++ examples/ray.rchit | 12 ++++ examples/ray.rgen | 94 +++++++++++++++--------------- examples/ray.rint | 24 ++++++++ examples/ray.rmiss | 11 ++++ examples/vk_ray.c | 125 ++++++++++++++++++++++++---------------- 7 files changed, 174 insertions(+), 101 deletions(-) create mode 100644 examples/ray.glsl create mode 100644 examples/ray.rchit create mode 100644 examples/ray.rint create mode 100644 examples/ray.rmiss diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index e1e534f..0a2562d 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -41,5 +41,5 @@ function(add_shaders) add_custom_target(${SHADERS_TARGET} ALL DEPENDS ${SHADERS_DEPS}) endfunction() -add_shaders(TARGET vk_shaders FILES shader.frag shader.vert ray.rgen) +add_shaders(TARGET vk_shaders FILES shader.frag shader.vert ray.rgen ray.rmiss ray.rchit ray.rint) add_dependencies(vk_ray vk_shaders) diff --git a/examples/ray.glsl b/examples/ray.glsl new file mode 100644 index 0000000..d698c67 --- /dev/null +++ b/examples/ray.glsl @@ -0,0 +1,7 @@ +#extension GL_EXT_ray_tracing : require +struct RayResult { + float l; + vec3 p; + vec3 n; +}; + diff --git a/examples/ray.rchit b/examples/ray.rchit new file mode 100644 index 0000000..9100b67 --- /dev/null +++ b/examples/ray.rchit @@ -0,0 +1,12 @@ +#version 460 +#extension GL_GOOGLE_include_directive : enable +#include "ray.glsl" + +//hitAttributeEXT RayResult hres; +layout(location = 0) rayPayloadInEXT RayResult rres; + +void main() { + rres.l = gl_HitTEXT; + rres.p = gl_HitTEXT * gl_WorldRayDirectionEXT + gl_WorldRayOriginEXT; + rres.n = normalize(rres.p); +} diff --git a/examples/ray.rgen b/examples/ray.rgen index 4847271..67fe25d 100644 --- a/examples/ray.rgen +++ b/examples/ray.rgen @@ -1,47 +1,43 @@ #version 460 -#extension GL_EXT_ray_tracing : require +#extension GL_GOOGLE_include_directive : enable +#include "ray.glsl" layout(binding = 0, set = 0, rgba8) uniform image2D image; layout(binding = 1, set = 0) uniform accelerationStructureEXT tlas; -struct RayResult { - vec4 pl; - vec3 n; -}; - -layout(location = 0) rayPayloadEXT RayResult ray_result; +layout(location = 0) rayPayloadEXT RayResult rres; float h(float f){return fract(sin(f)*38572.5432);} float h(vec2 f){return h(dot(f,vec2(37.,17.)));} float n(vec2 f){vec2 F=floor(f);f=f-F;f*=f*(3.-2.*f); return mix( - mix(h(F),h(F+vec2(1.,0.)),f.x), - mix(h(F+vec2(0.,1.)),h(F+vec2(1.,1.)),f.x), + mix(h(F),h(F+vec2(1.,0.)),f.x), + mix(h(F+vec2(0.,1.)),h(F+vec2(1.,1.)),f.x), f.y); } float kappa(vec3 p) { - float d = p.y - .3 * n(p.xz*2.); - p.y -= 1.; - d = min(d, length(p) - 1.); - return d; + float d = p.y - .3 * n(p.xz*2.); + p.y -= 1.; + //d = min(d, length(p) - 1.); + return d; } vec3 wn(vec3 p) { - return normalize(vec3( - kappa(p+vec3(.01,0.,0.)), - kappa(p+vec3(0.,.01,0.)), - kappa(p+vec3(0.,0.,.01)) - )-kappa(p)); + return normalize(vec3( + kappa(p+vec3(.01,0.,0.)), + kappa(p+vec3(0.,.01,0.)), + kappa(p+vec3(0.,0.,.01)) + )-kappa(p)); } float tr(vec3 O, vec3 D, float l, float L) { - for(int i=0;i<200;++i){ + for(int i=0;i<200;++i){ float d=kappa(O+D*l); l+=d; if(d<.001*l||l>L)break; - } - return l; + } + return l; } void main() { @@ -58,41 +54,41 @@ void main() { vec3 O=vec3(0., 1., 3.), D=normalize(vec3(uv, -1.)); vec3 kc = vec3(1.); - for(float r=0.;r<4.;++r) { - float L=20.,l=tr(O,D,0.,L); + for(float r=0.;r<3.;++r) { + vec3 p, n, m_albedo = vec3(1., 0., 1.); + float L=20., l=tr(O,D,0.,L); - /* - traceRayEXT(tlas, gl_RayFlagsOpaqueEXT, 0., 0xff, 0, 0, 0, - O, 0., D, L, 0 + traceRayEXT(tlas, gl_RayFlagsOpaqueEXT, 0xff, 0, 0, 0, + O, 0.001, D, L, 0 ); - float rl = ray_result.pl.w; - - if (rl < L && rl < l) { - C += kc * fract(abs(ray_result.pl.xyz)); - break; - } - */ - - if (l 0.) + reportIntersectionEXT(l, 0); +} diff --git a/examples/ray.rmiss b/examples/ray.rmiss new file mode 100644 index 0000000..2cc9fb2 --- /dev/null +++ b/examples/ray.rmiss @@ -0,0 +1,11 @@ +#version 460 +#extension GL_GOOGLE_include_directive : enable +#include "ray.glsl" + +layout(location = 0) rayPayloadInEXT RayResult rres; + +void main() { + rres.l = 1e6; + rres.p = vec3(1e6); + rres.n = vec3(1., 0., 0.); +} diff --git a/examples/vk_ray.c b/examples/vk_ray.c index 88ef245..84ed65c 100644 --- a/examples/vk_ray.c +++ b/examples/vk_ray.c @@ -132,6 +132,9 @@ static struct { VkPipelineLayout pipeline_layout; struct { VkShaderModule raygen; + VkShaderModule rayintersect; + VkShaderModule raymiss; + VkShaderModule rayclosesthit; } modules; VkDescriptorSetLayout desc_layout; VkDescriptorPool desc_pool; @@ -141,7 +144,7 @@ static struct { VkPipeline pipeline; struct Image rt_image; - struct Buffer sbt_buf; + struct Buffer sbt_buf, geom_buf, tl_geom_buffer; struct Accel blas, tlas; VkCommandPool cmdpool; @@ -197,10 +200,15 @@ struct Accel createAccelerationStructure(const VkAccelerationStructureGeometryKH AVK_CHECK_RESULT(vkQueueSubmit(a_vk.main_queue, 1, &subinfo, NULL)); AVK_CHECK_RESULT(vkQueueWaitIdle(a_vk.main_queue)); + destroyBuffer(&scratch_buffer); + return accel; } -//void destroyAccelerationStructure() {} +void destroyAccelerationStructure(struct Accel *a) { + AVK_DEV_FUNC(vkDestroyAccelerationStructureKHR)(a_vk.dev, a->handle, NULL); + destroyBuffer(&a->buffer); +} static void createLayouts() { @@ -258,6 +266,9 @@ static void createLayouts() { AVK_CHECK_RESULT(vkAllocateDescriptorSets(a_vk.dev, &dsai, &g.desc_set)); g.modules.raygen = loadShaderFromFile("ray.rgen.spv"); + g.modules.raymiss = loadShaderFromFile("ray.rmiss.spv"); + g.modules.rayintersect = loadShaderFromFile("ray.rint.spv"); + g.modules.rayclosesthit = loadShaderFromFile("ray.rchit.spv"); } static void createCommandPool() { @@ -287,20 +298,50 @@ static void createPipeline() { .stage = VK_SHADER_STAGE_RAYGEN_BIT_KHR, .module = g.modules.raygen, .pName = "main", - }, }; + }, { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_MISS_BIT_KHR, + .module = g.modules.raymiss, + .pName = "main", + }, { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR, + .module = g.modules.rayclosesthit, + .pName = "main", + }, { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_INTERSECTION_BIT_KHR, + .module = g.modules.rayintersect, + .pName = "main", + }, + }; VkRayTracingShaderGroupCreateInfoKHR groups[] = {{ .sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR, .type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR, - .generalShader = 0, + .generalShader = 0, // Raygen .closestHitShader = VK_SHADER_UNUSED_KHR, .anyHitShader = VK_SHADER_UNUSED_KHR, .intersectionShader = VK_SHADER_UNUSED_KHR, + }, { + .sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR, + .type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR, + .generalShader = 1, // Miss + .closestHitShader = VK_SHADER_UNUSED_KHR, + .anyHitShader = VK_SHADER_UNUSED_KHR, + .intersectionShader = VK_SHADER_UNUSED_KHR, + }, { // procedural + .sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR, + .type = VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR, + .generalShader = VK_SHADER_UNUSED_KHR, + .closestHitShader = 2, + .anyHitShader = VK_SHADER_UNUSED_KHR, + .intersectionShader = 3, }, }; VkRayTracingPipelineCreateInfoKHR rtci = {.sType = VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR}; - rtci.flags = 0; //VK_PIPELINE_CREATE_RAY_TRACING_SKIP_TRIANGLES_BIT_KHR + //rtci.flags = VK_PIPELINE_CREATE_RAY_TRACING_SKIP_TRIANGLES_BIT_KHR; rtci.stageCount = COUNTOF(shader_stages); rtci.pStages = shader_stages; rtci.groupCount = COUNTOF(groups); @@ -318,8 +359,16 @@ static void createPipeline() { const uint32_t sbt_size = g.shader_group_size * rtci.groupCount; g.sbt_buf = createBuffer(sbt_size, VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); - AVK_CHECK_RESULT( - AVK_DEV_FUNC(vkGetRayTracingShaderGroupHandlesKHR)(a_vk.dev, g.pipeline, 0, rtci.groupCount, sbt_size, g.sbt_buf.data)); + + const uint32_t handles_size = rtci.groupCount * g.prop.rt.shaderGroupHandleSize; + uint8_t *sbt_tmp_buf = malloc(handles_size); + AVK_CHECK_RESULT(AVK_DEV_FUNC(vkGetRayTracingShaderGroupHandlesKHR)( + a_vk.dev, g.pipeline, 0, rtci.groupCount, handles_size, sbt_tmp_buf)); + for (int i = 0; i < (int)rtci.groupCount; ++i) { + memcpy(((uint8_t *)g.sbt_buf.data) + i * g.shader_group_size, sbt_tmp_buf + i * g.prop.rt.shaderGroupHandleSize, + g.prop.rt.shaderGroupHandleSize); + } + free(sbt_tmp_buf); } VkDeviceAddress getASAddress(VkAccelerationStructureKHR as) { @@ -336,10 +385,10 @@ void createAccelerationStructures() { 1, 1, 1, }; - struct Buffer geom_buffer = createBuffer(sizeof(aabbox), + g.geom_buf = createBuffer(sizeof(aabbox), VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR); - memcpy(geom_buffer.data, &aabbox, sizeof(aabbox)); + memcpy(g.geom_buf.data, &aabbox, sizeof(aabbox)); const VkAccelerationStructureGeometryKHR geom[] = { { @@ -349,7 +398,7 @@ void createAccelerationStructures() { .geometry.aabbs = (VkAccelerationStructureGeometryAabbsDataKHR){ .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_AABBS_DATA_KHR, - .data.deviceAddress = getBufferDeviceAddress(geom_buffer.buffer), + .data.deviceAddress = getBufferDeviceAddress(g.geom_buf.buffer), .stride = sizeof(VkAabbPositionsKHR), }, }, @@ -372,10 +421,10 @@ void createAccelerationStructures() { .accelerationStructureReference = getASAddress(g.blas.handle), }; - struct Buffer tl_geom_buffer = createBuffer(sizeof(inst), + g.tl_geom_buffer = createBuffer(sizeof(inst), VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR); - memcpy(tl_geom_buffer.data, &inst, sizeof(inst)); + memcpy(g.tl_geom_buffer.data, &inst, sizeof(inst)); const VkAccelerationStructureGeometryKHR tl_geom[] = { { @@ -385,7 +434,7 @@ void createAccelerationStructures() { .geometry.instances = (VkAccelerationStructureGeometryInstancesDataKHR){ .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR, - .data.deviceAddress = getBufferDeviceAddress(tl_geom_buffer.buffer), + .data.deviceAddress = getBufferDeviceAddress(g.tl_geom_buffer.buffer), .arrayOfPointers = VK_FALSE, }, }, @@ -451,40 +500,6 @@ static void paint(ATimeUs timestamp, float dt) { beginfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; AVK_CHECK_RESULT(vkBeginCommandBuffer(g.cmdbuf, &beginfo)); - #if 0 - VkClearValue clear_value = {0}; - clear_value.color.float32[0] = .5f + .5f * sinf(t); - clear_value.color.float32[1] = .5f + .5f * sinf(t*3); - clear_value.color.float32[2] = .5f + .5f * sinf(t*5); - clear_value.color.float32[3] = 1.f; - /* clear_value.color.uint32[0] = 0xffffffff; */ - /* clear_value.color.uint32[3] = 0xffffffff; */ - VkRenderPassBeginInfo rpbi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; - rpbi.renderPass = g.render_pass; - rpbi.framebuffer = g.framebuffers[a_vk.swapchain.current_frame_image_index]; - rpbi.renderArea.offset.x = rpbi.renderArea.offset.y = 0; - rpbi.renderArea.extent.width = a_app_state->width; - rpbi.renderArea.extent.height = a_app_state->height; - rpbi.clearValueCount = 1; - rpbi.pClearValues = &clear_value; - //vkCmdBeginRenderPass(g.cmdbuf, &rpbi, VK_SUBPASS_CONTENTS_INLINE); - - vkCmdBindPipeline(g.cmdbuf, VK_PIPELINE_BIND_POINT_GRAPHICS, g.pipeline); - - VkDeviceSize offset = {0}; - vkCmdBindVertexBuffers(g.cmdbuf, 0, 1, &g.vertex_buf, &offset); - vkCmdPushConstants(g.cmdbuf, g.pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(float), &t); - vkCmdDraw(g.cmdbuf, 3, 1, 0, 0); - /* const int N = 32; */ - /* for (int i = 0; i < N; ++i) { */ - /* const float it = i / (float)N; */ - /* const float tt = t*(.8+it*.2) + it * ((1. + sin(t*.3))*.15 + .7) * 20.; */ - /* vkCmdPushConstants(cmdbuf, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(float), &tt); */ - /* vkCmdDraw(cmdbuf, 3, 1, 0, 0); */ - /* } */ - #endif - //vkCmdEndRenderPass(g.cmdbuf); - { VkImageMemoryBarrier image_barriers[] = { { @@ -549,7 +564,9 @@ static void paint(ATimeUs timestamp, float dt) { const VkStridedDeviceAddressRegionKHR sbt_null = {0}; const VkDeviceAddress sbt_addr = getBufferDeviceAddress(g.sbt_buf.buffer); const VkStridedDeviceAddressRegionKHR sbt_raygen = {.deviceAddress = sbt_addr, .size = g.shader_group_size, .stride = g.shader_group_size}; - vkCmdTraceRaysKHR_(g.cmdbuf, &sbt_raygen, &sbt_null, &sbt_null, &sbt_null, 1280, 720, 1); + const VkStridedDeviceAddressRegionKHR sbt_raymiss = {.deviceAddress = sbt_addr + g.shader_group_size, .size = g.shader_group_size, .stride = g.shader_group_size}; + const VkStridedDeviceAddressRegionKHR sbt_rayhit = {.deviceAddress = sbt_addr + g.shader_group_size * 2, .size = g.shader_group_size, .stride = g.shader_group_size}; + vkCmdTraceRaysKHR_(g.cmdbuf, &sbt_raygen, &sbt_raymiss, &sbt_rayhit, &sbt_null, 1280, 720, 1); VkImageMemoryBarrier image_barriers[] = { { @@ -667,9 +684,15 @@ static void close() { vkDestroyDescriptorPool(a_vk.dev, g.desc_pool, NULL); vkDestroyPipelineLayout(a_vk.dev, g.pipeline_layout, NULL); vkDestroyShaderModule(a_vk.dev, g.modules.raygen, NULL); + vkDestroyShaderModule(a_vk.dev, g.modules.raymiss, NULL); + vkDestroyShaderModule(a_vk.dev, g.modules.rayclosesthit, NULL); + vkDestroyShaderModule(a_vk.dev, g.modules.rayintersect, NULL); + destroyAccelerationStructure(&g.tlas); + destroyAccelerationStructure(&g.blas); destroyBuffer(&g.sbt_buf); - //destroyBuffer(&g.blas); + destroyBuffer(&g.geom_buf); + destroyBuffer(&g.tl_geom_buffer); vkDestroyRenderPass(a_vk.dev, g.render_pass, NULL); aVkDestroySemaphore(g.done); @@ -723,8 +746,8 @@ void attoAppInit(struct AAppProctable *proctable) { g.prop.rt = (VkPhysicalDeviceRayTracingPipelinePropertiesKHR){.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR}; g.prop.prop2 = (VkPhysicalDeviceProperties2){.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &g.prop.rt}; vkGetPhysicalDeviceProperties2(a_vk.phys_dev, &g.prop.prop2); - g.shader_group_size = g.prop.rt.shaderGroupHandleSize < g.prop.rt.shaderGroupHandleAlignment - ? g.prop.rt.shaderGroupHandleAlignment + g.shader_group_size = g.prop.rt.shaderGroupHandleSize < g.prop.rt.shaderGroupBaseAlignment + ? g.prop.rt.shaderGroupBaseAlignment : g.prop.rt.shaderGroupHandleSize; g.done = aVkCreateSemaphore(); From 5103931b742dc1e31b477ca1ec762b7a068414cb Mon Sep 17 00:00:00 2001 From: Ivan 'provod' Avdeev Date: Wed, 23 Dec 2020 12:52:15 -0800 Subject: [PATCH 13/18] add triangle ray intersections --- examples/CMakeLists.txt | 2 +- examples/ray.rgen | 11 +-- examples/ray_tri.rchit | 19 +++++ examples/vk_ray.c | 178 +++++++++++++++++++++++++++++++--------- 4 files changed, 164 insertions(+), 46 deletions(-) create mode 100644 examples/ray_tri.rchit diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 0a2562d..65bf78b 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -41,5 +41,5 @@ function(add_shaders) add_custom_target(${SHADERS_TARGET} ALL DEPENDS ${SHADERS_DEPS}) endfunction() -add_shaders(TARGET vk_shaders FILES shader.frag shader.vert ray.rgen ray.rmiss ray.rchit ray.rint) +add_shaders(TARGET vk_shaders FILES shader.frag shader.vert ray.rgen ray.rmiss ray.rchit ray.rint ray_tri.rchit) add_dependencies(vk_ray vk_shaders) diff --git a/examples/ray.rgen b/examples/ray.rgen index 67fe25d..8345052 100644 --- a/examples/ray.rgen +++ b/examples/ray.rgen @@ -17,10 +17,7 @@ f.y); } float kappa(vec3 p) { - float d = p.y - .3 * n(p.xz*2.); - p.y -= 1.; - //d = min(d, length(p) - 1.); - return d; + return p.y + 1. - .3 * n(p.xz*2.); } vec3 wn(vec3 p) { @@ -51,7 +48,7 @@ void main() { vec3 C = vec3(0.); vec3 ld=normalize(vec3(1.)); - vec3 O=vec3(0., 1., 3.), D=normalize(vec3(uv, -1.)); + vec3 O=vec3(0., 0., 3.), D=normalize(vec3(uv, -1.)); vec3 kc = vec3(1.); for(float r=0.;r<3.;++r) { @@ -59,7 +56,7 @@ void main() { float L=20., l=tr(O,D,0.,L); traceRayEXT(tlas, gl_RayFlagsOpaqueEXT, 0xff, 0, 0, 0, - O, 0.001, D, L, 0 + O, 0., D, L, 0 ); if (rres.l < L && rres.l < l) { @@ -84,7 +81,7 @@ void main() { c += vec3(.3,.5,.8) * .3 * max(0., n.y); c *= m_albedo; C += kc*c; - O = p + .02*n; + O = p + .01*n; D = normalize(reflect(D,n)); kc *= .7; } diff --git a/examples/ray_tri.rchit b/examples/ray_tri.rchit new file mode 100644 index 0000000..01a671a --- /dev/null +++ b/examples/ray_tri.rchit @@ -0,0 +1,19 @@ +#version 460 +#extension GL_GOOGLE_include_directive : enable +#include "ray.glsl" + +//hitAttributeEXT RayResult hres; +layout(location = 0) rayPayloadInEXT RayResult rres; +layout(binding = 2, set = 0) buffer Vertices { vec3 vertices[]; }; + +void main() { + rres.l = gl_HitTEXT; + rres.p = gl_HitTEXT * gl_WorldRayDirectionEXT + gl_WorldRayOriginEXT; + + const uint vi = gl_PrimitiveID * 3; + vec3 v0 = vertices[vi + 0]; + vec3 v1 = vertices[vi + 1]; + vec3 v2 = vertices[vi + 2]; + + rres.n = normalize(cross(v2-v0, v1-v0)); +} diff --git a/examples/vk_ray.c b/examples/vk_ray.c index 84ed65c..4801bc2 100644 --- a/examples/vk_ray.c +++ b/examples/vk_ray.c @@ -135,6 +135,7 @@ static struct { VkShaderModule rayintersect; VkShaderModule raymiss; VkShaderModule rayclosesthit; + VkShaderModule rayclosesthit_tri; } modules; VkDescriptorSetLayout desc_layout; VkDescriptorPool desc_pool; @@ -144,8 +145,8 @@ static struct { VkPipeline pipeline; struct Image rt_image; - struct Buffer sbt_buf, geom_buf, tl_geom_buffer; - struct Accel blas, tlas; + struct Buffer sbt_buf, aabb_buf, tri_buf, tl_geom_buffer; + struct Accel blas, blas_tri, tlas; VkCommandPool cmdpool; VkCommandBuffer cmdbuf; @@ -211,19 +212,21 @@ void destroyAccelerationStructure(struct Accel *a) { } static void createLayouts() { - - VkDescriptorSetLayoutBinding bindings[] = { - { + VkDescriptorSetLayoutBinding bindings[] = {{ .binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR, - }, - { + }, { .binding = 1, .descriptorType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, .descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR, + }, { + .binding = 2, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR, }, }; @@ -248,6 +251,7 @@ static void createLayouts() { VkDescriptorPoolSize pools[] = { {.type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .descriptorCount = 1}, + {.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, .descriptorCount = 1}, {.type = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, .descriptorCount = 1}, }; @@ -269,6 +273,7 @@ static void createLayouts() { g.modules.raymiss = loadShaderFromFile("ray.rmiss.spv"); g.modules.rayintersect = loadShaderFromFile("ray.rint.spv"); g.modules.rayclosesthit = loadShaderFromFile("ray.rchit.spv"); + g.modules.rayclosesthit_tri = loadShaderFromFile("ray_tri.rchit.spv"); } static void createCommandPool() { @@ -313,6 +318,11 @@ static void createPipeline() { .stage = VK_SHADER_STAGE_INTERSECTION_BIT_KHR, .module = g.modules.rayintersect, .pName = "main", + }, { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR, + .module = g.modules.rayclosesthit_tri, + .pName = "main", }, }; @@ -337,6 +347,13 @@ static void createPipeline() { .closestHitShader = 2, .anyHitShader = VK_SHADER_UNUSED_KHR, .intersectionShader = 3, + }, { // tri + .sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR, + .type = VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR, + .generalShader = VK_SHADER_UNUSED_KHR, + .closestHitShader = 4, // index into stages + .anyHitShader = VK_SHADER_UNUSED_KHR, + .intersectionShader = VK_SHADER_UNUSED_KHR, }, }; @@ -380,45 +397,113 @@ VkDeviceAddress getASAddress(VkAccelerationStructureKHR as) { } void createAccelerationStructures() { - const VkAabbPositionsKHR aabbox= { - -1, -1, -1, - 1, 1, 1, - }; + const VkAabbPositionsKHR aabbox = { + -1, -1, -1, + 1, 1, 1, + }; - g.geom_buf = createBuffer(sizeof(aabbox), + g.aabb_buf = createBuffer(sizeof(aabbox), VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR); - memcpy(g.geom_buf.data, &aabbox, sizeof(aabbox)); + memcpy(g.aabb_buf.data, &aabbox, sizeof(aabbox)); + + #define TRIS 32 + float triangles[TRIS * 9]; + for (int i = 0; i < TRIS; ++i) { + float x = (float)rand() / RAND_MAX; + float y = (float)rand() / RAND_MAX; + float z = (float)rand() / RAND_MAX; + + y *= 5.f; + x = (x - .5f) * 10.f; + z = (z - .5f) * 10.f; + + triangles[i * 9 + 0] = x; + triangles[i * 9 + 1] = y; + triangles[i * 9 + 2] = z; + + triangles[i * 9 + 3] = x + 2.f * (float)rand() / RAND_MAX; + triangles[i * 9 + 4] = y + 2.f * (float)rand() / RAND_MAX; + triangles[i * 9 + 5] = z + 2.f * (float)rand() / RAND_MAX; + + triangles[i * 9 + 6] = x + 2.f * (float)rand() / RAND_MAX; + triangles[i * 9 + 7] = y + 2.f * (float)rand() / RAND_MAX; + triangles[i * 9 + 8] = z + 2.f * (float)rand() / RAND_MAX; + } - const VkAccelerationStructureGeometryKHR geom[] = { - { - .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR, - //.flags = VK_GEOMETRY_OPAQUE_BIT, - .geometryType = VK_GEOMETRY_TYPE_AABBS_KHR, - .geometry.aabbs = - (VkAccelerationStructureGeometryAabbsDataKHR){ - .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_AABBS_DATA_KHR, - .data.deviceAddress = getBufferDeviceAddress(g.geom_buf.buffer), - .stride = sizeof(VkAabbPositionsKHR), - }, - }, - }; + + g.tri_buf = createBuffer(sizeof(triangles), + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR); + memcpy(g.tri_buf.data, triangles, sizeof(triangles)); - const uint32_t max_prim_counts[COUNTOF(geom)] = {1}; - const VkAccelerationStructureBuildRangeInfoKHR build_range = { + { + const VkAccelerationStructureGeometryKHR geom[] = { + { + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR, + .flags = VK_GEOMETRY_OPAQUE_BIT_KHR, + .geometryType = VK_GEOMETRY_TYPE_AABBS_KHR, + .geometry.aabbs = + (VkAccelerationStructureGeometryAabbsDataKHR){ + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_AABBS_DATA_KHR, + .data.deviceAddress = getBufferDeviceAddress(g.aabb_buf.buffer), + .stride = sizeof(VkAabbPositionsKHR), + }, + }, + }; + + const uint32_t max_prim_counts[COUNTOF(geom)] = {1}; + const VkAccelerationStructureBuildRangeInfoKHR build_range_aabb = { .primitiveCount = 1, - }; - const VkAccelerationStructureBuildRangeInfoKHR *build_ranges[] = {&build_range}; - g.blas = createAccelerationStructure( - geom, max_prim_counts, build_ranges, COUNTOF(geom), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); + }; + const VkAccelerationStructureBuildRangeInfoKHR *build_ranges[] = { + &build_range_aabb, + }; + g.blas = createAccelerationStructure( + geom, max_prim_counts, build_ranges, COUNTOF(geom), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); + } - const VkAccelerationStructureInstanceKHR inst = { + { + const VkAccelerationStructureGeometryKHR geom[] = { + { + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR, + .flags = VK_GEOMETRY_OPAQUE_BIT_KHR, + .geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR, + .geometry.triangles = + (VkAccelerationStructureGeometryTrianglesDataKHR){ + .sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR, + .indexType = VK_INDEX_TYPE_NONE_KHR, + .maxVertex = TRIS * 3, + .vertexFormat = VK_FORMAT_R32G32B32_SFLOAT, + .vertexStride = sizeof(float) * 3, + .vertexData.deviceAddress = getBufferDeviceAddress(g.tri_buf.buffer), + }, + }}; + + const uint32_t max_prim_counts[COUNTOF(geom)] = {TRIS}; + const VkAccelerationStructureBuildRangeInfoKHR build_range_tri = { + .primitiveCount = TRIS, + }; + const VkAccelerationStructureBuildRangeInfoKHR *build_ranges[COUNTOF(geom)] = {&build_range_tri}; + g.blas_tri = createAccelerationStructure( + geom, max_prim_counts, build_ranges, COUNTOF(geom), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); + } + + const VkAccelerationStructureInstanceKHR inst[] = {{ .transform = (VkTransformMatrixKHR){1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}, .instanceCustomIndex = 0, .mask = 0xff, .instanceShaderBindingTableRecordOffset = 0, .flags = 0, .accelerationStructureReference = getASAddress(g.blas.handle), + }, { + .transform = (VkTransformMatrixKHR){1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}, + .instanceCustomIndex = 0, + .mask = 0xff, + .instanceShaderBindingTableRecordOffset = 1, // index into sbt_hit group + .flags = 0, + .accelerationStructureReference = getASAddress(g.blas_tri.handle), + }, }; g.tl_geom_buffer = createBuffer(sizeof(inst), @@ -440,9 +525,9 @@ void createAccelerationStructures() { }, }; - const uint32_t tl_max_prim_counts[COUNTOF(tl_geom)] = {1}; + const uint32_t tl_max_prim_counts[COUNTOF(tl_geom)] = {COUNTOF(inst)}; const VkAccelerationStructureBuildRangeInfoKHR tl_build_range = { - .primitiveCount = 1, + .primitiveCount = COUNTOF(inst), }; const VkAccelerationStructureBuildRangeInfoKHR *tl_build_ranges[] = {&tl_build_range}; g.tlas = createAccelerationStructure( @@ -532,12 +617,17 @@ static void paint(ATimeUs timestamp, float dt) { .imageView = g.rt_image.view, .imageLayout = VK_IMAGE_LAYOUT_GENERAL, }; + const VkDescriptorBufferInfo dbi = { + .buffer = g.tri_buf.buffer, + .offset = 0, + .range = VK_WHOLE_SIZE, + }; const VkWriteDescriptorSetAccelerationStructureKHR wdsas = { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR, .accelerationStructureCount = 1, .pAccelerationStructures = &g.tlas.handle, }; - VkWriteDescriptorSet wds[] = { + const VkWriteDescriptorSet wds[] = { { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .descriptorCount = 1, @@ -547,6 +637,15 @@ static void paint(ATimeUs timestamp, float dt) { .dstArrayElement = 0, .pImageInfo = &dii, }, + { + .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .dstSet = g.desc_set, + .dstBinding = 2, + .dstArrayElement = 0, + .pBufferInfo = &dbi, + }, { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .descriptorCount = 1, @@ -565,7 +664,7 @@ static void paint(ATimeUs timestamp, float dt) { const VkDeviceAddress sbt_addr = getBufferDeviceAddress(g.sbt_buf.buffer); const VkStridedDeviceAddressRegionKHR sbt_raygen = {.deviceAddress = sbt_addr, .size = g.shader_group_size, .stride = g.shader_group_size}; const VkStridedDeviceAddressRegionKHR sbt_raymiss = {.deviceAddress = sbt_addr + g.shader_group_size, .size = g.shader_group_size, .stride = g.shader_group_size}; - const VkStridedDeviceAddressRegionKHR sbt_rayhit = {.deviceAddress = sbt_addr + g.shader_group_size * 2, .size = g.shader_group_size, .stride = g.shader_group_size}; + const VkStridedDeviceAddressRegionKHR sbt_rayhit = {.deviceAddress = sbt_addr + g.shader_group_size * 2, .size = g.shader_group_size * 2, .stride = g.shader_group_size}; vkCmdTraceRaysKHR_(g.cmdbuf, &sbt_raygen, &sbt_raymiss, &sbt_rayhit, &sbt_null, 1280, 720, 1); VkImageMemoryBarrier image_barriers[] = { @@ -686,12 +785,15 @@ static void close() { vkDestroyShaderModule(a_vk.dev, g.modules.raygen, NULL); vkDestroyShaderModule(a_vk.dev, g.modules.raymiss, NULL); vkDestroyShaderModule(a_vk.dev, g.modules.rayclosesthit, NULL); + vkDestroyShaderModule(a_vk.dev, g.modules.rayclosesthit_tri, NULL); vkDestroyShaderModule(a_vk.dev, g.modules.rayintersect, NULL); destroyAccelerationStructure(&g.tlas); destroyAccelerationStructure(&g.blas); + destroyAccelerationStructure(&g.blas_tri); destroyBuffer(&g.sbt_buf); - destroyBuffer(&g.geom_buf); + destroyBuffer(&g.tri_buf); + destroyBuffer(&g.aabb_buf); destroyBuffer(&g.tl_geom_buffer); vkDestroyRenderPass(a_vk.dev, g.render_pass, NULL); From f6aa31de1a8810307a84609129301c46d3cdb9a5 Mon Sep 17 00:00:00 2001 From: Ivan 'provod' Avdeev Date: Wed, 23 Dec 2020 13:39:09 -0800 Subject: [PATCH 14/18] fix triangle normals --- examples/ray.glsl | 1 + examples/ray.rchit | 1 + examples/ray.rgen | 25 ++++++++++++++++--- examples/ray_tri.rchit | 16 ++++++++---- examples/vk_ray.c | 55 +++++++++++++++++++++++++----------------- 5 files changed, 68 insertions(+), 30 deletions(-) diff --git a/examples/ray.glsl b/examples/ray.glsl index d698c67..874e7e5 100644 --- a/examples/ray.glsl +++ b/examples/ray.glsl @@ -3,5 +3,6 @@ struct RayResult { float l; vec3 p; vec3 n; + float num; }; diff --git a/examples/ray.rchit b/examples/ray.rchit index 9100b67..0e2858b 100644 --- a/examples/ray.rchit +++ b/examples/ray.rchit @@ -9,4 +9,5 @@ void main() { rres.l = gl_HitTEXT; rres.p = gl_HitTEXT * gl_WorldRayDirectionEXT + gl_WorldRayOriginEXT; rres.n = normalize(rres.p); + rres.num = 0.; } diff --git a/examples/ray.rgen b/examples/ray.rgen index 8345052..726b6a4 100644 --- a/examples/ray.rgen +++ b/examples/ray.rgen @@ -2,6 +2,10 @@ #extension GL_GOOGLE_include_directive : enable #include "ray.glsl" +layout(push_constant) uniform G { + float t; +}; + layout(binding = 0, set = 0, rgba8) uniform image2D image; layout(binding = 1, set = 0) uniform accelerationStructureEXT tlas; @@ -17,7 +21,7 @@ f.y); } float kappa(vec3 p) { - return p.y + 1. - .3 * n(p.xz*2.); + return p.y + 1. - .1 * n(p.xz*2.); } vec3 wn(vec3 p) { @@ -37,6 +41,8 @@ float tr(vec3 O, vec3 D, float l, float L) { return l; } +#define rm(a) mat2(cos(a),sin(a),-sin(a),cos(a)) + void main() { //const vec2 pixelCenter = vec2(gl_LaunchIDEXT.xy) + vec2(0.5); //const vec2 inUV = pixelCenter / vec2(gl_LaunchSizeEXT.xy); @@ -48,10 +54,14 @@ void main() { vec3 C = vec3(0.); vec3 ld=normalize(vec3(1.)); - vec3 O=vec3(0., 0., 3.), D=normalize(vec3(uv, -1.)); + vec3 O=vec3(0., 1. + cos(t), 6.), D=normalize(vec3(uv, -2.)); + + mat2 my = rm(t * .9); + D.xz *= my; + O.xz *= my; vec3 kc = vec3(1.); - for(float r=0.;r<3.;++r) { + for(float r=0.;r<8.;++r) { vec3 p, n, m_albedo = vec3(1., 0., 1.); float L=20., l=tr(O,D,0.,L); @@ -65,6 +75,12 @@ void main() { l = rres.l; p = O+D*l; m_albedo = vec3(1., 0., 0.); + //C = fract(n); + //vec3(rres.num/3.); + //break; + //C = n *.5 + .5; + //n = abs(n); + //break; } else if (l < L) { p = O+D*l; n = wn(p); @@ -74,6 +90,9 @@ void main() { break; } + //C = n; + //break; + vec3 c = .5 * vec3(.9,.7,.3) * max(0., dot(n,ld)); c += .5 * vec3(.9,.7,.3) * pow(max(0., dot(n,normalize(ld-D))), 100.); float sh=tr(p,ld,.1,10.); diff --git a/examples/ray_tri.rchit b/examples/ray_tri.rchit index 01a671a..d8793ef 100644 --- a/examples/ray_tri.rchit +++ b/examples/ray_tri.rchit @@ -2,18 +2,24 @@ #extension GL_GOOGLE_include_directive : enable #include "ray.glsl" -//hitAttributeEXT RayResult hres; layout(location = 0) rayPayloadInEXT RayResult rres; -layout(binding = 2, set = 0) buffer Vertices { vec3 vertices[]; }; +layout(binding = 2, set = 0) buffer Vertices { vec4 vertices[]; }; +hitAttributeEXT vec2 bary; void main() { rres.l = gl_HitTEXT; rres.p = gl_HitTEXT * gl_WorldRayDirectionEXT + gl_WorldRayOriginEXT; + rres.num = float(gl_PrimitiveID); const uint vi = gl_PrimitiveID * 3; - vec3 v0 = vertices[vi + 0]; - vec3 v1 = vertices[vi + 1]; - vec3 v2 = vertices[vi + 2]; + vec3 v0 = vertices[vi + 0].xyz; + vec3 v1 = vertices[vi + 1].xyz; + vec3 v2 = vertices[vi + 2].xyz; rres.n = normalize(cross(v2-v0, v1-v0)); + if (gl_HitKindEXT == gl_HitKindFrontFacingTriangleEXT) + rres.n = -rres.n; + //vec3 b = vec3(1. - bary.x - bary.y, bary.x, bary.y); + //rres.n = v0 * b.x + v1 * b.y + v2 * b.z; + //rres.n = b; } diff --git a/examples/vk_ray.c b/examples/vk_ray.c index 4801bc2..77219da 100644 --- a/examples/vk_ray.c +++ b/examples/vk_ray.c @@ -234,19 +234,17 @@ static void createLayouts() { AVK_CHECK_RESULT(vkCreateDescriptorSetLayout(a_vk.dev, &dslci, NULL, &g.desc_layout)); - /* VkPushConstantRange push_const = {0}; push_const.offset = 0; push_const.size = sizeof(float); - push_const.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; - */ + push_const.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR; VkPipelineLayoutCreateInfo plci = {0}; plci.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; plci.setLayoutCount = 1; plci.pSetLayouts = &g.desc_layout; - // plci.pushConstantRangeCount = 1; - // plci.pPushConstantRanges = &push_const; + plci.pushConstantRangeCount = 1; + plci.pPushConstantRanges = &push_const; AVK_CHECK_RESULT(vkCreatePipelineLayout(a_vk.dev, &plci, NULL, &g.pipeline_layout)); VkDescriptorPoolSize pools[] = { @@ -407,28 +405,40 @@ void createAccelerationStructures() { VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR); memcpy(g.aabb_buf.data, &aabbox, sizeof(aabbox)); - #define TRIS 32 - float triangles[TRIS * 9]; - for (int i = 0; i < TRIS; ++i) { + #define TRIS 256 + float triangles[TRIS * 12] = { + 3.f, 0.f, 3.f, 0.f, + 3.f, 0.f, -3.f, 0.f, + 3.f, 3.f, 0.f, 0.f, + + 0.f, 3.f, 3.f, 0.f, + 0.f, -3.f, 3.f, 0.f, + 3.f, 0.f, 3.f, 0.f, + + 0.f, 3.f, 3.f, 0.f, + 0.f, 3.f, -3.f, 0.f, + 3.f, 3.f, 0.f, 0.f, + }; + for (int i = 3; i < TRIS; ++i) { float x = (float)rand() / RAND_MAX; float y = (float)rand() / RAND_MAX; float z = (float)rand() / RAND_MAX; - y *= 5.f; - x = (x - .5f) * 10.f; - z = (z - .5f) * 10.f; + y *= 10.f; + x = (x - .5f) * 20.f; + z = (z - .5f) * 20.f; - triangles[i * 9 + 0] = x; - triangles[i * 9 + 1] = y; - triangles[i * 9 + 2] = z; + triangles[i * 12 + 0] = x; + triangles[i * 12 + 1] = y; + triangles[i * 12 + 2] = z; - triangles[i * 9 + 3] = x + 2.f * (float)rand() / RAND_MAX; - triangles[i * 9 + 4] = y + 2.f * (float)rand() / RAND_MAX; - triangles[i * 9 + 5] = z + 2.f * (float)rand() / RAND_MAX; + triangles[i * 12 + 4] = x + 2.f * (float)rand() / RAND_MAX; + triangles[i * 12 + 5] = y + 2.f * (float)rand() / RAND_MAX; + triangles[i * 12 + 6] = z + 2.f * (float)rand() / RAND_MAX; - triangles[i * 9 + 6] = x + 2.f * (float)rand() / RAND_MAX; - triangles[i * 9 + 7] = y + 2.f * (float)rand() / RAND_MAX; - triangles[i * 9 + 8] = z + 2.f * (float)rand() / RAND_MAX; + triangles[i * 12 + 8] = x + 2.f * (float)rand() / RAND_MAX; + triangles[i * 12 + 9] = y + 2.f * (float)rand() / RAND_MAX; + triangles[i * 12 + 10] = z + 2.f * (float)rand() / RAND_MAX; } @@ -475,7 +485,7 @@ void createAccelerationStructures() { .indexType = VK_INDEX_TYPE_NONE_KHR, .maxVertex = TRIS * 3, .vertexFormat = VK_FORMAT_R32G32B32_SFLOAT, - .vertexStride = sizeof(float) * 3, + .vertexStride = sizeof(float) * 4, .vertexData.deviceAddress = getBufferDeviceAddress(g.tri_buf.buffer), }, }}; @@ -620,7 +630,7 @@ static void paint(ATimeUs timestamp, float dt) { const VkDescriptorBufferInfo dbi = { .buffer = g.tri_buf.buffer, .offset = 0, - .range = VK_WHOLE_SIZE, + .range = VK_WHOLE_SIZE, }; const VkWriteDescriptorSetAccelerationStructureKHR wdsas = { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR, @@ -658,6 +668,7 @@ static void paint(ATimeUs timestamp, float dt) { }; vkUpdateDescriptorSets(a_vk.dev, COUNTOF(wds), wds, 0, NULL); + vkCmdPushConstants(g.cmdbuf, g.pipeline_layout, VK_SHADER_STAGE_RAYGEN_BIT_KHR, 0, sizeof(float), &t); vkCmdBindDescriptorSets(g.cmdbuf, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, g.pipeline_layout, 0, 1, &g.desc_set, 0, NULL); const VkStridedDeviceAddressRegionKHR sbt_null = {0}; From 132084af82575fd714f9121b755d338e7bd3e2eb Mon Sep 17 00:00:00 2001 From: Ivan Avdeev Date: Sat, 26 Dec 2020 12:19:09 -0800 Subject: [PATCH 15/18] make wayland great again --- CMakeLists.txt | 8 +++--- examples/vk_ray.c | 3 +- include/atto/app.h | 9 ++++-- include/atto/worobushek.h | 58 +++++++++++++++++---------------------- src/app_wayland.c | 33 ++++++++-------------- src/app_windows.c | 2 -- 6 files changed, 49 insertions(+), 64 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 55c05ab..b24dcc5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,11 +14,12 @@ if(WIN32) set(ATTO_DEFINES ATTO_PLATFORM_WINDOWS ATTO_VK) elseif(CMAKE_SYSTEM_NAME MATCHES ".*Linux") # find_package(X11 REQUIRED) - # set(ATTO_LIBS + set(ATTO_LIBS # ${X11_LIBRARIES} # ${X11_Xext_LIB} # ${X11_Xfixes_LIB} - # m) + wayland-client + m) # set(ATTO_SRC # ${CMAKE_CURRENT_SOURCE_DIR}/src/app_linux.c # # ${CMAKE_CURRENT_SOURCE_DIR}/src/app_x11.c) @@ -30,7 +31,7 @@ elseif(CMAKE_SYSTEM_NAME MATCHES ".*Linux") ${CMAKE_CURRENT_SOURCE_DIR}/3p/wl-xdg-proto.c ${CMAKE_CURRENT_SOURCE_DIR}/include/atto/worobushek.h ) - set(ATTO_DEFINES ATTO_PLATFORM_POSIX ATTO_PLATFORM_LINUX ATTO_VK) +set(ATTO_DEFINES ATTO_PLATFORM_POSIX ATTO_PLATFORM_LINUX ATTO_PLATFORM_WAYLAND ATTO_VK) else() message(FATAL_ERROR "Not ported") endif() @@ -41,7 +42,6 @@ target_include_directories(atto PRIVATE 3p) target_compile_definitions(atto PUBLIC ${ATTO_DEFINES}) target_link_libraries(atto #PUBLIC OpenGL::GL - #PUBLIC wayland-client PUBLIC Vulkan::Vulkan PRIVATE ${ATTO_LIBS}) set_target_properties(atto PROPERTIES diff --git a/examples/vk_ray.c b/examples/vk_ray.c index 77219da..9c811ec 100644 --- a/examples/vk_ray.c +++ b/examples/vk_ray.c @@ -835,6 +835,7 @@ void attoAppInit(struct AAppProctable *proctable) { proctable->key = key; // TODO FIXME VK INIT + // TODO FIGURE OUT WHAT I MEANT BY THAT ^^^ aVkInitInstance(); aVkCreateSurface(); @@ -854,7 +855,7 @@ void attoAppInit(struct AAppProctable *proctable) { .pNext = &pdasf, }; - aVkInitDevice(&pdrtf); + aVkInitDevice(&pdrtf, NULL, NULL); g.prop.rt = (VkPhysicalDeviceRayTracingPipelinePropertiesKHR){.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR}; g.prop.prop2 = (VkPhysicalDeviceProperties2){.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &g.prop.rt}; diff --git a/include/atto/app.h b/include/atto/app.h index 4080366..7ecc722 100644 --- a/include/atto/app.h +++ b/include/atto/app.h @@ -135,8 +135,11 @@ struct AAppState { #endif #ifdef ATTO_VK #if defined(ATTO_PLATFORM_WINDOWS) - void* hInstance; - void* hWnd; + void *hInstance; + void *hWnd; +#elif defined(ATTO_PLATFORM_WAYLAND) + void *surface; + void *display; #endif #endif unsigned int width, height; @@ -157,6 +160,8 @@ extern const struct AAppState *a_app_state; struct AAppProctable { void (*resize)(ATimeUs ts, unsigned int old_width, unsigned int old_height); + + // resize must be called at least once before paint can be called void (*paint)(ATimeUs ts, float dt); void (*key)(ATimeUs ts, AKey key, int down); void (*pointer)(ATimeUs ts, int dx, int dy, unsigned int buttons_changed_bits); diff --git a/include/atto/worobushek.h b/include/atto/worobushek.h index 091c1a5..9351628 100644 --- a/include/atto/worobushek.h +++ b/include/atto/worobushek.h @@ -55,6 +55,8 @@ struct AVkState { int surface_width, surface_height; VkPhysicalDevice phys_dev; + VkPhysicalDeviceProperties2 props2; + VkPhysicalDeviceFeatures2 features2; VkPhysicalDeviceMemoryProperties mem_props; //VkSurfaceCapabilitiesKHR surf_caps; VkDevice dev; @@ -76,15 +78,16 @@ void aVkDestroySemaphore(VkSemaphore sema); VkShaderModule loadShaderFromFile(const char *filename); uint32_t aVkFindMemoryWithType(uint32_t type_index_bits, VkMemoryPropertyFlags flags); +void aVkInitDevice(const void *device_create_info_chain, void *props_chain, void *features_chain); void aVkCreateSurface(); void aVkPokePresentModes(); -void aVkCreateSwapchain(int w, int h); +void aVkCreateSwapchain(uint32_t w, uint32_t h); void aVkAcquireNextImage(); void aVkDestroy(); void aVkDestroySwapchain(); -void* aVkLoadDeviceFunction(const char *name); -void* aVkLoadInstanceFunction(const char *name); +PFN_vkVoidFunction aVkLoadDeviceFunction(const char *name); +PFN_vkVoidFunction aVkLoadInstanceFunction(const char *name); #define AVK_DEV_FUNC(name) ((PFN_##name)aVkLoadDeviceFunction(#name)) #define AVK_INST_FUNC(name) ((PFN_##name)aVkLoadInstanceFunction(#name)) @@ -151,9 +154,9 @@ static const char *instance_exts[] = { struct AVkState a_vk; -void *aVkLoadDeviceFunction(const char *name) { - void *ret = vkGetDeviceProcAddr(a_vk.dev, name); - aAppDebugPrintf("%s = %p", name, ret); +PFN_vkVoidFunction aVkLoadDeviceFunction(const char *name) { + PFN_vkVoidFunction ret = vkGetDeviceProcAddr(a_vk.dev, name); + aAppDebugPrintf("%s = %p", name, (void*)ret); if (!ret) { aAppDebugPrintf("Cannot load device function %s", name); aAppTerminate(-1); @@ -161,9 +164,9 @@ void *aVkLoadDeviceFunction(const char *name) { return ret; } -void *aVkLoadInstanceFunction(const char *name) { - void *ret = vkGetInstanceProcAddr(a_vk.inst, name); - aAppDebugPrintf("%s = %p", name, ret); +PFN_vkVoidFunction aVkLoadInstanceFunction(const char *name) { + PFN_vkVoidFunction ret = vkGetInstanceProcAddr(a_vk.inst, name); + aAppDebugPrintf("%s = %p", name, (void*)ret); if (!ret) { aAppDebugPrintf("Cannot load instance function %s", name); aAppTerminate(-1); @@ -227,29 +230,18 @@ void aVkInitInstance() { #endif } -void aVkInitDevice(const void* device_create_info_chain) { +void aVkInitDevice(const void *device_create_info_chain, void *props_chain, void *features_chain) { // Get only the first device uint32_t num_devices = 1; vkEnumeratePhysicalDevices(a_vk.inst, &num_devices, &a_vk.phys_dev); uint32_t queue_index = UINT32_MAX; - VkPhysicalDeviceProperties2 prop2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,}; - vkGetPhysicalDeviceProperties2(a_vk.phys_dev, &prop2); + a_vk.props2 = (VkPhysicalDeviceProperties2){.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = props_chain}; + vkGetPhysicalDeviceProperties2(a_vk.phys_dev, &a_vk.props2); - VkPhysicalDeviceBufferDeviceAddressFeaturesEXT pdbdaf = { - .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT, - }; - VkPhysicalDeviceAccelerationStructureFeaturesKHR pdasf = { - .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR, - .pNext = &pdbdaf, - }; - VkPhysicalDeviceRayTracingPipelineFeaturesKHR pdrtf = { - .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR, - .pNext = &pdasf, - }; - VkPhysicalDeviceFeatures2 features2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, .pNext = &pdrtf}; - vkGetPhysicalDeviceFeatures2(a_vk.phys_dev, &features2); + a_vk.features2 = (VkPhysicalDeviceFeatures2){.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, .pNext = features_chain}; + vkGetPhysicalDeviceFeatures2(a_vk.phys_dev, &a_vk.features2); #define MAX_QUEUE_FAMILIES 8 uint32_t num_queue_families = MAX_QUEUE_FAMILIES; @@ -310,12 +302,12 @@ void aVkInitDevice(const void* device_create_info_chain) { a_vk.swapchain.image_available = aVkCreateSemaphore(); } -void aVkCreateSwapchain(int w, int h) { +void aVkCreateSwapchain(uint32_t w, uint32_t h) { VkSurfaceCapabilitiesKHR scap; AVK_CHECK_RESULT(AVK_INST_FUNC(vkGetPhysicalDeviceSurfaceCapabilitiesKHR)(a_vk.phys_dev, a_vk.surf, &scap)); - //AVK_CHECK_RESULT(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(a_vk.phys_dev, a_vk.surf, &scap)); - a_vk.surface_width = scap.currentExtent.width; - a_vk.surface_height = scap.currentExtent.height; + + a_vk.surface_width = (int)scap.currentExtent.width > 0 ? scap.currentExtent.width : w; + a_vk.surface_height = (int)scap.currentExtent.height > 0 ? scap.currentExtent.height : h; struct AVkSwapchain* sw = &a_vk.swapchain; sw->info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; @@ -324,8 +316,8 @@ void aVkCreateSwapchain(int w, int h) { sw->info.minImageCount = 5; // TODO get from caps sw->info.imageFormat = VK_FORMAT_B8G8R8A8_SRGB; // TODO get from caps sw->info.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; // TODO get from caps - sw->info.imageExtent.width = scap.currentExtent.width; - sw->info.imageExtent.height = scap.currentExtent.height; + sw->info.imageExtent.width = a_vk.surface_width; + sw->info.imageExtent.height = a_vk.surface_height; sw->info.imageArrayLayers = 1; sw->info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT /* FIXME FOR RT */ | VK_IMAGE_USAGE_TRANSFER_DST_BIT; sw->info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; @@ -362,8 +354,8 @@ void aVkCreateSurface() { #else VkWaylandSurfaceCreateInfoKHR wsci = {0}; wsci.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR; - wsci.surface = surf; - wsci.display = disp; + wsci.surface = a_app_state->surface; + wsci.display = a_app_state->display; AVK_CHECK_RESULT(vkCreateWaylandSurfaceKHR(a_vk.inst, &wsci, NULL, &a_vk.surf)); #endif } diff --git a/src/app_wayland.c b/src/app_wayland.c index e2521cc..4d43fac 100644 --- a/src/app_wayland.c +++ b/src/app_wayland.c @@ -10,7 +10,6 @@ #define ATTO_APP_NAME "atto app" #endif -#include "atto/platform.h" #include "atto/app.h" #include "wl-xdg-proto.h" #include @@ -207,18 +206,16 @@ static void xtop_configure(void *data, if (width == 0 || height == 0) return; - if (width == a__app_state.width && height == a__app_state.height) - return; + const unsigned int oldw = a__app_state.width, oldh = a__app_state.height; - if (a__app_proctable.swapchain_will_destroy) - a__app_proctable.swapchain_will_destroy(); + if (width == oldw && height == oldh) + return; a__app_state.width = width; a__app_state.height = height; - a_vkCreateSwapchain(width, height); - if (a__app_proctable.swapchain_created) - a__app_proctable.swapchain_created(); + if (a__app_proctable.resize) + a__app_proctable.resize(aAppTime(), oldw, oldh); } static struct xdg_toplevel_listener xtop_listener = { @@ -244,21 +241,16 @@ int main(int argc, char *argv[]) { wl_surface_commit(surf); wl_display_roundtrip(a__wl.disp); - a_vkInitWithWayland(a__wl.disp, surf); + a__app_state.display = a__wl.disp; + a__app_state.surface = surf; a__app_state.argc = argc; a__app_state.argv = (const char *const *)argv; - a__app_state.graphics_version = AOVK10; + //a__app_state.graphics_version = AOVK10; a__app_state.width = 1280; a__app_state.height = 720; - ATTO_APP_INIT_FUNC(&a__app_proctable); - aAppDebugPrintf("post-init"); - - a_vkCreateSwapchain(a__app_state.width, a__app_state.height); - a__app_proctable.swapchain_created(); - - aAppDebugPrintf("post-swapchain"); + ATTO_APP_INIT_FUNC(&a__app_proctable); ATimeUs last_paint = 0; while (running) { @@ -267,17 +259,14 @@ int main(int argc, char *argv[]) { dt = (now - last_paint) * 1e-6f; last_paint = now; - //aAppDebugPrintf("DRAW"); - a_vkPaint(&a__app_proctable, now, dt); + if (a__app_proctable.paint) + a__app_proctable.paint(now, dt); ATTO_ASSERT(wl_display_dispatch(a__wl.disp) != -1); } - a__app_proctable.swapchain_will_destroy(); if (a__app_proctable.close) a__app_proctable.close(); - a_vkDestroySwapchain(); - a_vkDestroy(); xdg_toplevel_destroy(xtop); xdg_surface_destroy(xsurf); wl_surface_destroy(surf); diff --git a/src/app_windows.c b/src/app_windows.c index 6c4aaa8..05ab368 100644 --- a/src/app_windows.c +++ b/src/app_windows.c @@ -139,9 +139,7 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine a__app_state.hInstance = hInstance; a__app_state.hWnd = g.hwnd; -#ifdef ATTO_VK ATTO_APP_INIT_FUNC(&a__app_proctable); -#endif #if defined(ATTO_GL) if (a__app_proctable.resize) From 36bd895d04688c9dfa7e31227965c923a3479768 Mon Sep 17 00:00:00 2001 From: Ivan 'provod' Avdeev Date: Mon, 28 Dec 2020 13:43:48 -0800 Subject: [PATCH 16/18] fix unused warnings --- include/atto/worobushek.h | 3 +++ src/app_windows.c | 2 ++ 2 files changed, 5 insertions(+) diff --git a/include/atto/worobushek.h b/include/atto/worobushek.h index 9351628..89077d9 100644 --- a/include/atto/worobushek.h +++ b/include/atto/worobushek.h @@ -180,6 +180,9 @@ VkBool32 debugCallback( VkDebugUtilsMessageTypeFlagsEXT messageTypes, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void *pUserData) { + (void)(pUserData); + (void)(messageTypes); + (void)(messageSeverity); if (messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) { aAppDebugPrintf("%s", pCallbackData->pMessage); __debugbreak(); diff --git a/src/app_windows.c b/src/app_windows.c index 05ab368..58de78e 100644 --- a/src/app_windows.c +++ b/src/app_windows.c @@ -39,9 +39,11 @@ static struct AAppState a__app_state; const struct AAppState *a_app_state = &a__app_state; static struct AAppProctable a__app_proctable; +#if defined(ATTO_GL) static const PIXELFORMATDESCRIPTOR a__pfd = {sizeof(a__pfd), 0, PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL, PFD_TYPE_RGBA, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +#endif static LARGE_INTEGER a__time_freq; static LARGE_INTEGER a__time_start; From 9d9536cb23b7d06ee48c6bab648d4b7d18febdea Mon Sep 17 00:00:00 2001 From: Ivan Avdeev Date: Sat, 2 Jan 2021 12:06:55 -0800 Subject: [PATCH 17/18] fix debug break on validation errors on linux --- include/atto/worobushek.h | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/include/atto/worobushek.h b/include/atto/worobushek.h index 89077d9..fbd660d 100644 --- a/include/atto/worobushek.h +++ b/include/atto/worobushek.h @@ -65,7 +65,7 @@ struct AVkState { struct AVkSwapchain swapchain; -#ifdef _DEBUG +#ifndef NDEBUG VkDebugUtilsMessengerEXT debug_messenger; #endif }; @@ -138,7 +138,7 @@ const char *aVkResultName(VkResult result) { } static const char *instance_exts[] = { -#ifdef _DEBUG +#ifndef NDEBUG VK_EXT_DEBUG_UTILS_EXTENSION_NAME, #endif #ifdef ATTO_VK_INSTANCE_EXTENSIONS @@ -174,7 +174,7 @@ PFN_vkVoidFunction aVkLoadInstanceFunction(const char *name) { return ret; } -#ifdef _DEBUG +#ifndef NDEBUG VkBool32 debugCallback( VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageTypes, @@ -185,7 +185,11 @@ VkBool32 debugCallback( (void)(messageSeverity); if (messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) { aAppDebugPrintf("%s", pCallbackData->pMessage); +#ifdef _MSC_VER __debugbreak(); +#else + __builtin_trap(); +#endif } return VK_FALSE; } @@ -206,7 +210,7 @@ void aVkInitInstance() { ai.pEngineName = "KEK"; const char *layers[] = { - #ifdef _DEBUG + #ifndef NDEBUG "VK_LAYER_KHRONOS_validation", #endif }; @@ -222,7 +226,7 @@ void aVkInitInstance() { //PFN_vkCreateRayTracingPipelinesKHR fn = AVK_INST_FUNC(vkCreateRayTracingPipelinesKHR); //fn(NULL, VK_NULL_HANDLE, VK_NULL_HANDLE, 0, NULL, NULL, NULL); -#ifdef _DEBUG +#ifndef NDEBUG VkDebugUtilsMessengerCreateInfoEXT dumcie = { .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, .messageSeverity = 0x1111, //:vovka: VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT, @@ -375,7 +379,7 @@ void aVkDestroy() { vkDestroySurfaceKHR(a_vk.inst, a_vk.surf, NULL); aVkDestroySemaphore(a_vk.swapchain.image_available); vkDestroyDevice(a_vk.dev, NULL); -#ifdef _DEBUG +#ifndef NDEBUG AVK_INST_FUNC(vkDestroyDebugUtilsMessengerEXT)(a_vk.inst, a_vk.debug_messenger, NULL); #endif vkDestroyInstance(a_vk.inst, NULL); From 5cc33036913888668ba5e66e7694370c1793549b Mon Sep 17 00:00:00 2001 From: Ivan 'provod' Avdeev Date: Wed, 6 Jan 2021 21:56:56 -0800 Subject: [PATCH 18/18] fix msvc release build; improve buffer address compat --- examples/vk_ray.c | 18 ++++++++++++------ include/atto/worobushek.h | 7 +++---- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/examples/vk_ray.c b/examples/vk_ray.c index 9c811ec..6c11e5b 100644 --- a/examples/vk_ray.c +++ b/examples/vk_ray.c @@ -89,10 +89,16 @@ static struct Buffer createBuffer(size_t size, VkBufferUsageFlags usage) { vkGetBufferMemoryRequirements(a_vk.dev, ret.buffer, &memreq); aAppDebugPrintf("memreq: memoryTypeBits=0x%x alignment=%zu size=%zu", memreq.memoryTypeBits, memreq.alignment, memreq.size); - VkMemoryAllocateInfo mai={0}; - mai.allocationSize = memreq.size; - mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - mai.memoryTypeIndex = aVkFindMemoryWithType(memreq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + VkMemoryAllocateFlagsInfo mafi = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, + .flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, + }; + VkMemoryAllocateInfo mai = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .pNext = &mafi, + .allocationSize = memreq.size, + .memoryTypeIndex = aVkFindMemoryWithType(memreq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), + }; AVK_CHECK_RESULT(vkAllocateMemory(a_vk.dev, &mai, NULL, &ret.devmem)); AVK_CHECK_RESULT(vkBindBufferMemory(a_vk.dev, ret.buffer, ret.devmem, 0)); @@ -839,8 +845,8 @@ void attoAppInit(struct AAppProctable *proctable) { aVkInitInstance(); aVkCreateSurface(); - VkPhysicalDeviceBufferDeviceAddressFeaturesEXT pdbdaf = { - .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT, + VkPhysicalDeviceBufferDeviceAddressFeatures pdbdaf = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES, .bufferDeviceAddress = VK_TRUE, }; VkPhysicalDeviceAccelerationStructureFeaturesKHR pdasf = { diff --git a/include/atto/worobushek.h b/include/atto/worobushek.h index fbd660d..0778688 100644 --- a/include/atto/worobushek.h +++ b/include/atto/worobushek.h @@ -209,15 +209,14 @@ void aVkInitInstance() { ai.pApplicationName = "LOL"; ai.pEngineName = "KEK"; - const char *layers[] = { + VkInstanceCreateInfo vici = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; #ifndef NDEBUG + const char *layers[] = { "VK_LAYER_KHRONOS_validation", - #endif }; - - VkInstanceCreateInfo vici = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; vici.enabledLayerCount = COUNTOF(layers); vici.ppEnabledLayerNames = layers; + #endif vici.enabledExtensionCount = COUNTOF(instance_exts); vici.ppEnabledExtensionNames = instance_exts; vici.pApplicationInfo = &ai;