diff --git a/.gitignore b/.gitignore index d2bf98a016f588760241f9dc7f90f6197c458404..7ee4ff1903e902c4715c6e2b0c3e784ed5755aaf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,3 @@ -<<<<<<< HEAD -======= - ->>>>>>> develop # IDE specific files .project .cproject @@ -19,3 +15,6 @@ cmake-build-release/ *.exe *.ilk *.pdb + +# GUI configuration files +imgui.ini diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 318f3e931e557421a5e9275735174cdee7947453..33b70018e368ecc3ad019ea33e57485814eb233a 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -14,7 +14,7 @@ build_ubuntu_gcc: - $RUN =~ /\bubuntu.*/i || $RUN =~ /\ball.*/i stage: build tags: - - ubuntu-gcc + - ubuntu-gcc-cached variables: GIT_SUBMODULE_STRATEGY: recursive timeout: 10m @@ -37,11 +37,11 @@ build_win10_msvc: - $RUN =~ /\bwin.*/i || $RUN =~ /\ball.*/i stage: build tags: - - win10-msvc + - win10-msvc-cached variables: GIT_SUBMODULE_STRATEGY: recursive timeout: 10m - retry: 1 + retry: 0 script: - cd 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\Tools\' - .\Launch-VsDevShell.ps1 diff --git a/.gitmodules b/.gitmodules index 983b753744e8767da0ec3c959c32a3766ee346f6..e0aaf2d17c340f98ae875f7e0f1238bfe04f7e5d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -15,4 +15,10 @@ url = https://github.com/nothings/stb.git [submodule "modules/camera/lib/glm"] path = modules/camera/lib/glm - url = https://github.com/g-truc/glm.git \ No newline at end of file + url = https://github.com/g-truc/glm.git +[submodule "modules/shader_compiler/lib/glslang"] + path = modules/shader_compiler/lib/glslang + url = https://github.com/KhronosGroup/glslang.git +[submodule "modules/gui/lib/imgui"] + path = modules/gui/lib/imgui + url = https://github.com/ocornut/imgui.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 0a7f978f81313ecc3a657dd670d2a16db3cd4e8d..bff486150f082c2e96e543436d977cf3112403ba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -41,15 +41,15 @@ if (vkcv_build_debug) endif() endif() +# configure everything to use the required dependencies +include(${vkcv_config}/Libraries.cmake) + # add modules as targets add_subdirectory(modules) # add source files for compilation include(${vkcv_config}/Sources.cmake) -# configure everything to use the required dependencies -include(${vkcv_config}/Libraries.cmake) - message("-- Libraries: [ ${vkcv_libraries} ]") message("-- Flags: [ ${vkcv_flags} ]") diff --git a/config/Sources.cmake b/config/Sources.cmake index 4f673e00d1e42e733534480d6085affd651a8c04..4397e4978eb022d267571d185a1f122d053a5ea1 100644 --- a/config/Sources.cmake +++ b/config/Sources.cmake @@ -32,8 +32,8 @@ set(vkcv_sources ${vkcv_include}/vkcv/Logger.hpp - ${vkcv_include}/vkcv/SwapChain.hpp - ${vkcv_source}/vkcv/SwapChain.cpp + ${vkcv_include}/vkcv/Swapchain.hpp + ${vkcv_source}/vkcv/Swapchain.cpp ${vkcv_include}/vkcv/ShaderStage.hpp @@ -41,7 +41,6 @@ set(vkcv_sources ${vkcv_source}/vkcv/ShaderProgram.cpp ${vkcv_include}/vkcv/PipelineConfig.hpp - ${vkcv_source}/vkcv/PipelineConfig.cpp ${vkcv_source}/vkcv/PipelineManager.hpp ${vkcv_source}/vkcv/PipelineManager.cpp diff --git a/include/vkcv/BufferManager.hpp b/include/vkcv/BufferManager.hpp index a390a2ff3be7f84b0c12f065398f9e40a42017e0..9eb80d70862a79a01593e6fe4c3aabe98d253ac8 100644 --- a/include/vkcv/BufferManager.hpp +++ b/include/vkcv/BufferManager.hpp @@ -132,6 +132,9 @@ namespace vkcv */ void unmapBuffer(const BufferHandle& handle); + void recordBufferMemoryBarrier( + const BufferHandle& handle, + vk::CommandBuffer cmdBuffer); }; } diff --git a/include/vkcv/Core.hpp b/include/vkcv/Core.hpp index 4a51b24f5c978daebc5116e20b527252c8063d61..c7512346c9137b77c365e807b679b3950925f535 100644 --- a/include/vkcv/Core.hpp +++ b/include/vkcv/Core.hpp @@ -8,7 +8,7 @@ #include <vulkan/vulkan.hpp> #include "vkcv/Context.hpp" -#include "vkcv/SwapChain.hpp" +#include "vkcv/Swapchain.hpp" #include "vkcv/Window.hpp" #include "vkcv/PassConfig.hpp" #include "vkcv/Handles.hpp" @@ -52,7 +52,7 @@ namespace vkcv * * @param context encapsulates various Vulkan objects */ - Core(Context &&context, Window &window, const SwapChain& swapChain, std::vector<vk::ImageView> imageViews, + Core(Context &&context, Window &window, const Swapchain& swapChain, std::vector<vk::ImageView> imageViews, const CommandResources& commandResources, const SyncResources& syncResources) noexcept; // explicit destruction of default constructor Core() = delete; @@ -61,11 +61,8 @@ namespace vkcv Context m_Context; - SwapChain m_swapchain; - std::vector<vk::ImageView> m_swapchainImageViews; - std::vector<vk::Image> m_swapchainImages; - std::vector<vk::ImageLayout> m_swapchainImageLayouts; - const Window& m_window; + Swapchain m_swapchain; + Window& m_window; std::unique_ptr<PassManager> m_PassManager; std::unique_ptr<PipelineManager> m_PipelineManager; @@ -79,11 +76,9 @@ namespace vkcv SyncResources m_SyncResources; uint32_t m_currentSwapchainImageIndex; - std::function<void(int, int)> e_resizeHandle; + event_handle<int,int> e_resizeHandle; - static std::vector<vk::ImageView> createImageViews( Context &context, SwapChain& swapChain); - - void recordSwapchainImageLayoutTransition(vk::CommandBuffer cmdBuffer, vk::ImageLayout newLayout); + static std::vector<vk::ImageView> createSwapchainImageViews( Context &context, Swapchain& swapChain); public: /** @@ -123,6 +118,9 @@ namespace vkcv [[nodiscard]] const Context &getContext() const; + + [[nodiscard]] + const Swapchain& getSwapchain() const; /** * Creates a #Core with given @p applicationName and @p applicationVersion for your application. @@ -216,7 +214,14 @@ namespace vkcv * @return Image-Object */ [[nodiscard]] - Image createImage(vk::Format format, uint32_t width, uint32_t height, uint32_t depth = 1); + Image createImage( + vk::Format format, + uint32_t width, + uint32_t height, + uint32_t depth = 1, + bool createMipChain = false, + bool supportStorage = false, + bool supportColorAttachment = false); /** TODO: * @param setDescriptions @@ -253,8 +258,6 @@ namespace vkcv */ void endFrame(); - vk::Format getSwapchainImageFormat(); - /** * Submit a command buffer to any queue of selected type. The recording can be customized by a * custom record-command-function. If the command submission has finished, an optional finish-function @@ -264,7 +267,7 @@ namespace vkcv * @param record Record-command-function * @param finish Finish-command-function or nullptr */ - void recordAndSubmitCommands( + void recordAndSubmitCommandsImmediate( const SubmitInfo &submitInfo, const RecordCommandFunction &record, const FinishCommandFunction &finish); @@ -279,5 +282,11 @@ namespace vkcv void submitCommandStream(const CommandStreamHandle handle); void prepareSwapchainImageForPresent(const CommandStreamHandle handle); void prepareImageForSampling(const CommandStreamHandle cmdStream, const ImageHandle image); + void prepareImageForStorage(const CommandStreamHandle cmdStream, const ImageHandle image); + void recordImageMemoryBarrier(const CommandStreamHandle cmdStream, const ImageHandle image); + void recordBufferMemoryBarrier(const CommandStreamHandle cmdStream, const BufferHandle buffer); + + vk::ImageView getSwapchainImageView() const; + }; } diff --git a/include/vkcv/Event.hpp b/include/vkcv/Event.hpp index 0836e836e84ff7dfc4931a7cedd65497bf9a89cf..b66e4e6579d887f3beee5cdd20c88dff361bd3b9 100644 --- a/include/vkcv/Event.hpp +++ b/include/vkcv/Event.hpp @@ -1,12 +1,21 @@ #pragma once #include <functional> +#include <mutex> namespace vkcv { + + template<typename... T> + struct event_handle { + uint32_t id; + }; template<typename... T> struct event_function { typedef std::function<void(T...)> type; + + event_handle<T...> handle; + type callback; }; /** @@ -16,7 +25,9 @@ namespace vkcv { template<typename... T> struct event { private: - std::vector<typename event_function<T...>::type> m_handles; + std::vector< event_function<T...> > m_functions; + uint32_t m_id_counter; + std::mutex m_mutex; public: @@ -25,30 +36,54 @@ namespace vkcv { * @param arguments of the given function */ void operator()(T... arguments) { - for (auto &handle : this->m_handles) { - handle(arguments...); - } + lock(); + + for (auto &function : this->m_functions) { + function.callback(arguments...); + } + + unlock(); } /** * adds a function handle to the event to be called - * @param handle of the function + * @param callback of the function + * @return handle of the function */ - typename event_function<T...>::type add(typename event_function<T...>::type handle) { - this->m_handles.push_back(handle); - return handle; + event_handle<T...> add(typename event_function<T...>::type callback) { + event_function<T...> function; + function.handle = { m_id_counter++ }; + function.callback = callback; + this->m_functions.push_back(function); + return function.handle; } /** * removes a function handle of the event * @param handle of the function */ - void remove(typename event_function<T...>::type handle) { - this->m_handles.erase( - remove(this->m_handles.begin(), this->m_handles.end(), handle), - this->m_handles.end() + void remove(event_handle<T...> handle) { + this->m_functions.erase( + std::remove_if(this->m_functions.begin(), this->m_functions.end(), [&handle](auto function){ + return (handle.id == function.handle.id); + }), + this->m_functions.end() ); } + + /** + * locks the event so its function handles won't be called + */ + void lock() { + m_mutex.lock(); + } + + /** + * unlocks the event so its function handles can be called after locking + */ + void unlock() { + m_mutex.unlock(); + } event() = default; diff --git a/include/vkcv/Image.hpp b/include/vkcv/Image.hpp index a1219ce4147ebbb8ae0650da8a87766f8967874b..98a0943bcb253142c836cdfd13623a13f18c2871 100644 --- a/include/vkcv/Image.hpp +++ b/include/vkcv/Image.hpp @@ -29,9 +29,6 @@ namespace vkcv { [[nodiscard]] uint32_t getDepth() const; - - [[nodiscard]] - vk::ImageLayout getLayout() const; [[nodiscard]] vkcv::ImageHandle getHandle() const; @@ -39,13 +36,22 @@ namespace vkcv { void switchLayout(vk::ImageLayout newLayout); void fill(void* data, size_t size = SIZE_MAX); + void generateMipChainImmediate(); private: ImageManager* const m_manager; const ImageHandle m_handle; Image(ImageManager* manager, const ImageHandle& handle); - static Image create(ImageManager* manager, vk::Format format, uint32_t width, uint32_t height, uint32_t depth); + static Image create( + ImageManager* manager, + vk::Format format, + uint32_t width, + uint32_t height, + uint32_t depth, + uint32_t mipCount, + bool supportStorage, + bool supportColorAttachment); }; diff --git a/include/vkcv/PipelineConfig.hpp b/include/vkcv/PipelineConfig.hpp index 729330fcaf7eeac2acfdd1816b86ac29c7d9e30b..1e00c5209118469a7dc6ff1eb1e3c98a3c6903a7 100644 --- a/include/vkcv/PipelineConfig.hpp +++ b/include/vkcv/PipelineConfig.hpp @@ -13,34 +13,18 @@ namespace vkcv { - struct PipelineConfig { - /** - * Constructor for the pipeline. Creates a pipeline using @p vertexCode, @p fragmentCode as well as the - * dimensions of the application window @p width and @p height. A handle for the Render Pass is also needed, @p passHandle. - * - * @param shaderProgram shaders of the pipeline - * @param height height of the application window - * @param width width of the application window - * @param passHandle handle for render pass - * @param vertexLayout layout of vertex buffer, comprised of its bindings and the bindings' attachments - */ - PipelineConfig( - const ShaderProgram& shaderProgram, - uint32_t width, - uint32_t height, - const PassHandle &passHandle, - const VertexLayout &vertexLayouts, - const std::vector<vk::DescriptorSetLayout> &descriptorLayouts, - bool useDynamicViewport); + enum class PrimitiveTopology{PointList, LineList, TriangleList }; + struct PipelineConfig { ShaderProgram m_ShaderProgram; - uint32_t m_Height; uint32_t m_Width; + uint32_t m_Height; PassHandle m_PassHandle; VertexLayout m_VertexLayout; std::vector<vk::DescriptorSetLayout> m_DescriptorLayouts; bool m_UseDynamicViewport; - + bool m_UseConservativeRasterization = false; + PrimitiveTopology m_PrimitiveTopology = PrimitiveTopology::TriangleList; }; } \ No newline at end of file diff --git a/include/vkcv/ShaderProgram.hpp b/include/vkcv/ShaderProgram.hpp index 28f746d78477062eae9b0ad88f8c5de71e11efd0..78b1f02169fe630427b9f66150e32078d42b7b3f 100644 --- a/include/vkcv/ShaderProgram.hpp +++ b/include/vkcv/ShaderProgram.hpp @@ -51,7 +51,7 @@ namespace vkcv { const std::vector<VertexAttachment> &getVertexAttachments() const; size_t getPushConstantSize() const; - const std::vector<std::vector<DescriptorBinding>> &getReflectedDescriptors() const; + const std::vector<std::vector<DescriptorBinding>>& getReflectedDescriptors() const; private: /** diff --git a/include/vkcv/SwapChain.hpp b/include/vkcv/Swapchain.hpp similarity index 83% rename from include/vkcv/SwapChain.hpp rename to include/vkcv/Swapchain.hpp index 089205d1633551b4ad9f11d0bdd5540b2bb61bbb..b75fc5a87156ea56061e41b4b0974928c83ffa28 100644 --- a/include/vkcv/SwapChain.hpp +++ b/include/vkcv/Swapchain.hpp @@ -7,8 +7,9 @@ namespace vkcv { - class SwapChain final { + class Swapchain final { private: + friend class Core; struct Surface { @@ -21,10 +22,10 @@ namespace vkcv Surface m_Surface; vk::SwapchainKHR m_Swapchain; - vk::Format m_SwapchainFormat; - vk::ColorSpaceKHR m_SwapchainColorSpace; - vk::PresentModeKHR m_SwapchainPresentMode; - uint32_t m_SwapchainImageCount; + vk::Format m_Format; + vk::ColorSpaceKHR m_ColorSpace; + vk::PresentModeKHR m_PresentMode; + uint32_t m_ImageCount; vk::Extent2D m_Extent; @@ -39,16 +40,36 @@ namespace vkcv * @param format */ // TODO: - SwapChain(const Surface &surface, + Swapchain(const Surface &surface, vk::SwapchainKHR swapchain, vk::Format format, vk::ColorSpaceKHR colorSpace, vk::PresentModeKHR presentMode, uint32_t imageCount, vk::Extent2D extent) noexcept; + + /** + * TODO + * + * @return + */ + bool shouldUpdateSwapchain() const; + + /** + * TODO + * + * context + * window + */ + void updateSwapchain(const Context &context, const Window &window); + + /** + * + */ + void signalSwapchainRecreation(); public: - SwapChain(const SwapChain& other); + Swapchain(const Swapchain& other); /** * @return The swapchain linked with the #SwapChain class @@ -69,7 +90,7 @@ namespace vkcv * @return gets the chosen swapchain format */ [[nodiscard]] - vk::Format getSwapchainFormat() const; + vk::Format getFormat() const; /** * creates a swap chain object out of the given window and the given context @@ -77,37 +98,17 @@ namespace vkcv * @param context of the application * @return returns an object of swapChain */ - static SwapChain create(const Window &window, const Context &context); + static Swapchain create(const Window &window, const Context &context); /** * Destructor of SwapChain */ - virtual ~SwapChain(); + virtual ~Swapchain(); /** * @return number of images in swapchain */ - uint32_t getImageCount(); - - /** - * TODO - * - * @return - */ - bool shouldUpdateSwapchain() const; - - /** - * TODO - * - * context - * window - */ - void updateSwapchain(const Context &context, const Window &window); - - /** - * - */ - void signalSwapchainRecreation(); + uint32_t getImageCount() const; /** * TODO diff --git a/include/vkcv/VertexLayout.hpp b/include/vkcv/VertexLayout.hpp index 9f609b48472386cd7628ff40b5fa4b90bc91649a..0600b99a24a327605e89b2e8ec304c20dbf7ad2e 100644 --- a/include/vkcv/VertexLayout.hpp +++ b/include/vkcv/VertexLayout.hpp @@ -63,4 +63,4 @@ namespace vkcv{ std::vector<VertexBinding> vertexBindings; }; -} \ No newline at end of file +} diff --git a/include/vkcv/Window.hpp b/include/vkcv/Window.hpp index f71671c935a0a5e17bb517c726d75ffff2973532..d2b5854bce056bc50f8c08c55e6bcdd771bfc13b 100644 --- a/include/vkcv/Window.hpp +++ b/include/vkcv/Window.hpp @@ -7,22 +7,24 @@ #define NOMINMAX #include <algorithm> + #include "Event.hpp" struct GLFWwindow; namespace vkcv { - class Window final { - private: - GLFWwindow *m_window; - - /** + class Window { + protected: + GLFWwindow *m_window; + + /** * * @param GLFWwindow of the class */ - explicit Window(GLFWwindow *window); - + explicit Window(GLFWwindow *window); + + private: /** * mouse callback for moving the mouse on the screen * @param[in] window The window that received the event. @@ -39,6 +41,12 @@ namespace vkcv { */ static void onMouseButtonEvent(GLFWwindow *callbackWindow, int button, int action, int mods); + /** + * @brief A callback function for handling mouse scrolling events. + * @param[in] callbackWindow The window that received the event. + * @param[in] xoffset The extent of horizontal scrolling. + * @param[in] yoffset The extent of vertical scrolling. + */ static void onMouseScrollEvent(GLFWwindow *callbackWindow, double xoffset, double yoffset); /** @@ -58,6 +66,26 @@ namespace vkcv { * @param[in] mods Bit field describing which [modifier keys](@ref mods) were held down. */ static void onKeyEvent(GLFWwindow *callbackWindow, int key, int scancode, int action, int mods); + + /** + * char callback for any typed character + * @param[in] window The window that received the event + * @param[in] c The character that got typed + */ + static void onCharEvent(GLFWwindow *callbackWindow, unsigned int c); + + /** + * @brief A callback function for handling gamepad re-connection. + * @param gamepadIndex The gamepad index. + * @param gamepadEvent The gamepad connection event. + */ + static void onGamepadConnection(int gamepadIndex, int gamepadEvent); + + /** + * @brief A callback function for gamepad input events. + * @param gamepadIndex The gamepad index. + */ + static void onGamepadEvent(int gamepadIndex); public: /** @@ -77,11 +105,6 @@ namespace vkcv { [[nodiscard]] bool isWindowOpen() const; - /** - * binds windowEvents to lambda events - */ - void initEvents(); - /** * polls all events on the GLFWwindow */ @@ -95,6 +118,8 @@ namespace vkcv { event< double, double > e_mouseScroll; event< int, int > e_resize; event< int, int, int, int > e_key; + event< unsigned int > e_char; + event< int > e_gamepad; /** * returns the current window @@ -141,4 +166,4 @@ namespace vkcv { virtual ~Window(); }; -} \ No newline at end of file +} diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index f29ff2fc86c88aa8bae2560f199d3882c9919b65..5edb802b3adf16878c2dec4050d8444278739026 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -2,4 +2,6 @@ # Add new modules here: add_subdirectory(asset_loader) add_subdirectory(camera) +add_subdirectory(gui) +add_subdirectory(shader_compiler) add_subdirectory(testing) diff --git a/modules/asset_loader/include/vkcv/asset/asset_loader.hpp b/modules/asset_loader/include/vkcv/asset/asset_loader.hpp index d687bbf60a03a59eee8c29f9b676f10cc7f2f2b3..4107d57ee97a6efe0475c6d9dbd80d2603e0afe8 100644 --- a/modules/asset_loader/include/vkcv/asset/asset_loader.hpp +++ b/modules/asset_loader/include/vkcv/asset/asset_loader.hpp @@ -1,15 +1,16 @@ #pragma once /** - * @authors Trevor Hollmann + * @authors Trevor Hollmann, Mara Vogt, Susanne Dötsch * @file include/vkcv/asset/asset_loader.h * @brief Interface of the asset loader module for the vkcv framework. */ #include <string> #include <vector> +#include <array> #include <cstdint> -/* These macros define limits of the following structs. Implementations can +/** These macros define limits of the following structs. Implementations can * test against these limits when performing sanity checks. The main constraint * expressed is that of the data type: Material indices are identified by a * uint8_t in the VertexGroup struct, so there can't be more than UINT8_MAX @@ -19,17 +20,18 @@ #define MAX_MATERIALS_PER_MESH UINT8_MAX #define MAX_VERTICES_PER_VERTEX_GROUP UINT32_MAX -/* LOADING MESHES +/** LOADING MESHES * The description of meshes is a hierarchy of structures with the Mesh at the * top. * * Each Mesh has an array of one or more vertex groups (called "primitives" in - * glTF parlance) and an array of zero or more Materials. + * glTF parlance). Specifically, it has an array of indices into an array of + * vertex groups defined by the Scene struct. * * Each vertex group describes a part of the meshes vertices by defining how * they should be rendered (as points, lines, triangles), how many indices and * vertices there are, how the content of the vertex buffer is to be - * interpreted and which material from the Meshes materials array should be + * interpreted and which material from the Scenes materials array should be * used for the surface of the vertices. * As a bonus there is also the axis aligned bounding box of the vertices. * @@ -43,37 +45,99 @@ namespace vkcv::asset { -/* This enum matches modes in fx-gltf, the library returns a standard mode +/** This enum matches modes in fx-gltf, the library returns a standard mode * (TRIANGLES) if no mode is given in the file. */ -enum PrimitiveMode { +enum class PrimitiveMode : uint8_t { POINTS=0, LINES, LINELOOP, LINESTRIP, TRIANGLES, TRIANGLESTRIP, TRIANGLEFAN }; -/* The indices in the index buffer can be of different bit width. */ -enum IndexType { UINT32=0, UINT16=1, UINT8=2 }; -/* With these enums, 0 is reserved to signal uninitialized or invalid data. */ +/** The indices in the index buffer can be of different bit width. */ +enum class IndexType : uint8_t { UNDEFINED=0, UINT8=1, UINT16=2, UINT32=3 }; + +typedef struct { + // TODO define struct for samplers (low priority) + // NOTE: glTF defines samplers based on OpenGL, which can not be + // directly translated to Vulkan. Specifically, OpenGL (and glTF) + // define a different set of Min/Mag-filters than Vulkan. +} Sampler; + +/** struct for defining the loaded texture */ +typedef struct { + int sampler; // index into the sampler array of the Scene + uint8_t channels; // number of channels + uint16_t w, h; // width and height of the texture + std::vector<uint8_t> data; // binary data of the decoded texture +} Texture; + +/** The asset loader module only supports the PBR-MetallicRoughness model for + * materials.*/ +typedef struct { + uint16_t textureMask; // bit mask with active texture targets + // Indices into the Array.textures array + int baseColor, metalRough, normal, occlusion, emissive; + // Scaling factors for each texture target + struct { float r, g, b, a; } baseColorFactor; + float metallicFactor, roughnessFactor; + float normalScale; + float occlusionStrength; + struct { float r, g, b; } emissiveFactor; +} Material; + +/** Flags for the bit-mask in the Material struct. To check if a material has a + * certain texture target, you can use the hasTexture() function below, passing + * the material struct and the enum. */ +enum class PBRTextureTarget { + baseColor=1, metalRough=2, normal=4, occlusion=8, emissive=16 +}; + +/** This macro translates the index of an enum in the defined order to an + * integer with a single bit set in the corresponding place. It is used for + * working with the bitmask of texture targets ("textureMask") in the Material + * struct: + * Material mat = ...; + * if (mat.textureMask & bitflag(PBRTextureTarget::baseColor)) {...} + * However, this logic is also encapsulated in the convenience-function + * materialHasTexture() so users of the asset loader module can avoid direct + * contact with bit-level operations. */ +#define bitflag(ENUM) (0x1u << ((unsigned)(ENUM))) + +/** To signal that a certain texture target is active in a Material struct, its + * bit is set in the textureMask. You can use this function to check that: + * Material mat = ...; + * if (materialHasTexture(&mat, baseColor)) {...} */ +bool materialHasTexture(const Material *const m, const PBRTextureTarget t); + +/** With these enums, 0 is reserved to signal uninitialized or invalid data. */ enum class PrimitiveType : uint32_t { UNDEFINED = 0, POSITION = 1, NORMAL = 2, - TEXCOORD_0 = 3 + TEXCOORD_0 = 3, + TEXCOORD_1 = 4 }; -/* This struct describes one vertex attribute of a vertex buffer. */ + +/** These integer values are used the same way in OpenGL, Vulkan and glTF. This + * enum is not needed for translation, it's only for the programmers + * convenience (easier to read in if/switch statements etc). While this enum + * exists in (almost) the same definition in the fx-gltf library, we want to + * avoid exposing that dependency, thus it is re-defined here. */ +enum class ComponentType : uint16_t { + NONE = 0, INT8 = 5120, UINT8 = 5121, INT16 = 5122, UINT16 = 5123, + UINT32 = 5125, FLOAT32 = 5126 +}; + +/** This struct describes one vertex attribute of a vertex buffer. */ typedef struct { PrimitiveType type; // POSITION, NORMAL, ... uint32_t offset; // offset in bytes uint32_t length; // length of ... in bytes uint32_t stride; // stride in bytes - uint16_t componentType; // eg. 5126 for float + ComponentType componentType; // eg. 5126 for float uint8_t componentCount; // eg. 3 for vec3 } VertexAttribute; -typedef struct { - // TODO not yet needed for the first (unlit) triangle -} Material; - -/* This struct represents one (possibly the only) part of a mesh. There is +/** This struct represents one (possibly the only) part of a mesh. There is * always one vertexBuffer and zero or one indexBuffer (indexed rendering is * common but not always used). If there is no index buffer, this is indicated * by indexBuffer.data being empty. Each vertex buffer can have one or more @@ -91,34 +155,39 @@ typedef struct { } vertexBuffer; struct { float x, y, z; } min; // bounding box lower left struct { float x, y, z; } max; // bounding box upper right - uint8_t materialIndex; // index to one of the meshes materials + int materialIndex; // index to one of the materials } VertexGroup; -/* This struct represents a single mesh loaded from a glTF file. It consists of - * at least one VertexVroup and any number of Materials. */ +/** This struct represents a single mesh as it was loaded from a glTF file. It + * consists of at least one VertexGroup, which then references other resources + * such as Materials. */ typedef struct { std::string name; - std::vector<VertexGroup> vertexGroups; - std::vector<Material> materials; - // FIXME Dirty hack to get one(!) texture for our cube demo - // hardcoded to always have RGBA channel layout - struct { - int w, h, ch; // width, height and channels of image - uint8_t *img; // raw bytes, free after use (deal with it) - } texture_hack; + std::array<float, 16> modelMatrix; + std::vector<int> vertexGroups; } Mesh; +/** The scene struct is simply a collection of objects in the scene as well as + * the resources used by those objects. + * For now the only type of object are the meshes and they are represented in a + * flat array. + * Note that parent-child relations are not yet possible. */ +typedef struct { + std::vector<Mesh> meshes; + std::vector<VertexGroup> vertexGroups; + std::vector<Material> materials; + std::vector<Texture> textures; + std::vector<Sampler> samplers; +} Scene; /** - * In its first iteration the asset loader module will only allow loading - * single meshes, one per glTF file. - * It will later be extended to allow loading entire scenes from glTF files. + * Load every mesh from the glTF file, as well as materials and textures. * - * @param path must be the path to a glTF file containing a single mesh. - * @param mesh is a reference to a Mesh struct that will be filled with the + * @param path must be the path to a glTF or glb file. + * @param scene is a reference to a Scene struct that will be filled with the * content of the glTF file being loaded. * */ -int loadMesh(const std::string &path, Mesh &mesh); +int loadScene(const std::string &path, Scene &scene); } diff --git a/modules/asset_loader/src/vkcv/asset/asset_loader.cpp b/modules/asset_loader/src/vkcv/asset/asset_loader.cpp index f3823cc8f3fe54b53835f356dd14a086515118dd..97fd39515290ac9235b3936d44d3e40a584ef84f 100644 --- a/modules/asset_loader/src/vkcv/asset/asset_loader.cpp +++ b/modules/asset_loader/src/vkcv/asset/asset_loader.cpp @@ -5,9 +5,10 @@ #include <fx/gltf.h> #define STB_IMAGE_IMPLEMENTATION #define STBI_ONLY_JPEG +#define STBI_ONLY_PNG #include <stb_image.h> - #include <vkcv/Logger.hpp> +#include <algorithm> namespace vkcv::asset { @@ -51,160 +52,318 @@ void print_what (const std::exception& e, const std::string &path) { } } -int loadMesh(const std::string &path, Mesh &mesh) { - fx::gltf::Document object; - - try { - if (path.rfind(".glb", (path.length()-4)) != std::string::npos) { - object = fx::gltf::LoadFromBinary(path); - } else { - object = fx::gltf::LoadFromText(path); - } - } catch (const std::system_error &err) { - print_what(err, path); - return 0; - } catch (const std::exception &e) { - print_what(e, path); - return 0; - } - - // TODO Temporary restriction: Only one mesh per glTF file allowed - // currently. Later, we want to support whole scenes with more than - // just meshes. - if (object.meshes.size() != 1) return 0; - - fx::gltf::Mesh const &objectMesh = object.meshes[0]; - // TODO We want to support more than one vertex group per mesh - // eventually... right now this is hard-coded to use only the first one - // because we only care about the example triangle and cube - fx::gltf::Primitive const &objectPrimitive = objectMesh.primitives[0]; - fx::gltf::Accessor posAccessor; - - std::vector<VertexAttribute> vertexAttributes; - vertexAttributes.reserve(objectPrimitive.attributes.size()); - - for (auto const & attrib : objectPrimitive.attributes) { - fx::gltf::Accessor accessor = object.accessors[attrib.second]; - VertexAttribute attribute; - - if (attrib.first == "POSITION") { - attribute.type = PrimitiveType::POSITION; - posAccessor = accessor; - } else if (attrib.first == "NORMAL") { - attribute.type = PrimitiveType::NORMAL; - } else if (attrib.first == "TEXCOORD_0") { - attribute.type = PrimitiveType::TEXCOORD_0; - } else { - return 0; - } - - attribute.offset = object.bufferViews[accessor.bufferView].byteOffset; - attribute.length = object.bufferViews[accessor.bufferView].byteLength; - attribute.stride = object.bufferViews[accessor.bufferView].byteStride; - attribute.componentType = static_cast<uint16_t>(accessor.componentType); - - if (convertTypeToInt(accessor.type) != 10) { - attribute.componentCount = convertTypeToInt(accessor.type); - } else { - return 0; - } - - vertexAttributes.push_back(attribute); - } - - // TODO consider the case where there is no index buffer (not all - // meshes have to use indexed rendering) - const fx::gltf::Accessor &indexAccessor = object.accessors[objectPrimitive.indices]; - const fx::gltf::BufferView &indexBufferView = object.bufferViews[indexAccessor.bufferView]; - const fx::gltf::Buffer &indexBuffer = object.buffers[indexBufferView.buffer]; - - std::vector<uint8_t> indexBufferData; - indexBufferData.resize(indexBufferView.byteLength); - { - const size_t off = indexBufferView.byteOffset; - const void *const ptr = ((char*)indexBuffer.data.data()) + off; - if (!memcpy(indexBufferData.data(), ptr, indexBufferView.byteLength)) { - vkcv_log(LogLevel::ERROR, "Copying index buffer data"); - return 0; - } - } - - const fx::gltf::BufferView& vertexBufferView = object.bufferViews[posAccessor.bufferView]; - const fx::gltf::Buffer& vertexBuffer = object.buffers[vertexBufferView.buffer]; - - // FIXME: This only works when all vertex attributes are in one buffer - std::vector<uint8_t> vertexBufferData; - vertexBufferData.resize(vertexBuffer.byteLength); - { - const size_t off = 0; - const void *const ptr = ((char*)vertexBuffer.data.data()) + off; - if (!memcpy(vertexBufferData.data(), ptr, vertexBuffer.byteLength)) { - vkcv_log(LogLevel::ERROR, "Copying vertex buffer data"); - return 0; - } - } - - IndexType indexType; - switch(indexAccessor.componentType) { +/** Translate the component type used in the index accessor of fx-gltf to our + * enum for index type. The reason we have defined an incompatible enum that + * needs translation is that only a subset of component types is valid for + * indices and we want to catch these incompatibilities here. */ +enum IndexType getIndexType(const enum fx::gltf::Accessor::ComponentType &t) +{ + switch (t) { case fx::gltf::Accessor::ComponentType::UnsignedByte: - indexType = UINT8; break; + return IndexType::UINT8; case fx::gltf::Accessor::ComponentType::UnsignedShort: - indexType = UINT16; break; + return IndexType::UINT16; case fx::gltf::Accessor::ComponentType::UnsignedInt: - indexType = UINT32; break; + return IndexType::UINT32; default: - vkcv_log(LogLevel::ERROR, "Index type (%u) not supported", - static_cast<uint16_t>(indexAccessor.componentType)); - return 0; + std::cerr << "ERROR: Index type not supported: " << + static_cast<uint16_t>(t) << std::endl; + return IndexType::UNDEFINED; } +} - const size_t numVertexGroups = objectMesh.primitives.size(); - - std::vector<VertexGroup> vertexGroups; - vertexGroups.reserve(numVertexGroups); - - vertexGroups.push_back({ - static_cast<PrimitiveMode>(objectPrimitive.mode), - object.accessors[objectPrimitive.indices].count, - posAccessor.count, - {indexType, indexBufferData}, - {vertexBufferData, vertexAttributes}, - {posAccessor.min[0], posAccessor.min[1], posAccessor.min[2]}, - {posAccessor.max[0], posAccessor.max[1], posAccessor.max[2]}, - static_cast<uint8_t>(objectPrimitive.material) - }); - - std::vector<Material> materials; - - mesh = { - object.meshes[0].name, - vertexGroups, - materials, - 0, 0, 0, NULL - }; - - // FIXME HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK - // fail quietly if there is no texture - if (object.textures.size()) { - const std::string mime_type("image/jpeg"); - const fx::gltf::Texture &tex = object.textures[0]; - const fx::gltf::Image &img = object.images[tex.source]; -#ifndef NDEBUG - printf("texture name=%s sampler=%u source=%u\n", - tex.name.c_str(), tex.sampler, tex.source); - printf("image name=%s uri=%s mime=%s\n", img.name.c_str(), - img.uri.c_str(), img.mimeType.c_str()); -#endif - - size_t pos = path.find_last_of("/"); - auto dir = path.substr(0, pos); - - mesh.texture_hack.img = stbi_load((dir + "/" + img.uri).c_str(), - &mesh.texture_hack.w, &mesh.texture_hack.h, - &mesh.texture_hack.ch, 4); - } - // FIXME HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK - return 1; +/** + * This function computes the modelMatrix out of the data given in the gltf file. It also checks, whether a modelMatrix was given. + * @param translation possible translation vector (default 0,0,0) + * @param scale possible scale vector (default 1,1,1) + * @param rotation possible rotation, given in quaternion (default 0,0,0,1) + * @param matrix possible modelmatrix (default identity) + * @return model Matrix as an array of floats + */ +std::array<float, 16> computeModelMatrix(std::array<float, 3> translation, std::array<float, 3> scale, std::array<float, 4> rotation, std::array<float, 16> matrix){ + std::array<float, 16> modelMatrix = {1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1}; + if (matrix != modelMatrix){ + return matrix; + } else { + // translation + modelMatrix[3] = translation[0]; + modelMatrix[7] = translation[1]; + modelMatrix[11] = translation[2]; + // rotation and scale + auto a = rotation[0]; + auto q1 = rotation[1]; + auto q2 = rotation[2]; + auto q3 = rotation[3]; + + modelMatrix[0] = (2 * (a * a + q1 * q1) - 1) * scale[0]; + modelMatrix[1] = (2 * (q1 * q2 - a * q3)) * scale[1]; + modelMatrix[2] = (2 * (q1 * q3 + a * q2)) * scale[2]; + + modelMatrix[4] = (2 * (q1 * q2 + a * q3)) * scale[0]; + modelMatrix[5] = (2 * (a * a + q2 * q2) - 1) * scale[1]; + modelMatrix[6] = (2 * (q2 * q3 - a * q1)) * scale[2]; + + modelMatrix[8] = (2 * (q1 * q3 - a * q2)) * scale[0]; + modelMatrix[9] = (2 * (q2 * q3 + a * q1)) * scale[1]; + modelMatrix[10] = (2 * (a * a + q3 * q3) - 1) * scale[2]; + + // flip y, because GLTF uses y up, but vulkan -y up + modelMatrix[5] *= -1; + + return modelMatrix; + } + +} + +bool materialHasTexture(const Material *const m, const PBRTextureTarget t) +{ + return m->textureMask & bitflag(t); +} + +int loadScene(const std::string &path, Scene &scene){ + fx::gltf::Document sceneObjects; + + try { + if (path.rfind(".glb", (path.length()-4)) != std::string::npos) { + sceneObjects = fx::gltf::LoadFromBinary(path); + } else { + sceneObjects = fx::gltf::LoadFromText(path); + } + } catch (const std::system_error &err) { + print_what(err, path); + return 0; + } catch (const std::exception &e) { + print_what(e, path); + return 0; + } + size_t pos = path.find_last_of("/"); + auto dir = path.substr(0, pos); + + // file has to contain at least one mesh + if (sceneObjects.meshes.size() == 0) return 0; + + fx::gltf::Accessor posAccessor; + std::vector<VertexAttribute> vertexAttributes; + std::vector<Material> materials; + std::vector<Texture> textures; + std::vector<Sampler> samplers; + std::vector<Mesh> meshes; + std::vector<VertexGroup> vertexGroups; + int groupCount = 0; + + Mesh mesh = {}; + + for(int i = 0; i < sceneObjects.meshes.size(); i++){ + std::vector<int> vertexGroupsIndices; + fx::gltf::Mesh const &objectMesh = sceneObjects.meshes[i]; + + for(int j = 0; j < objectMesh.primitives.size(); j++){ + fx::gltf::Primitive const &objectPrimitive = objectMesh.primitives[j]; + vertexAttributes.clear(); + vertexAttributes.reserve(objectPrimitive.attributes.size()); + + for (auto const & attrib : objectPrimitive.attributes) { + + fx::gltf::Accessor accessor = sceneObjects.accessors[attrib.second]; + VertexAttribute attribute; + + if (attrib.first == "POSITION") { + attribute.type = PrimitiveType::POSITION; + posAccessor = accessor; + } else if (attrib.first == "NORMAL") { + attribute.type = PrimitiveType::NORMAL; + } else if (attrib.first == "TEXCOORD_0") { + attribute.type = PrimitiveType::TEXCOORD_0; + } else if (attrib.first == "TEXCOORD_1") { + attribute.type = PrimitiveType::TEXCOORD_1; + } else { + return 0; + } + + attribute.offset = sceneObjects.bufferViews[accessor.bufferView].byteOffset; + attribute.length = sceneObjects.bufferViews[accessor.bufferView].byteLength; + attribute.stride = sceneObjects.bufferViews[accessor.bufferView].byteStride; + attribute.componentType = static_cast<ComponentType>(accessor.componentType); + + if (convertTypeToInt(accessor.type) != 10) { + attribute.componentCount = convertTypeToInt(accessor.type); + } else { + return 0; + } + + vertexAttributes.push_back(attribute); + } + + IndexType indexType; + std::vector<uint8_t> indexBufferData = {}; + if (objectPrimitive.indices >= 0){ // if there is no index buffer, -1 is returned from fx-gltf + const fx::gltf::Accessor &indexAccessor = sceneObjects.accessors[objectPrimitive.indices]; + const fx::gltf::BufferView &indexBufferView = sceneObjects.bufferViews[indexAccessor.bufferView]; + const fx::gltf::Buffer &indexBuffer = sceneObjects.buffers[indexBufferView.buffer]; + + indexBufferData.resize(indexBufferView.byteLength); + { + const size_t off = indexBufferView.byteOffset; + const void *const ptr = ((char*)indexBuffer.data.data()) + off; + if (!memcpy(indexBufferData.data(), ptr, indexBufferView.byteLength)) { + vkcv_log(LogLevel::ERROR, "Copying index buffer data"); + return 0; + } + } + + indexType = getIndexType(indexAccessor.componentType); + if (indexType == IndexType::UNDEFINED){ + vkcv_log(LogLevel::ERROR, "Index Type undefined."); + return 0; + } + } + + const fx::gltf::BufferView& vertexBufferView = sceneObjects.bufferViews[posAccessor.bufferView]; + const fx::gltf::Buffer& vertexBuffer = sceneObjects.buffers[vertexBufferView.buffer]; + + // only copy relevant part of vertex data + uint32_t relevantBufferOffset = std::numeric_limits<uint32_t>::max(); + uint32_t relevantBufferEnd = 0; + for (const auto &attribute : vertexAttributes) { + relevantBufferOffset = std::min(attribute.offset, relevantBufferOffset); + const uint32_t attributeEnd = attribute.offset + attribute.length; + relevantBufferEnd = std::max(relevantBufferEnd, attributeEnd); // TODO: need to incorporate stride? + } + const uint32_t relevantBufferSize = relevantBufferEnd - relevantBufferOffset; + + // FIXME: This only works when all vertex attributes are in one buffer + std::vector<uint8_t> vertexBufferData; + vertexBufferData.resize(relevantBufferSize); + { + const void *const ptr = ((char*)vertexBuffer.data.data()) + relevantBufferOffset; + if (!memcpy(vertexBufferData.data(), ptr, relevantBufferSize)) { + vkcv_log(LogLevel::ERROR, "Copying vertex buffer data"); + return 0; + } + } + + // make vertex attributes relative to copied section + for (auto &attribute : vertexAttributes) { + attribute.offset -= relevantBufferOffset; + } + + const size_t numVertexGroups = objectMesh.primitives.size(); + vertexGroups.reserve(numVertexGroups); + + vertexGroups.push_back({ + static_cast<PrimitiveMode>(objectPrimitive.mode), + sceneObjects.accessors[objectPrimitive.indices].count, + posAccessor.count, + {indexType, indexBufferData}, + {vertexBufferData, vertexAttributes}, + {posAccessor.min[0], posAccessor.min[1], posAccessor.min[2]}, + {posAccessor.max[0], posAccessor.max[1], posAccessor.max[2]}, + static_cast<uint8_t>(objectPrimitive.material) + }); + + vertexGroupsIndices.push_back(groupCount); + groupCount++; + } + + mesh.name = sceneObjects.meshes[i].name; + mesh.vertexGroups = vertexGroupsIndices; + + meshes.push_back(mesh); + } + + for(int m = 0; m < sceneObjects.nodes.size(); m++) { + meshes[sceneObjects.nodes[m].mesh].modelMatrix = computeModelMatrix(sceneObjects.nodes[m].translation, + sceneObjects.nodes[m].scale, + sceneObjects.nodes[m].rotation, + sceneObjects.nodes[m].matrix); + } + + if (sceneObjects.textures.size() > 0){ + textures.reserve(sceneObjects.textures.size()); + + for(int k = 0; k < sceneObjects.textures.size(); k++){ + const fx::gltf::Texture &tex = sceneObjects.textures[k]; + const fx::gltf::Image &img = sceneObjects.images[tex.source]; + std::string img_uri = dir + "/" + img.uri; + int w, h, c; + uint8_t *data = stbi_load(img_uri.c_str(), &w, &h, &c, 4); + c = 4; // FIXME hardcoded to always have RGBA channel layout + if (!data) { + vkcv_log(LogLevel::ERROR, "Loading texture image data.") + return 0; + } + const size_t byteLen = w * h * c; + + std::vector<uint8_t> imgdata; + imgdata.resize(byteLen); + if (!memcpy(imgdata.data(), data, byteLen)) { + vkcv_log(LogLevel::ERROR, "Copying texture image data") + free(data); + return 0; + } + free(data); + + textures.push_back({ + 0, + static_cast<uint8_t>(c), + static_cast<uint16_t>(w), + static_cast<uint16_t>(h), + imgdata + }); + + } + } + + if (sceneObjects.materials.size() > 0){ + materials.reserve(sceneObjects.materials.size()); + + for (int l = 0; l < sceneObjects.materials.size(); l++){ + fx::gltf::Material material = sceneObjects.materials[l]; + // TODO I think we shouldn't set the index for a texture target if + // it isn't defined. So we need to test first if there is a normal + // texture before assigning material.normalTexture.index. + // About the bitmask: If a normal texture is there, modify the + // materials textureMask like this: + // mat.textureMask |= bitflag(asset::normal); + materials.push_back({ + 0, + material.pbrMetallicRoughness.baseColorTexture.index, + material.pbrMetallicRoughness.metallicRoughnessTexture.index, + material.normalTexture.index, + material.occlusionTexture.index, + material.emissiveTexture.index, + { + material.pbrMetallicRoughness.baseColorFactor[0], + material.pbrMetallicRoughness.baseColorFactor[1], + material.pbrMetallicRoughness.baseColorFactor[2], + material.pbrMetallicRoughness.baseColorFactor[3] + }, + material.pbrMetallicRoughness.metallicFactor, + material.pbrMetallicRoughness.roughnessFactor, + material.normalTexture.scale, + material.occlusionTexture.strength, + { + material.emissiveFactor[0], + material.emissiveFactor[1], + material.emissiveFactor[2] + } + + }); + } + } + + scene = { + meshes, + vertexGroups, + materials, + textures, + samplers + }; + + return 1; } } diff --git a/modules/camera/CMakeLists.txt b/modules/camera/CMakeLists.txt index 28080bf2b1cd3bbc88d6c13d7ef26a43d7c3e19a..73f2dd1c81be9c6cadf563f7936bfaba8c1d0025 100644 --- a/modules/camera/CMakeLists.txt +++ b/modules/camera/CMakeLists.txt @@ -11,10 +11,13 @@ set(vkcv_camera_include ${PROJECT_SOURCE_DIR}/include) set(vkcv_camera_sources ${vkcv_camera_include}/vkcv/camera/Camera.hpp ${vkcv_camera_source}/vkcv/camera/Camera.cpp - ${vkcv_camera_include}/vkcv/camera/TrackballCamera.hpp - ${vkcv_camera_source}/vkcv/camera/TrackballCamera.cpp ${vkcv_camera_include}/vkcv/camera/CameraManager.hpp ${vkcv_camera_source}/vkcv/camera/CameraManager.cpp + ${vkcv_camera_include}/vkcv/camera/CameraController.hpp + ${vkcv_camera_include}/vkcv/camera/PilotCameraController.hpp + ${vkcv_camera_source}/vkcv/camera/PilotCameraController.cpp + ${vkcv_camera_include}/vkcv/camera/TrackballCameraController.hpp + ${vkcv_camera_source}/vkcv/camera/TrackballCameraController.cpp ) # adding source files to the project diff --git a/modules/camera/include/vkcv/camera/Camera.hpp b/modules/camera/include/vkcv/camera/Camera.hpp index ff8fda811eaad7a99dbb940601f9e5904025255e..dc9f2dcb3038655f51fb2404abc21f98a2120399 100644 --- a/modules/camera/include/vkcv/camera/Camera.hpp +++ b/modules/camera/include/vkcv/camera/Camera.hpp @@ -1,101 +1,199 @@ #pragma once +#define GLM_DEPTH_ZERO_TO_ONE +#define GLM_FORCE_LEFT_HANDED #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/matrix_access.hpp> -namespace vkcv { +namespace vkcv::camera { - class Camera { + /** + * @brief Used to create a camera which governs the view and projection matrices. + */ + class Camera final { protected: glm::mat4 m_view; glm::mat4 m_projection; - int m_width; - int m_height; - float m_near; float m_far; - float m_fov; - float m_ratio; - glm::vec3 m_up; + glm::vec3 m_up; glm::vec3 m_position; - float m_cameraSpeed; + glm::vec3 m_center; + float m_pitch; float m_yaw; - - int m_fov_nsteps; - float m_fov_min; - float m_fov_max; - - bool m_forward; - bool m_backward; - bool m_left; - bool m_right; + + /** + * @brief Sets the view matrix of the camera to @p view + * @param[in] view The view matrix + */ + void setView(const glm::mat4& view); + + /** + * @brief Sets the projection matrix of the camera to @p projection + * @param[in] projection The projection matrix + */ + void setProjection(const glm::mat4& projection); public: - Camera(); - virtual ~Camera(); + /** + * @brief The default constructor of the camera + */ + Camera(); + /** + * @brief The destructor of the camera (default behavior) + */ + ~Camera(); + + /** + * @brief Sets the perspective object according to @p fov, @p ratio, @p near and @p far. This leads to changes in the projection matrix of the camera + * @param[in] fov The desired field of view in radians + * @param[in] ratio The aspect ratio + * @param[in] near Distance to near clipping plane + * @param[in] far Distance to far clipping plane + */ void setPerspective(float fov, float ratio, float near, float far); - const glm::mat4 getView() const; - - void getView(glm::vec3 &x, glm::vec3 &y, glm::vec3 &z, glm::vec3 &pos); - - glm::mat4 updateView(double deltatime); - - void lookAt(glm::vec3 position, glm::vec3 center, glm::vec3 up); - + /** + * @brief Gets the view matrix of the camera + * @return The view matrix of the camera + */ + const glm::mat4& getView() const; + + /** + * @brief Sets the view matrix of the camera according to @p position, @p center and @p up + * @param[in] position The position of the camera + * @param[in] center The target position the camera is looking at + * @param[in] up The vector that defines which direction is 'up' depending on the camera's orientation + */ + void lookAt(const glm::vec3& position, const glm::vec3& center, const glm::vec3& up); + + /** + * @brief Gets the current projection of the camera + * @return The current projection matrix + */ const glm::mat4& getProjection() const; - void setProjection(const glm::mat4 projection); - + /** + * @brief Gets the model-view-projection matrix of the camera with y-axis-correction applied + * @return The model-view-projection matrix + */ + glm::mat4 getMVP() const; + + /** + * @brief Gets the near and far bounds of the view frustum of the camera. + * @param[out] near The near bound of the view frustum + * @param[out] far The far bound of the view frustum + */ void getNearFar(float &near, float &far) const; - void setUp(const glm::vec3 &Up); - + /** + * @brief Gets the current field of view of the camera in radians + * @return[in] The current field of view in radians + */ float getFov() const; + /** + * @brief Sets the field of view of the camera to @p fov in radians + * @param[in] fov The new field of view in radians + */ void setFov(float fov); - - void changeFov(double fov); - - void updateRatio(int width, int height); + /** + * @brief Gets the current aspect ratio of the camera + * @return The current aspect ratio of the camera + */ float getRatio() const; + /** + * @brief Updates the aspect ratio of the camera with @p ratio and, thus, changes the projection matrix + * @param[in] ratio The new aspect ratio of the camera + */ + void setRatio(float ratio); + + /** + * @brief Sets @p near and @p far as new values for the view frustum of the camera. This leads to changes in the projection matrix according to these two values. + * @param[in] near The new near bound of the view frustum + * @param[in] far The new far bound of the view frustum + */ void setNearFar(float near, float far); + /** + * @brief Gets the current front vector of the camera in world space + * @return The current front vector of the camera + */ glm::vec3 getFront() const; - - glm::vec3 getPosition() const; - - void setPosition( glm::vec3 position ); - + + /** + * @brief Sets the front vector of the camera in world space to @p front + * @param[in] front The new front vector of the camera + */ + void setFront(const glm::vec3& front); + + /** + * @brief Gets the current position of the camera in world space + * @return The current position of the camera in world space + */ + const glm::vec3& getPosition() const; + + /** + * @brief Sets the position of the camera to @p position + * @param[in] position The new position of the camera + */ + void setPosition( const glm::vec3& position ); + + /** + * @brief Gets the center point. + * @return The center point. + */ + const glm::vec3& getCenter() const; + + /** + * @brief Sets @p center as the new center point. + * @param[in] center The new center point. + */ + void setCenter(const glm::vec3& center); + + /** + * @brief Gets the pitch value of the camera in degrees. + * @return The pitch value in degrees. + */ float getPitch() const; + /** + * @brief Sets the pitch value of the camera to @p pitch in degrees. + * @param[in] pitch The new pitch value in degrees. + */ void setPitch(float pitch); + /** + * @brief Gets the yaw value of the camera in degrees. + * @return The yaw value in degrees. + */ float getYaw() const; + /** + * @brief Sets the yaw value of the camera to @p yaw. + * @param[in] yaw The new yaw value in degrees. + */ void setYaw(float yaw); - void panView( double xOffset, double yOffset ); - - void updatePosition(double deltatime); - - void moveForward(int action); - - void moveBackward(int action); - - void moveLeft(int action); - - void moveRight(int action); - - + /** + * @brief Gets the up vector. + * @return The up vector. + */ + const glm::vec3& getUp() const; + + /** + * @brief Sets @p up as the new up vector. + * @param[in] up The new up vector. + */ + void setUp(const glm::vec3 &up); }; } diff --git a/modules/camera/include/vkcv/camera/CameraController.hpp b/modules/camera/include/vkcv/camera/CameraController.hpp new file mode 100644 index 0000000000000000000000000000000000000000..28dd8436bab07da759cd1a6bf4dba5d7cbd2b46f --- /dev/null +++ b/modules/camera/include/vkcv/camera/CameraController.hpp @@ -0,0 +1,71 @@ +#pragma once + +#include "Camera.hpp" +#include "vkcv/Window.hpp" + +namespace vkcv::camera { + + /** + * @brief Used as a base class for defining camera controller classes with different behaviors, e.g. the + * #PilotCameraController. + */ + class CameraController { + + public: + + /** + * @brief The constructor of the #CameraController (default behavior). + */ + CameraController() = default; + + /** + * @brief Updates @p camera in respect to @p deltaTime. + * @param[in] deltaTime The time that has passed since last update. + * @param[in] camera The camera object. + */ + virtual void updateCamera(double deltaTime, Camera &camera) = 0; + + /** + * @brief A callback function for key events. + * @param[in] key The keyboard key. + * @param[in] scancode The platform-specific scancode. + * @param[in] action The key action. + * @param[in] mods The modifier bits. + * @param[in] camera The camera object. + */ + virtual void keyCallback(int key, int scancode, int action, int mods, Camera &camera) = 0; + + /** + * @brief A callback function for mouse scrolling events. + * @param[in] offsetX The offset in horizontal direction. + * @param[in] offsetY The offset in vertical direction. + * @param[in] camera The camera object. + */ + virtual void scrollCallback( double offsetX, double offsetY, Camera &camera) = 0; + + /** + * @brief A callback function for mouse movement events. + * @param[in] x The horizontal mouse position. + * @param[in] y The vertical mouse position. + * @param[in] camera The camera object. + */ + virtual void mouseMoveCallback(double offsetX, double offsetY, Camera &camera) = 0; + + /** + * @brief A callback function for mouse button events. + * @param[in] button The mouse button. + * @param[in] action The button action. + * @param[in] mods The modifier bits. + * @param[in] camera The camera object. + */ + virtual void mouseButtonCallback(int button, int action, int mods, Camera &camera) = 0; + + /** + * @brief A callback function for gamepad input events. + * @param gamepadIndex The gamepad index. + * @param camera The camera object. + */ + virtual void gamepadCallback(int gamepadIndex, Camera &camera) = 0; + }; + +} \ No newline at end of file diff --git a/modules/camera/include/vkcv/camera/CameraManager.hpp b/modules/camera/include/vkcv/camera/CameraManager.hpp index 4e52eccea25e8544a9a5cc89d0dc74ddd0e023c6..b0597da4cab1f553a7bd22da388a66e7fc19de19 100644 --- a/modules/camera/include/vkcv/camera/CameraManager.hpp +++ b/modules/camera/include/vkcv/camera/CameraManager.hpp @@ -1,40 +1,194 @@ #pragma once -#include "TrackballCamera.hpp" +#include "PilotCameraController.hpp" +#include "TrackballCameraController.hpp" +#include "CameraController.hpp" #include "vkcv/Window.hpp" #include <GLFW/glfw3.h> #include <functional> -namespace vkcv{ +namespace vkcv::camera { + /** + * @brief Used for specifying existing types of camera controllers when adding a new controller object to the + * #CameraManager. + */ + enum class ControllerType { + NONE, + PILOT, + TRACKBALL, + TRACE + }; + + /** + * @brief Used for managing an arbitrary amount of camera controllers. + */ class CameraManager{ private: - std::function<void(int, int, int, int)> e_keyHandle; - std::function<void(double, double)> e_mouseMoveHandle; - std::function<void(double, double)> e_mouseScrollHandle; - std::function<void(int, int, int)> e_mouseButtonHandle; - std::function<void(int, int)> e_resizeHandle; - - Window &m_window; - Camera m_camera; - float m_width; - float m_height; -// std::shared_ptr<vkcv::TrackballCamera> m_trackball; - - bool m_roationActive = false; - double m_lastX ; - double m_lastY ; - - void bindCamera(); + event_handle<int, int, int, int> m_keyHandle; + event_handle<double, double> m_mouseMoveHandle; + event_handle<double, double> m_mouseScrollHandle; + event_handle<int, int, int> m_mouseButtonHandle; + event_handle<int, int> m_resizeHandle; + event_handle<int> m_gamepadHandle; + + Window& m_window; + std::vector<Camera> m_cameras; + std::vector<ControllerType> m_cameraControllerTypes; + uint32_t m_activeCameraIndex; + + PilotCameraController m_pilotController; + TrackballCameraController m_trackController; + + double m_lastX; + double m_lastY; + + double m_inputDelayTimer; + + /** + * @brief Binds the camera object to the window event handles. + */ + void bindCameraToEvents(); + + /** + * @brief A callback function for key events. Currently, cycling between all existing camera controllers via Tab, + * window closure via Esc and polling key events from the active camera controller are supported. + * @param[in] key The keyboard key. + * @param[in] scancode The platform-specific scancode. + * @param[in] action The key action. + * @param[in] mods The modifier bits. + */ void keyCallback(int key, int scancode, int action, int mods); - void scrollCallback( double offsetX, double offsetY); - void mouseMoveCallback( double offsetX, double offsetY); + + /** + * @brief A callback function for mouse scrolling events. + * @param[in] offsetX The offset in horizontal direction. + * @param[in] offsetY The offset in vertical direction. + */ + void scrollCallback(double offsetX, double offsetY); + + /** + * @brief A callback function for mouse movement events. + * @param[in] x The horizontal mouse position. + * @param[in] y The vertical mouse position. + */ + void mouseMoveCallback(double x, double y); + + /** + * @brief A callback function for mouse button events. + * @param[in] button The mouse button. + * @param[in] action The button action. + * @param[in] mods The modifier bits. + */ void mouseButtonCallback(int button, int action, int mods); + + /** + * @brief A callback function for handling the window resizing event. Each existing camera is resized in respect + * of the window size. + * @param[in] width The new width of the window. + * @param[in] height The new height of the window. + */ void resizeCallback(int width, int height); + /** + * @brief A callback function for gamepad input events. Currently, inputs are handled only for the first + * connected gamepad! + * @param gamepadIndex The gamepad index. + */ + void gamepadCallback(int gamepadIndex); + + /** + * @brief Gets a camera controller object of specified @p controllerType. + * @param[in] controllerType The type of the camera controller. + * @return The specified camera controller object. + */ + CameraController& getControllerByType(ControllerType controllerType); + + /** + * @briof A method to get the currently active controller for the active camera. + * @return Reference to the active #CameraController + */ + CameraController& getActiveController(); + public: - CameraManager(Window &window, float width, float height, glm::vec3 up = glm::vec3(0.0f,-1.0f,0.0f), glm::vec3 position = glm::vec3(0.0f,0.0f,0.0f)); - Camera &getCamera(); + /** + * @brief The constructor of the #CameraManager. + * @param[in] window The window. + */ + CameraManager(Window &window); + + /** + * @brief The destructor of the #CameraManager. Destroying the #CameraManager leads to deletion of all stored + * camera objects and camera controller objects. + */ + ~CameraManager(); + + /** + * @brief Adds a new camera object to the #CameraManager and binds it to a camera controller object of specified + * @p controllerType. + * @param[in] controllerType The type of the camera controller. + * @return The index of the newly created camera object. + */ + uint32_t addCamera(ControllerType controllerType = ControllerType::NONE); + + /** + * @brief Adds a new camera object to the #CameraManager and binds it to a camera controller object of specified + * @p controllerType. + * @param[in] controllerType The type of the camera controller. + * @param[in] camera The new camera object. + * @return The index of the newly bound camera object. + */ + uint32_t addCamera(ControllerType controllerType, const Camera& camera); + + /** + * @brief Gets the stored camera object located at @p cameraIndex. + * @param[in] cameraIndex The camera index. + * @return The camera object at @p cameraIndex. + * @throws std::runtime_error If @p cameraIndex is not a valid camera index. + */ + Camera& getCamera(uint32_t cameraIndex); + + /** + * @brief Gets the stored camera object set as the active camera. + * @return The active camera. + */ + Camera& getActiveCamera(); + + /** + * @brief Sets the stored camera object located at @p cameraIndex as the active camera. + * @param[in] cameraIndex The camera index. + * @throws std::runtime_error If @p cameraIndex is not a valid camera index. + */ + void setActiveCamera(uint32_t cameraIndex); + + /** + * @brief Gets the index of the stored active camera object. + * @return The active camera index. + */ + uint32_t getActiveCameraIndex() const; + + /** + * @brief Binds a stored camera object located at @p cameraIndex to a camera controller of specified + * @p controllerType. + * @param[in] cameraIndex The camera index. + * @param[in] controllerType The type of the camera controller. + * @throws std::runtime_error If @p cameraIndex is not a valid camera index. + */ + void setControllerType(uint32_t cameraIndex, ControllerType controllerType); + + /** + * @brief Gets the currently bound camera controller type of the stored camera object located at @p cameraIndex. + * @param[in] cameraIndex The camera index. + * @return The type of the camera controller of the specified camera object. + * @throws std::runtime_error If @p cameraIndex is not a valid camera index. + */ + ControllerType getControllerType(uint32_t cameraIndex); + + /** + * @brief Updates all stored camera controllers in respect to @p deltaTime. + * @param[in] deltaTime The time that has passed since last update. + */ + void update(double deltaTime); }; } diff --git a/modules/camera/include/vkcv/camera/PilotCameraController.hpp b/modules/camera/include/vkcv/camera/PilotCameraController.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2ba358546e9c0ef7927dd9445901d4eaab1b2f36 --- /dev/null +++ b/modules/camera/include/vkcv/camera/PilotCameraController.hpp @@ -0,0 +1,149 @@ +#pragma once + +#include <vkcv/camera/CameraController.hpp> + +namespace vkcv::camera { + + /** + * @brief Used to move around a camera object in world space. + */ + class PilotCameraController final : public CameraController { + private: + // camera movement indicators + bool m_forward; + bool m_backward; + bool m_upward; + bool m_downward; + bool m_left; + bool m_right; + + float m_gamepadX; + float m_gamepadY; + float m_gamepadZ; + + bool m_rotationActive; + + float m_cameraSpeed; + + int m_fov_nsteps; + float m_fov_min; + float m_fov_max; + + /** + * @brief Indicates forward movement of the camera depending on the performed @p action. + * @param[in] action The performed action. + */ + void moveForward(int action); + + /** + * @brief Indicates backward movement of the camera depending on the performed @p action. + * @param[in] action The performed action. + */ + void moveBackward(int action); + + /** + * @brief Indicates left movement of the camera depending on the performed @p action. + * @param[in] action The performed action. + */ + void moveLeft(int action); + + /** + * @brief Indicates right movement of the camera depending on the performed @p action. + * @param[in] action The performed action. + */ + void moveRight(int action); + + /** + * @brief Indicates upward movement of the camera depending on the performed @p action. + * @param[in] action The performed action. + */ + void moveUpward(int action); + + /** + * @brief Indicates downward movement of the camera depending on the performed @p action. + * @param[in] action The performed action. + */ + void moveDownward(int action); + + public: + + /** + * @brief The default constructor of the #PilotCameraController. + */ + PilotCameraController(); + + /** + * @brief The destructor of the #PilotCameraController (default behavior). + */ + ~PilotCameraController() = default; + + /** + * @brief Changes the field of view of @p camera with an @p offset in degrees. + * @param[in] offset The offset in degrees. + * @param[in] camera The camera object. + */ + void changeFov(double offset, Camera &camera); + + /** + * @brief Pans the view of @p camera according to the pitch and yaw values and additional offsets @p xOffset + * and @p yOffset. + * @param[in] xOffset The offset added to the yaw value. + * @param[in] yOffset The offset added to the pitch value. + * @param[in] camera The camera object. + */ + void panView(double xOffset, double yOffset, Camera &camera); + + /** + * @brief Updates @p camera in respect to @p deltaTime. + * @param[in] deltaTime The time that has passed since last update. + * @param[in] camera The camera object. + */ + void updateCamera(double deltaTime, Camera &camera); + + /** + * @brief A callback function for key events. Currently, 3D camera movement via W, A, S, D, E, Q are supported. + * @param[in] key The keyboard key. + * @param[in] scancode The platform-specific scancode. + * @param[in] action The key action. + * @param[in] mods The modifier bits. + * @param[in] camera The camera object. + */ + void keyCallback(int key, int scancode, int action, int mods, Camera &camera); + + /** + * @brief A callback function for mouse scrolling events. Currently, this leads to changes in the field of view + * of @p camera. + * @param[in] offsetX The offset in horizontal direction. + * @param[in] offsetY The offset in vertical direction. + * @param[in] camera The camera object. + */ + void scrollCallback(double offsetX, double offsetY, Camera &camera); + + /** + * @brief A callback function for mouse movement events. Currently, this leads to panning the view of the camera, + * if #mouseButtonCallback(int button, int action, int mods) enabled panning. + * @param[in] x The horizontal mouse position + * @param[in] y The vertical mouse position + * @param[in] camera The camera object. + */ + void mouseMoveCallback(double x, double y, Camera &camera); + + /** + * @brief A callback function for mouse button events. Currently, the right mouse button enables panning the + * view of the camera as long as it is pressed. + * @param[in] button The mouse button + * @param[in] action The button action + * @param[in] mods The modifier bits + * @param[in] camera The camera object. + */ + void mouseButtonCallback(int button, int action, int mods, Camera &camera); + + /** + * @brief A callback function for gamepad input events. + * @param gamepadIndex The gamepad index. + * @param camera The camera object. + */ + void gamepadCallback(int gamepadIndex, Camera &camera); + }; + +} \ No newline at end of file diff --git a/modules/camera/include/vkcv/camera/TrackballCamera.hpp b/modules/camera/include/vkcv/camera/TrackballCamera.hpp deleted file mode 100644 index c9e269e9f7ad708c68158d5b358efbf37c5bb7a9..0000000000000000000000000000000000000000 --- a/modules/camera/include/vkcv/camera/TrackballCamera.hpp +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include "Camera.hpp" - -namespace vkcv { - - class TrackballCamera : public vkcv::Camera { - public: - - TrackballCamera( int width, int height, glm::mat4 projection); - - TrackballCamera(int width, int height); - - ~TrackballCamera(); - - float getSensitivity() const; - - void setSensitivity(float sensitivity); - - float getStepSize() const; - - void setStepSize(float stepSize); - - float getTheta() const; - - void setTheta(float theta); - - float getPhi() const; - - void setPhi(float phi); - - float getRadius() const; - - void setRadius(float radius); - - const glm::vec3& getCenter() const; - - void setCenter(const glm::vec3 ¢er); - - private: - float m_sensitivity; - float m_stepSize, m_theta, m_phi, m_radius; - glm::vec3 m_center; - - float m_oldX; - float m_oldY; - }; - -} \ No newline at end of file diff --git a/modules/camera/include/vkcv/camera/TrackballCameraController.hpp b/modules/camera/include/vkcv/camera/TrackballCameraController.hpp new file mode 100644 index 0000000000000000000000000000000000000000..1fbf59e56b3edbc4b7719402fd55a9eaebdf7c94 --- /dev/null +++ b/modules/camera/include/vkcv/camera/TrackballCameraController.hpp @@ -0,0 +1,106 @@ +#pragma once + +#include "CameraController.hpp" + +namespace vkcv::camera { + + /** + * @brief Used to orbit a camera around its center point. + */ + class TrackballCameraController final : public CameraController { + private: + bool m_rotationActive; + + float m_cameraSpeed; + float m_scrollSensitivity; + float m_radius; + + /** + * @brief Updates the current radius of @p camera in respect to the @p offset. + * @param[in] offset The offset between the old and new radius. + * @param[in] camera The camera object. + */ + void updateRadius(double offset, Camera &camera); + + public: + + /** + * @brief The default constructor of the #TrackballCameraController. + */ + TrackballCameraController(); + + /** + * @brief The destructor of the #TrackballCameraController (default behavior). + */ + ~TrackballCameraController() = default; + + /** + * @brief Sets @p radius as the new radius for orbiting around the camera's center point. + * @param[in] radius The new radius. + */ + void setRadius(const float radius); + + /** + * @brief Pans the view of @p camera according to the pitch and yaw values and additional offsets @p xOffset + * and @p yOffset. + * @param[in] xOffset The offset added to the yaw value. + * @param[in] yOffset The offset added to the pitch value. + * @param[in] camera The camera object. + */ + void panView(double xOffset, double yOffset, Camera &camera); + + /** + * @brief Updates @p camera in respect to @p deltaTime. + * @param[in] deltaTime The time that has passed since last update. + * @param[in] camera The camera object + */ + void updateCamera(double deltaTime, Camera &camera); + + /** + * @brief A callback function for key events. Currently, the trackball camera does not support camera movement. + * It can only orbit around its center point. + * @param[in] key The keyboard key. + * @param[in] scancode The platform-specific scancode. + * @param[in] action The key action. + * @param[in] mods The modifier bits. + * @param[in] camera The camera object. + */ + void keyCallback(int key, int scancode, int action, int mods, Camera &camera); + + /** + * @brief A callback function for mouse scrolling events. Currently, this leads to changes in the field of view + * of the camera object. + * @param[in] offsetX The offset in horizontal direction. + * @param[in] offsetY The offset in vertical direction. + * @param[in] camera The camera object. + */ + void scrollCallback(double offsetX, double offsetY, Camera &camera); + + /** + * @brief A callback function for mouse movement events. Currently, this leads to panning the view of the + * camera, if #mouseButtonCallback(int button, int action, int mods) enabled panning. + * @param[in] xoffset The horizontal mouse position. + * @param[in] yoffset The vertical mouse position. + * @param[in] camera The camera object. + */ + void mouseMoveCallback(double xoffset, double yoffset, Camera &camera); + + /** + * @brief A callback function for mouse button events. Currently, the right mouse button enables panning the + * view of the camera as long as it is pressed. + * @param[in] button The mouse button. + * @param[in] action The button action. + * @param[in] mods The modifier bits. + * @param[in] camera The camera object. + */ + void mouseButtonCallback(int button, int action, int mods, Camera &camera); + + /** + * @brief A callback function for gamepad input events. + * @param gamepadIndex The gamepad index. + * @param camera The camera object. + */ + void gamepadCallback(int gamepadIndex, Camera &camera); + }; + +} \ No newline at end of file diff --git a/modules/camera/src/vkcv/camera/Camera.cpp b/modules/camera/src/vkcv/camera/Camera.cpp index af89ed86881acc8b754a041d32599a78caac57b4..eb1857968b2284287691c6ed41ba168db30d3f84 100644 --- a/modules/camera/src/vkcv/camera/Camera.cpp +++ b/modules/camera/src/vkcv/camera/Camera.cpp @@ -1,44 +1,28 @@ #include "vkcv/camera/Camera.hpp" -#include <iostream> -namespace vkcv { +#define _USE_MATH_DEFINES +#include <math.h> - Camera::Camera(){ - m_up = glm::vec3(0.0f, -1.0f, 0.0f); - m_position = glm::vec3(0.0f, 0.0f, 0.0f); - m_cameraSpeed = 2.f; - // front - m_pitch = 0.0; - m_yaw = 180.0; +namespace vkcv::camera { - m_fov_nsteps = 100; - m_fov_min = 10; - m_fov_max = 120; - - m_forward = false; - m_backward = false; - m_left = false; - m_right = false; + Camera::Camera() { + lookAt( + glm::vec3(0.0f, 0.0f, -1.0f), + glm::vec3(0.0f, 0.0f, 0.0f), + glm::vec3(0.0f, 1.0f, 0.0f) + ); + + setFront(glm::normalize(m_center - m_position)); } Camera::~Camera() = default; - void Camera::lookAt(glm::vec3 position, glm::vec3 center, glm::vec3 up){ - m_view = glm::lookAt(position, center, up); - } - - glm::mat4 Camera::updateView(double deltatime){ - updatePosition(deltatime); - return m_view = glm::lookAt(m_position, m_position + getFront() , m_up); - } - - void Camera::getView(glm::vec3 &x, glm::vec3 &y, glm::vec3 &z, glm::vec3 &pos){ - x = glm::vec3( glm::row(m_view, 0)); - y = glm::vec3( glm::row(m_view, 1)); - z = glm::vec3( glm::row(m_view, 2)); - pos = glm::vec3( glm::column(m_view, 3)); - glm::mat3 mat_inv = glm::inverse( glm::mat3(m_view)); - pos = -mat_inv * pos; + void Camera::lookAt(const glm::vec3& position, const glm::vec3& center, const glm::vec3& up) { + m_position = position; + m_center = center; + m_up = up; + + setView(glm::lookAt(position, center, up)); } void Camera::getNearFar( float &near, float &far) const { @@ -46,98 +30,111 @@ namespace vkcv { far = m_far; } - - const glm::mat4 Camera::getView() const { + const glm::mat4& Camera::getView() const { return m_view; } + + void Camera::setView(const glm::mat4 &view) { + m_view = view; + } const glm::mat4& Camera::getProjection() const { return m_projection; } - void Camera::setProjection(const glm::mat4 projection){ - m_projection = projection; + void Camera::setProjection(const glm::mat4& projection) { + m_projection = projection; } - float Camera::getFov() const { - return m_fov; + glm::mat4 Camera::getMVP() const { + const glm::mat4 y_correction ( + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, -1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + + return y_correction * m_projection * m_view; } - void Camera::setFov( float fov){ - m_fov = fov; - setPerspective( m_fov, m_ratio, m_near, m_far); + float Camera::getFov() const { + const float tanHalfFovy = 1.0f / m_projection[1][1]; + float halfFovy = std::atan(tanHalfFovy); + + if (halfFovy < 0) { + halfFovy += static_cast<float>(M_PI); + } + + return halfFovy * 2.0f; } - void Camera::changeFov(double offset){ - float fov = m_fov; - float fov_range = m_fov_max - m_fov_min; - float fov_stepsize = glm::radians(fov_range)/m_fov_nsteps; - fov -= (float) offset*fov_stepsize; - if (fov < glm::radians(m_fov_min)) { - fov = glm::radians(m_fov_min); - } - if (fov > glm::radians(m_fov_max)) { - fov = glm::radians(m_fov_max); - } - setFov(fov); + void Camera::setFov( float fov){ + setPerspective(fov, getRatio(), m_near, m_far); } - void Camera::updateRatio( int width, int height){ - m_width = width; - m_height = height; - m_ratio = static_cast<float>(width)/glm::max(height, 1); - setPerspective( m_fov, m_ratio, m_near, m_far); + float Camera::getRatio() const { + const float aspectProduct = 1.0f / m_projection[0][0]; + const float tanHalfFovy = 1.0f / m_projection[1][1]; + + return aspectProduct / tanHalfFovy; } - float Camera::getRatio() const { - return m_ratio; + void Camera::setRatio(float ratio){ + setPerspective( getFov(), ratio, m_near, m_far); } - void Camera::setNearFar( float near, float far){ - m_near = near; - m_far = far; - setPerspective(m_fov, m_ratio, m_near, m_far); + void Camera::setNearFar(float near, float far){ + setPerspective(getFov(), getRatio(), near, far); } - void Camera::setPerspective(float fov, float ratio, float near, float far){ - m_fov = fov; - m_ratio = ratio; - m_near = near; - m_far = far; - m_projection = glm::perspective( m_fov, ratio, m_near, m_far); + void Camera::setPerspective(float fov, float ratio, float near, float far) { + m_near = near; + m_far = far; + setProjection(glm::perspective(fov, ratio, near, far)); } glm::vec3 Camera::getFront() const { glm::vec3 direction; - direction.x = sin(glm::radians(m_yaw)) * cos(glm::radians(m_pitch)); - direction.y = sin(glm::radians(m_pitch)); - direction.z = cos(glm::radians(m_yaw)) * cos(glm::radians(m_pitch)); + direction.x = std::sin(glm::radians(m_yaw)) * std::cos(glm::radians(m_pitch)); + direction.y = std::sin(glm::radians(m_pitch)); + direction.z = std::cos(glm::radians(m_yaw)) * std::cos(glm::radians(m_pitch)); return glm::normalize(direction); } + + void Camera::setFront(const glm::vec3 &front) { + m_pitch = std::atan2(front.y, std::sqrt(front.x * front.x + front.z * front.z)); + m_yaw = std::atan2(front.x, front.z); + } - glm::vec3 Camera::getPosition() const { + const glm::vec3& Camera::getPosition() const { return m_position; } - void Camera::setPosition( glm::vec3 position ){ - m_position = position; + void Camera::setPosition( const glm::vec3& position ){ + lookAt(position, m_center, m_up); } - void Camera::setUp(const glm::vec3 &up) { - m_up = up; + const glm::vec3& Camera::getCenter() const { + return m_center; } + void Camera::setCenter(const glm::vec3& center) { + lookAt(m_position, center, m_up); + } + + const glm::vec3& Camera::getUp() const { + return m_up; + } + + void Camera::setUp(const glm::vec3 &up) { + lookAt(m_position, m_center, up); + } + float Camera::getPitch() const { return m_pitch; } void Camera::setPitch(float pitch) { - if (pitch > 89.0f) { - pitch = 89.0f; - } - if (pitch < -89.0f) { - pitch = -89.0f; - } m_pitch = pitch; } @@ -149,31 +146,4 @@ namespace vkcv { m_yaw = yaw; } - void Camera::panView(double xOffset, double yOffset) { - m_yaw += xOffset; - m_pitch += yOffset; - } - - void Camera::updatePosition(double deltatime ){ - m_position += (m_cameraSpeed * getFront() * static_cast<float> (m_forward) * static_cast<float>(deltatime)); - m_position -= (m_cameraSpeed * getFront() * static_cast<float> (m_backward) * static_cast<float>(deltatime)); - m_position -= (glm::normalize(glm::cross(getFront(), m_up)) * m_cameraSpeed * static_cast<float> (m_left) * static_cast<float>(deltatime)); - m_position += (glm::normalize(glm::cross(getFront(), m_up)) * m_cameraSpeed * static_cast<float> (m_right) * static_cast<float>(deltatime)); - } - - void Camera::moveForward(int action){ - m_forward = static_cast<bool>(action); - } - - void Camera::moveBackward(int action){ - m_backward = static_cast<bool>(action); - } - - void Camera::moveLeft(int action){ - m_left = static_cast<bool>(action); - } - - void Camera::moveRight(int action){ - m_right = static_cast<bool>(action); - } } \ No newline at end of file diff --git a/modules/camera/src/vkcv/camera/CameraManager.cpp b/modules/camera/src/vkcv/camera/CameraManager.cpp index 2631890d646fbf27a4fbb14cfeef706678d8918c..d539994dc0071dd52764477a86ff202955c1b8f3 100644 --- a/modules/camera/src/vkcv/camera/CameraManager.cpp +++ b/modules/camera/src/vkcv/camera/CameraManager.cpp @@ -1,88 +1,189 @@ -#include <iostream> + #include "vkcv/camera/CameraManager.hpp" +#include <vkcv/Logger.hpp> -namespace vkcv{ +namespace vkcv::camera { - CameraManager::CameraManager(Window &window, float width, float height, glm::vec3 up, glm::vec3 position): - m_window(window), m_width(width), m_height(height) + CameraManager::CameraManager(Window& window) + : m_window(window) { - m_camera.setUp(up); - m_camera.setPosition(position); - m_camera.setPerspective( glm::radians(60.0f), m_width / m_height, 0.1f, 10.f); - m_lastX = width/2.0; - m_lastY = height/2.0; - bindCamera(); + bindCameraToEvents(); + m_activeCameraIndex = 0; + m_lastX = static_cast<float>(window.getWidth()) / 2.0f; + m_lastY = static_cast<float>(window.getHeight()) / 2.0f; + m_inputDelayTimer = glfwGetTime() + 0.2; + } + + CameraManager::~CameraManager() { + m_window.e_key.remove(m_keyHandle); + m_window.e_mouseMove.remove(m_mouseMoveHandle); + m_window.e_mouseScroll.remove(m_mouseScrollHandle); + m_window.e_mouseButton.remove(m_mouseButtonHandle); + m_window.e_resize.remove(m_resizeHandle); + m_window.e_gamepad.remove(m_gamepadHandle); + } + + void CameraManager::bindCameraToEvents() { + m_keyHandle = m_window.e_key.add( [&](int key, int scancode, int action, int mods) { this->keyCallback(key, scancode, action, mods); }); + m_mouseMoveHandle = m_window.e_mouseMove.add( [&]( double offsetX, double offsetY) {this->mouseMoveCallback( offsetX, offsetY);} ); + m_mouseScrollHandle = m_window.e_mouseScroll.add([&](double offsetX, double offsetY) {this->scrollCallback( offsetX, offsetY);} ); + m_mouseButtonHandle = m_window.e_mouseButton.add([&] (int button, int action, int mods) {this->mouseButtonCallback( button, action, mods);}); + m_resizeHandle = m_window.e_resize.add([&](int width, int height) {this->resizeCallback(width, height);}); + m_gamepadHandle = m_window.e_gamepad.add([&](int gamepadIndex) {this->gamepadCallback(gamepadIndex);}); } - void CameraManager::bindCamera(){ - e_keyHandle = m_window.e_key.add( [&](int key, int scancode, int action, int mods) { this->keyCallback(key, scancode, action, mods); }); - e_mouseMoveHandle = m_window.e_mouseMove.add( [&]( double offsetX, double offsetY) {this->mouseMoveCallback( offsetX, offsetY);} ); - e_mouseScrollHandle = m_window.e_mouseScroll.add([&](double offsetX, double offsetY) {this->scrollCallback( offsetX, offsetY);} ); - e_mouseButtonHandle = m_window.e_mouseButton.add([&] (int button, int action, int mods) {this->mouseButtonCallback( button, action, mods);}); - e_resizeHandle = m_window.e_resize.add([&] (int width, int height) {this->resizeCallback( width, height);}); + void CameraManager::resizeCallback(int width, int height) { + for (size_t i = 0; i < m_cameras.size(); i++) { + getCamera(i).setRatio(static_cast<float>(width) / static_cast<float>(height));; + } } void CameraManager::mouseButtonCallback(int button, int action, int mods){ - if(button == GLFW_MOUSE_BUTTON_2 && m_roationActive == false && action == GLFW_PRESS){ + if(button == GLFW_MOUSE_BUTTON_2 && action == GLFW_PRESS){ glfwSetInputMode(m_window.getWindow(), GLFW_CURSOR, GLFW_CURSOR_DISABLED); - m_roationActive = true; - }else if(button == GLFW_MOUSE_BUTTON_2 && m_roationActive == true && action == GLFW_RELEASE){ + } + else if(button == GLFW_MOUSE_BUTTON_2 && action == GLFW_RELEASE){ glfwSetInputMode(m_window.getWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL); - m_roationActive = false; } + getActiveController().mouseButtonCallback(button, action, mods, getActiveCamera()); } void CameraManager::mouseMoveCallback(double x, double y){ - - float xoffset = x - m_lastX; - float yoffset = m_lastY - y; + auto xoffset = static_cast<float>(x - m_lastX); + auto yoffset = static_cast<float>(y - m_lastY); m_lastX = x; m_lastY = y; + getActiveController().mouseMoveCallback(xoffset, yoffset, getActiveCamera()); + } + + void CameraManager::scrollCallback(double offsetX, double offsetY) { + getActiveController().scrollCallback(offsetX, offsetY, getActiveCamera()); + } - if(!m_roationActive){ - return; + void CameraManager::keyCallback(int key, int scancode, int action, int mods) { + switch (action) { + case GLFW_RELEASE: + switch (key) { + case GLFW_KEY_TAB: + if (m_activeCameraIndex + 1 == m_cameras.size()) { + m_activeCameraIndex = 0; + } + else { + m_activeCameraIndex++; + } + return; + case GLFW_KEY_ESCAPE: + glfwSetWindowShouldClose(m_window.getWindow(), 1); + return; + default: + break; + } + default: + getActiveController().keyCallback(key, scancode, action, mods, getActiveCamera()); + break; } + } - float sensitivity = 0.05f; - xoffset *= sensitivity; - yoffset *= sensitivity; + // todo: fix event catch speed + void CameraManager::gamepadCallback(int gamepadIndex) { + // handle camera switching + GLFWgamepadstate gamepadState; + glfwGetGamepadState(gamepadIndex, &gamepadState); - m_camera.panView( xoffset , yoffset ); + double time = glfwGetTime(); + if (time - m_inputDelayTimer > 0.2) { + int switchDirection = gamepadState.buttons[GLFW_GAMEPAD_BUTTON_DPAD_RIGHT] - gamepadState.buttons[GLFW_GAMEPAD_BUTTON_DPAD_LEFT]; + m_activeCameraIndex += switchDirection; + if (std::greater<int>{}(m_activeCameraIndex, m_cameras.size() - 1)) { + m_activeCameraIndex = 0; + } + else if (std::less<int>{}(m_activeCameraIndex, 0)) { + m_activeCameraIndex = m_cameras.size() - 1; + } + uint32_t triggered = abs(switchDirection); + m_inputDelayTimer = (1-triggered)*m_inputDelayTimer + triggered * time; // Only reset timer, if dpad was pressed - is this cheaper than if-clause? + } + + getActiveController().gamepadCallback(gamepadIndex, getActiveCamera()); // handle camera rotation, translation } - void CameraManager::scrollCallback(double offsetX, double offsetY) { - m_camera.changeFov(offsetY); + CameraController& CameraManager::getActiveController() { + const ControllerType type = getControllerType(getActiveCameraIndex()); + return getControllerByType(type); + } + + uint32_t CameraManager::addCamera(ControllerType controllerType) { + const float ratio = static_cast<float>(m_window.getWidth()) / static_cast<float>(m_window.getHeight()); + + Camera camera; + camera.setPerspective(glm::radians(60.0f), ratio, 0.1f, 10.0f); + return addCamera(controllerType, camera); + } + + uint32_t CameraManager::addCamera(ControllerType controllerType, const Camera &camera) { + const uint32_t index = static_cast<uint32_t>(m_cameras.size()); + m_cameras.push_back(camera); + m_cameraControllerTypes.push_back(controllerType); + return index; } - void CameraManager::keyCallback(int key, int scancode, int action, int mods) { + Camera& CameraManager::getCamera(uint32_t cameraIndex) { + if (cameraIndex < 0 || cameraIndex > m_cameras.size() - 1) { + vkcv_log(LogLevel::ERROR, "Invalid camera index: The index must range from 0 to %lu", m_cameras.size()); + return getActiveCamera(); + } + + return m_cameras[cameraIndex]; + } - switch (key) { - case GLFW_KEY_W: - m_camera.moveForward(action); - break; - case GLFW_KEY_S: - m_camera.moveBackward(action); - break; - case GLFW_KEY_A: - m_camera.moveLeft(action); - break; - case GLFW_KEY_D: - m_camera.moveRight(action); - break; - case GLFW_KEY_ESCAPE: - glfwSetWindowShouldClose(m_window.getWindow(), 1); - break; - default: - break; + Camera& CameraManager::getActiveCamera() { + return m_cameras[getActiveCameraIndex()]; + } + + void CameraManager::setActiveCamera(uint32_t cameraIndex) { + if (cameraIndex < 0 || cameraIndex > m_cameras.size() - 1) { + vkcv_log(LogLevel::ERROR, "Invalid camera index: The index must range from 0 to %lu", m_cameras.size()); + return; } + + m_activeCameraIndex = cameraIndex; } - void CameraManager::resizeCallback(int width, int height){ - m_camera.updateRatio(width, height); + uint32_t CameraManager::getActiveCameraIndex() const { + return m_activeCameraIndex; } - Camera &CameraManager::getCamera(){ - return m_camera; + void CameraManager::setControllerType(uint32_t cameraIndex, ControllerType controllerType) { + if (cameraIndex < 0 || cameraIndex > m_cameras.size() - 1) { + vkcv_log(LogLevel::ERROR, "Invalid camera index: The index must range from 0 to %lu", m_cameras.size()); + return; + } + + m_cameraControllerTypes[cameraIndex] = controllerType; + } + + ControllerType CameraManager::getControllerType(uint32_t cameraIndex) { + if (cameraIndex < 0 || cameraIndex > m_cameras.size() - 1) { + vkcv_log(LogLevel::ERROR, "Invalid camera index: The index must range from 0 to %lu", m_cameras.size()); + return ControllerType::NONE; + } + + return m_cameraControllerTypes[cameraIndex]; + } + + CameraController& CameraManager::getControllerByType(ControllerType controllerType) { + switch(controllerType) { + case ControllerType::PILOT: + return m_pilotController; + case ControllerType::TRACKBALL: + return m_trackController; + default: + return m_pilotController; + } } -} \ No newline at end of file + void CameraManager::update(double deltaTime) { + getActiveController().updateCamera(deltaTime, getActiveCamera()); + } + +} diff --git a/modules/camera/src/vkcv/camera/PilotCameraController.cpp b/modules/camera/src/vkcv/camera/PilotCameraController.cpp new file mode 100644 index 0000000000000000000000000000000000000000..39796f028e7bafb8e0ed0908226c0ed824f237a4 --- /dev/null +++ b/modules/camera/src/vkcv/camera/PilotCameraController.cpp @@ -0,0 +1,191 @@ +#include "vkcv/camera/PilotCameraController.hpp" +#include <GLFW/glfw3.h> + +namespace vkcv::camera { + + PilotCameraController::PilotCameraController() { + m_forward = false; + m_backward = false; + m_upward = false; + m_downward = false; + m_left = false; + m_right = false; + + m_gamepadX = 0.0f; + m_gamepadY = 0.0f; + m_gamepadZ = 0.0f; + + m_rotationActive = false; + + m_cameraSpeed = 2.5f; + + m_fov_nsteps = 100; + m_fov_min = 10; + m_fov_max = 120; + } + + void PilotCameraController::changeFov(double offset, Camera &camera){ + float fov = camera.getFov(); + float fov_range = m_fov_max - m_fov_min; + float fov_stepsize = glm::radians(fov_range) / static_cast<float>(m_fov_nsteps); + fov -= (float) offset*fov_stepsize; + if (fov < glm::radians(m_fov_min)) { + fov = glm::radians(m_fov_min); + } + if (fov > glm::radians(m_fov_max)) { + fov = glm::radians(m_fov_max); + } + camera.setFov(fov); + } + + void PilotCameraController::panView(double xOffset, double yOffset, Camera &camera) { + // handle yaw rotation + float yaw = camera.getYaw() + xOffset; + if (yaw < -180.0f) { + yaw += 360.0f; + } + else if (yaw > 180.0f) { + yaw -= 360.0f; + } + camera.setYaw(yaw); + + // handle pitch rotation + float pitch = camera.getPitch() - yOffset; + if (pitch > 89.0f) { + pitch = 89.0f; + } + if (pitch < -89.0f) { + pitch = -89.0f; + } + camera.setPitch(pitch); + } + + constexpr float getDirectionFactor(bool positive, bool negative) { + return static_cast<float>(positive) - static_cast<float>(negative); + } + + void PilotCameraController::updateCamera(double deltaTime, Camera &camera) { + glm::vec3 position = camera.getPosition(); + + const glm::vec3 front = camera.getFront(); + const glm::vec3 up = camera.getUp(); + const glm::vec3 left = glm::normalize(glm::cross(front, up)); + + const float distance = m_cameraSpeed * static_cast<float>(deltaTime); + + position += distance * (getDirectionFactor(m_forward, m_backward) + m_gamepadZ) * front; + position += distance * (getDirectionFactor(m_left, m_right) + m_gamepadX) * left; + position += distance * (getDirectionFactor(m_upward, m_downward) + m_gamepadY) * up; + + camera.lookAt(position, position + front, up); + } + + void PilotCameraController::keyCallback(int key, int scancode, int action, int mods, Camera &camera) { + switch (key) { + case GLFW_KEY_W: + moveForward(action); + break; + case GLFW_KEY_S: + moveBackward(action); + break; + case GLFW_KEY_A: + moveLeft(action); + break; + case GLFW_KEY_D: + moveRight(action); + break; + case GLFW_KEY_E: + moveUpward(action); + break; + case GLFW_KEY_Q: + moveDownward(action); + break; + default: + break; + } + } + + void PilotCameraController::scrollCallback(double offsetX, double offsetY, Camera &camera) { + changeFov(offsetY, camera); + } + + void PilotCameraController::mouseMoveCallback(double xoffset, double yoffset, Camera &camera) { + if(!m_rotationActive){ + return; + } + + float sensitivity = 0.05f; + xoffset *= sensitivity; + yoffset *= sensitivity; + + panView(xoffset , yoffset, camera); + } + + void PilotCameraController::mouseButtonCallback(int button, int action, int mods, Camera &camera) { + if(button == GLFW_MOUSE_BUTTON_2 && m_rotationActive == false && action == GLFW_PRESS){ + m_rotationActive = true; + } + else if(button == GLFW_MOUSE_BUTTON_2 && m_rotationActive == true && action == GLFW_RELEASE){ + m_rotationActive = false; + } + } + + void PilotCameraController::gamepadCallback(int gamepadIndex, Camera &camera) { + GLFWgamepadstate gamepadState; + glfwGetGamepadState(gamepadIndex, &gamepadState); + + float sensitivity = 0.05f; + double threshold = 0.1; // todo: needs further investigation! + + // handle rotations + double stickRightX = static_cast<double>(gamepadState.axes[GLFW_GAMEPAD_AXIS_RIGHT_X]); + double stickRightY = static_cast<double>(gamepadState.axes[GLFW_GAMEPAD_AXIS_RIGHT_Y]); + + double rightXVal = glm::clamp(std::abs(stickRightX) - threshold, 0.0, 1.0) + * copysign(1.0, stickRightX) * sensitivity; + double rightYVal = glm::clamp(std::abs(stickRightY) - threshold, 0.0, 1.0) + * copysign(1.0, stickRightY) * sensitivity; + panView(rightXVal, rightYVal, camera); + + // handle zooming + double zoom = static_cast<double>((gamepadState.axes[GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER] + - gamepadState.axes[GLFW_GAMEPAD_AXIS_LEFT_TRIGGER]) + * sensitivity * 0.5); + changeFov(zoom, camera); + + // handle translation + m_gamepadY = gamepadState.buttons[GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER] - gamepadState.buttons[GLFW_GAMEPAD_BUTTON_LEFT_BUMPER]; + float stickLeftX = gamepadState.axes[GLFW_GAMEPAD_AXIS_LEFT_X]; + float stickLeftY = gamepadState.axes[GLFW_GAMEPAD_AXIS_LEFT_Y]; + m_gamepadZ = glm::clamp(std::abs(stickLeftY) - threshold, 0.0, 1.0) + * -copysign(1.0, stickLeftY); + m_gamepadX = glm::clamp(std::abs(stickLeftX) - threshold, 0.0, 1.0) + * -copysign(1.0, stickLeftX); + } + + + void PilotCameraController::moveForward(int action){ + m_forward = static_cast<bool>(action); + } + + void PilotCameraController::moveBackward(int action){ + m_backward = static_cast<bool>(action); + } + + void PilotCameraController::moveLeft(int action){ + m_left = static_cast<bool>(action); + } + + void PilotCameraController::moveRight(int action){ + m_right = static_cast<bool>(action); + } + + void PilotCameraController::moveUpward(int action){ + m_upward = static_cast<bool>(action); + } + + void PilotCameraController::moveDownward(int action){ + m_downward = static_cast<bool>(action); + } + +} \ No newline at end of file diff --git a/modules/camera/src/vkcv/camera/TrackballCamera.cpp b/modules/camera/src/vkcv/camera/TrackballCamera.cpp deleted file mode 100644 index 3bbb8611dd234499fb9ba08ba87009c8c76660f6..0000000000000000000000000000000000000000 --- a/modules/camera/src/vkcv/camera/TrackballCamera.cpp +++ /dev/null @@ -1,146 +0,0 @@ -#include "vkcv/camera/TrackballCamera.hpp" - -namespace vkcv{ - - TrackballCamera::TrackballCamera( int width, int height, glm::mat4 projection) - { - setPosition( glm::vec3(0.0f, 0.0f, 5.0) ); - m_center = glm::vec3( 0.0f, 0.0f, 0.0f); - m_up = glm::vec3(0.0f, 1.0f, 0.0f); - - m_width = width; - m_height = height; - - m_sensitivity = 0.010f; - m_stepSize = 0.1f; - m_theta = glm::pi<float>() / 2.0f; - m_phi = 0.f; - m_radius = 1.5; - - m_view = glm::lookAt( m_center + getPosition(), m_center, m_up); - - m_oldX = width/2.f; - m_oldY = height/2.f; - - setProjection(projection); - } - - - TrackballCamera::TrackballCamera(int width, int height) - { - setPosition( glm::vec3(0.0f, 0.0f, 5.0)); - m_center = glm::vec3( 0.0f, 0.0f, 0.0f); - m_up = glm::vec3(0.0f, 1.0f, 0.0f); - - m_width = width; - m_height = height; - - m_sensitivity = 0.010f; - m_stepSize = 0.1f; - m_theta = glm::pi<float>() / 2.0f; - m_phi = 0.f; - m_radius = 1.5; - - m_view = glm::lookAt( m_center + getPosition(), m_center, m_up); - - m_oldX = width/2.f; - m_oldY = height/2.f; - - m_fov = glm::radians(60.f); - m_ratio = m_width / (float) m_height; - m_near = 0.001f; - m_far = 10.f; - glm::mat4 projection = glm::perspective(m_fov, m_ratio, m_near, m_far); - - setProjection(projection); - } - - TrackballCamera::~TrackballCamera() - { - } - - // TODO: Can be done as events... (mouseMove, mouseDown, mouseUp) - /*void TrackballCamera::update( GLFWwindow* window) { - - double x, y; - - glfwGetCursorPos( window, &x, &y); - if (glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) - { - float changeX = ((float) x - m_oldX) * m_sensitivity; - float changeY = ((float) y - m_oldY) * m_sensitivity; - - m_theta -= changeY; - if (m_theta < 0.01f) m_theta = 0.01f; - else if (m_theta > glm::pi<float>() - 0.01f) m_theta = glm::pi<float>() - 0.01f; - - m_phi -= changeX; - if (m_phi < 0) m_phi += 2*glm::pi<float>(); - else if (m_phi > 2*glm::pi<float>()) m_phi -= 2*glm::pi<float>(); - } - - m_oldX = (float) x; - m_oldY = (float) y; - - if (glfwGetKey( window, GLFW_KEY_UP) == GLFW_PRESS) - m_radius -= m_stepSize; - if (glfwGetKey( window, GLFW_KEY_DOWN) == GLFW_PRESS) - m_radius += m_stepSize; - if (m_radius < 0.1f) m_radius = 0.1f; - - m_position.x = m_center.x + m_radius * sin(m_theta) * sin(m_phi); - m_position.y = m_center.y + m_radius * cos(m_theta); - m_position.z = m_center.z + m_radius * sin(m_theta) * cos(m_phi); - - m_view = glm::lookAt( m_position, m_center, m_up); - - }*/ - - float TrackballCamera::getSensitivity() const { - return m_sensitivity; - } - - void TrackballCamera::setSensitivity(float sensitivity) { - m_sensitivity = sensitivity; - } - - float TrackballCamera::getStepSize() const { - return m_stepSize; - } - - void TrackballCamera::setStepSize(float stepSize) { - m_stepSize = stepSize; - } - - float TrackballCamera::getTheta() const { - return m_theta; - } - - void TrackballCamera::setTheta(float theta) { - m_theta = theta; - } - - float TrackballCamera::getPhi() const { - return m_phi; - } - - void TrackballCamera::setPhi(float phi) { - m_phi = phi; - } - - float TrackballCamera::getRadius() const { - return m_radius; - } - - void TrackballCamera::setRadius(float radius) { - m_radius = radius; - } - - const glm::vec3& TrackballCamera::getCenter() const { - return m_center; - } - - void TrackballCamera::setCenter(const glm::vec3 ¢er) { - m_center = center; - } -} \ No newline at end of file diff --git a/modules/camera/src/vkcv/camera/TrackballCameraController.cpp b/modules/camera/src/vkcv/camera/TrackballCameraController.cpp new file mode 100644 index 0000000000000000000000000000000000000000..278feb761fbd674571dcf7dc438f11c1a6958257 --- /dev/null +++ b/modules/camera/src/vkcv/camera/TrackballCameraController.cpp @@ -0,0 +1,122 @@ +#include "vkcv/camera/TrackballCameraController.hpp" +#include <GLFW/glfw3.h> +#include <math.h> + +namespace vkcv::camera { + + TrackballCameraController::TrackballCameraController() { + m_rotationActive = false; + m_radius = 3.0f; + m_cameraSpeed = 2.5f; + m_scrollSensitivity = 0.2f; + } + + void TrackballCameraController::setRadius(const float radius) { + if (radius < 0.1f) { + m_radius = 0.1f; + } + else { + m_radius = radius; + } + } + + void TrackballCameraController::panView(double xOffset, double yOffset, Camera &camera) { + // handle yaw rotation + float yaw = camera.getYaw() + xOffset * m_cameraSpeed; + if (yaw < 0.0f) { + yaw += 360.0f; + } + else if (yaw > 360.0f) { + yaw -= 360.0f; + } + camera.setYaw(yaw); + + // handle pitch rotation + float pitch = camera.getPitch() + yOffset * m_cameraSpeed; + if (pitch < 0.0f) { + pitch += 360.0f; + } + else if (pitch > 360.0f) { + pitch -= 360.0f; + } + camera.setPitch(pitch); + } + + void TrackballCameraController::updateRadius(double offset, Camera &camera) { + glm::vec3 cameraPosition = camera.getPosition(); + glm::vec3 cameraCenter = camera.getCenter(); + float radius = glm::length(cameraCenter - cameraPosition); // get current camera radius + setRadius(radius - offset * m_scrollSensitivity); + } + + void TrackballCameraController::updateCamera(double deltaTime, Camera &camera) { + float yaw = camera.getYaw(); + float pitch = camera.getPitch(); + + const glm::vec3 yAxis = glm::vec3(0.0f, 1.0f, 0.0f); + const glm::vec3 xAxis = glm::vec3(1.0f, 0.0f, 0.0f); + + const glm::mat4 rotationY = glm::rotate(glm::mat4(1.0f), glm::radians(yaw), yAxis); + const glm::mat4 rotationX = glm::rotate(rotationY, -glm::radians(pitch), xAxis); + const glm::vec3 translation = glm::vec3( + rotationX * glm::vec4(0.0f, 0.0f, m_radius, 0.0f) + ); + + const glm::vec3 center = camera.getCenter(); + const glm::vec3 position = center + translation; + const glm::vec3 up = glm::vec3( + rotationX * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f) + ); + + camera.lookAt(position, center, up); + } + + void TrackballCameraController::keyCallback(int key, int scancode, int action, int mods, Camera &camera) {} + + void TrackballCameraController::scrollCallback(double offsetX, double offsetY, Camera &camera) { + updateRadius(offsetY, camera); + } + + void TrackballCameraController::mouseMoveCallback(double xoffset, double yoffset, Camera &camera) { + if(!m_rotationActive){ + return; + } + + float sensitivity = 0.025f; + xoffset *= sensitivity; + yoffset *= sensitivity; + + panView(xoffset , yoffset, camera); + } + + void TrackballCameraController::mouseButtonCallback(int button, int action, int mods, Camera &camera) { + if(button == GLFW_MOUSE_BUTTON_2 && m_rotationActive == false && action == GLFW_PRESS){ + m_rotationActive = true; + } + else if(button == GLFW_MOUSE_BUTTON_2 && m_rotationActive == true && action == GLFW_RELEASE){ + m_rotationActive = false; + } + } + + void TrackballCameraController::gamepadCallback(int gamepadIndex, Camera &camera) { + GLFWgamepadstate gamepadState; + glfwGetGamepadState(gamepadIndex, &gamepadState); + + float sensitivity = 0.025f; + double threshold = 0.1; // todo: needs further investigation! + + // handle rotations + double stickRightX = static_cast<double>(gamepadState.axes[GLFW_GAMEPAD_AXIS_RIGHT_X]); + double stickRightY = static_cast<double>(gamepadState.axes[GLFW_GAMEPAD_AXIS_RIGHT_Y]); + + double rightXVal = glm::clamp((abs(stickRightX)-threshold), 0.0, 1.0) * std::copysign(1.0, stickRightX); + double rightYVal = glm::clamp((abs(stickRightY)-threshold), 0.0, 1.0) * std::copysign(1.0, stickRightY); + panView(rightXVal * sensitivity, rightYVal * sensitivity, camera); + + // handle translation + double stickLeftY = static_cast<double>(gamepadState.axes[GLFW_GAMEPAD_AXIS_LEFT_Y]); + double leftYVal = glm::clamp((abs(stickLeftY)-threshold), 0.0, 1.0) * std::copysign(1.0, stickLeftY); + updateRadius(-leftYVal * sensitivity, camera); + + } +} \ No newline at end of file diff --git a/modules/gui/CMakeLists.txt b/modules/gui/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..ce03f16e1f8d421f5b8e6c2fe913c0da04d34598 --- /dev/null +++ b/modules/gui/CMakeLists.txt @@ -0,0 +1,34 @@ +cmake_minimum_required(VERSION 3.16) +project(vkcv_gui) + +# setting c++ standard for the module +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(vkcv_gui_source ${PROJECT_SOURCE_DIR}/src) +set(vkcv_gui_include ${PROJECT_SOURCE_DIR}/include) + +# Add source and header files to the module +set(vkcv_gui_sources + ${vkcv_gui_include}/vkcv/gui/GUI.hpp + ${vkcv_gui_source}/vkcv/gui/GUI.cpp + ) + +# Setup some path variables to load libraries +set(vkcv_gui_lib lib) +set(vkcv_gui_lib_path ${PROJECT_SOURCE_DIR}/${vkcv_gui_lib}) + +# Check and load IMGUI +include(config/ImGui.cmake) + +# adding source files to the module +add_library(vkcv_gui STATIC ${vkcv_gui_sources} ${vkcv_imgui_sources}) + +# link the required libraries to the module +target_link_libraries(vkcv_gui ${vkcv_gui_libraries} vkcv ${vkcv_libraries}) + +# including headers of dependencies and the VkCV framework +target_include_directories(vkcv_gui SYSTEM BEFORE PRIVATE ${vkcv_gui_includes} ${vkcv_include} ${vkcv_includes}) + +# add the own include directory for public headers +target_include_directories(vkcv_gui BEFORE PUBLIC ${vkcv_gui_include} ${vkcv_imgui_includes}) diff --git a/modules/gui/config/ImGui.cmake b/modules/gui/config/ImGui.cmake new file mode 100644 index 0000000000000000000000000000000000000000..3f55ad05c34783ba0e82c41d2cbc4e5b204d60e7 --- /dev/null +++ b/modules/gui/config/ImGui.cmake @@ -0,0 +1,17 @@ + +if (EXISTS "${vkcv_gui_lib_path}/imgui") + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/backends/imgui_impl_glfw.cpp) + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/backends/imgui_impl_vulkan.cpp ) + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/imgui.cpp) + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/imgui_draw.cpp) + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/imgui_demo.cpp) + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/imgui_tables.cpp) + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/imgui_widgets.cpp) + + list(APPEND vkcv_imgui_includes ${vkcv_gui_lib}/imgui) + list(APPEND vkcv_imgui_includes ${vkcv_gui_lib}/imgui/backend) + + list(APPEND vkcv_gui_include ${vkcv_gui_lib}) +else() + message(WARNING "IMGUI is required..! Update the submodules!") +endif () diff --git a/modules/gui/include/vkcv/gui/GUI.hpp b/modules/gui/include/vkcv/gui/GUI.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d1a9986c5f69bfd9d4392bd5ae50f0b1f8b60642 --- /dev/null +++ b/modules/gui/include/vkcv/gui/GUI.hpp @@ -0,0 +1,62 @@ +#pragma once + +#include "imgui/imgui.h" +#include "imgui/backends/imgui_impl_glfw.h" +#include "imgui/backends/imgui_impl_vulkan.h" + +#include <vkcv/Core.hpp> +#include <vkcv/Window.hpp> + +namespace vkcv::gui { + + class GUI final { + private: + Window& m_window; + Core& m_core; + + const Context& m_context; + + ImGuiContext* m_gui_context; + + vk::DescriptorPool m_descriptor_pool; + vk::RenderPass m_render_pass; + + event_handle<int,int,int> f_mouseButton; + event_handle<double,double> f_mouseScroll; + event_handle<int,int,int,int> f_key; + event_handle<unsigned int> f_char; + + public: + /** + * Constructor of a new instance of ImGui management + * + * @param core Valid #Core instance of the framework + * @param window Valid #Window instance of the framework + */ + GUI(Core& core, Window& window); + + GUI(const GUI& other) = delete; + GUI(GUI&& other) = delete; + + GUI& operator=(const GUI& other) = delete; + GUI& operator=(GUI&& other) = delete; + + /** + * Destructor of a #GUI instance + */ + virtual ~GUI(); + + /** + * Sets up a new frame for ImGui to draw + */ + void beginGUI(); + + /** + * Ends a frame for ImGui, renders it and draws it onto + * the currently active swapchain image of the core (ready to present). + */ + void endGUI(); + + }; + +} diff --git a/modules/gui/lib/imgui b/modules/gui/lib/imgui new file mode 160000 index 0000000000000000000000000000000000000000..d5828cd988db525f27128edeadb1a689cd2d7461 --- /dev/null +++ b/modules/gui/lib/imgui @@ -0,0 +1 @@ +Subproject commit d5828cd988db525f27128edeadb1a689cd2d7461 diff --git a/modules/gui/src/vkcv/gui/GUI.cpp b/modules/gui/src/vkcv/gui/GUI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a9a8bd01df379a0f4615c2c53aee09082d107b1c --- /dev/null +++ b/modules/gui/src/vkcv/gui/GUI.cpp @@ -0,0 +1,241 @@ + +#include "vkcv/gui/GUI.hpp" + +#include <GLFW/glfw3.h> +#include <vkcv/Logger.hpp> + +namespace vkcv::gui { + + static void checkVulkanResult(VkResult resultCode) { + if (resultCode == 0) + return; + + const auto result = vk::Result(resultCode); + + vkcv_log(LogLevel::ERROR, "ImGui has a problem with Vulkan! (%s)", vk::to_string(result).c_str()); + } + + GUI::GUI(Core& core, Window& window) : + m_window(window), + m_core(core), + m_context(m_core.getContext()), + m_gui_context(nullptr) { + IMGUI_CHECKVERSION(); + + m_gui_context = ImGui::CreateContext(); + + ImGui_ImplGlfw_InitForVulkan(m_window.getWindow(), false); + + f_mouseButton = m_window.e_mouseButton.add([&](int button, int action, int mods) { + ImGui_ImplGlfw_MouseButtonCallback(m_window.getWindow(), button, action, mods); + }); + + f_mouseScroll = m_window.e_mouseScroll.add([&](double xoffset, double yoffset) { + ImGui_ImplGlfw_ScrollCallback(m_window.getWindow(), xoffset, yoffset); + }); + + f_key = m_window.e_key.add([&](int key, int scancode, int action, int mods) { + ImGui_ImplGlfw_KeyCallback(m_window.getWindow(), key, scancode, action, mods); + }); + + f_char = m_window.e_char.add([&](unsigned int c) { + ImGui_ImplGlfw_CharCallback(m_window.getWindow(), c); + }); + + vk::DescriptorPoolSize pool_sizes[] = { + vk::DescriptorPoolSize(vk::DescriptorType::eSampler, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eCombinedImageSampler, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eSampledImage, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eStorageImage, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eUniformTexelBuffer, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eStorageTexelBuffer, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eUniformBuffer, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eStorageBuffer, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eUniformBufferDynamic, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eStorageBufferDynamic, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eInputAttachment, 1000) + }; + + const vk::DescriptorPoolCreateInfo descriptorPoolCreateInfo ( + vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, + static_cast<uint32_t>(1000 * IM_ARRAYSIZE(pool_sizes)), + static_cast<uint32_t>(IM_ARRAYSIZE(pool_sizes)), + pool_sizes + ); + + m_descriptor_pool = m_context.getDevice().createDescriptorPool(descriptorPoolCreateInfo); + + const vk::PhysicalDevice& physicalDevice = m_context.getPhysicalDevice(); + const Swapchain& swapchain = m_core.getSwapchain(); + + const uint32_t graphicsQueueFamilyIndex = ( + m_context.getQueueManager().getGraphicsQueues()[0].familyIndex + ); + + ImGui_ImplVulkan_InitInfo init_info = {}; + init_info.Instance = m_context.getInstance(); + init_info.PhysicalDevice = m_context.getPhysicalDevice(); + init_info.Device = m_context.getDevice(); + init_info.QueueFamily = graphicsQueueFamilyIndex; + init_info.Queue = m_context.getQueueManager().getGraphicsQueues()[0].handle; + init_info.PipelineCache = nullptr; + init_info.DescriptorPool = m_descriptor_pool; + init_info.Allocator = nullptr; + init_info.MinImageCount = swapchain.getImageCount(); + init_info.ImageCount = swapchain.getImageCount(); + init_info.CheckVkResultFn = checkVulkanResult; + + const vk::AttachmentDescription attachment ( + vk::AttachmentDescriptionFlags(), + swapchain.getFormat(), + vk::SampleCountFlagBits::e1, + vk::AttachmentLoadOp::eLoad, + vk::AttachmentStoreOp::eStore, + vk::AttachmentLoadOp::eDontCare, + vk::AttachmentStoreOp::eDontCare, + vk::ImageLayout::eUndefined, + vk::ImageLayout::ePresentSrcKHR + ); + + const vk::AttachmentReference attachmentReference ( + 0, + vk::ImageLayout::eColorAttachmentOptimal + ); + + const vk::SubpassDescription subpass ( + vk::SubpassDescriptionFlags(), + vk::PipelineBindPoint::eGraphics, + 0, + nullptr, + 1, + &attachmentReference, + nullptr, + nullptr, + 0, + nullptr + ); + + const vk::SubpassDependency dependency ( + VK_SUBPASS_EXTERNAL, + 0, + vk::PipelineStageFlagBits::eColorAttachmentOutput, + vk::PipelineStageFlagBits::eColorAttachmentOutput, + vk::AccessFlags(), + vk::AccessFlagBits::eColorAttachmentWrite, + vk::DependencyFlags() + ); + + const vk::RenderPassCreateInfo passCreateInfo ( + vk::RenderPassCreateFlags(), + 1, + &attachment, + 1, + &subpass, + 1, + &dependency + ); + + m_render_pass = m_context.getDevice().createRenderPass(passCreateInfo); + + ImGui_ImplVulkan_Init(&init_info, m_render_pass); + + const SubmitInfo submitInfo { QueueType::Graphics, {}, {} }; + + m_core.recordAndSubmitCommandsImmediate(submitInfo, [](const vk::CommandBuffer& commandBuffer) { + ImGui_ImplVulkan_CreateFontsTexture(commandBuffer); + }, []() { + ImGui_ImplVulkan_DestroyFontUploadObjects(); + }); + + m_context.getDevice().waitIdle(); + } + + GUI::~GUI() { + m_context.getDevice().waitIdle(); + + ImGui_ImplVulkan_Shutdown(); + + m_context.getDevice().destroyRenderPass(m_render_pass); + m_context.getDevice().destroyDescriptorPool(m_descriptor_pool); + + ImGui_ImplGlfw_Shutdown(); + + m_window.e_mouseButton.remove(f_mouseButton); + m_window.e_mouseScroll.remove(f_mouseScroll); + m_window.e_key.remove(f_key); + m_window.e_char.remove(f_char); + + if (m_gui_context) { + ImGui::DestroyContext(m_gui_context); + } + } + + void GUI::beginGUI() { + const Swapchain& swapchain = m_core.getSwapchain(); + const auto extent = swapchain.getExtent(); + + if ((extent.width > 0) && (extent.height > 0)) { + ImGui_ImplVulkan_SetMinImageCount(swapchain.getImageCount()); + } + + ImGui_ImplVulkan_NewFrame(); + ImGui_ImplGlfw_NewFrame(); + ImGui::NewFrame(); + } + + void GUI::endGUI() { + ImGui::Render(); + + ImDrawData* drawData = ImGui::GetDrawData(); + + if ((!drawData) || + (drawData->DisplaySize.x <= 0.0f) || + (drawData->DisplaySize.y <= 0.0f)) { + return; + } + + const Swapchain& swapchain = m_core.getSwapchain(); + const auto extent = swapchain.getExtent(); + + const vk::ImageView swapchainImageView = m_core.getSwapchainImageView(); + + const vk::FramebufferCreateInfo framebufferCreateInfo ( + vk::FramebufferCreateFlags(), + m_render_pass, + 1, + &swapchainImageView, + extent.width, + extent.height, + 1 + ); + + const vk::Framebuffer framebuffer = m_context.getDevice().createFramebuffer(framebufferCreateInfo); + + SubmitInfo submitInfo; + submitInfo.queueType = QueueType::Graphics; + + m_core.recordAndSubmitCommandsImmediate(submitInfo, [&](const vk::CommandBuffer& commandBuffer) { + const vk::Rect2D renderArea ( + vk::Offset2D(0, 0), + extent + ); + + const vk::RenderPassBeginInfo beginInfo ( + m_render_pass, + framebuffer, + renderArea, + 0, + nullptr + ); + + commandBuffer.beginRenderPass(beginInfo, vk::SubpassContents::eInline); + + ImGui_ImplVulkan_RenderDrawData(drawData, commandBuffer); + + commandBuffer.endRenderPass(); + }, [&]() { + m_context.getDevice().destroyFramebuffer(framebuffer); + }); + } + +} diff --git a/modules/shader_compiler/CMakeLists.txt b/modules/shader_compiler/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..4b674ec41ed4ea5f42dc73187c212e6a69952cec --- /dev/null +++ b/modules/shader_compiler/CMakeLists.txt @@ -0,0 +1,34 @@ +cmake_minimum_required(VERSION 3.16) +project(vkcv_shader_compiler) + +# setting c++ standard for the module +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(vkcv_shader_compiler_source ${PROJECT_SOURCE_DIR}/src) +set(vkcv_shader_compiler_include ${PROJECT_SOURCE_DIR}/include) + +# Add source and header files to the module +set(vkcv_shader_compiler_sources + ${vkcv_shader_compiler_include}/vkcv/shader/GLSLCompiler.hpp + ${vkcv_shader_compiler_source}/vkcv/shader/GLSLCompiler.cpp +) + +# adding source files to the module +add_library(vkcv_shader_compiler STATIC ${vkcv_shader_compiler_sources}) + +# Setup some path variables to load libraries +set(vkcv_shader_compiler_lib lib) +set(vkcv_shader_compiler_lib_path ${PROJECT_SOURCE_DIR}/${vkcv_shader_compiler_lib}) + +# Check and load GLSLANG +include(config/GLSLANG.cmake) + +# link the required libraries to the module +target_link_libraries(vkcv_shader_compiler ${vkcv_shader_compiler_libraries} vkcv) + +# including headers of dependencies and the VkCV framework +target_include_directories(vkcv_shader_compiler SYSTEM BEFORE PRIVATE ${vkcv_shader_compiler_includes} ${vkcv_include}) + +# add the own include directory for public headers +target_include_directories(vkcv_shader_compiler BEFORE PUBLIC ${vkcv_shader_compiler_include}) diff --git a/modules/shader_compiler/config/GLSLANG.cmake b/modules/shader_compiler/config/GLSLANG.cmake new file mode 100644 index 0000000000000000000000000000000000000000..50b9fd46bd0db9421c632aa0b80fb8df7e3f2123 --- /dev/null +++ b/modules/shader_compiler/config/GLSLANG.cmake @@ -0,0 +1,28 @@ + +if (EXISTS "${vkcv_shader_compiler_lib_path}/glslang") + set(SKIP_GLSLANG_INSTALL ON CACHE INTERNAL "") + set(ENABLE_SPVREMAPPER OFF CACHE INTERNAL "") + set(ENABLE_GLSLANG_BINARIES OFF CACHE INTERNAL "") + set(ENABLE_GLSLANG_JS OFF CACHE INTERNAL "") + set(ENABLE_GLSLANG_WEBMIN OFF CACHE INTERNAL "") + set(ENABLE_GLSLANG_WEBMIN_DEVEL OFF CACHE INTERNAL "") + set(ENABLE_EMSCRIPTEN_SINGLE_FILE OFF CACHE INTERNAL "") + set(ENABLE_EMSCRIPTEN_ENVIRONMENT_NODE OFF CACHE INTERNAL "") + set(ENABLE_HLSL OFF CACHE INTERNAL "") + set(ENABLE_RTTI OFF CACHE INTERNAL "") + set(ENABLE_EXCEPTIONS OFF CACHE INTERNAL "") + set(ENABLE_OPT OFF CACHE INTERNAL "") + set(ENABLE_PCH OFF CACHE INTERNAL "") + set(ENABLE_CTEST OFF CACHE INTERNAL "") + set(USE_CCACHE OFF CACHE INTERNAL "") + + set(BUILD_SHARED_LIBS OFF CACHE INTERNAL "") + set(BUILD_EXTERNAL OFF CACHE INTERNAL "") + + add_subdirectory(${vkcv_shader_compiler_lib}/glslang) + + list(APPEND vkcv_shader_compiler_libraries glslang SPIRV) + list(APPEND vkcv_shader_compiler_includes ${vkcv_shader_compiler_lib}) +else() + message(WARNING "GLSLANG is required..! Update the submodules!") +endif () diff --git a/modules/shader_compiler/include/vkcv/shader/Compiler.hpp b/modules/shader_compiler/include/vkcv/shader/Compiler.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d7b7af7178531aea358cecbc8b86a29527173014 --- /dev/null +++ b/modules/shader_compiler/include/vkcv/shader/Compiler.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include <vkcv/Event.hpp> + +namespace vkcv::shader { + + typedef typename event_function<ShaderStage, const std::filesystem::path&>::type ShaderCompiledFunction; + + class Compiler { + private: + public: + virtual void compile(ShaderStage shaderStage, const std::filesystem::path& shaderPath, + const ShaderCompiledFunction& compiled, bool update = false) = 0; + + }; + +} diff --git a/modules/shader_compiler/include/vkcv/shader/GLSLCompiler.hpp b/modules/shader_compiler/include/vkcv/shader/GLSLCompiler.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7105d93a0c3e153bf3abe1d624d0c13c6f09ac6d --- /dev/null +++ b/modules/shader_compiler/include/vkcv/shader/GLSLCompiler.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include <filesystem> + +#include <vkcv/ShaderStage.hpp> +#include "Compiler.hpp" + +namespace vkcv::shader { + + class GLSLCompiler { + private: + public: + GLSLCompiler(); + + GLSLCompiler(const GLSLCompiler& other); + GLSLCompiler(GLSLCompiler&& other) = default; + + ~GLSLCompiler(); + + GLSLCompiler& operator=(const GLSLCompiler& other); + GLSLCompiler& operator=(GLSLCompiler&& other) = default; + + void compile(ShaderStage shaderStage, const std::filesystem::path& shaderPath, + const ShaderCompiledFunction& compiled, bool update = false); + + }; + +} diff --git a/modules/shader_compiler/lib/glslang b/modules/shader_compiler/lib/glslang new file mode 160000 index 0000000000000000000000000000000000000000..fe15158676657bf965e41c32e15ae5db7ea2ab6a --- /dev/null +++ b/modules/shader_compiler/lib/glslang @@ -0,0 +1 @@ +Subproject commit fe15158676657bf965e41c32e15ae5db7ea2ab6a diff --git a/modules/shader_compiler/src/vkcv/shader/GLSLCompiler.cpp b/modules/shader_compiler/src/vkcv/shader/GLSLCompiler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ec358188b8e871da6f4d62ffd397f32bfb795ee2 --- /dev/null +++ b/modules/shader_compiler/src/vkcv/shader/GLSLCompiler.cpp @@ -0,0 +1,283 @@ + +#include "vkcv/shader/GLSLCompiler.hpp" + +#include <fstream> +#include <glslang/SPIRV/GlslangToSpv.h> +#include <glslang/StandAlone/DirStackFileIncluder.h> + +#include <vkcv/Logger.hpp> + +namespace vkcv::shader { + + static uint32_t s_CompilerCount = 0; + + GLSLCompiler::GLSLCompiler() { + if (s_CompilerCount == 0) { + glslang::InitializeProcess(); + } + + s_CompilerCount++; + } + + GLSLCompiler::GLSLCompiler(const GLSLCompiler &other) { + s_CompilerCount++; + } + + GLSLCompiler::~GLSLCompiler() { + s_CompilerCount--; + + if (s_CompilerCount == 0) { + glslang::FinalizeProcess(); + } + } + + GLSLCompiler &GLSLCompiler::operator=(const GLSLCompiler &other) { + s_CompilerCount++; + return *this; + } + + constexpr EShLanguage findShaderLanguage(ShaderStage shaderStage) { + switch (shaderStage) { + case ShaderStage::VERTEX: + return EShLangVertex; + case ShaderStage::TESS_CONTROL: + return EShLangTessControl; + case ShaderStage::TESS_EVAL: + return EShLangTessEvaluation; + case ShaderStage::GEOMETRY: + return EShLangGeometry; + case ShaderStage::FRAGMENT: + return EShLangFragment; + case ShaderStage::COMPUTE: + return EShLangCompute; + default: + return EShLangCount; + } + } + + static void initResources(TBuiltInResource& resources) { + resources.maxLights = 32; + resources.maxClipPlanes = 6; + resources.maxTextureUnits = 32; + resources.maxTextureCoords = 32; + resources.maxVertexAttribs = 64; + resources.maxVertexUniformComponents = 4096; + resources.maxVaryingFloats = 64; + resources.maxVertexTextureImageUnits = 32; + resources.maxCombinedTextureImageUnits = 80; + resources.maxTextureImageUnits = 32; + resources.maxFragmentUniformComponents = 4096; + resources.maxDrawBuffers = 32; + resources.maxVertexUniformVectors = 128; + resources.maxVaryingVectors = 8; + resources.maxFragmentUniformVectors = 16; + resources.maxVertexOutputVectors = 16; + resources.maxFragmentInputVectors = 15; + resources.minProgramTexelOffset = -8; + resources.maxProgramTexelOffset = 7; + resources.maxClipDistances = 8; + resources.maxComputeWorkGroupCountX = 65535; + resources.maxComputeWorkGroupCountY = 65535; + resources.maxComputeWorkGroupCountZ = 65535; + resources.maxComputeWorkGroupSizeX = 1024; + resources.maxComputeWorkGroupSizeY = 1024; + resources.maxComputeWorkGroupSizeZ = 64; + resources.maxComputeUniformComponents = 1024; + resources.maxComputeTextureImageUnits = 16; + resources.maxComputeImageUniforms = 8; + resources.maxComputeAtomicCounters = 8; + resources.maxComputeAtomicCounterBuffers = 1; + resources.maxVaryingComponents = 60; + resources.maxVertexOutputComponents = 64; + resources.maxGeometryInputComponents = 64; + resources.maxGeometryOutputComponents = 128; + resources.maxFragmentInputComponents = 128; + resources.maxImageUnits = 8; + resources.maxCombinedImageUnitsAndFragmentOutputs = 8; + resources.maxCombinedShaderOutputResources = 8; + resources.maxImageSamples = 0; + resources.maxVertexImageUniforms = 0; + resources.maxTessControlImageUniforms = 0; + resources.maxTessEvaluationImageUniforms = 0; + resources.maxGeometryImageUniforms = 0; + resources.maxFragmentImageUniforms = 8; + resources.maxCombinedImageUniforms = 8; + resources.maxGeometryTextureImageUnits = 16; + resources.maxGeometryOutputVertices = 256; + resources.maxGeometryTotalOutputComponents = 1024; + resources.maxGeometryUniformComponents = 1024; + resources.maxGeometryVaryingComponents = 64; + resources.maxTessControlInputComponents = 128; + resources.maxTessControlOutputComponents = 128; + resources.maxTessControlTextureImageUnits = 16; + resources.maxTessControlUniformComponents = 1024; + resources.maxTessControlTotalOutputComponents = 4096; + resources.maxTessEvaluationInputComponents = 128; + resources.maxTessEvaluationOutputComponents = 128; + resources.maxTessEvaluationTextureImageUnits = 16; + resources.maxTessEvaluationUniformComponents = 1024; + resources.maxTessPatchComponents = 120; + resources.maxPatchVertices = 32; + resources.maxTessGenLevel = 64; + resources.maxViewports = 16; + resources.maxVertexAtomicCounters = 0; + resources.maxTessControlAtomicCounters = 0; + resources.maxTessEvaluationAtomicCounters = 0; + resources.maxGeometryAtomicCounters = 0; + resources.maxFragmentAtomicCounters = 8; + resources.maxCombinedAtomicCounters = 8; + resources.maxAtomicCounterBindings = 1; + resources.maxVertexAtomicCounterBuffers = 0; + resources.maxTessControlAtomicCounterBuffers = 0; + resources.maxTessEvaluationAtomicCounterBuffers = 0; + resources.maxGeometryAtomicCounterBuffers = 0; + resources.maxFragmentAtomicCounterBuffers = 1; + resources.maxCombinedAtomicCounterBuffers = 1; + resources.maxAtomicCounterBufferSize = 16384; + resources.maxTransformFeedbackBuffers = 4; + resources.maxTransformFeedbackInterleavedComponents = 64; + resources.maxCullDistances = 8; + resources.maxCombinedClipAndCullDistances = 8; + resources.maxSamples = 4; + resources.maxMeshOutputVerticesNV = 256; + resources.maxMeshOutputPrimitivesNV = 512; + resources.maxMeshWorkGroupSizeX_NV = 32; + resources.maxMeshWorkGroupSizeY_NV = 1; + resources.maxMeshWorkGroupSizeZ_NV = 1; + resources.maxTaskWorkGroupSizeX_NV = 32; + resources.maxTaskWorkGroupSizeY_NV = 1; + resources.maxTaskWorkGroupSizeZ_NV = 1; + resources.maxMeshViewCountNV = 4; + resources.limits.nonInductiveForLoops = 1; + resources.limits.whileLoops = 1; + resources.limits.doWhileLoops = 1; + resources.limits.generalUniformIndexing = 1; + resources.limits.generalAttributeMatrixVectorIndexing = 1; + resources.limits.generalVaryingIndexing = 1; + resources.limits.generalSamplerIndexing = 1; + resources.limits.generalVariableIndexing = 1; + resources.limits.generalConstantMatrixVectorIndexing = 1; + } + + static std::vector<char> readShaderCode(const std::filesystem::path &shaderPath) { + std::ifstream file (shaderPath.string(), std::ios::ate); + + if (!file.is_open()) { + vkcv_log(LogLevel::ERROR, "The file could not be opened (%s)", shaderPath.string().c_str()); + return std::vector<char>{}; + } + + std::streamsize fileSize = file.tellg(); + std::vector<char> buffer (fileSize + 1); + + file.seekg(0); + file.read(buffer.data(), fileSize); + file.close(); + + buffer[fileSize] = '\0'; + return buffer; + } + + static bool writeSpirvCode(const std::filesystem::path &shaderPath, const std::vector<uint32_t>& spirv) { + std::ofstream file (shaderPath.string(), std::ios::out | std::ios::binary); + + if (!file.is_open()) { + vkcv_log(LogLevel::ERROR, "The file could not be opened (%s)", shaderPath.string().c_str()); + return false; + } + + const auto fileSize = static_cast<std::streamsize>( + sizeof(uint32_t) * spirv.size() + ); + + file.seekp(0); + file.write(reinterpret_cast<const char*>(spirv.data()), fileSize); + file.close(); + + return true; + } + + void GLSLCompiler::compile(ShaderStage shaderStage, const std::filesystem::path &shaderPath, + const ShaderCompiledFunction& compiled, bool update) { + const EShLanguage language = findShaderLanguage(shaderStage); + + if (language == EShLangCount) { + vkcv_log(LogLevel::ERROR, "Shader stage not supported (%s)", shaderPath.string().c_str()); + return; + } + + const std::vector<char> code = readShaderCode(shaderPath); + + glslang::TShader shader (language); + glslang::TProgram program; + + const char *shaderStrings [1]; + shaderStrings[0] = code.data(); + + shader.setStrings(shaderStrings, 1); + + TBuiltInResource resources = {}; + initResources(resources); + + const auto messages = (EShMessages)( + EShMsgSpvRules | + EShMsgVulkanRules + ); + + std::string preprocessedGLSL; + + DirStackFileIncluder includer; + includer.pushExternalLocalDirectory(shaderPath.parent_path().string()); + + if (!shader.preprocess(&resources, 100, ENoProfile, false, false, messages, &preprocessedGLSL, includer)) { + vkcv_log(LogLevel::ERROR, "Shader parsing failed {\n%s\n%s\n} (%s)", + shader.getInfoLog(), shader.getInfoDebugLog(), shaderPath.string().c_str()); + return; + } + + const char* preprocessedCString = preprocessedGLSL.c_str(); + shader.setStrings(&preprocessedCString, 1); + + if (!shader.parse(&resources, 100, false, messages)) { + vkcv_log(LogLevel::ERROR, "Shader parsing failed {\n%s\n%s\n} (%s)", + shader.getInfoLog(), shader.getInfoDebugLog(), shaderPath.string().c_str()); + return; + } + + program.addShader(&shader); + + if (!program.link(messages)) { + vkcv_log(LogLevel::ERROR, "Shader linking failed {\n%s\n%s\n} (%s)", + shader.getInfoLog(), shader.getInfoDebugLog(), shaderPath.string().c_str()); + return; + } + + const glslang::TIntermediate* intermediate = program.getIntermediate(language); + + if (!intermediate) { + vkcv_log(LogLevel::ERROR, "No valid intermediate representation (%s)", shaderPath.string().c_str()); + return; + } + + std::vector<uint32_t> spirv; + glslang::GlslangToSpv(*intermediate, spirv); + + const std::filesystem::path tmp_path (std::tmpnam(nullptr)); + + if (!writeSpirvCode(tmp_path, spirv)) { + vkcv_log(LogLevel::ERROR, "Spir-V could not be written to disk (%s)", shaderPath.string().c_str()); + return; + } + + if (compiled) { + compiled(shaderStage, tmp_path); + } + + std::filesystem::remove(tmp_path); + + if (update) { + // TODO: Shader hot compilation during runtime + } + } + +} diff --git a/projects/CMakeLists.txt b/projects/CMakeLists.txt index 6a2a20b755b46a5259b18b50278efc5f55fe1e42..3098bd55405c4494f1841d41ab805337c492849f 100644 --- a/projects/CMakeLists.txt +++ b/projects/CMakeLists.txt @@ -2,5 +2,7 @@ # Add new projects/examples here: add_subdirectory(first_triangle) add_subdirectory(first_mesh) -add_subdirectory(cmd_sync_test) add_subdirectory(particle_simulation) +add_subdirectory(first_scene) +add_subdirectory(voxelization) +add_subdirectory(voxelization) diff --git a/projects/cmd_sync_test/.gitignore b/projects/cmd_sync_test/.gitignore deleted file mode 100644 index 16f72da367245ad14a38ee756816f06f8cbbe3d2..0000000000000000000000000000000000000000 --- a/projects/cmd_sync_test/.gitignore +++ /dev/null @@ -1 +0,0 @@ -cmd_sync_test \ No newline at end of file diff --git a/projects/cmd_sync_test/resources/shaders/compile.bat b/projects/cmd_sync_test/resources/shaders/compile.bat deleted file mode 100644 index 516c2f2f78001e1a5d182356e7c3fe82d66a45ee..0000000000000000000000000000000000000000 --- a/projects/cmd_sync_test/resources/shaders/compile.bat +++ /dev/null @@ -1,5 +0,0 @@ -%VULKAN_SDK%\Bin32\glslc.exe shader.vert -o vert.spv -%VULKAN_SDK%\Bin32\glslc.exe shader.frag -o frag.spv -%VULKAN_SDK%\Bin32\glslc.exe shadow.vert -o shadow_vert.spv -%VULKAN_SDK%\Bin32\glslc.exe shadow.frag -o shadow_frag.spv -pause \ No newline at end of file diff --git a/projects/cmd_sync_test/resources/shaders/frag.spv b/projects/cmd_sync_test/resources/shaders/frag.spv deleted file mode 100644 index ff3110571871d65ce119dc6c5006e7e67aa53546..0000000000000000000000000000000000000000 Binary files a/projects/cmd_sync_test/resources/shaders/frag.spv and /dev/null differ diff --git a/projects/cmd_sync_test/resources/shaders/shadow_frag.spv b/projects/cmd_sync_test/resources/shaders/shadow_frag.spv deleted file mode 100644 index 6be3bd2518a3b1f234e39aea2503ba86cfb3314b..0000000000000000000000000000000000000000 Binary files a/projects/cmd_sync_test/resources/shaders/shadow_frag.spv and /dev/null differ diff --git a/projects/cmd_sync_test/resources/shaders/shadow_vert.spv b/projects/cmd_sync_test/resources/shaders/shadow_vert.spv deleted file mode 100644 index afaa0824ee9be2c22209d611943c6512587dce24..0000000000000000000000000000000000000000 Binary files a/projects/cmd_sync_test/resources/shaders/shadow_vert.spv and /dev/null differ diff --git a/projects/cmd_sync_test/resources/shaders/vert.spv b/projects/cmd_sync_test/resources/shaders/vert.spv deleted file mode 100644 index 5e514eef5983927316465679af5461f507497130..0000000000000000000000000000000000000000 Binary files a/projects/cmd_sync_test/resources/shaders/vert.spv and /dev/null differ diff --git a/projects/cmd_sync_test/src/main.cpp b/projects/cmd_sync_test/src/main.cpp index 426cc3a56033cea1e468c5612f4e32981d18f8c1..eccc0af7331dc140f3a15ddf12c5645e685abc90 100644 --- a/projects/cmd_sync_test/src/main.cpp +++ b/projects/cmd_sync_test/src/main.cpp @@ -18,9 +18,15 @@ int main(int argc, const char** argv) { true ); - vkcv::CameraManager cameraManager(window, windowWidth, windowHeight); - cameraManager.getCamera().setPosition(glm::vec3(0.f, 0.f, 3.f)); - cameraManager.getCamera().setNearFar(0.1, 30); + vkcv::camera::CameraManager cameraManager(window); + uint32_t camIndex = cameraManager.addCamera(vkcv::camera::ControllerType::PILOT); + uint32_t camIndex2 = cameraManager.addCamera(vkcv::camera::ControllerType::TRACKBALL); + + cameraManager.getCamera(camIndex).setPosition(glm::vec3(0.f, 0.f, 3.f)); + cameraManager.getCamera(camIndex).setNearFar(0.1f, 30.0f); + cameraManager.getCamera(camIndex).setYaw(180.0f); + + cameraManager.getCamera(camIndex2).setNearFar(0.1f, 30.0f); window.initEvents(); @@ -33,10 +39,10 @@ int main(int argc, const char** argv) { { "VK_KHR_swapchain" } ); - vkcv::asset::Mesh mesh; + vkcv::asset::Scene mesh; const char* path = argc > 1 ? argv[1] : "resources/cube/cube.gltf"; - int result = vkcv::asset::loadMesh(path, mesh); + int result = vkcv::asset::loadScene(path, mesh); if (result == 1) { std::cout << "Mesh loading successful!" << std::endl; @@ -80,7 +86,7 @@ int main(int argc, const char** argv) { const vkcv::AttachmentDescription present_color_attachment( vkcv::AttachmentOperation::STORE, vkcv::AttachmentOperation::CLEAR, - core.getSwapchainImageFormat() + core.getSwapchain().getFormat() ); const vkcv::AttachmentDescription depth_attachment( @@ -113,14 +119,16 @@ int main(int argc, const char** argv) { std::vector<vkcv::DescriptorBinding> descriptorBindings = { firstMeshProgram.getReflectedDescriptors()[0] }; vkcv::DescriptorSetHandle descriptorSet = core.createDescriptorSet(descriptorBindings); - const vkcv::PipelineConfig firstMeshPipelineConfig( + const vkcv::PipelineConfig firstMeshPipelineConfig { firstMeshProgram, windowWidth, windowHeight, firstMeshPass, - {firstMeshLayout}, + firstMeshLayout, { core.getDescriptorSet(descriptorSet).layout }, - true); + true + }; + vkcv::PipelineHandle firstMeshPipeline = core.createGraphicsPipeline(firstMeshPipelineConfig); if (!firstMeshPipeline) { @@ -128,8 +136,11 @@ int main(int argc, const char** argv) { return EXIT_FAILURE; } - vkcv::Image texture = core.createImage(vk::Format::eR8G8B8A8Srgb, mesh.texture_hack.w, mesh.texture_hack.h); - texture.fill(mesh.texture_hack.img); + //vkcv::Image texture = core.createImage(vk::Format::eR8G8B8A8Srgb, mesh.texture_hack.w, mesh.texture_hack.h); + //texture.fill(mesh.texture_hack.img); + vkcv::asset::Texture &tex = mesh.textures[0]; + vkcv::Image texture = core.createImage(vk::Format::eR8G8B8A8Srgb, tex.w, tex.h); + texture.fill(tex.data.data()); vkcv::SamplerHandle sampler = core.createSampler( vkcv::SamplerFilterType::LINEAR, @@ -186,14 +197,16 @@ int main(int argc, const char** argv) { const uint32_t shadowMapResolution = 1024; const vkcv::Image shadowMap = core.createImage(shadowMapFormat, shadowMapResolution, shadowMapResolution, 1); - const vkcv::PipelineConfig shadowPipeConfig( + const vkcv::PipelineConfig shadowPipeConfig { shadowShader, shadowMapResolution, shadowMapResolution, shadowPass, - {firstMeshLayout}, - {}, - false); + firstMeshLayout, + {}, + false + }; + const vkcv::PipelineHandle shadowPipe = core.createGraphicsPipeline(shadowPipeConfig); struct LightInfo { @@ -217,7 +230,7 @@ int main(int argc, const char** argv) { auto start = std::chrono::system_clock::now(); const auto appStartTime = start; while (window.isWindowOpen()) { - vkcv::Window::pollEvents(); + window.pollEvents(); uint32_t swapchainWidth, swapchainHeight; if (!core.beginFrame(swapchainWidth, swapchainHeight)) { @@ -233,10 +246,13 @@ int main(int argc, const char** argv) { auto end = std::chrono::system_clock::now(); auto deltatime = std::chrono::duration_cast<std::chrono::microseconds>(end - start); + start = end; - cameraManager.getCamera().updateView(deltatime.count() * 0.000001); + cameraManager.update(0.000001 * static_cast<double>(deltatime.count())); - const float sunTheta = std::chrono::duration_cast<std::chrono::milliseconds>(end - appStartTime).count() * 0.001f; + auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - appStartTime); + + const float sunTheta = 0.001f * static_cast<float>(duration.count()); lightInfo.direction = glm::normalize(glm::vec3(std::cos(sunTheta), 1, std::sin(sunTheta))); const float shadowProjectionSize = 5.f; @@ -258,7 +274,7 @@ int main(int argc, const char** argv) { lightInfo.lightMatrix = projectionLight * viewLight; lightBuffer.fill({ lightInfo }); - const glm::mat4 viewProjectionCamera = cameraManager.getCamera().getProjection() * cameraManager.getCamera().getView(); + const glm::mat4 viewProjectionCamera = cameraManager.getActiveCamera().getMVP(); mainPassMatrices.clear(); mvpLight.clear(); diff --git a/projects/first_mesh/resources/Szene/Szene.bin b/projects/first_mesh/resources/Szene/Szene.bin new file mode 100644 index 0000000000000000000000000000000000000000..c87d27637516b0bbf864251dd162773f5cc53e06 --- /dev/null +++ b/projects/first_mesh/resources/Szene/Szene.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee4742718f720d589a2a03f5d879f8c50ba9057718d191a43b046eaa9071080d +size 70328 diff --git a/projects/first_mesh/resources/Szene/Szene.gltf b/projects/first_mesh/resources/Szene/Szene.gltf new file mode 100644 index 0000000000000000000000000000000000000000..e5a32b29af5d0a2ac5f497e60b4b92c1873e1df9 --- /dev/null +++ b/projects/first_mesh/resources/Szene/Szene.gltf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75ba834118792ebbacf528a1690c7d04df4b4c8122b9f99a9aa9a9d075d2c86a +size 7421 diff --git a/projects/cmd_sync_test/resources/cube/boards2_vcyc_jpg.jpg b/projects/first_mesh/resources/Szene/boards2_vcyc.jpg similarity index 100% rename from projects/cmd_sync_test/resources/cube/boards2_vcyc_jpg.jpg rename to projects/first_mesh/resources/Szene/boards2_vcyc.jpg diff --git a/projects/first_mesh/resources/Szene/boards2_vcyc_jpg.jpg b/projects/first_mesh/resources/Szene/boards2_vcyc_jpg.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2636039e272289c0fba3fa2d88a060b857501248 --- /dev/null +++ b/projects/first_mesh/resources/Szene/boards2_vcyc_jpg.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cca33a6e58ddd1b37a6e6853a9aa0e7b15ca678937119194752393dd2a0a0564 +size 1192476 diff --git a/projects/first_mesh/src/main.cpp b/projects/first_mesh/src/main.cpp index d3be8c990ac581ec1b056926ce95c5ed9d5c2a31..5b7bc1edb7ab1b645f713098170bd5aa50657b91 100644 --- a/projects/first_mesh/src/main.cpp +++ b/projects/first_mesh/src/main.cpp @@ -18,10 +18,6 @@ int main(int argc, const char** argv) { true ); - vkcv::CameraManager cameraManager(window, static_cast<float>(window.getWidth()), static_cast<float>(window.getHeight())); - - window.initEvents(); - vkcv::Core core = vkcv::Core::create( window, applicationName, @@ -31,10 +27,10 @@ int main(int argc, const char** argv) { { "VK_KHR_swapchain" } ); - vkcv::asset::Mesh mesh; + vkcv::asset::Scene mesh; const char* path = argc > 1 ? argv[1] : "resources/cube/cube.gltf"; - int result = vkcv::asset::loadMesh(path, mesh); + int result = vkcv::asset::loadScene(path, mesh); if (result == 1) { std::cout << "Mesh loading successful!" << std::endl; @@ -65,7 +61,7 @@ int main(int argc, const char** argv) { const vkcv::AttachmentDescription present_color_attachment( vkcv::AttachmentOperation::STORE, vkcv::AttachmentOperation::CLEAR, - core.getSwapchainImageFormat() + core.getSwapchain().getFormat() ); const vkcv::AttachmentDescription depth_attachment( @@ -105,14 +101,15 @@ int main(int argc, const char** argv) { std::vector<vkcv::DescriptorBinding> descriptorBindings = { firstMeshProgram.getReflectedDescriptors()[setID] }; vkcv::DescriptorSetHandle descriptorSet = core.createDescriptorSet(descriptorBindings); - const vkcv::PipelineConfig firstMeshPipelineConfig( + const vkcv::PipelineConfig firstMeshPipelineConfig { firstMeshProgram, UINT32_MAX, UINT32_MAX, firstMeshPass, {firstMeshLayout}, { core.getDescriptorSet(descriptorSet).layout }, - true); + true + }; vkcv::PipelineHandle firstMeshPipeline = core.createGraphicsPipeline(firstMeshPipelineConfig); if (!firstMeshPipeline) { @@ -120,8 +117,13 @@ int main(int argc, const char** argv) { return EXIT_FAILURE; } - vkcv::Image texture = core.createImage(vk::Format::eR8G8B8A8Srgb, mesh.texture_hack.w, mesh.texture_hack.h); - texture.fill(mesh.texture_hack.img); + // FIXME There should be a test here to make sure there is at least 1 + // texture in the mesh. + vkcv::asset::Texture &tex = mesh.textures[0]; + vkcv::Image texture = core.createImage(vk::Format::eR8G8B8A8Srgb, tex.w, tex.h); + texture.fill(tex.data.data()); + texture.generateMipChainImmediate(); + texture.switchLayout(vk::ImageLayout::eShaderReadOnlyOptimal); vkcv::SamplerHandle sampler = core.createSampler( vkcv::SamplerFilterType::LINEAR, @@ -131,16 +133,17 @@ int main(int argc, const char** argv) { ); const std::vector<vkcv::VertexBufferBinding> vertexBufferBindings = { - vkcv::VertexBufferBinding(static_cast<vk::DeviceSize>(attributes[0].offset), vertexBuffer.getVulkanHandle()), - vkcv::VertexBufferBinding(static_cast<vk::DeviceSize>(attributes[1].offset), vertexBuffer.getVulkanHandle()), - vkcv::VertexBufferBinding(static_cast<vk::DeviceSize>(attributes[2].offset), vertexBuffer.getVulkanHandle()) }; + vkcv::VertexBufferBinding(static_cast<vk::DeviceSize>(attributes[0].offset), vertexBuffer.getVulkanHandle()), + vkcv::VertexBufferBinding(static_cast<vk::DeviceSize>(attributes[1].offset), vertexBuffer.getVulkanHandle()), + vkcv::VertexBufferBinding(static_cast<vk::DeviceSize>(attributes[2].offset), vertexBuffer.getVulkanHandle()) }; vkcv::DescriptorWrites setWrites; - setWrites.sampledImageWrites = { vkcv::SampledImageDescriptorWrite(0, texture.getHandle()) }; - setWrites.samplerWrites = { vkcv::SamplerDescriptorWrite(1, sampler) }; + setWrites.sampledImageWrites = { vkcv::SampledImageDescriptorWrite(0, texture.getHandle()) }; + setWrites.samplerWrites = { vkcv::SamplerDescriptorWrite(1, sampler) }; + core.writeDescriptorSet(descriptorSet, setWrites); - vkcv::ImageHandle depthBuffer = core.createImage(vk::Format::eD32Sfloat, windowWidth, windowHeight).getHandle(); + vkcv::ImageHandle depthBuffer = core.createImage(vk::Format::eD32Sfloat, windowWidth, windowHeight, 1, false).getHandle(); const vkcv::ImageHandle swapchainInput = vkcv::ImageHandle::createSwapchainImageHandle(); @@ -149,9 +152,16 @@ int main(int argc, const char** argv) { vkcv::DescriptorSetUsage descriptorUsage(0, core.getDescriptorSet(descriptorSet).vulkanHandle); vkcv::DrawcallInfo drawcall(renderMesh, { descriptorUsage }); - auto start = std::chrono::system_clock::now(); + vkcv::camera::CameraManager cameraManager(window); + uint32_t camIndex0 = cameraManager.addCamera(vkcv::camera::ControllerType::PILOT); + uint32_t camIndex1 = cameraManager.addCamera(vkcv::camera::ControllerType::TRACKBALL); + + cameraManager.getCamera(camIndex0).setPosition(glm::vec3(0, 0, -3)); + + auto start = std::chrono::system_clock::now(); + while (window.isWindowOpen()) { - vkcv::Window::pollEvents(); + window.pollEvents(); if(window.getHeight() == 0 || window.getWidth() == 0) continue; @@ -169,10 +179,11 @@ int main(int argc, const char** argv) { } auto end = std::chrono::system_clock::now(); - auto deltatime = end - start; + auto deltatime = std::chrono::duration_cast<std::chrono::microseconds>(end - start); + start = end; - cameraManager.getCamera().updateView(std::chrono::duration<double>(deltatime).count()); - const glm::mat4 mvp = cameraManager.getCamera().getProjection() * cameraManager.getCamera().getView(); + cameraManager.update(0.000001 * static_cast<double>(deltatime.count())); + glm::mat4 mvp = cameraManager.getActiveCamera().getMVP(); vkcv::PushConstantData pushConstantData((void*)&mvp, sizeof(glm::mat4)); @@ -188,7 +199,6 @@ int main(int argc, const char** argv) { renderTargets); core.prepareSwapchainImageForPresent(cmdStream); core.submitCommandStream(cmdStream); - core.endFrame(); } diff --git a/projects/first_scene/.gitignore b/projects/first_scene/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b0d802667a184267e6ee764264e976dfead8e9dd --- /dev/null +++ b/projects/first_scene/.gitignore @@ -0,0 +1 @@ +first_scene diff --git a/projects/cmd_sync_test/CMakeLists.txt b/projects/first_scene/CMakeLists.txt similarity index 52% rename from projects/cmd_sync_test/CMakeLists.txt rename to projects/first_scene/CMakeLists.txt index da1d12949d9e8c918d78ab5cb0484106fae69b6a..8b90739750011a36b4c1d9e0bff7cba986074228 100644 --- a/projects/cmd_sync_test/CMakeLists.txt +++ b/projects/first_scene/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.16) -project(cmd_sync_test) +project(first_scene) # setting c++ standard for the project set(CMAKE_CXX_STANDARD 17) @@ -9,20 +9,20 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) # adding source files to the project -add_executable(cmd_sync_test src/main.cpp) +add_executable(first_scene src/main.cpp) # this should fix the execution path to load local files from the project (for MSVC) if(MSVC) - set_target_properties(cmd_sync_test PROPERTIES RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) - set_target_properties(cmd_sync_test PROPERTIES RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) + set_target_properties(first_scene PROPERTIES RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) + set_target_properties(first_scene PROPERTIES RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) # in addition to setting the output directory, the working directory has to be set # by default visual studio sets the working directory to the build directory, when using the debugger - set_target_properties(cmd_sync_test PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) + set_target_properties(first_scene PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) endif() # including headers of dependencies and the VkCV framework -target_include_directories(cmd_sync_test SYSTEM BEFORE PRIVATE ${vkcv_include} ${vkcv_includes} ${vkcv_asset_loader_include} ${vkcv_camera_include}) +target_include_directories(first_scene SYSTEM BEFORE PRIVATE ${vkcv_include} ${vkcv_includes} ${vkcv_asset_loader_include} ${vkcv_camera_include}) # linking with libraries from all dependencies and the VkCV framework -target_link_libraries(cmd_sync_test vkcv ${vkcv_libraries} vkcv_asset_loader ${vkcv_asset_loader_libraries} vkcv_camera) +target_link_libraries(first_scene vkcv ${vkcv_libraries} vkcv_asset_loader ${vkcv_asset_loader_libraries} vkcv_camera) diff --git a/projects/first_scene/resources/Cutlery/Cutlery_chrome_BaseColor.png b/projects/first_scene/resources/Cutlery/Cutlery_chrome_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..8258525f22097f2382ec5c26ad0df7eb50718642 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Cutlery_chrome_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ce87f6407ee40ffa60983587aeb52333d59b4b1c01a53e11f4bb227ba1099d9 +size 109 diff --git a/projects/first_scene/resources/Cutlery/Cutlery_chrome_Normal.png b/projects/first_scene/resources/Cutlery/Cutlery_chrome_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..620fe7621cf35409ae8c04099dc8bc4bbc04343b --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Cutlery_chrome_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:68a0064d457a6f7994814b07d943deda778754128935689874334300ede6161d +size 2332064 diff --git a/projects/first_scene/resources/Cutlery/Cutlery_details_BaseColor.png b/projects/first_scene/resources/Cutlery/Cutlery_details_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..5570e88c569036b9d00155ef6113013aa23f2503 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Cutlery_details_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42c2715635081eb29c4489ce631798b0e9c881460efc0aa63d0e81641a0dcfe9 +size 108 diff --git a/projects/first_scene/resources/Cutlery/Cutlery_details_Normal.png b/projects/first_scene/resources/Cutlery/Cutlery_details_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..d07681f5bfa25c279321c3074e21e4900c5eb0fa --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Cutlery_details_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15b0133e140899c47ccf35b0f99a7e337e3110ae089f45d27faf9983f3e0a1f7 +size 770758 diff --git a/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Caps_BaseColor.png b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Caps_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..1845e8a7d586a0d23300ad9d04a82f1d5048fcf5 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Caps_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea7c82c0f9e25afa401470df1fb6903f508fa138d21ad30f57a9153b0395b198 +size 521315 diff --git a/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Caps_Normal.png b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Caps_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..1c800c0489693b66d6163bdc2156d453b68ca19b --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Caps_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:119efbbc020244ff9b7ff16ac9795a6d4b1808d1b90d81d20d2c874d0dc8a924 +size 1693468 diff --git a/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Glass_Wine_BaseColor.png b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Glass_Wine_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..36f46ebf25158c78bc26d83860e1c08b2c9e96cf --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Glass_Wine_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99896468c7d47dd5391d585eecf149f420eca3bfec31923c21fa86c45fe02d0f +size 108 diff --git a/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Glass_Wine_Normal.png b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Glass_Wine_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..28c205d4e70867ec58448ca8ba2c2117c611a367 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Glass_Wine_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b31618aa5adce4ad476bec2c03718c5ae097250e784344f2d298b8a74c3bfd46 +size 90 diff --git a/projects/first_scene/resources/Cutlery/Plates_Ceramic_BaseColor.png b/projects/first_scene/resources/Cutlery/Plates_Ceramic_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..e0104189a1190c160152101e9e328e81ed89121b --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Plates_Ceramic_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6eff6ccd12d8b39d60ae5ee91edd73d4d7838fcb5d9bc6ff0e671bdf009134e9 +size 109 diff --git a/projects/first_scene/resources/Cutlery/Plates_Ceramic_Normal.png b/projects/first_scene/resources/Cutlery/Plates_Ceramic_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..fa13483d25595ee6b3a00e7fe6ce48aed7b6aaca --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Plates_Ceramic_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe92c40ff4032fdaf10eeafd943657a0c6e0bfb3f38770f5654aa943a660f421 +size 59419 diff --git a/projects/first_scene/resources/Cutlery/Plates_Details_BaseColor-Plates_Details_BaseColor.png b/projects/first_scene/resources/Cutlery/Plates_Details_BaseColor-Plates_Details_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..b91d0ac62fbeabbef1ed78f1343f919836cbca40 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Plates_Details_BaseColor-Plates_Details_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ca7d436a68a2a1237aee6e763b2954f01666b21f1dbd46929a322ea277483d2 +size 779227 diff --git a/projects/first_scene/resources/Cutlery/Plates_Details_Normal.png b/projects/first_scene/resources/Cutlery/Plates_Details_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..6efd967984ee2e68b89de9e471b93396c13ca69a --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Plates_Details_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b01fc6482054c64d7407b283731e57fce0601a8db28b6781c14fae3c6b30b0fe +size 504362 diff --git a/projects/first_scene/resources/Cutlery/ToffeeJar_Label_BaseColor.png b/projects/first_scene/resources/Cutlery/ToffeeJar_Label_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..d0e0c4f4134cb99d3765d6f078f71efab8861bf1 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/ToffeeJar_Label_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:df138ee68c1d455652d1b9ae3dd03e93fcd2f6a0d8a1f12e3710f39143088674 +size 1593466 diff --git a/projects/first_scene/resources/Cutlery/ToffeeJar_Label_Normal.png b/projects/first_scene/resources/Cutlery/ToffeeJar_Label_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..9f310653b5211575da3cab2f6deb47ec6826a936 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/ToffeeJar_Label_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6af5da97cbb25d79aea2dde8dd71ecbd495334fe34e99497ba17821be93fd7fd +size 2696676 diff --git a/projects/first_scene/resources/Cutlery/TransparentGlass_BaseColor.png b/projects/first_scene/resources/Cutlery/TransparentGlass_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..4e4f0fcb312b8f8bd0df965bfe6b8ac62ec5df4d --- /dev/null +++ b/projects/first_scene/resources/Cutlery/TransparentGlass_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2796affdfdcf6bc805176d9f85505680b5ee52eeec625e9eaeea4f0ff3854883 +size 108 diff --git a/projects/first_scene/resources/Cutlery/TransparentGlass_Normal.png b/projects/first_scene/resources/Cutlery/TransparentGlass_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..28c205d4e70867ec58448ca8ba2c2117c611a367 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/TransparentGlass_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b31618aa5adce4ad476bec2c03718c5ae097250e784344f2d298b8a74c3bfd46 +size 90 diff --git a/projects/first_scene/resources/Cutlery/cutlerySzene.bin b/projects/first_scene/resources/Cutlery/cutlerySzene.bin new file mode 100644 index 0000000000000000000000000000000000000000..ab9a0aa47205e8f3064d2f16a950d4733fb4f472 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/cutlerySzene.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f545b986e0a1ac5bff5d49693a52042aa37878425818f72c69c243da20d1f99d +size 183324 diff --git a/projects/first_scene/resources/Cutlery/cutlerySzene.glb b/projects/first_scene/resources/Cutlery/cutlerySzene.glb new file mode 100644 index 0000000000000000000000000000000000000000..b0c5f345aaaa3f96d7158a0992ee124aae99a69a --- /dev/null +++ b/projects/first_scene/resources/Cutlery/cutlerySzene.glb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb1bad604192ca36222c0ca485ba87b846ecbd11ee8254327e04e3c993b00116 +size 11150396 diff --git a/projects/first_scene/resources/Cutlery/cutlerySzene.gltf b/projects/first_scene/resources/Cutlery/cutlerySzene.gltf new file mode 100644 index 0000000000000000000000000000000000000000..53e339cda4511f3f1a8670b36469e184aac530e2 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/cutlerySzene.gltf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c77cd60e2327daca1a01044e45f2c38655f7b781bd07985fc0135328a8a96b57 +size 34312 diff --git a/projects/first_scene/resources/Sponza/Sponza.bin b/projects/first_scene/resources/Sponza/Sponza.bin new file mode 100644 index 0000000000000000000000000000000000000000..cfedd26ca5a67b6d0a47d44d13a75e14a141717a --- /dev/null +++ b/projects/first_scene/resources/Sponza/Sponza.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b809f7a17687dc99e6f41ca1ea32c06eded8779bf34d16f1f565d750b0ffd68 +size 6347696 diff --git a/projects/first_scene/resources/Sponza/Sponza.gltf b/projects/first_scene/resources/Sponza/Sponza.gltf new file mode 100644 index 0000000000000000000000000000000000000000..172ea07e21c94465211c860cd805355704cef230 --- /dev/null +++ b/projects/first_scene/resources/Sponza/Sponza.gltf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cc0ecad5c4694088ff820e663619c370421afc1323ac487406e8e9b4735d787 +size 713962 diff --git a/projects/first_scene/resources/Sponza/background.png b/projects/first_scene/resources/Sponza/background.png new file mode 100644 index 0000000000000000000000000000000000000000..b64def129da38f4e23d89e21b4af1039008a4327 --- /dev/null +++ b/projects/first_scene/resources/Sponza/background.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5b5f900ff8ed83a31750ec8e428b5b91273794ddcbfc4e4b8a6a7e781f8c686 +size 1417666 diff --git a/projects/first_scene/resources/Sponza/chain_texture.png b/projects/first_scene/resources/Sponza/chain_texture.png new file mode 100644 index 0000000000000000000000000000000000000000..c1e1768cff78e0614ad707eca8602a4c4edab5e5 --- /dev/null +++ b/projects/first_scene/resources/Sponza/chain_texture.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8362cfd472880daeaea37439326a4651d1338680ae69bb2513fc6b17c8de7d4 +size 490895 diff --git a/projects/first_scene/resources/Sponza/lion.png b/projects/first_scene/resources/Sponza/lion.png new file mode 100644 index 0000000000000000000000000000000000000000..c49c7f0ed31e762e19284d0d3624fbc47664e56b --- /dev/null +++ b/projects/first_scene/resources/Sponza/lion.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f882f746c3a9cd51a9c6eedc1189b97668721d91a3fe49232036e789912c652 +size 2088728 diff --git a/projects/first_scene/resources/Sponza/spnza_bricks_a_diff.png b/projects/first_scene/resources/Sponza/spnza_bricks_a_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..cde4c7a6511e9a5f03c63ad996437fcdba3ce2df --- /dev/null +++ b/projects/first_scene/resources/Sponza/spnza_bricks_a_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b94219c2f5f943f3f4715c74e7d1038bf0ab3b3b3216a758eaee67f875df0851 +size 1928829 diff --git a/projects/first_scene/resources/Sponza/sponza_arch_diff.png b/projects/first_scene/resources/Sponza/sponza_arch_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..bcd9bda2918d226039f9e2d03902d377b706fab6 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_arch_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0df2c8a01b2843b1c792b494f7173cdbc4f834840fc2177af3e5d690fceda57 +size 1596151 diff --git a/projects/first_scene/resources/Sponza/sponza_ceiling_a_diff.png b/projects/first_scene/resources/Sponza/sponza_ceiling_a_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..59de631ffac4414cabf69b2dc794c46fc187d6cb --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_ceiling_a_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab6c187a81aa68f4eba30119e17fce2e4882a9ec320f70c90482dbe9da82b1c6 +size 1872074 diff --git a/projects/first_scene/resources/Sponza/sponza_column_a_diff.png b/projects/first_scene/resources/Sponza/sponza_column_a_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..01a82432d3f9939bbefe850bdb900f1ff9a3f6db --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_column_a_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c291507e2808bb83e160ab4b020689817df273baad3713a9ad19ac15fac6826 +size 1840992 diff --git a/projects/first_scene/resources/Sponza/sponza_column_b_diff.png b/projects/first_scene/resources/Sponza/sponza_column_b_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..10a660cce2a5a9b8997772c746058ce23e7d45d7 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_column_b_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2820b0267c4289c6cedbb42721792a57ef244ec2d0935941011c2a7d3fe88a9b +size 2170433 diff --git a/projects/first_scene/resources/Sponza/sponza_column_c_diff.png b/projects/first_scene/resources/Sponza/sponza_column_c_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..bc46fd979044a938d3adca7601689e71504e48bf --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_column_c_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0bc993ff59865468ef4530798930c7dfefb07482d71db45bc2a520986b27735 +size 2066950 diff --git a/projects/first_scene/resources/Sponza/sponza_curtain_blue_diff.png b/projects/first_scene/resources/Sponza/sponza_curtain_blue_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..384c8c2c051160d530eb3ac8b05c9c60752a2d2b --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_curtain_blue_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b85c6bb3cd5105f48d3812ec8e7a1068521ce69e917300d79e136e19d45422fb +size 9510905 diff --git a/projects/first_scene/resources/Sponza/sponza_curtain_diff.png b/projects/first_scene/resources/Sponza/sponza_curtain_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..af842e9f5fe18c1f609875e00899a6770fa4488b --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_curtain_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:563c56bdbbee395a6ef7f0c51c8ac9223c162e517b4cdba0d4654e8de27c98d8 +size 9189263 diff --git a/projects/first_scene/resources/Sponza/sponza_curtain_green_diff.png b/projects/first_scene/resources/Sponza/sponza_curtain_green_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..6c9b6391a199407637fa71033d79fb58b8b4f0d7 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_curtain_green_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:238fe1c7f481388d1c1d578c2da8d411b99e8f0030ab62060a306db333124476 +size 8785458 diff --git a/projects/first_scene/resources/Sponza/sponza_details_diff.png b/projects/first_scene/resources/Sponza/sponza_details_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..12656686362c3e0a297e060491f33bd7351551f9 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_details_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb1223b3bb82f8757e7df25a6891f1239cdd7ec59990340e952fb2d6b7ea570c +size 1522643 diff --git a/projects/first_scene/resources/Sponza/sponza_fabric_blue_diff.png b/projects/first_scene/resources/Sponza/sponza_fabric_blue_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..879d16ef84722a4fc13e83a771778de326e4bc54 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_fabric_blue_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:467d290bf5d4b2a017da140ba9e244ed8a8a9be5418a9ac9bcb4ad572ae2d7ab +size 2229440 diff --git a/projects/first_scene/resources/Sponza/sponza_fabric_diff.png b/projects/first_scene/resources/Sponza/sponza_fabric_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..3311287a219d2148620b87fe428fea071688d051 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_fabric_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1594f59cc2848db26add47361f4e665e3d8afa147760ed915d839fea42b20287 +size 2267382 diff --git a/projects/first_scene/resources/Sponza/sponza_fabric_green_diff.png b/projects/first_scene/resources/Sponza/sponza_fabric_green_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..de110f369004388dae4cd5067c63428db3a07834 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_fabric_green_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:902b87faab221173bf370cea7c74cb9060b4d870ac6316b190dafded1cb12993 +size 2258220 diff --git a/projects/first_scene/resources/Sponza/sponza_flagpole_diff.png b/projects/first_scene/resources/Sponza/sponza_flagpole_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..5f6e0812a0df80346318baa3cb50a6888afc58f8 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_flagpole_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bfffb62e770959c725d0f3db6dc7dbdd46a380ec55ef884dab94d44ca017b438 +size 1425673 diff --git a/projects/first_scene/resources/Sponza/sponza_floor_a_diff.png b/projects/first_scene/resources/Sponza/sponza_floor_a_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..788ed764f79ba724f04a2d603076a5b85013e188 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_floor_a_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a16f9230fa91f9f31dfca6216ce205f1ef132d44f3b012fbf6efc0fba69770ab +size 1996838 diff --git a/projects/first_scene/resources/Sponza/sponza_roof_diff.png b/projects/first_scene/resources/Sponza/sponza_roof_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..c5b84261fdd1cc776a94b3ce398c7806b895f9a3 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_roof_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7fc412138c20da19f8173e53545e771f4652558dff624d4dc67143e40efe562b +size 2320533 diff --git a/projects/first_scene/resources/Sponza/sponza_thorn_diff.png b/projects/first_scene/resources/Sponza/sponza_thorn_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..7a9142674a7d4a6f94a48c5152cf0300743b597a --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_thorn_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a73a17c883cd0d0d67cfda2dc4118400a916366c05b9a5ac465f0c8b30fd9c8e +size 635001 diff --git a/projects/first_scene/resources/Sponza/vase_dif.png b/projects/first_scene/resources/Sponza/vase_dif.png new file mode 100644 index 0000000000000000000000000000000000000000..61236a81cb324af8797b05099cd264cefe189e56 --- /dev/null +++ b/projects/first_scene/resources/Sponza/vase_dif.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53d06f52bf9e59df4cf00237707cca76c4f692bda61a62b06a30d321311d6dd9 +size 1842101 diff --git a/projects/first_scene/resources/Sponza/vase_hanging.png b/projects/first_scene/resources/Sponza/vase_hanging.png new file mode 100644 index 0000000000000000000000000000000000000000..36a3cee71d8213225090c74f8c0dce33b9d44378 --- /dev/null +++ b/projects/first_scene/resources/Sponza/vase_hanging.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9d10b4f27a3c9a78d5bac882fdd4b6a6987c262f48fa490670fe5e235951e31 +size 1432804 diff --git a/projects/first_scene/resources/Sponza/vase_plant.png b/projects/first_scene/resources/Sponza/vase_plant.png new file mode 100644 index 0000000000000000000000000000000000000000..7ad95e702e229f1ebd803e5203a266d15f2c07b9 --- /dev/null +++ b/projects/first_scene/resources/Sponza/vase_plant.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2087371ff02212fb7014b6daefa191cf5676d2227193fff261a5d02f554cb8e +size 998089 diff --git a/projects/first_scene/resources/Sponza/vase_round.png b/projects/first_scene/resources/Sponza/vase_round.png new file mode 100644 index 0000000000000000000000000000000000000000..c17953abc000c44b8991e23c136c2b67348f3d1b --- /dev/null +++ b/projects/first_scene/resources/Sponza/vase_round.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa23d48d492d5d4ada2ddb27d1ef22952b214e6eb3b301c65f9d88442723d20a +size 1871399 diff --git a/projects/first_scene/resources/Szene/Szene.bin b/projects/first_scene/resources/Szene/Szene.bin new file mode 100644 index 0000000000000000000000000000000000000000..c87d27637516b0bbf864251dd162773f5cc53e06 --- /dev/null +++ b/projects/first_scene/resources/Szene/Szene.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee4742718f720d589a2a03f5d879f8c50ba9057718d191a43b046eaa9071080d +size 70328 diff --git a/projects/first_scene/resources/Szene/Szene.gltf b/projects/first_scene/resources/Szene/Szene.gltf new file mode 100644 index 0000000000000000000000000000000000000000..e5a32b29af5d0a2ac5f497e60b4b92c1873e1df9 --- /dev/null +++ b/projects/first_scene/resources/Szene/Szene.gltf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75ba834118792ebbacf528a1690c7d04df4b4c8122b9f99a9aa9a9d075d2c86a +size 7421 diff --git a/projects/first_scene/resources/Szene/boards2_vcyc.jpg b/projects/first_scene/resources/Szene/boards2_vcyc.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2636039e272289c0fba3fa2d88a060b857501248 --- /dev/null +++ b/projects/first_scene/resources/Szene/boards2_vcyc.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cca33a6e58ddd1b37a6e6853a9aa0e7b15ca678937119194752393dd2a0a0564 +size 1192476 diff --git a/projects/first_scene/resources/Szene/boards2_vcyc_jpg.jpg b/projects/first_scene/resources/Szene/boards2_vcyc_jpg.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2636039e272289c0fba3fa2d88a060b857501248 --- /dev/null +++ b/projects/first_scene/resources/Szene/boards2_vcyc_jpg.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cca33a6e58ddd1b37a6e6853a9aa0e7b15ca678937119194752393dd2a0a0564 +size 1192476 diff --git a/projects/first_scene/resources/shaders/compile.bat b/projects/first_scene/resources/shaders/compile.bat new file mode 100644 index 0000000000000000000000000000000000000000..b4521235c40fe5fb163bab874560c2f219b7517f --- /dev/null +++ b/projects/first_scene/resources/shaders/compile.bat @@ -0,0 +1,3 @@ +%VULKAN_SDK%\Bin32\glslc.exe shader.vert -o vert.spv +%VULKAN_SDK%\Bin32\glslc.exe shader.frag -o frag.spv +pause \ No newline at end of file diff --git a/projects/first_scene/resources/shaders/frag.spv b/projects/first_scene/resources/shaders/frag.spv new file mode 100644 index 0000000000000000000000000000000000000000..087e4e22fb2fcec27d99b3ff2aa1a705fe755796 Binary files /dev/null and b/projects/first_scene/resources/shaders/frag.spv differ diff --git a/projects/first_scene/resources/shaders/shader.frag b/projects/first_scene/resources/shaders/shader.frag new file mode 100644 index 0000000000000000000000000000000000000000..b5494bea7d6497e2e3dcd8559606864a71adb74e --- /dev/null +++ b/projects/first_scene/resources/shaders/shader.frag @@ -0,0 +1,15 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout(location = 0) in vec3 passNormal; +layout(location = 1) in vec2 passUV; + +layout(location = 0) out vec3 outColor; + +layout(set=0, binding=0) uniform texture2D meshTexture; +layout(set=0, binding=1) uniform sampler textureSampler; + +void main() { + outColor = texture(sampler2D(meshTexture, textureSampler), passUV).rgb; + //outColor = passNormal * 0.5 + 0.5; +} \ No newline at end of file diff --git a/projects/first_scene/resources/shaders/shader.vert b/projects/first_scene/resources/shaders/shader.vert new file mode 100644 index 0000000000000000000000000000000000000000..76855152253b48b7400f016d063ed4f0e507435e --- /dev/null +++ b/projects/first_scene/resources/shaders/shader.vert @@ -0,0 +1,19 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout(location = 0) in vec3 inPosition; +layout(location = 1) in vec3 inNormal; +layout(location = 2) in vec2 inUV; + +layout(location = 0) out vec3 passNormal; +layout(location = 1) out vec2 passUV; + +layout( push_constant ) uniform constants{ + mat4 mvp; +}; + +void main() { + gl_Position = mvp * vec4(inPosition, 1.0); + passNormal = inNormal; + passUV = inUV; +} \ No newline at end of file diff --git a/projects/first_scene/resources/shaders/vert.spv b/projects/first_scene/resources/shaders/vert.spv new file mode 100644 index 0000000000000000000000000000000000000000..374c023e14b351eb43cbcda5951cbb8b3d6f96a1 Binary files /dev/null and b/projects/first_scene/resources/shaders/vert.spv differ diff --git a/projects/first_scene/src/main.cpp b/projects/first_scene/src/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..420400cdd04865ddd48eec7cf6000e36417d8095 --- /dev/null +++ b/projects/first_scene/src/main.cpp @@ -0,0 +1,264 @@ +#include <iostream> +#include <vkcv/Core.hpp> +#include <GLFW/glfw3.h> +#include <vkcv/camera/CameraManager.hpp> +#include <chrono> +#include <vkcv/asset/asset_loader.hpp> +#include <vkcv/Logger.hpp> + +glm::mat4 arrayTo4x4Matrix(std::array<float,16> array){ + glm::mat4 matrix; + for (int i = 0; i < 4; i++){ + for (int j = 0; j < 4; j++){ + matrix[i][j] = array[j * 4 + i]; + } + } + return matrix; +} + +int main(int argc, const char** argv) { + const char* applicationName = "First Scene"; + + uint32_t windowWidth = 800; + uint32_t windowHeight = 600; + + vkcv::Window window = vkcv::Window::create( + applicationName, + windowWidth, + windowHeight, + true + ); + + vkcv::camera::CameraManager cameraManager(window); + uint32_t camIndex0 = cameraManager.addCamera(vkcv::camera::ControllerType::PILOT); + uint32_t camIndex1 = cameraManager.addCamera(vkcv::camera::ControllerType::TRACKBALL); + + cameraManager.getCamera(camIndex0).setPosition(glm::vec3(0, 0, -3)); + cameraManager.getCamera(camIndex0).setNearFar(0.1f, 30.0f); + + cameraManager.getCamera(camIndex1).setNearFar(0.1f, 30.0f); + + vkcv::Core core = vkcv::Core::create( + window, + applicationName, + VK_MAKE_VERSION(0, 0, 1), + { vk::QueueFlagBits::eGraphics ,vk::QueueFlagBits::eCompute , vk::QueueFlagBits::eTransfer }, + {}, + { "VK_KHR_swapchain" } + ); + + vkcv::asset::Scene scene; + + const char* path = argc > 1 ? argv[1] : "resources/Sponza/Sponza.gltf"; + int result = vkcv::asset::loadScene(path, scene); + + if (result == 1) { + std::cout << "Mesh loading successful!" << std::endl; + } + else { + std::cout << "Mesh loading failed: " << result << std::endl; + return 1; + } + + assert(!scene.vertexGroups.empty()); + std::vector<std::vector<uint8_t>> vBuffers; + std::vector<std::vector<uint8_t>> iBuffers; + + std::vector<vkcv::VertexBufferBinding> vBufferBindings; + std::vector<std::vector<vkcv::VertexBufferBinding>> vertexBufferBindings; + std::vector<vkcv::asset::VertexAttribute> vAttributes; + + for (int i = 0; i < scene.vertexGroups.size(); i++) { + + vBuffers.push_back(scene.vertexGroups[i].vertexBuffer.data); + iBuffers.push_back(scene.vertexGroups[i].indexBuffer.data); + + auto& attributes = scene.vertexGroups[i].vertexBuffer.attributes; + + std::sort(attributes.begin(), attributes.end(), [](const vkcv::asset::VertexAttribute& x, const vkcv::asset::VertexAttribute& y) { + return static_cast<uint32_t>(x.type) < static_cast<uint32_t>(y.type); + }); + } + + std::vector<vkcv::Buffer<uint8_t>> vertexBuffers; + for (const vkcv::asset::VertexGroup& group : scene.vertexGroups) { + vertexBuffers.push_back(core.createBuffer<uint8_t>( + vkcv::BufferType::VERTEX, + group.vertexBuffer.data.size())); + vertexBuffers.back().fill(group.vertexBuffer.data); + } + + std::vector<vkcv::Buffer<uint8_t>> indexBuffers; + for (const auto& dataBuffer : iBuffers) { + indexBuffers.push_back(core.createBuffer<uint8_t>( + vkcv::BufferType::INDEX, + dataBuffer.size())); + indexBuffers.back().fill(dataBuffer); + } + + int vertexBufferIndex = 0; + for (const auto& vertexGroup : scene.vertexGroups) { + for (const auto& attribute : vertexGroup.vertexBuffer.attributes) { + vAttributes.push_back(attribute); + vBufferBindings.push_back(vkcv::VertexBufferBinding(attribute.offset, vertexBuffers[vertexBufferIndex].getVulkanHandle())); + } + vertexBufferBindings.push_back(vBufferBindings); + vBufferBindings.clear(); + vertexBufferIndex++; + } + + const vkcv::AttachmentDescription present_color_attachment( + vkcv::AttachmentOperation::STORE, + vkcv::AttachmentOperation::CLEAR, + core.getSwapchain().getFormat() + ); + + const vkcv::AttachmentDescription depth_attachment( + vkcv::AttachmentOperation::STORE, + vkcv::AttachmentOperation::CLEAR, + vk::Format::eD32Sfloat + ); + + vkcv::PassConfig scenePassDefinition({ present_color_attachment, depth_attachment }); + vkcv::PassHandle scenePass = core.createPass(scenePassDefinition); + + if (!scenePass) { + std::cout << "Error. Could not create renderpass. Exiting." << std::endl; + return EXIT_FAILURE; + } + + vkcv::ShaderProgram sceneShaderProgram{}; + sceneShaderProgram.addShader(vkcv::ShaderStage::VERTEX, std::filesystem::path("resources/shaders/vert.spv")); + sceneShaderProgram.addShader(vkcv::ShaderStage::FRAGMENT, std::filesystem::path("resources/shaders/frag.spv")); + + const std::vector<vkcv::VertexAttachment> vertexAttachments = sceneShaderProgram.getVertexAttachments(); + std::vector<vkcv::VertexBinding> bindings; + for (size_t i = 0; i < vertexAttachments.size(); i++) { + bindings.push_back(vkcv::VertexBinding(i, { vertexAttachments[i] })); + } + + const vkcv::VertexLayout sceneLayout(bindings); + + uint32_t setID = 0; + + std::vector<vkcv::DescriptorBinding> descriptorBindings = { sceneShaderProgram.getReflectedDescriptors()[setID] }; + + vkcv::SamplerHandle sampler = core.createSampler( + vkcv::SamplerFilterType::LINEAR, + vkcv::SamplerFilterType::LINEAR, + vkcv::SamplerMipmapMode::LINEAR, + vkcv::SamplerAddressMode::REPEAT + ); + + std::vector<vkcv::Image> sceneImages; + std::vector<vkcv::DescriptorSetHandle> descriptorSets; + for (const auto& vertexGroup : scene.vertexGroups) { + descriptorSets.push_back(core.createDescriptorSet(descriptorBindings)); + + const auto& material = scene.materials[vertexGroup.materialIndex]; + + int baseColorIndex = material.baseColor; + if (baseColorIndex < 0) { + vkcv_log(vkcv::LogLevel::WARNING, "Material lacks base color"); + baseColorIndex = 0; + } + + vkcv::asset::Texture& sceneTexture = scene.textures[baseColorIndex]; + + sceneImages.push_back(core.createImage(vk::Format::eR8G8B8A8Srgb, sceneTexture.w, sceneTexture.h)); + sceneImages.back().fill(sceneTexture.data.data()); + + vkcv::DescriptorWrites setWrites; + setWrites.sampledImageWrites = { vkcv::SampledImageDescriptorWrite(0, sceneImages.back().getHandle()) }; + setWrites.samplerWrites = { vkcv::SamplerDescriptorWrite(1, sampler) }; + core.writeDescriptorSet(descriptorSets.back(), setWrites); + } + + const vkcv::PipelineConfig scenePipelineDefsinition{ + sceneShaderProgram, + UINT32_MAX, + UINT32_MAX, + scenePass, + {sceneLayout}, + { core.getDescriptorSet(descriptorSets[0]).layout }, + true }; + vkcv::PipelineHandle scenePipeline = core.createGraphicsPipeline(scenePipelineDefsinition); + + if (!scenePipeline) { + std::cout << "Error. Could not create graphics pipeline. Exiting." << std::endl; + return EXIT_FAILURE; + } + + vkcv::ImageHandle depthBuffer = core.createImage(vk::Format::eD32Sfloat, windowWidth, windowHeight).getHandle(); + + const vkcv::ImageHandle swapchainInput = vkcv::ImageHandle::createSwapchainImageHandle(); + + std::vector<vkcv::DrawcallInfo> drawcalls; + for(int i = 0; i < scene.vertexGroups.size(); i++){ + vkcv::Mesh renderMesh(vertexBufferBindings[i], indexBuffers[i].getVulkanHandle(), scene.vertexGroups[i].numIndices); + + vkcv::DescriptorSetUsage descriptorUsage(0, core.getDescriptorSet(descriptorSets[i]).vulkanHandle); + + drawcalls.push_back(vkcv::DrawcallInfo(renderMesh, {descriptorUsage})); + } + + std::vector<glm::mat4> modelMatrices; + modelMatrices.resize(scene.vertexGroups.size(), glm::mat4(1.f)); + for (const auto &mesh : scene.meshes) { + const glm::mat4 m = arrayTo4x4Matrix(mesh.modelMatrix); + for (const auto &vertexGroupIndex : mesh.vertexGroups) { + modelMatrices[vertexGroupIndex] = m; + } + } + std::vector<glm::mat4> mvp; + + auto start = std::chrono::system_clock::now(); + while (window.isWindowOpen()) { + vkcv::Window::pollEvents(); + + if(window.getHeight() == 0 || window.getWidth() == 0) + continue; + + uint32_t swapchainWidth, swapchainHeight; + if (!core.beginFrame(swapchainWidth, swapchainHeight)) { + continue; + } + + if ((swapchainWidth != windowWidth) || ((swapchainHeight != windowHeight))) { + depthBuffer = core.createImage(vk::Format::eD32Sfloat, swapchainWidth, swapchainHeight).getHandle(); + + windowWidth = swapchainWidth; + windowHeight = swapchainHeight; + } + + auto end = std::chrono::system_clock::now(); + auto deltatime = std::chrono::duration_cast<std::chrono::microseconds>(end - start); + + start = end; + cameraManager.update(0.000001 * static_cast<double>(deltatime.count())); + glm::mat4 vp = cameraManager.getActiveCamera().getMVP(); + + mvp.clear(); + for (const auto& m : modelMatrices) { + mvp.push_back(vp * m); + } + + vkcv::PushConstantData pushConstantData((void*)mvp.data(), sizeof(glm::mat4)); + + const std::vector<vkcv::ImageHandle> renderTargets = { swapchainInput, depthBuffer }; + auto cmdStream = core.createCommandStream(vkcv::QueueType::Graphics); + + core.recordDrawcallsToCmdStream( + cmdStream, + scenePass, + scenePipeline, + pushConstantData, + drawcalls, + renderTargets); + core.prepareSwapchainImageForPresent(cmdStream); + core.submitCommandStream(cmdStream); + core.endFrame(); + } + + return 0; +} diff --git a/projects/first_triangle/CMakeLists.txt b/projects/first_triangle/CMakeLists.txt index e7c8373e085df6497060b8d1d8164cf740dfb01f..ba8c83c06fc804082e6a0a14c3c0414899ef3057 100644 --- a/projects/first_triangle/CMakeLists.txt +++ b/projects/first_triangle/CMakeLists.txt @@ -22,7 +22,7 @@ if(MSVC) endif() # including headers of dependencies and the VkCV framework -target_include_directories(first_triangle SYSTEM BEFORE PRIVATE ${vkcv_include} ${vkcv_includes} ${vkcv_testing_include} ${vkcv_camera_include}) +target_include_directories(first_triangle SYSTEM BEFORE PRIVATE ${vkcv_include} ${vkcv_includes} ${vkcv_testing_include} ${vkcv_camera_include} ${vkcv_shader_compiler_include} ${vkcv_gui_include}) # linking with libraries from all dependencies and the VkCV framework -target_link_libraries(first_triangle vkcv vkcv_testing vkcv_camera) +target_link_libraries(first_triangle vkcv vkcv_testing vkcv_camera vkcv_shader_compiler vkcv_gui) diff --git a/projects/first_triangle/shaders/shader.frag b/projects/first_triangle/shaders/shader.frag index d26446a73020111695aa2c86166205796dfa5e44..080678beb011afe4b03aed3bf7ae7148b77932dc 100644 --- a/projects/first_triangle/shaders/shader.frag +++ b/projects/first_triangle/shaders/shader.frag @@ -4,6 +4,6 @@ layout(location = 0) in vec3 fragColor; layout(location = 0) out vec4 outColor; -void main() { +void main() { outColor = vec4(fragColor, 1.0); } \ No newline at end of file diff --git a/projects/first_triangle/src/main.cpp b/projects/first_triangle/src/main.cpp index b6b75bca82a8479f3d6b09577337503424ce7a83..20cfdddf5c1baa9e8727312daa36de94bd56672f 100644 --- a/projects/first_triangle/src/main.cpp +++ b/projects/first_triangle/src/main.cpp @@ -4,6 +4,9 @@ #include <vkcv/camera/CameraManager.hpp> #include <chrono> +#include <vkcv/shader/GLSLCompiler.hpp> +#include <vkcv/gui/GUI.hpp> + int main(int argc, const char** argv) { const char* applicationName = "First Triangle"; @@ -16,10 +19,6 @@ int main(int argc, const char** argv) { false ); - vkcv::CameraManager cameraManager(window, windowWidth, windowHeight); - - window.initEvents(); - vkcv::Core core = vkcv::Core::create( window, applicationName, @@ -28,6 +27,8 @@ int main(int argc, const char** argv) { {}, { "VK_KHR_swapchain" } ); + + vkcv::gui::GUI gui (core, window); const auto& context = core.getContext(); const vk::Instance& instance = context.getInstance(); @@ -81,7 +82,7 @@ int main(int argc, const char** argv) { const vkcv::AttachmentDescription present_color_attachment( vkcv::AttachmentOperation::STORE, vkcv::AttachmentOperation::CLEAR, - core.getSwapchainImageFormat()); + core.getSwapchain().getFormat()); vkcv::PassConfig trianglePassDefinition({ present_color_attachment }); vkcv::PassHandle trianglePass = core.createPass(trianglePassDefinition); @@ -92,19 +93,28 @@ int main(int argc, const char** argv) { return EXIT_FAILURE; } - // Graphics Pipeline vkcv::ShaderProgram triangleShaderProgram{}; - triangleShaderProgram.addShader(vkcv::ShaderStage::VERTEX, std::filesystem::path("shaders/vert.spv")); - triangleShaderProgram.addShader(vkcv::ShaderStage::FRAGMENT, std::filesystem::path("shaders/frag.spv")); - - const vkcv::PipelineConfig trianglePipelineDefinition( + vkcv::shader::GLSLCompiler compiler; + + compiler.compile(vkcv::ShaderStage::VERTEX, std::filesystem::path("shaders/shader.vert"), + [&triangleShaderProgram](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + triangleShaderProgram.addShader(shaderStage, path); + }); + + compiler.compile(vkcv::ShaderStage::FRAGMENT, std::filesystem::path("shaders/shader.frag"), + [&triangleShaderProgram](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + triangleShaderProgram.addShader(shaderStage, path); + }); + + const vkcv::PipelineConfig trianglePipelineDefinition { triangleShaderProgram, (uint32_t)windowWidth, (uint32_t)windowHeight, trianglePass, {}, {}, - false); + false + }; vkcv::PipelineHandle trianglePipeline = core.createGraphicsPipeline(trianglePipelineDefinition); @@ -161,20 +171,29 @@ int main(int argc, const char** argv) { const vkcv::ImageHandle swapchainInput = vkcv::ImageHandle::createSwapchainImageHandle(); + vkcv::camera::CameraManager cameraManager(window); + uint32_t camIndex0 = cameraManager.addCamera(vkcv::camera::ControllerType::PILOT); + uint32_t camIndex1 = cameraManager.addCamera(vkcv::camera::ControllerType::TRACKBALL); + + cameraManager.getCamera(camIndex0).setPosition(glm::vec3(0, 0, -2)); + cameraManager.getCamera(camIndex1).setPosition(glm::vec3(0.0f, 0.0f, 0.0f)); + cameraManager.getCamera(camIndex1).setCenter(glm::vec3(0.0f, 0.0f, -1.0f)); + while (window.isWindowOpen()) { window.pollEvents(); - + uint32_t swapchainWidth, swapchainHeight; // No resizing = No problem if (!core.beginFrame(swapchainWidth, swapchainHeight)) { continue; } auto end = std::chrono::system_clock::now(); - auto deltatime = end - start; + auto deltatime = std::chrono::duration_cast<std::chrono::microseconds>(end - start); start = end; - cameraManager.getCamera().updateView(std::chrono::duration<double>(deltatime).count()); - const glm::mat4 mvp = cameraManager.getCamera().getProjection() * cameraManager.getCamera().getView(); + + cameraManager.update(0.000001 * static_cast<double>(deltatime.count())); + glm::mat4 mvp = cameraManager.getActiveCamera().getMVP(); vkcv::PushConstantData pushConstantData((void*)&mvp, sizeof(glm::mat4)); auto cmdStream = core.createCommandStream(vkcv::QueueType::Graphics); @@ -199,6 +218,14 @@ int main(int argc, const char** argv) { core.prepareSwapchainImageForPresent(cmdStream); core.submitCommandStream(cmdStream); + + gui.beginGUI(); + + ImGui::Begin("Hello world"); + ImGui::Text("This is a test!"); + ImGui::End(); + + gui.endGUI(); core.endFrame(); } diff --git a/projects/voxelization/.gitignore b/projects/voxelization/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f07a22d4e0641a9114e998212f38ca9cb83a9655 --- /dev/null +++ b/projects/voxelization/.gitignore @@ -0,0 +1 @@ +voxelization \ No newline at end of file diff --git a/projects/voxelization/CMakeLists.txt b/projects/voxelization/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..33cfaef6197079b72ab2f295a4503e80be724db4 --- /dev/null +++ b/projects/voxelization/CMakeLists.txt @@ -0,0 +1,32 @@ +cmake_minimum_required(VERSION 3.16) +project(voxelization) + +# setting c++ standard for the project +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# this should fix the execution path to load local files from the project +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + +# adding source files to the project +add_executable(voxelization src/main.cpp) + +target_sources(voxelization PRIVATE + src/Voxelization.hpp + src/Voxelization.cpp) + +# this should fix the execution path to load local files from the project (for MSVC) +if(MSVC) + set_target_properties(voxelization PROPERTIES RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) + set_target_properties(voxelization PROPERTIES RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) + + # in addition to setting the output directory, the working directory has to be set + # by default visual studio sets the working directory to the build directory, when using the debugger + set_target_properties(voxelization PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +endif() + +# including headers of dependencies and the VkCV framework +target_include_directories(voxelization SYSTEM BEFORE PRIVATE ${vkcv_include} ${vkcv_includes} ${vkcv_asset_loader_include} ${vkcv_camera_include} ${vkcv_shader_compiler_include}) + +# linking with libraries from all dependencies and the VkCV framework +target_link_libraries(voxelization vkcv ${vkcv_libraries} vkcv_asset_loader ${vkcv_asset_loader_libraries} vkcv_camera vkcv_shader_compiler) diff --git a/projects/voxelization/resources/Sponza/Sponza.bin b/projects/voxelization/resources/Sponza/Sponza.bin new file mode 100644 index 0000000000000000000000000000000000000000..cfedd26ca5a67b6d0a47d44d13a75e14a141717a --- /dev/null +++ b/projects/voxelization/resources/Sponza/Sponza.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b809f7a17687dc99e6f41ca1ea32c06eded8779bf34d16f1f565d750b0ffd68 +size 6347696 diff --git a/projects/voxelization/resources/Sponza/Sponza.gltf b/projects/voxelization/resources/Sponza/Sponza.gltf new file mode 100644 index 0000000000000000000000000000000000000000..172ea07e21c94465211c860cd805355704cef230 --- /dev/null +++ b/projects/voxelization/resources/Sponza/Sponza.gltf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cc0ecad5c4694088ff820e663619c370421afc1323ac487406e8e9b4735d787 +size 713962 diff --git a/projects/voxelization/resources/Sponza/background.png b/projects/voxelization/resources/Sponza/background.png new file mode 100644 index 0000000000000000000000000000000000000000..b64def129da38f4e23d89e21b4af1039008a4327 --- /dev/null +++ b/projects/voxelization/resources/Sponza/background.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5b5f900ff8ed83a31750ec8e428b5b91273794ddcbfc4e4b8a6a7e781f8c686 +size 1417666 diff --git a/projects/voxelization/resources/Sponza/chain_texture.png b/projects/voxelization/resources/Sponza/chain_texture.png new file mode 100644 index 0000000000000000000000000000000000000000..c1e1768cff78e0614ad707eca8602a4c4edab5e5 --- /dev/null +++ b/projects/voxelization/resources/Sponza/chain_texture.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8362cfd472880daeaea37439326a4651d1338680ae69bb2513fc6b17c8de7d4 +size 490895 diff --git a/projects/voxelization/resources/Sponza/lion.png b/projects/voxelization/resources/Sponza/lion.png new file mode 100644 index 0000000000000000000000000000000000000000..c49c7f0ed31e762e19284d0d3624fbc47664e56b --- /dev/null +++ b/projects/voxelization/resources/Sponza/lion.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f882f746c3a9cd51a9c6eedc1189b97668721d91a3fe49232036e789912c652 +size 2088728 diff --git a/projects/voxelization/resources/Sponza/spnza_bricks_a_diff.png b/projects/voxelization/resources/Sponza/spnza_bricks_a_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..cde4c7a6511e9a5f03c63ad996437fcdba3ce2df --- /dev/null +++ b/projects/voxelization/resources/Sponza/spnza_bricks_a_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b94219c2f5f943f3f4715c74e7d1038bf0ab3b3b3216a758eaee67f875df0851 +size 1928829 diff --git a/projects/voxelization/resources/Sponza/sponza_arch_diff.png b/projects/voxelization/resources/Sponza/sponza_arch_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..bcd9bda2918d226039f9e2d03902d377b706fab6 --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_arch_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0df2c8a01b2843b1c792b494f7173cdbc4f834840fc2177af3e5d690fceda57 +size 1596151 diff --git a/projects/voxelization/resources/Sponza/sponza_ceiling_a_diff.png b/projects/voxelization/resources/Sponza/sponza_ceiling_a_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..59de631ffac4414cabf69b2dc794c46fc187d6cb --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_ceiling_a_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab6c187a81aa68f4eba30119e17fce2e4882a9ec320f70c90482dbe9da82b1c6 +size 1872074 diff --git a/projects/voxelization/resources/Sponza/sponza_column_a_diff.png b/projects/voxelization/resources/Sponza/sponza_column_a_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..01a82432d3f9939bbefe850bdb900f1ff9a3f6db --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_column_a_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c291507e2808bb83e160ab4b020689817df273baad3713a9ad19ac15fac6826 +size 1840992 diff --git a/projects/voxelization/resources/Sponza/sponza_column_b_diff.png b/projects/voxelization/resources/Sponza/sponza_column_b_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..10a660cce2a5a9b8997772c746058ce23e7d45d7 --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_column_b_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2820b0267c4289c6cedbb42721792a57ef244ec2d0935941011c2a7d3fe88a9b +size 2170433 diff --git a/projects/voxelization/resources/Sponza/sponza_column_c_diff.png b/projects/voxelization/resources/Sponza/sponza_column_c_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..bc46fd979044a938d3adca7601689e71504e48bf --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_column_c_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0bc993ff59865468ef4530798930c7dfefb07482d71db45bc2a520986b27735 +size 2066950 diff --git a/projects/voxelization/resources/Sponza/sponza_curtain_blue_diff.png b/projects/voxelization/resources/Sponza/sponza_curtain_blue_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..384c8c2c051160d530eb3ac8b05c9c60752a2d2b --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_curtain_blue_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b85c6bb3cd5105f48d3812ec8e7a1068521ce69e917300d79e136e19d45422fb +size 9510905 diff --git a/projects/voxelization/resources/Sponza/sponza_curtain_diff.png b/projects/voxelization/resources/Sponza/sponza_curtain_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..af842e9f5fe18c1f609875e00899a6770fa4488b --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_curtain_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:563c56bdbbee395a6ef7f0c51c8ac9223c162e517b4cdba0d4654e8de27c98d8 +size 9189263 diff --git a/projects/voxelization/resources/Sponza/sponza_curtain_green_diff.png b/projects/voxelization/resources/Sponza/sponza_curtain_green_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..6c9b6391a199407637fa71033d79fb58b8b4f0d7 --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_curtain_green_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:238fe1c7f481388d1c1d578c2da8d411b99e8f0030ab62060a306db333124476 +size 8785458 diff --git a/projects/voxelization/resources/Sponza/sponza_details_diff.png b/projects/voxelization/resources/Sponza/sponza_details_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..12656686362c3e0a297e060491f33bd7351551f9 --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_details_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb1223b3bb82f8757e7df25a6891f1239cdd7ec59990340e952fb2d6b7ea570c +size 1522643 diff --git a/projects/voxelization/resources/Sponza/sponza_fabric_blue_diff.png b/projects/voxelization/resources/Sponza/sponza_fabric_blue_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..879d16ef84722a4fc13e83a771778de326e4bc54 --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_fabric_blue_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:467d290bf5d4b2a017da140ba9e244ed8a8a9be5418a9ac9bcb4ad572ae2d7ab +size 2229440 diff --git a/projects/voxelization/resources/Sponza/sponza_fabric_diff.png b/projects/voxelization/resources/Sponza/sponza_fabric_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..3311287a219d2148620b87fe428fea071688d051 --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_fabric_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1594f59cc2848db26add47361f4e665e3d8afa147760ed915d839fea42b20287 +size 2267382 diff --git a/projects/voxelization/resources/Sponza/sponza_fabric_green_diff.png b/projects/voxelization/resources/Sponza/sponza_fabric_green_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..de110f369004388dae4cd5067c63428db3a07834 --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_fabric_green_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:902b87faab221173bf370cea7c74cb9060b4d870ac6316b190dafded1cb12993 +size 2258220 diff --git a/projects/voxelization/resources/Sponza/sponza_flagpole_diff.png b/projects/voxelization/resources/Sponza/sponza_flagpole_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..5f6e0812a0df80346318baa3cb50a6888afc58f8 --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_flagpole_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bfffb62e770959c725d0f3db6dc7dbdd46a380ec55ef884dab94d44ca017b438 +size 1425673 diff --git a/projects/voxelization/resources/Sponza/sponza_floor_a_diff.png b/projects/voxelization/resources/Sponza/sponza_floor_a_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..788ed764f79ba724f04a2d603076a5b85013e188 --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_floor_a_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a16f9230fa91f9f31dfca6216ce205f1ef132d44f3b012fbf6efc0fba69770ab +size 1996838 diff --git a/projects/voxelization/resources/Sponza/sponza_roof_diff.png b/projects/voxelization/resources/Sponza/sponza_roof_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..c5b84261fdd1cc776a94b3ce398c7806b895f9a3 --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_roof_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7fc412138c20da19f8173e53545e771f4652558dff624d4dc67143e40efe562b +size 2320533 diff --git a/projects/voxelization/resources/Sponza/sponza_thorn_diff.png b/projects/voxelization/resources/Sponza/sponza_thorn_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..7a9142674a7d4a6f94a48c5152cf0300743b597a --- /dev/null +++ b/projects/voxelization/resources/Sponza/sponza_thorn_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a73a17c883cd0d0d67cfda2dc4118400a916366c05b9a5ac465f0c8b30fd9c8e +size 635001 diff --git a/projects/voxelization/resources/Sponza/vase_dif.png b/projects/voxelization/resources/Sponza/vase_dif.png new file mode 100644 index 0000000000000000000000000000000000000000..61236a81cb324af8797b05099cd264cefe189e56 --- /dev/null +++ b/projects/voxelization/resources/Sponza/vase_dif.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53d06f52bf9e59df4cf00237707cca76c4f692bda61a62b06a30d321311d6dd9 +size 1842101 diff --git a/projects/voxelization/resources/Sponza/vase_hanging.png b/projects/voxelization/resources/Sponza/vase_hanging.png new file mode 100644 index 0000000000000000000000000000000000000000..36a3cee71d8213225090c74f8c0dce33b9d44378 --- /dev/null +++ b/projects/voxelization/resources/Sponza/vase_hanging.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9d10b4f27a3c9a78d5bac882fdd4b6a6987c262f48fa490670fe5e235951e31 +size 1432804 diff --git a/projects/voxelization/resources/Sponza/vase_plant.png b/projects/voxelization/resources/Sponza/vase_plant.png new file mode 100644 index 0000000000000000000000000000000000000000..7ad95e702e229f1ebd803e5203a266d15f2c07b9 --- /dev/null +++ b/projects/voxelization/resources/Sponza/vase_plant.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2087371ff02212fb7014b6daefa191cf5676d2227193fff261a5d02f554cb8e +size 998089 diff --git a/projects/voxelization/resources/Sponza/vase_round.png b/projects/voxelization/resources/Sponza/vase_round.png new file mode 100644 index 0000000000000000000000000000000000000000..c17953abc000c44b8991e23c136c2b67348f3d1b --- /dev/null +++ b/projects/voxelization/resources/Sponza/vase_round.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa23d48d492d5d4ada2ddb27d1ef22952b214e6eb3b301c65f9d88442723d20a +size 1871399 diff --git a/projects/voxelization/resources/cube/boards2_vcyc_jpg.jpg b/projects/voxelization/resources/cube/boards2_vcyc_jpg.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2636039e272289c0fba3fa2d88a060b857501248 --- /dev/null +++ b/projects/voxelization/resources/cube/boards2_vcyc_jpg.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cca33a6e58ddd1b37a6e6853a9aa0e7b15ca678937119194752393dd2a0a0564 +size 1192476 diff --git a/projects/cmd_sync_test/resources/cube/cube.bin b/projects/voxelization/resources/cube/cube.bin similarity index 100% rename from projects/cmd_sync_test/resources/cube/cube.bin rename to projects/voxelization/resources/cube/cube.bin diff --git a/projects/cmd_sync_test/resources/cube/cube.blend b/projects/voxelization/resources/cube/cube.blend similarity index 100% rename from projects/cmd_sync_test/resources/cube/cube.blend rename to projects/voxelization/resources/cube/cube.blend diff --git a/projects/cmd_sync_test/resources/cube/cube.blend1 b/projects/voxelization/resources/cube/cube.blend1 similarity index 100% rename from projects/cmd_sync_test/resources/cube/cube.blend1 rename to projects/voxelization/resources/cube/cube.blend1 diff --git a/projects/cmd_sync_test/resources/cube/cube.glb b/projects/voxelization/resources/cube/cube.glb similarity index 100% rename from projects/cmd_sync_test/resources/cube/cube.glb rename to projects/voxelization/resources/cube/cube.glb diff --git a/projects/cmd_sync_test/resources/cube/cube.gltf b/projects/voxelization/resources/cube/cube.gltf similarity index 100% rename from projects/cmd_sync_test/resources/cube/cube.gltf rename to projects/voxelization/resources/cube/cube.gltf diff --git a/projects/voxelization/resources/shaders/gammaCorrection.comp b/projects/voxelization/resources/shaders/gammaCorrection.comp new file mode 100644 index 0000000000000000000000000000000000000000..411a59c3e38b3414adbda260803c3f3322b16ff2 --- /dev/null +++ b/projects/voxelization/resources/shaders/gammaCorrection.comp @@ -0,0 +1,18 @@ +#version 440 + +layout(set=0, binding=0, r11f_g11f_b10f) uniform image2D inImage; +layout(set=0, binding=1, rgba8) uniform image2D outImage; + + +layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in; + +void main(){ + + if(any(greaterThanEqual(gl_GlobalInvocationID.xy, imageSize(inImage)))){ + return; + } + ivec2 uv = ivec2(gl_GlobalInvocationID.xy); + vec3 linearColor = imageLoad(inImage, uv).rgb; + vec3 gammaCorrected = pow(linearColor, vec3(1.f / 2.2f)); + imageStore(outImage, uv, vec4(gammaCorrected, 0.f)); +} \ No newline at end of file diff --git a/projects/voxelization/resources/shaders/perMeshResources.inc b/projects/voxelization/resources/shaders/perMeshResources.inc new file mode 100644 index 0000000000000000000000000000000000000000..95e4fb7c27009965659d14a9c72acfec950c37e3 --- /dev/null +++ b/projects/voxelization/resources/shaders/perMeshResources.inc @@ -0,0 +1,2 @@ +layout(set=1, binding=0) uniform texture2D albedoTexture; +layout(set=1, binding=1) uniform sampler textureSampler; \ No newline at end of file diff --git a/projects/cmd_sync_test/resources/shaders/shader.frag b/projects/voxelization/resources/shaders/shader.frag similarity index 74% rename from projects/cmd_sync_test/resources/shaders/shader.frag rename to projects/voxelization/resources/shaders/shader.frag index 95f1b3319e1ca5c7c34ff94e5e7198819c0233c1..edafc8c0077416cb57aedc4e7358126846507e18 100644 --- a/projects/cmd_sync_test/resources/shaders/shader.frag +++ b/projects/voxelization/resources/shaders/shader.frag @@ -1,5 +1,8 @@ #version 450 #extension GL_ARB_separate_shader_objects : enable +#extension GL_GOOGLE_include_directive : enable + +#include "perMeshResources.inc" layout(location = 0) in vec3 passNormal; layout(location = 1) in vec2 passUV; @@ -7,14 +10,12 @@ layout(location = 2) in vec3 passPos; layout(location = 0) out vec3 outColor; -layout(set=0, binding=0) uniform texture2D meshTexture; -layout(set=0, binding=1) uniform sampler textureSampler; -layout(set=0, binding=2) uniform sunBuffer { +layout(set=0, binding=0) uniform sunBuffer { vec3 L; float padding; mat4 lightMatrix; }; -layout(set=0, binding=3) uniform texture2D shadowMap; -layout(set=0, binding=4) uniform sampler shadowMapSampler; +layout(set=0, binding=1) uniform texture2D shadowMap; +layout(set=0, binding=2) uniform sampler shadowMapSampler; float shadowTest(vec3 worldPos){ vec4 lightPos = lightMatrix * vec4(worldPos, 1); @@ -39,6 +40,6 @@ void main() { vec3 sun = sunColor * clamp(dot(N, L), 0, 1); sun *= shadowTest(passPos); vec3 ambient = vec3(0.1); - vec3 albedo = texture(sampler2D(meshTexture, textureSampler), passUV).rgb; + vec3 albedo = texture(sampler2D(albedoTexture, textureSampler), passUV).rgb; outColor = albedo * (sun + ambient); } \ No newline at end of file diff --git a/projects/cmd_sync_test/resources/shaders/shader.vert b/projects/voxelization/resources/shaders/shader.vert similarity index 82% rename from projects/cmd_sync_test/resources/shaders/shader.vert rename to projects/voxelization/resources/shaders/shader.vert index 0ab82c203806356d0f35dc52c0a6988b286d90d1..926f86af2860cb57c44d2d5ee78712b6ae155e5c 100644 --- a/projects/cmd_sync_test/resources/shaders/shader.vert +++ b/projects/voxelization/resources/shaders/shader.vert @@ -16,7 +16,7 @@ layout( push_constant ) uniform constants{ void main() { gl_Position = mvp * vec4(inPosition, 1.0); - passNormal = inNormal; + passNormal = mat3(model) * inNormal; // assuming no weird stuff like shearing or non-uniform scaling passUV = inUV; passPos = (model * vec4(inPosition, 1)).xyz; } \ No newline at end of file diff --git a/projects/cmd_sync_test/resources/shaders/shadow.frag b/projects/voxelization/resources/shaders/shadow.frag similarity index 100% rename from projects/cmd_sync_test/resources/shaders/shadow.frag rename to projects/voxelization/resources/shaders/shadow.frag diff --git a/projects/cmd_sync_test/resources/shaders/shadow.vert b/projects/voxelization/resources/shaders/shadow.vert similarity index 100% rename from projects/cmd_sync_test/resources/shaders/shadow.vert rename to projects/voxelization/resources/shaders/shadow.vert diff --git a/projects/voxelization/resources/shaders/voxel.inc b/projects/voxelization/resources/shaders/voxel.inc new file mode 100644 index 0000000000000000000000000000000000000000..d2b4400235817e3be1739dc46857ab42f260ebf7 --- /dev/null +++ b/projects/voxelization/resources/shaders/voxel.inc @@ -0,0 +1,25 @@ +struct VoxelInfo{ + vec3 offset; + float extent; +}; + +uint flattenVoxelUVToIndex(ivec3 UV, ivec3 voxelImageSize){ + return UV.x + UV.y * voxelImageSize.x + UV.z * voxelImageSize.x* voxelImageSize.y; +} + +uint packVoxelInfo(vec3 color){ + uint opaqueBit = 1 << 31; + uint redBits = uint(color.r * 255); + uint greenBits = uint(color.g * 255) << 8; + uint blueBits = uint(color.b * 255) << 16; + return opaqueBit | redBits | greenBits | blueBits; +} + +vec4 unpackVoxelInfo(uint packed){ + vec4 rgba; + rgba.r = (packed >> 0 & 0x000000FF) / 255.f; + rgba.g = (packed >> 8 & 0x000000FF) / 255.f; + rgba.b = (packed >> 16 & 0x000000FF) / 255.f; + rgba.a = packed >> 31; + return rgba; +} \ No newline at end of file diff --git a/projects/voxelization/resources/shaders/voxelBufferToImage.comp b/projects/voxelization/resources/shaders/voxelBufferToImage.comp new file mode 100644 index 0000000000000000000000000000000000000000..5e8298886cb2bacbc81f981e8e90310cdc876d5d --- /dev/null +++ b/projects/voxelization/resources/shaders/voxelBufferToImage.comp @@ -0,0 +1,24 @@ +#version 450 +#extension GL_GOOGLE_include_directive : enable +#include "voxel.inc" + +layout(set=0, binding=0, std430) buffer voxelBuffer{ + uint packedVoxelData[]; +}; + +layout(set=0, binding=1, rgba16f) uniform image3D voxelImage; + +layout(local_size_x = 4, local_size_y = 4, local_size_z = 4) in; + +void main(){ + + ivec3 voxelImageSize = imageSize(voxelImage); + if(any(greaterThanEqual(gl_GlobalInvocationID, voxelImageSize))){ + return; + } + ivec3 UV = ivec3(gl_GlobalInvocationID); + uint flatIndex = flattenVoxelUVToIndex(UV, voxelImageSize); + + vec4 color = unpackVoxelInfo(packedVoxelData[flatIndex]); + imageStore(voxelImage, UV, vec4(color)); +} \ No newline at end of file diff --git a/projects/voxelization/resources/shaders/voxelReset.comp b/projects/voxelization/resources/shaders/voxelReset.comp new file mode 100644 index 0000000000000000000000000000000000000000..14b78d6584d703be68594e3cb03ebcd47c94b6e0 --- /dev/null +++ b/projects/voxelization/resources/shaders/voxelReset.comp @@ -0,0 +1,19 @@ +#version 450 + +layout(set=0, binding=0) buffer voxelizationBuffer{ + uint isFilled[]; +}; + +layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in; + +layout( push_constant ) uniform constants{ + uint voxelCount; +}; + +void main(){ + + if(gl_GlobalInvocationID.x> voxelCount){ + return; + } + isFilled[gl_GlobalInvocationID.x] = 0; +} \ No newline at end of file diff --git a/projects/voxelization/resources/shaders/voxelVisualisation.frag b/projects/voxelization/resources/shaders/voxelVisualisation.frag new file mode 100644 index 0000000000000000000000000000000000000000..0b02beb7e848ab20cda4b012f77d1fa664b6ab53 --- /dev/null +++ b/projects/voxelization/resources/shaders/voxelVisualisation.frag @@ -0,0 +1,9 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout(location=0) in vec3 passColorToFrag; +layout(location=0) out vec3 outColor; + +void main() { + outColor = passColorToFrag; +} \ No newline at end of file diff --git a/projects/voxelization/resources/shaders/voxelVisualisation.geom b/projects/voxelization/resources/shaders/voxelVisualisation.geom new file mode 100644 index 0000000000000000000000000000000000000000..e98076fcc83a69a903df454cb00267da84e3f223 --- /dev/null +++ b/projects/voxelization/resources/shaders/voxelVisualisation.geom @@ -0,0 +1,104 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout(points) in; +layout (triangle_strip, max_vertices = 24) out; + +layout( push_constant ) uniform constants{ + mat4 viewProjection; +}; + +layout(location = 0) in float passCubeHalf[1]; +layout(location = 1) in vec3 passColorToGeom[1]; + + +layout(location = 0) out vec3 passColorToFrag; + +void main() { + float cubeHalf = passCubeHalf[0]; + // right + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(1, 1, 1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(1, 1, -1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(1, -1, 1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(1, -1, -1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + EndPrimitive(); + // left + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(-1, 1, 1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(-1, 1, -1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(-1, -1, 1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(-1, -1, -1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + EndPrimitive(); + // back + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(1, 1, -1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(1, -1, -1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(-1, 1, -1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(-1, -1, -1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + EndPrimitive(); + // front + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(1, 1, 1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(1, -1, 1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(-1, 1, 1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(-1, -1, 1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + EndPrimitive(); + // bot + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(1, 1, 1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(1, 1, -1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(-1, 1, 1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(-1, 1, -1), 1); + passColorToFrag = passColorToGeom[0]; + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + EndPrimitive(); + // top + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(1, -1, 1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(1, -1, -1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(-1, -1, 1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + gl_Position = viewProjection * vec4(gl_in[0].gl_Position.xyz + cubeHalf * vec3(-1, -1, -1), 1); + passColorToFrag = passColorToGeom[0]; + EmitVertex(); + EndPrimitive(); +} \ No newline at end of file diff --git a/projects/voxelization/resources/shaders/voxelVisualisation.vert b/projects/voxelization/resources/shaders/voxelVisualisation.vert new file mode 100644 index 0000000000000000000000000000000000000000..8377143f4f4bbf351d3251df9724d37e1747a4dc --- /dev/null +++ b/projects/voxelization/resources/shaders/voxelVisualisation.vert @@ -0,0 +1,36 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable +#extension GL_GOOGLE_include_directive : enable + +#include "voxel.inc" + +layout(location = 0) out float passCubeHalf; +layout(location = 1) out vec3 passColorToGeom; + +layout( push_constant ) uniform constants{ + mat4 viewProjection; +}; + +layout(set=0, binding=0, rgba16f) uniform image3D voxelImage; +layout(set=0, binding=1) uniform voxelizationInfo{ + VoxelInfo voxelInfo; +}; + + +void main() { + passCubeHalf = voxelInfo.extent / float(imageSize(voxelImage).x) * 0.5f; + int voxelResolution = imageSize(voxelImage).x; + int slicePixelCount = voxelResolution * voxelResolution; + int z = gl_VertexIndex / slicePixelCount; + int index2D = gl_VertexIndex % slicePixelCount; + int y = index2D / voxelResolution; + int x = index2D % voxelResolution; + vec3 position = (vec3(x, y, z) / voxelResolution - 0.5) * voxelInfo.extent + passCubeHalf + voxelInfo.offset; + gl_Position = vec4(position, 1.0); + + vec4 voxelColor = imageLoad(voxelImage, ivec3(x,y,z)); + if(voxelColor.a == 0){ + gl_Position.x /= 0; // clip + } + passColorToGeom = voxelColor.rgb; +} \ No newline at end of file diff --git a/projects/voxelization/resources/shaders/voxelization.frag b/projects/voxelization/resources/shaders/voxelization.frag new file mode 100644 index 0000000000000000000000000000000000000000..7ea161ce4f5a4d59bb3d50c78553df0dfb5ab4ec --- /dev/null +++ b/projects/voxelization/resources/shaders/voxelization.frag @@ -0,0 +1,40 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable +#extension GL_GOOGLE_include_directive : enable + +#include "voxel.inc" +#include "perMeshResources.inc" + +layout(location = 0) in vec3 passPos; +layout(location = 1) out vec2 passUV; + +layout(set=0, binding=0, std430) buffer voxelizationBuffer{ + uint packedVoxelData[]; +}; + +layout(set=0, binding=1) uniform voxelizationInfo{ + VoxelInfo voxelInfo; +}; + +layout(set=0, binding=2, r8) uniform image3D voxelImage; + +vec3 worldToVoxelCoordinates(vec3 world, VoxelInfo info){ + return (world - info.offset) / info.extent + 0.5f; +} + +ivec3 voxelCoordinatesToUV(vec3 voxelCoordinates, ivec3 voxelImageResolution){ + return ivec3(voxelCoordinates * voxelImageResolution); +} + +void main() { + vec3 voxelCoordinates = worldToVoxelCoordinates(passPos, voxelInfo); + ivec3 voxelImageSize = imageSize(voxelImage); + ivec3 UV = voxelCoordinatesToUV(voxelCoordinates, voxelImageSize); + if(any(lessThan(UV, ivec3(0))) || any(greaterThanEqual(UV, voxelImageSize))){ + return; + } + uint flatIndex = flattenVoxelUVToIndex(UV, voxelImageSize); + + vec3 color = texture(sampler2D(albedoTexture, textureSampler), passUV).rgb; + atomicMax(packedVoxelData[flatIndex], packVoxelInfo(color)); +} \ No newline at end of file diff --git a/projects/voxelization/resources/shaders/voxelization.geom b/projects/voxelization/resources/shaders/voxelization.geom new file mode 100644 index 0000000000000000000000000000000000000000..19e31e2d2d032b5a9e5c273f6420c6449be9203e --- /dev/null +++ b/projects/voxelization/resources/shaders/voxelization.geom @@ -0,0 +1,35 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout(triangles) in; +layout (triangle_strip, max_vertices = 3) out; + +layout(location = 0) in vec3 passPosIn[3]; +layout(location = 1) in vec2 passUVIn[3]; + +layout(location = 0) out vec3 passPos; +layout(location = 1) out vec2 passUV; + +void main() { + // compute geometric normal, no normalization necessary + vec3 N = cross(passPosIn[0] - passPosIn[1], passPosIn[0] - passPosIn[2]); + N = abs(N); // only interested in the magnitude + + for(int i = 0; i < 3; i++){ + // swizzle position, so biggest side is rasterized + if(N.z > N.x && N.z > N.y){ + gl_Position = gl_in[i].gl_Position.xyzw; + } + else if(N.x > N.y){ + gl_Position = gl_in[i].gl_Position.yzxw; + } + else{ + gl_Position = gl_in[i].gl_Position.xzyw; + } + gl_Position.z = gl_Position.z * 0.5 + 0.5; // xyz are kept in NDC range [-1, 1] so swizzling works, but vulkan needs final z in range [0, 1] + passPos = passPosIn[i]; + passUV = passUVIn[i]; + EmitVertex(); + } + EndPrimitive(); +} \ No newline at end of file diff --git a/projects/voxelization/resources/shaders/voxelization.vert b/projects/voxelization/resources/shaders/voxelization.vert new file mode 100644 index 0000000000000000000000000000000000000000..7a43c08b64d3df384d3a7e627d789db9be99f680 --- /dev/null +++ b/projects/voxelization/resources/shaders/voxelization.vert @@ -0,0 +1,20 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout(location = 0) in vec3 inPosition; +layout(location = 1) in vec3 inNormal; +layout(location = 2) in vec2 inUV; + +layout(location = 0) out vec3 passPos; +layout(location = 1) out vec2 passUV; + +layout( push_constant ) uniform constants{ + mat4 mvp; + mat4 model; +}; + +void main() { + gl_Position = mvp * vec4(inPosition, 1.0); + passPos = (model * vec4(inPosition, 1)).xyz; + passUV = inUV; +} \ No newline at end of file diff --git a/projects/cmd_sync_test/resources/triangle/Triangle.bin b/projects/voxelization/resources/triangle/Triangle.bin similarity index 100% rename from projects/cmd_sync_test/resources/triangle/Triangle.bin rename to projects/voxelization/resources/triangle/Triangle.bin diff --git a/projects/cmd_sync_test/resources/triangle/Triangle.blend b/projects/voxelization/resources/triangle/Triangle.blend similarity index 100% rename from projects/cmd_sync_test/resources/triangle/Triangle.blend rename to projects/voxelization/resources/triangle/Triangle.blend diff --git a/projects/cmd_sync_test/resources/triangle/Triangle.glb b/projects/voxelization/resources/triangle/Triangle.glb similarity index 100% rename from projects/cmd_sync_test/resources/triangle/Triangle.glb rename to projects/voxelization/resources/triangle/Triangle.glb diff --git a/projects/cmd_sync_test/resources/triangle/Triangle.gltf b/projects/voxelization/resources/triangle/Triangle.gltf similarity index 100% rename from projects/cmd_sync_test/resources/triangle/Triangle.gltf rename to projects/voxelization/resources/triangle/Triangle.gltf diff --git a/projects/voxelization/src/Voxelization.cpp b/projects/voxelization/src/Voxelization.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b04fab9a2b61430d24bd7171d9fd3637dd428699 --- /dev/null +++ b/projects/voxelization/src/Voxelization.cpp @@ -0,0 +1,285 @@ +#include "Voxelization.hpp" +#include <vkcv/shader/GLSLCompiler.hpp> +#include <glm/gtc/matrix_transform.hpp> + +vkcv::ShaderProgram loadVoxelizationShader() { + vkcv::shader::GLSLCompiler compiler; + vkcv::ShaderProgram shader; + compiler.compile(vkcv::ShaderStage::VERTEX, "resources/shaders/voxelization.vert", + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + shader.addShader(shaderStage, path); + }); + compiler.compile(vkcv::ShaderStage::GEOMETRY, "resources/shaders/voxelization.geom", + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + shader.addShader(shaderStage, path); + }); + compiler.compile(vkcv::ShaderStage::FRAGMENT, "resources/shaders/voxelization.frag", + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + shader.addShader(shaderStage, path); + }); + return shader; +} + +vkcv::ShaderProgram loadVoxelVisualisationShader() { + vkcv::shader::GLSLCompiler compiler; + vkcv::ShaderProgram shader; + compiler.compile(vkcv::ShaderStage::VERTEX, "resources/shaders/voxelVisualisation.vert", + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + shader.addShader(shaderStage, path); + }); + compiler.compile(vkcv::ShaderStage::GEOMETRY, "resources/shaders/voxelVisualisation.geom", + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + shader.addShader(shaderStage, path); + }); + compiler.compile(vkcv::ShaderStage::FRAGMENT, "resources/shaders/voxelVisualisation.frag", + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + shader.addShader(shaderStage, path); + }); + return shader; +} + +vkcv::ShaderProgram loadVoxelResetShader() { + vkcv::shader::GLSLCompiler compiler; + vkcv::ShaderProgram shader; + compiler.compile(vkcv::ShaderStage::COMPUTE, "resources/shaders/voxelReset.comp", + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + shader.addShader(shaderStage, path); + }); + return shader; +} + +vkcv::ShaderProgram loadVoxelBufferToImageShader() { + vkcv::shader::GLSLCompiler compiler; + vkcv::ShaderProgram shader; + compiler.compile(vkcv::ShaderStage::COMPUTE, "resources/shaders/voxelBufferToImage.comp", + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + shader.addShader(shaderStage, path); + }); + return shader; +} + +const uint32_t voxelResolution = 128; +uint32_t voxelCount = voxelResolution * voxelResolution * voxelResolution; +const vk::Format voxelizationDummyFormat = vk::Format::eR8Unorm; + +Voxelization::Voxelization(vkcv::Core* corePtr, const Dependencies& dependencies) + : + m_corePtr(corePtr), + m_voxelImage(m_corePtr->createImage(vk::Format::eR16G16B16A16Sfloat, voxelResolution, voxelResolution, voxelResolution, false, true)), + m_dummyRenderTarget(m_corePtr->createImage(voxelizationDummyFormat, voxelResolution, voxelResolution, 1, false, false, true)), + m_voxelInfoBuffer(m_corePtr->createBuffer<VoxelizationInfo>(vkcv::BufferType::UNIFORM, 1)), + m_voxelBuffer(m_corePtr->createBuffer<VoxelBufferContent>(vkcv::BufferType::STORAGE, voxelCount)){ + + const vkcv::ShaderProgram voxelizationShader = loadVoxelizationShader(); + + const vkcv::PassConfig voxelizationPassConfig({vkcv::AttachmentDescription( + vkcv::AttachmentOperation::DONT_CARE, + vkcv::AttachmentOperation::DONT_CARE, + voxelizationDummyFormat) }); + m_voxelizationPass = m_corePtr->createPass(voxelizationPassConfig); + + std::vector<vkcv::DescriptorBinding> voxelizationDescriptorBindings = + { voxelizationShader.getReflectedDescriptors()[0] }; + m_voxelizationDescriptorSet = m_corePtr->createDescriptorSet(voxelizationDescriptorBindings); + + vkcv::DescriptorSetHandle dummyPerMeshDescriptorSet = + m_corePtr->createDescriptorSet({ voxelizationShader.getReflectedDescriptors()[1] }); + + const vkcv::PipelineConfig voxelizationPipeConfig{ + voxelizationShader, + voxelResolution, + voxelResolution, + m_voxelizationPass, + dependencies.vertexLayout, + { + m_corePtr->getDescriptorSet(m_voxelizationDescriptorSet).layout, + m_corePtr->getDescriptorSet(dummyPerMeshDescriptorSet).layout}, + false, + true }; + m_voxelizationPipe = m_corePtr->createGraphicsPipeline(voxelizationPipeConfig); + + vkcv::DescriptorWrites voxelizationDescriptorWrites; + voxelizationDescriptorWrites.storageBufferWrites = { vkcv::StorageBufferDescriptorWrite(0, m_voxelBuffer.getHandle()) }; + voxelizationDescriptorWrites.uniformBufferWrites = { vkcv::UniformBufferDescriptorWrite(1, m_voxelInfoBuffer.getHandle()) }; + voxelizationDescriptorWrites.storageImageWrites = { vkcv::StorageImageDescriptorWrite(2, m_voxelImage.getHandle()) }; + m_corePtr->writeDescriptorSet(m_voxelizationDescriptorSet, voxelizationDescriptorWrites); + + vkcv::ShaderProgram voxelVisualisationShader = loadVoxelVisualisationShader(); + + const std::vector<vkcv::DescriptorBinding> voxelVisualisationDescriptorBindings = + { voxelVisualisationShader.getReflectedDescriptors()[0] }; + m_visualisationDescriptorSet = m_corePtr->createDescriptorSet(voxelVisualisationDescriptorBindings); + + const vkcv::AttachmentDescription voxelVisualisationColorAttachments( + vkcv::AttachmentOperation::STORE, + vkcv::AttachmentOperation::LOAD, + dependencies.colorBufferFormat + ); + + const vkcv::AttachmentDescription voxelVisualisationDepthAttachments( + vkcv::AttachmentOperation::STORE, + vkcv::AttachmentOperation::LOAD, + dependencies.depthBufferFormat + ); + + vkcv::PassConfig voxelVisualisationPassDefinition( + { voxelVisualisationColorAttachments, voxelVisualisationDepthAttachments }); + m_visualisationPass = m_corePtr->createPass(voxelVisualisationPassDefinition); + + const vkcv::PipelineConfig voxelVisualisationPipeConfig{ + voxelVisualisationShader, + 0, + 0, + m_visualisationPass, + {}, + { m_corePtr->getDescriptorSet(m_visualisationDescriptorSet).layout }, + true, + false, + vkcv::PrimitiveTopology::PointList }; // points are extended to cubes in the geometry shader + m_visualisationPipe = m_corePtr->createGraphicsPipeline(voxelVisualisationPipeConfig); + + std::vector<uint16_t> voxelIndexData; + for (int i = 0; i < voxelCount; i++) { + voxelIndexData.push_back(i); + } + + vkcv::DescriptorWrites voxelVisualisationDescriptorWrite; + voxelVisualisationDescriptorWrite.storageImageWrites = + { vkcv::StorageImageDescriptorWrite(0, m_voxelImage.getHandle()) }; + voxelVisualisationDescriptorWrite.uniformBufferWrites = + { vkcv::UniformBufferDescriptorWrite(1, m_voxelInfoBuffer.getHandle()) }; + m_corePtr->writeDescriptorSet(m_visualisationDescriptorSet, voxelVisualisationDescriptorWrite); + + const vkcv::DescriptorSetUsage voxelizationDescriptorUsage(0, m_corePtr->getDescriptorSet(m_visualisationDescriptorSet).vulkanHandle); + + vkcv::ShaderProgram resetVoxelShader = loadVoxelResetShader(); + + m_voxelResetDescriptorSet = m_corePtr->createDescriptorSet(resetVoxelShader.getReflectedDescriptors()[0]); + m_voxelResetPipe = m_corePtr->createComputePipeline( + resetVoxelShader, + { m_corePtr->getDescriptorSet(m_voxelResetDescriptorSet).layout }); + + vkcv::DescriptorWrites resetVoxelWrites; + resetVoxelWrites.storageBufferWrites = { vkcv::StorageBufferDescriptorWrite(0, m_voxelBuffer.getHandle()) }; + m_corePtr->writeDescriptorSet(m_voxelResetDescriptorSet, resetVoxelWrites); + + + vkcv::ShaderProgram bufferToImageShader = loadVoxelBufferToImageShader(); + + m_bufferToImageDescriptorSet = m_corePtr->createDescriptorSet(bufferToImageShader.getReflectedDescriptors()[0]); + m_bufferToImagePipe = m_corePtr->createComputePipeline( + bufferToImageShader, + { m_corePtr->getDescriptorSet(m_bufferToImageDescriptorSet).layout }); + + vkcv::DescriptorWrites bufferToImageDescriptorWrites; + bufferToImageDescriptorWrites.storageBufferWrites = { vkcv::StorageBufferDescriptorWrite(0, m_voxelBuffer.getHandle()) }; + bufferToImageDescriptorWrites.storageImageWrites = { vkcv::StorageImageDescriptorWrite(1, m_voxelImage.getHandle()) }; + m_corePtr->writeDescriptorSet(m_bufferToImageDescriptorSet, bufferToImageDescriptorWrites); +} + +void Voxelization::voxelizeMeshes( + vkcv::CommandStreamHandle cmdStream, + const glm::vec3& cameraPosition, + const std::vector<vkcv::Mesh>& meshes, + const std::vector<glm::mat4>& modelMatrices, + const std::vector<vkcv::DescriptorSetHandle>& perMeshDescriptorSets) { + + VoxelizationInfo voxelizationInfo; + voxelizationInfo.extent = m_voxelExtent; + + // move voxel offset with camera in voxel sized steps + const float voxelSize = m_voxelExtent / voxelResolution; + voxelizationInfo.offset = glm::floor(cameraPosition / voxelSize) * voxelSize; + + m_voxelInfoBuffer.fill({ voxelizationInfo }); + + const float voxelizationHalfExtent = 0.5f * m_voxelExtent; + const glm::mat4 voxelizationProjection = glm::ortho( + -voxelizationHalfExtent, + voxelizationHalfExtent, + -voxelizationHalfExtent, + voxelizationHalfExtent, + -voxelizationHalfExtent, + voxelizationHalfExtent); + + const glm::mat4 voxelizationView = glm::translate(glm::mat4(1.f), -voxelizationInfo.offset); + const glm::mat4 voxelizationViewProjection = voxelizationProjection * voxelizationView; + + std::vector<std::array<glm::mat4, 2>> voxelizationMatrices; + for (const auto& m : modelMatrices) { + voxelizationMatrices.push_back({ voxelizationViewProjection * m, m }); + } + + const vkcv::PushConstantData voxelizationPushConstantData((void*)voxelizationMatrices.data(), 2 * sizeof(glm::mat4)); + + // reset voxels + const uint32_t resetVoxelGroupSize = 64; + uint32_t resetVoxelDispatchCount[3]; + resetVoxelDispatchCount[0] = glm::ceil(voxelCount / float(resetVoxelGroupSize)); + resetVoxelDispatchCount[1] = 1; + resetVoxelDispatchCount[2] = 1; + + m_corePtr->prepareImageForStorage(cmdStream, m_voxelImage.getHandle()); + m_corePtr->recordComputeDispatchToCmdStream( + cmdStream, + m_voxelResetPipe, + resetVoxelDispatchCount, + { vkcv::DescriptorSetUsage(0, m_corePtr->getDescriptorSet(m_voxelResetDescriptorSet).vulkanHandle) }, + vkcv::PushConstantData(&voxelCount, sizeof(voxelCount))); + m_corePtr->recordBufferMemoryBarrier(cmdStream, m_voxelBuffer.getHandle()); + + // voxelization + std::vector<vkcv::DrawcallInfo> drawcalls; + for (int i = 0; i < meshes.size(); i++) { + drawcalls.push_back(vkcv::DrawcallInfo( + meshes[i], + { + vkcv::DescriptorSetUsage(0, m_corePtr->getDescriptorSet(m_voxelizationDescriptorSet).vulkanHandle), + vkcv::DescriptorSetUsage(1, m_corePtr->getDescriptorSet(perMeshDescriptorSets[i]).vulkanHandle) + })); + } + + m_corePtr->recordDrawcallsToCmdStream( + cmdStream, + m_voxelizationPass, + m_voxelizationPipe, + voxelizationPushConstantData, + drawcalls, + { m_dummyRenderTarget.getHandle() }); + + // buffer to image + const uint32_t bufferToImageGroupSize[3] = { 4, 4, 4 }; + uint32_t bufferToImageDispatchCount[3]; + for (int i = 0; i < 3; i++) { + bufferToImageDispatchCount[i] = glm::ceil(voxelResolution / float(bufferToImageGroupSize[i])); + } + + m_corePtr->recordComputeDispatchToCmdStream( + cmdStream, + m_bufferToImagePipe, + bufferToImageDispatchCount, + { vkcv::DescriptorSetUsage(0, m_corePtr->getDescriptorSet(m_bufferToImageDescriptorSet).vulkanHandle) }, + vkcv::PushConstantData(nullptr, 0)); + + m_corePtr->recordImageMemoryBarrier(cmdStream, m_voxelImage.getHandle()); +} + +void Voxelization::renderVoxelVisualisation( + vkcv::CommandStreamHandle cmdStream, + const glm::mat4& viewProjectin, + const std::vector<vkcv::ImageHandle>& renderTargets) { + + const vkcv::PushConstantData voxelVisualisationPushConstantData((void*)&viewProjectin, sizeof(glm::mat4)); + + const auto drawcall = vkcv::DrawcallInfo( + vkcv::Mesh({}, nullptr, voxelCount), + { vkcv::DescriptorSetUsage(0, m_corePtr->getDescriptorSet(m_visualisationDescriptorSet).vulkanHandle) }); + + m_corePtr->recordDrawcallsToCmdStream( + cmdStream, + m_visualisationPass, + m_visualisationPipe, + voxelVisualisationPushConstantData, + { drawcall }, + renderTargets); +} \ No newline at end of file diff --git a/projects/voxelization/src/Voxelization.hpp b/projects/voxelization/src/Voxelization.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f9b96998b39e24a3481d130efa68ebaa813b8256 --- /dev/null +++ b/projects/voxelization/src/Voxelization.hpp @@ -0,0 +1,59 @@ +#pragma once +#include <vkcv/Core.hpp> +#include <glm/glm.hpp> + +class Voxelization{ +public: + struct Dependencies { + vkcv::VertexLayout vertexLayout; + vk::Format colorBufferFormat; + vk::Format depthBufferFormat; + }; + Voxelization(vkcv::Core* corePtr, const Dependencies& dependencies); + + void voxelizeMeshes( + vkcv::CommandStreamHandle cmdStream, + const glm::vec3& cameraPosition, + const std::vector<vkcv::Mesh>& meshes, + const std::vector<glm::mat4>& modelMatrices, + const std::vector<vkcv::DescriptorSetHandle>& perMeshDescriptorSets); + + void renderVoxelVisualisation( + vkcv::CommandStreamHandle cmdStream, + const glm::mat4& viewProjectin, + const std::vector<vkcv::ImageHandle>& renderTargets); + +private: + vkcv::Core* m_corePtr; + + struct VoxelBufferContent{ + uint32_t isFilled; + }; + + vkcv::Image m_voxelImage; + vkcv::Buffer<VoxelBufferContent> m_voxelBuffer; + + vkcv::Image m_dummyRenderTarget; + vkcv::PassHandle m_voxelizationPass; + vkcv::PipelineHandle m_voxelizationPipe; + vkcv::DescriptorSetHandle m_voxelizationDescriptorSet; + + vkcv::PipelineHandle m_voxelResetPipe; + vkcv::DescriptorSetHandle m_voxelResetDescriptorSet; + + vkcv::PipelineHandle m_bufferToImagePipe; + vkcv::DescriptorSetHandle m_bufferToImageDescriptorSet; + + vkcv::PassHandle m_visualisationPass; + vkcv::PipelineHandle m_visualisationPipe; + + vkcv::DescriptorSetHandle m_visualisationDescriptorSet; + + struct VoxelizationInfo { + glm::vec3 offset; + float extent; + }; + vkcv::Buffer<VoxelizationInfo> m_voxelInfoBuffer; + + const float m_voxelExtent = 20.f; +}; \ No newline at end of file diff --git a/projects/voxelization/src/main.cpp b/projects/voxelization/src/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bab5d0f07271cf737cdc0334634e155cfbded179 --- /dev/null +++ b/projects/voxelization/src/main.cpp @@ -0,0 +1,441 @@ +#include <iostream> +#include <vkcv/Core.hpp> +#include <GLFW/glfw3.h> +#include <vkcv/camera/CameraManager.hpp> +#include <chrono> +#include <vkcv/asset/asset_loader.hpp> +#include <vkcv/shader/GLSLCompiler.hpp> +#include <vkcv/Logger.hpp> +#include "Voxelization.hpp" +#include <glm/glm.hpp> + +int main(int argc, const char** argv) { + const char* applicationName = "Voxelization"; + + uint32_t windowWidth = 800; + uint32_t windowHeight = 600; + + vkcv::Window window = vkcv::Window::create( + applicationName, + windowWidth, + windowHeight, + true + ); + + vkcv::camera::CameraManager cameraManager(window); + uint32_t camIndex = cameraManager.addCamera(vkcv::camera::ControllerType::PILOT); + uint32_t camIndex2 = cameraManager.addCamera(vkcv::camera::ControllerType::TRACKBALL); + + cameraManager.getCamera(camIndex).setPosition(glm::vec3(0.f, 0.f, 3.f)); + cameraManager.getCamera(camIndex).setNearFar(0.1f, 30.0f); + cameraManager.getCamera(camIndex).setYaw(180.0f); + + cameraManager.getCamera(camIndex2).setNearFar(0.1f, 30.0f); + + vkcv::Core core = vkcv::Core::create( + window, + applicationName, + VK_MAKE_VERSION(0, 0, 1), + { vk::QueueFlagBits::eTransfer,vk::QueueFlagBits::eGraphics, vk::QueueFlagBits::eCompute }, + {}, + { "VK_KHR_swapchain" } + ); + + vkcv::asset::Scene mesh; + + const char* path = argc > 1 ? argv[1] : "resources/Sponza/Sponza.gltf"; + vkcv::asset::Scene scene; + int result = vkcv::asset::loadScene(path, scene); + + if (result == 1) { + std::cout << "Scene loading successful!" << std::endl; + } + else { + std::cout << "Scene loading failed: " << result << std::endl; + return 1; + } + + // build index and vertex buffers + assert(!scene.vertexGroups.empty()); + std::vector<std::vector<uint8_t>> vBuffers; + std::vector<std::vector<uint8_t>> iBuffers; + + std::vector<vkcv::VertexBufferBinding> vBufferBindings; + std::vector<std::vector<vkcv::VertexBufferBinding>> vertexBufferBindings; + std::vector<vkcv::asset::VertexAttribute> vAttributes; + + for (int i = 0; i < scene.vertexGroups.size(); i++) { + + vBuffers.push_back(scene.vertexGroups[i].vertexBuffer.data); + iBuffers.push_back(scene.vertexGroups[i].indexBuffer.data); + + auto& attributes = scene.vertexGroups[i].vertexBuffer.attributes; + + std::sort(attributes.begin(), attributes.end(), [](const vkcv::asset::VertexAttribute& x, const vkcv::asset::VertexAttribute& y) { + return static_cast<uint32_t>(x.type) < static_cast<uint32_t>(y.type); + }); + } + + std::vector<vkcv::Buffer<uint8_t>> vertexBuffers; + for (const vkcv::asset::VertexGroup& group : scene.vertexGroups) { + vertexBuffers.push_back(core.createBuffer<uint8_t>( + vkcv::BufferType::VERTEX, + group.vertexBuffer.data.size())); + vertexBuffers.back().fill(group.vertexBuffer.data); + } + + std::vector<vkcv::Buffer<uint8_t>> indexBuffers; + for (const auto& dataBuffer : iBuffers) { + indexBuffers.push_back(core.createBuffer<uint8_t>( + vkcv::BufferType::INDEX, + dataBuffer.size())); + indexBuffers.back().fill(dataBuffer); + } + + int vertexBufferIndex = 0; + for (const auto& vertexGroup : scene.vertexGroups) { + for (const auto& attribute : vertexGroup.vertexBuffer.attributes) { + vAttributes.push_back(attribute); + vBufferBindings.push_back(vkcv::VertexBufferBinding(attribute.offset, vertexBuffers[vertexBufferIndex].getVulkanHandle())); + } + vertexBufferBindings.push_back(vBufferBindings); + vBufferBindings.clear(); + vertexBufferIndex++; + } + + const vk::Format colorBufferFormat = vk::Format::eB10G11R11UfloatPack32; + const vkcv::AttachmentDescription color_attachment( + vkcv::AttachmentOperation::STORE, + vkcv::AttachmentOperation::CLEAR, + colorBufferFormat + ); + + const vk::Format depthBufferFormat = vk::Format::eD32Sfloat; + const vkcv::AttachmentDescription depth_attachment( + vkcv::AttachmentOperation::STORE, + vkcv::AttachmentOperation::CLEAR, + depthBufferFormat + ); + + vkcv::PassConfig forwardPassDefinition({ color_attachment, depth_attachment }); + vkcv::PassHandle forwardPass = core.createPass(forwardPassDefinition); + + vkcv::shader::GLSLCompiler compiler; + + vkcv::ShaderProgram forwardProgram; + compiler.compile(vkcv::ShaderStage::VERTEX, std::filesystem::path("resources/shaders/shader.vert"), + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + forwardProgram.addShader(shaderStage, path); + }); + compiler.compile(vkcv::ShaderStage::FRAGMENT, std::filesystem::path("resources/shaders/shader.frag"), + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + forwardProgram.addShader(shaderStage, path); + }); + + const std::vector<vkcv::VertexAttachment> vertexAttachments = forwardProgram.getVertexAttachments(); + + std::vector<vkcv::VertexBinding> vertexBindings; + for (size_t i = 0; i < vertexAttachments.size(); i++) { + vertexBindings.push_back(vkcv::VertexBinding(i, { vertexAttachments[i] })); + } + const vkcv::VertexLayout vertexLayout (vertexBindings); + + // shadow map + vkcv::SamplerHandle shadowSampler = core.createSampler( + vkcv::SamplerFilterType::NEAREST, + vkcv::SamplerFilterType::NEAREST, + vkcv::SamplerMipmapMode::NEAREST, + vkcv::SamplerAddressMode::CLAMP_TO_EDGE + ); + const vk::Format shadowMapFormat = vk::Format::eD16Unorm; + const uint32_t shadowMapResolution = 1024; + const vkcv::Image shadowMap = core.createImage(shadowMapFormat, shadowMapResolution, shadowMapResolution); + + // light info buffer + struct LightInfo { + glm::vec3 direction; + float padding; + glm::mat4 lightMatrix; + }; + LightInfo lightInfo; + vkcv::Buffer lightBuffer = core.createBuffer<LightInfo>(vkcv::BufferType::UNIFORM, sizeof(glm::vec3)); + + vkcv::DescriptorSetHandle forwardShadingDescriptorSet = + core.createDescriptorSet({ forwardProgram.getReflectedDescriptors()[0] }); + + vkcv::DescriptorWrites forwardDescriptorWrites; + forwardDescriptorWrites.uniformBufferWrites = { vkcv::UniformBufferDescriptorWrite(0, lightBuffer.getHandle()) }; + forwardDescriptorWrites.sampledImageWrites = { vkcv::SampledImageDescriptorWrite(1, shadowMap.getHandle()) }; + forwardDescriptorWrites.samplerWrites = { vkcv::SamplerDescriptorWrite(2, shadowSampler) }; + core.writeDescriptorSet(forwardShadingDescriptorSet, forwardDescriptorWrites); + + vkcv::SamplerHandle colorSampler = core.createSampler( + vkcv::SamplerFilterType::LINEAR, + vkcv::SamplerFilterType::LINEAR, + vkcv::SamplerMipmapMode::LINEAR, + vkcv::SamplerAddressMode::REPEAT + ); + + // prepare per mesh descriptor sets + std::vector<vkcv::DescriptorSetHandle> perMeshDescriptorSets; + std::vector<vkcv::Image> sceneImages; + for (const auto& vertexGroup : scene.vertexGroups) { + perMeshDescriptorSets.push_back(core.createDescriptorSet(forwardProgram.getReflectedDescriptors()[1])); + + const auto& material = scene.materials[vertexGroup.materialIndex]; + + int baseColorIndex = material.baseColor; + if (baseColorIndex < 0) { + vkcv_log(vkcv::LogLevel::WARNING, "Material lacks base color"); + baseColorIndex = 0; + } + + vkcv::asset::Texture& sceneTexture = scene.textures[baseColorIndex]; + + sceneImages.push_back(core.createImage(vk::Format::eR8G8B8A8Srgb, sceneTexture.w, sceneTexture.h, 1, true)); + sceneImages.back().fill(sceneTexture.data.data()); + sceneImages.back().generateMipChainImmediate(); + sceneImages.back().switchLayout(vk::ImageLayout::eShaderReadOnlyOptimal); + + vkcv::DescriptorWrites setWrites; + setWrites.sampledImageWrites = { + vkcv::SampledImageDescriptorWrite(0, sceneImages.back().getHandle()) + }; + setWrites.samplerWrites = { + vkcv::SamplerDescriptorWrite(1, colorSampler), + }; + core.writeDescriptorSet(perMeshDescriptorSets.back(), setWrites); + } + + const vkcv::PipelineConfig forwardPipelineConfig { + forwardProgram, + windowWidth, + windowHeight, + forwardPass, + vertexLayout, + { core.getDescriptorSet(forwardShadingDescriptorSet).layout, + core.getDescriptorSet(perMeshDescriptorSets[0]).layout }, + true + }; + + vkcv::PipelineHandle forwardPipeline = core.createGraphicsPipeline(forwardPipelineConfig); + + if (!forwardPipeline) { + std::cout << "Error. Could not create graphics pipeline. Exiting." << std::endl; + return EXIT_FAILURE; + } + + vkcv::ImageHandle depthBuffer = core.createImage(depthBufferFormat, windowWidth, windowHeight).getHandle(); + vkcv::ImageHandle colorBuffer = core.createImage(colorBufferFormat, windowWidth, windowHeight, 1, false, true, true).getHandle(); + + const vkcv::ImageHandle swapchainInput = vkcv::ImageHandle::createSwapchainImageHandle(); + + vkcv::ShaderProgram shadowShader; + compiler.compile(vkcv::ShaderStage::VERTEX, "resources/shaders/shadow.vert", + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + shadowShader.addShader(shaderStage, path); + }); + compiler.compile(vkcv::ShaderStage::FRAGMENT, "resources/shaders/shadow.frag", + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + shadowShader.addShader(shaderStage, path); + }); + + const std::vector<vkcv::AttachmentDescription> shadowAttachments = { + vkcv::AttachmentDescription(vkcv::AttachmentOperation::STORE, vkcv::AttachmentOperation::CLEAR, shadowMapFormat) + }; + const vkcv::PassConfig shadowPassConfig(shadowAttachments); + const vkcv::PassHandle shadowPass = core.createPass(shadowPassConfig); + const vkcv::PipelineConfig shadowPipeConfig{ + shadowShader, + shadowMapResolution, + shadowMapResolution, + shadowPass, + vertexLayout, + {}, + false + }; + const vkcv::PipelineHandle shadowPipe = core.createGraphicsPipeline(shadowPipeConfig); + + std::vector<std::array<glm::mat4, 2>> mainPassMatrices; + std::vector<glm::mat4> mvpLight; + + bool renderVoxelVis = false; + window.e_key.add([&renderVoxelVis](int key ,int scancode, int action, int mods) { + if (key == GLFW_KEY_V && action == GLFW_PRESS) { + renderVoxelVis = !renderVoxelVis; + } + }); + + // gamma correction compute shader + vkcv::ShaderProgram gammaCorrectionProgram; + compiler.compile(vkcv::ShaderStage::COMPUTE, "resources/shaders/gammaCorrection.comp", + [&](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + gammaCorrectionProgram.addShader(shaderStage, path); + }); + vkcv::DescriptorSetHandle gammaCorrectionDescriptorSet = core.createDescriptorSet(gammaCorrectionProgram.getReflectedDescriptors()[0]); + vkcv::PipelineHandle gammaCorrectionPipeline = core.createComputePipeline(gammaCorrectionProgram, + { core.getDescriptorSet(gammaCorrectionDescriptorSet).layout }); + + // model matrices per mesh + std::vector<glm::mat4> modelMatrices; + modelMatrices.resize(scene.vertexGroups.size(), glm::mat4(1.f)); + for (const auto& mesh : scene.meshes) { + const glm::mat4 m = *reinterpret_cast<const glm::mat4*>(&mesh.modelMatrix[0]); + for (const auto& vertexGroupIndex : mesh.vertexGroups) { + modelMatrices[vertexGroupIndex] = m; + } + } + + // prepare drawcalls + std::vector<vkcv::Mesh> meshes; + for (int i = 0; i < scene.vertexGroups.size(); i++) { + vkcv::Mesh mesh( + vertexBufferBindings[i], + indexBuffers[i].getVulkanHandle(), + scene.vertexGroups[i].numIndices); + meshes.push_back(mesh); + } + + std::vector<vkcv::DrawcallInfo> drawcalls; + std::vector<vkcv::DrawcallInfo> shadowDrawcalls; + for (int i = 0; i < meshes.size(); i++) { + + drawcalls.push_back(vkcv::DrawcallInfo(meshes[i], { + vkcv::DescriptorSetUsage(0, core.getDescriptorSet(forwardShadingDescriptorSet).vulkanHandle), + vkcv::DescriptorSetUsage(1, core.getDescriptorSet(perMeshDescriptorSets[i]).vulkanHandle) })); + shadowDrawcalls.push_back(vkcv::DrawcallInfo(meshes[i], {})); + } + + Voxelization::Dependencies voxelDependencies; + voxelDependencies.colorBufferFormat = colorBufferFormat; + voxelDependencies.depthBufferFormat = depthBufferFormat; + voxelDependencies.vertexLayout = vertexLayout; + Voxelization voxelization(&core, voxelDependencies); + + auto start = std::chrono::system_clock::now(); + const auto appStartTime = start; + while (window.isWindowOpen()) { + vkcv::Window::pollEvents(); + + uint32_t swapchainWidth, swapchainHeight; + if (!core.beginFrame(swapchainWidth, swapchainHeight)) { + continue; + } + + if ((swapchainWidth != windowWidth) || ((swapchainHeight != windowHeight))) { + depthBuffer = core.createImage(depthBufferFormat, swapchainWidth, swapchainHeight).getHandle(); + colorBuffer = core.createImage(colorBufferFormat, swapchainWidth, swapchainHeight, 1, false, true, true).getHandle(); + + windowWidth = swapchainWidth; + windowHeight = swapchainHeight; + } + + auto end = std::chrono::system_clock::now(); + auto deltatime = std::chrono::duration_cast<std::chrono::microseconds>(end - start); + + // update descriptor sets which use swapchain image + vkcv::DescriptorWrites gammaCorrectionDescriptorWrites; + gammaCorrectionDescriptorWrites.storageImageWrites = { + vkcv::StorageImageDescriptorWrite(0, colorBuffer), + vkcv::StorageImageDescriptorWrite(1, swapchainInput) }; + core.writeDescriptorSet(gammaCorrectionDescriptorSet, gammaCorrectionDescriptorWrites); + + start = end; + cameraManager.update(0.000001 * static_cast<double>(deltatime.count())); + + auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - appStartTime); + + const float sunTheta = 0.001f * static_cast<float>(duration.count()); + lightInfo.direction = glm::normalize(glm::vec3(std::cos(sunTheta), 1, std::sin(sunTheta))); + + const float shadowProjectionSize = 20.f; + glm::mat4 projectionLight = glm::ortho( + -shadowProjectionSize, + shadowProjectionSize, + -shadowProjectionSize, + shadowProjectionSize, + -shadowProjectionSize, + shadowProjectionSize); + + glm::mat4 vulkanCorrectionMatrix(1.f); + vulkanCorrectionMatrix[2][2] = 0.5; + vulkanCorrectionMatrix[3][2] = 0.5; + projectionLight = vulkanCorrectionMatrix * projectionLight; + + const glm::mat4 viewLight = glm::lookAt(glm::vec3(0), -lightInfo.direction, glm::vec3(0, -1, 0)); + + lightInfo.lightMatrix = projectionLight * viewLight; + lightBuffer.fill({ lightInfo }); + + const glm::mat4 viewProjectionCamera = cameraManager.getActiveCamera().getMVP(); + + mainPassMatrices.clear(); + mvpLight.clear(); + for (const auto& m : modelMatrices) { + mainPassMatrices.push_back({ viewProjectionCamera * m, m }); + mvpLight.push_back(lightInfo.lightMatrix * m); + } + + vkcv::PushConstantData pushConstantData((void*)mainPassMatrices.data(), 2 * sizeof(glm::mat4)); + const std::vector<vkcv::ImageHandle> renderTargets = { colorBuffer, depthBuffer }; + + const vkcv::PushConstantData shadowPushConstantData((void*)mvpLight.data(), sizeof(glm::mat4)); + + auto cmdStream = core.createCommandStream(vkcv::QueueType::Graphics); + + // shadow map + core.recordDrawcallsToCmdStream( + cmdStream, + shadowPass, + shadowPipe, + shadowPushConstantData, + shadowDrawcalls, + { shadowMap.getHandle() }); + core.prepareImageForSampling(cmdStream, shadowMap.getHandle()); + + voxelization.voxelizeMeshes( + cmdStream, + cameraManager.getActiveCamera().getPosition(), + meshes, + modelMatrices, + perMeshDescriptorSets); + + // main pass + core.recordDrawcallsToCmdStream( + cmdStream, + forwardPass, + forwardPipeline, + pushConstantData, + drawcalls, + renderTargets); + + if (renderVoxelVis) { + voxelization.renderVoxelVisualisation(cmdStream, viewProjectionCamera, renderTargets); + } + + const uint32_t gammaCorrectionLocalGroupSize = 8; + const uint32_t gammaCorrectionDispatchCount[3] = { + static_cast<uint32_t>(glm::ceil(windowWidth / static_cast<float>(gammaCorrectionLocalGroupSize))), + static_cast<uint32_t>(glm::ceil(windowHeight / static_cast<float>(gammaCorrectionLocalGroupSize))), + 1 + }; + + core.prepareImageForStorage(cmdStream, swapchainInput); + core.prepareImageForStorage(cmdStream, colorBuffer); + + core.recordComputeDispatchToCmdStream( + cmdStream, + gammaCorrectionPipeline, + gammaCorrectionDispatchCount, + { vkcv::DescriptorSetUsage(0, core.getDescriptorSet(gammaCorrectionDescriptorSet).vulkanHandle) }, + vkcv::PushConstantData(nullptr, 0)); + + // present and end + core.prepareSwapchainImageForPresent(cmdStream); + core.submitCommandStream(cmdStream); + + core.endFrame(); + } + + return 0; +} diff --git a/src/vkcv/BufferManager.cpp b/src/vkcv/BufferManager.cpp index 6d494c4ec90726d46039007607464378624f1c75..aec96411c5d9e07f200b24fbdcf9fa69e2af53d5 100644 --- a/src/vkcv/BufferManager.cpp +++ b/src/vkcv/BufferManager.cpp @@ -5,6 +5,7 @@ #include "vkcv/BufferManager.hpp" #include "vkcv/Core.hpp" +#include <vkcv/Logger.hpp> namespace vkcv { @@ -158,7 +159,7 @@ namespace vkcv { SubmitInfo submitInfo; submitInfo.queueType = QueueType::Transfer; - core->recordAndSubmitCommands( + core->recordAndSubmitCommandsImmediate( submitInfo, [&info, &mapped_size](const vk::CommandBuffer& commandBuffer) { const vk::BufferCopy region ( @@ -335,4 +336,33 @@ namespace vkcv { } } + void BufferManager ::recordBufferMemoryBarrier(const BufferHandle& handle, vk::CommandBuffer cmdBuffer) { + + const uint64_t id = handle.getId(); + + if (id >= m_buffers.size()) { + vkcv_log(vkcv::LogLevel::ERROR, "Invalid buffer handle"); + return; + } + + auto& buffer = m_buffers[id]; + + vk::BufferMemoryBarrier memoryBarrier( + vk::AccessFlagBits::eMemoryWrite, + vk::AccessFlagBits::eMemoryRead, + 0, + 0, + buffer.m_handle, + 0, + buffer.m_size); + + cmdBuffer.pipelineBarrier( + vk::PipelineStageFlagBits::eTopOfPipe, + vk::PipelineStageFlagBits::eBottomOfPipe, + {}, + nullptr, + memoryBarrier, + nullptr); + } + } diff --git a/src/vkcv/Context.cpp b/src/vkcv/Context.cpp index b53a1a2c2db1008e7c69c880ef1c5a608d879021..ac133d1affc81702ee1a19b3f66810e606bec58d 100644 --- a/src/vkcv/Context.cpp +++ b/src/vkcv/Context.cpp @@ -275,7 +275,13 @@ namespace vkcv deviceCreateInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); deviceCreateInfo.ppEnabledLayerNames = validationLayers.data(); #endif - + + // FIXME: check if device feature is supported + vk::PhysicalDeviceFeatures deviceFeatures; + deviceFeatures.fragmentStoresAndAtomics = true; + deviceFeatures.geometryShader = true; + deviceCreateInfo.pEnabledFeatures = &deviceFeatures; + // Ablauf // qCreateInfos erstellen --> braucht das Device // device erstellen diff --git a/src/vkcv/Core.cpp b/src/vkcv/Core.cpp index 44e7111e1f4941ef2f0f8114ac788d7db4a13b5a..1492b1afa563543e6a9eef380295bcb71fef58b8 100644 --- a/src/vkcv/Core.cpp +++ b/src/vkcv/Core.cpp @@ -15,7 +15,7 @@ #include "DescriptorManager.hpp" #include "ImageLayoutTransitions.hpp" #include "vkcv/CommandStreamManager.hpp" - +#include <cmath> #include "vkcv/Logger.hpp" namespace vkcv @@ -35,10 +35,9 @@ namespace vkcv deviceExtensions ); - SwapChain swapChain = SwapChain::create(window, context); + Swapchain swapChain = Swapchain::create(window, context); - std::vector<vk::ImageView> imageViews; - imageViews = createImageViews( context, swapChain); + std::vector<vk::ImageView> swapchainImageViews = createSwapchainImageViews( context, swapChain); const auto& queueManager = context.getQueueManager(); @@ -47,20 +46,23 @@ namespace vkcv const auto commandResources = createCommandResources(context.getDevice(), queueFamilySet); const auto defaultSyncResources = createSyncResources(context.getDevice()); - return Core(std::move(context) , window, swapChain, imageViews, commandResources, defaultSyncResources); + return Core(std::move(context) , window, swapChain, swapchainImageViews, commandResources, defaultSyncResources); } const Context &Core::getContext() const { return m_Context; } + + const Swapchain& Core::getSwapchain() const { + return m_swapchain; + } - Core::Core(Context &&context, Window &window, const SwapChain& swapChain, std::vector<vk::ImageView> imageViews, + Core::Core(Context &&context, Window &window, const Swapchain& swapChain, std::vector<vk::ImageView> swapchainImageViews, const CommandResources& commandResources, const SyncResources& syncResources) noexcept : m_Context(std::move(context)), m_window(window), m_swapchain(swapChain), - m_swapchainImageViews(imageViews), m_PassManager{std::make_unique<PassManager>(m_Context.m_Device)}, m_PipelineManager{std::make_unique<PipelineManager>(m_Context.m_Device)}, m_DescriptorManager(std::make_unique<DescriptorManager>(m_Context.m_Device)), @@ -76,20 +78,24 @@ namespace vkcv m_CommandStreamManager->init(this); m_ImageManager->m_core = this; - - e_resizeHandle = window.e_resize.add( [&](int width, int height) { + + e_resizeHandle = m_window.e_resize.add( [&](int width, int height) { m_swapchain.signalSwapchainRecreation(); }); - m_swapchainImages = m_Context.getDevice().getSwapchainImagesKHR(m_swapchain.getSwapchain()); - m_swapchainImageLayouts.resize(m_swapchainImages.size(), vk::ImageLayout::eUndefined); + const auto swapchainImages = m_Context.getDevice().getSwapchainImagesKHR(m_swapchain.getSwapchain()); + m_ImageManager->setSwapchainImages( + swapchainImages, + swapchainImageViews, + swapChain.getExtent().width, + swapChain.getExtent().height, + swapChain.getFormat()); } Core::~Core() noexcept { + m_window.e_resize.remove(e_resizeHandle); + m_Context.getDevice().waitIdle(); - for (auto image : m_swapchainImageViews) { - m_Context.m_Device.destroyImageView(image); - } destroyCommandResources(m_Context.getDevice(), m_CommandResources); destroySyncResources(m_Context.getDevice(), m_SyncResources); @@ -145,16 +151,12 @@ namespace vkcv bool Core::beginFrame(uint32_t& width, uint32_t& height) { if (m_swapchain.shouldUpdateSwapchain()) { m_Context.getDevice().waitIdle(); - - for (auto image : m_swapchainImageViews) - m_Context.m_Device.destroyImageView(image); - + m_swapchain.updateSwapchain(m_Context, m_window); - m_swapchainImageViews = createImageViews(m_Context, m_swapchain); - m_swapchainImages = m_Context.getDevice().getSwapchainImagesKHR(m_swapchain.getSwapchain()); + const auto swapchainViews = createSwapchainImageViews(m_Context, m_swapchain); + const auto swapchainImages = m_Context.getDevice().getSwapchainImagesKHR(m_swapchain.getSwapchain()); - m_swapchainImageLayouts.clear(); - m_swapchainImageLayouts.resize(m_swapchainImages.size(), vk::ImageLayout::eUndefined); + m_ImageManager->setSwapchainImages(swapchainImages, swapchainViews, width, height, m_swapchain.getFormat()); } if (acquireSwapchainImage() != Result::SUCCESS) { @@ -170,6 +172,8 @@ namespace vkcv width = extent.width; height = extent.height; + m_ImageManager->setCurrentSwapchainImageIndex(m_currentSwapchainImageIndex); + return (m_currentSwapchainImageIndex != std::numeric_limits<uint32_t>::max()); } @@ -212,27 +216,19 @@ namespace vkcv const vk::PipelineLayout pipelineLayout = m_PipelineManager->getVkPipelineLayout(pipelineHandle); const vk::Rect2D renderArea(vk::Offset2D(0, 0), vk::Extent2D(width, height)); - const vk::ImageView swapchainImageView = m_swapchainImageViews[m_currentSwapchainImageIndex]; - std::vector<vk::ImageView> attachmentsViews; for (const ImageHandle handle : renderTargets) { vk::ImageView targetHandle; const auto cmdBuffer = m_CommandStreamManager->getStreamCommandBuffer(cmdStreamHandle); - if (handle.isSwapchainImage()) { - recordSwapchainImageLayoutTransition(cmdBuffer, vk::ImageLayout::eColorAttachmentOptimal); - targetHandle = m_swapchainImageViews[m_currentSwapchainImageIndex]; - } - else { - targetHandle = m_ImageManager->getVulkanImageView(handle); - const bool isDepthImage = isDepthFormat(m_ImageManager->getImageFormat(handle)); - const vk::ImageLayout targetLayout = - isDepthFormat ? vk::ImageLayout::eDepthStencilAttachmentOptimal : vk::ImageLayout::eColorAttachmentOptimal; - m_ImageManager->recordImageLayoutTransition(handle, targetLayout, cmdBuffer); - } + + targetHandle = m_ImageManager->getVulkanImageView(handle); + const bool isDepthImage = isDepthFormat(m_ImageManager->getImageFormat(handle)); + const vk::ImageLayout targetLayout = + isDepthImage ? vk::ImageLayout::eDepthStencilAttachmentOptimal : vk::ImageLayout::eColorAttachmentOptimal; + m_ImageManager->recordImageLayoutTransition(handle, targetLayout, cmdBuffer); attachmentsViews.push_back(targetHandle); } - vk::Framebuffer framebuffer = nullptr; const vk::FramebufferCreateInfo createInfo( {}, renderpass, @@ -240,16 +236,21 @@ namespace vkcv attachmentsViews.data(), width, height, - 1); - if(m_Context.m_Device.createFramebuffer(&createInfo, nullptr, &framebuffer) != vk::Result::eSuccess) - { + 1 + ); + + vk::Framebuffer framebuffer = m_Context.m_Device.createFramebuffer(createInfo); + + if (!framebuffer) { vkcv_log(LogLevel::ERROR, "Failed to create temporary framebuffer"); return; } - vk::Viewport dynamicViewport(0.0f, 0.0f, - static_cast<float>(width), static_cast<float>(height), - 0.0f, 1.0f); + vk::Viewport dynamicViewport( + 0.0f, 0.0f, + static_cast<float>(width), static_cast<float>(height), + 0.0f, 1.0f + ); vk::Rect2D dynamicScissor({0, 0}, {width, height}); @@ -349,15 +350,17 @@ namespace vkcv const auto swapchainImages = m_Context.getDevice().getSwapchainImagesKHR(m_swapchain.getSwapchain()); const auto& queueManager = m_Context.getQueueManager(); - std::array<vk::Semaphore, 2> waitSemaphores{ - m_SyncResources.renderFinished, - m_SyncResources.swapchainImageAcquired }; + std::array<vk::Semaphore, 2> waitSemaphores{ + m_SyncResources.renderFinished, + m_SyncResources.swapchainImageAcquired + }; const vk::SwapchainKHR& swapchain = m_swapchain.getSwapchain(); const vk::PresentInfoKHR presentInfo( waitSemaphores, swapchain, - m_currentSwapchainImageIndex); + m_currentSwapchainImageIndex + ); vk::Result result; @@ -371,12 +374,8 @@ namespace vkcv vkcv_log(LogLevel::ERROR, "Swapchain present failed (%s)", vk::to_string(result).c_str()); } } - - vk::Format Core::getSwapchainImageFormat() { - return m_swapchain.getSwapchainFormat(); - } - void Core::recordAndSubmitCommands( + void Core::recordAndSubmitCommandsImmediate( const SubmitInfo &submitInfo, const RecordCommandFunction &record, const FinishCommandFunction &finish) @@ -390,10 +389,12 @@ namespace vkcv beginCommandBuffer(cmdBuffer, vk::CommandBufferUsageFlagBits::eOneTimeSubmit); record(cmdBuffer); cmdBuffer.end(); + + vk::Fence waitFence = createFence(device); - const vk::Fence waitFence = createFence(device); submitCommandBufferToQueue(queue.handle, cmdBuffer, waitFence, submitInfo.waitSemaphores, submitInfo.signalSemaphores); waitForFence(device, waitFence); + device.destroyFence(waitFence); device.freeCommandBuffers(cmdPool, cmdBuffer); @@ -435,9 +436,30 @@ namespace vkcv return m_SamplerManager->createSampler(magFilter, minFilter, mipmapMode, addressMode); } - Image Core::createImage(vk::Format format, uint32_t width, uint32_t height, uint32_t depth) + Image Core::createImage( + vk::Format format, + uint32_t width, + uint32_t height, + uint32_t depth, + bool createMipChain, + bool supportStorage, + bool supportColorAttachment) { - return Image::create(m_ImageManager.get(), format, width, height, depth); + + uint32_t mipCount = 1; + if (createMipChain) { + mipCount = 1 + (uint32_t)std::floor(std::log2(std::max(width, std::max(height, depth)))); + } + + return Image::create( + m_ImageManager.get(), + format, + width, + height, + depth, + mipCount, + supportStorage, + supportColorAttachment); } DescriptorSetHandle Core::createDescriptorSet(const std::vector<DescriptorBinding>& bindings) @@ -447,7 +469,7 @@ namespace vkcv void Core::writeDescriptorSet(DescriptorSetHandle handle, const DescriptorWrites &writes) { m_DescriptorManager->writeDescriptorSet( - handle, + handle, writes, *m_ImageManager, *m_BufferManager, @@ -458,7 +480,7 @@ namespace vkcv return m_DescriptorManager->getDescriptorSet(handle); } - std::vector<vk::ImageView> Core::createImageViews( Context &context, SwapChain& swapChain){ + std::vector<vk::ImageView> Core::createSwapchainImageViews( Context &context, Swapchain& swapChain){ std::vector<vk::ImageView> imageViews; std::vector<vk::Image> swapChainImages = context.getDevice().getSwapchainImagesKHR(swapChain.getSwapchain()); imageViews.reserve( swapChainImages.size() ); @@ -477,7 +499,7 @@ namespace vkcv vk::ImageViewCreateFlags(), image, vk::ImageViewType::e2D, - swapChain.getSwapchainFormat(), + swapChain.getFormat(), componentMapping, subResourceRange); @@ -486,20 +508,11 @@ namespace vkcv return imageViews; } - void Core::recordSwapchainImageLayoutTransition(vk::CommandBuffer cmdBuffer, vk::ImageLayout newLayout) { - auto& imageLayout = m_swapchainImageLayouts[m_currentSwapchainImageIndex]; - const auto transitionBarrier = createSwapchainImageLayoutTransitionBarrier( - m_swapchainImages[m_currentSwapchainImageIndex], - imageLayout, - newLayout); - recordImageBarrier(cmdBuffer, transitionBarrier); - imageLayout = newLayout; - } - - void Core::prepareSwapchainImageForPresent(const CommandStreamHandle handle) { - m_CommandStreamManager->recordCommandsToStream(handle, [&](vk::CommandBuffer cmdBuffer) { - recordSwapchainImageLayoutTransition(cmdBuffer, vk::ImageLayout::ePresentSrcKHR); - }); + void Core::prepareSwapchainImageForPresent(const CommandStreamHandle cmdStream) { + auto swapchainHandle = ImageHandle::createSwapchainImageHandle(); + recordCommandsToStream(cmdStream, [swapchainHandle, this](const vk::CommandBuffer cmdBuffer) { + m_ImageManager->recordImageLayoutTransition(swapchainHandle, vk::ImageLayout::ePresentSrcKHR, cmdBuffer); + }, nullptr); } void Core::prepareImageForSampling(const CommandStreamHandle cmdStream, const ImageHandle image) { @@ -507,4 +520,27 @@ namespace vkcv m_ImageManager->recordImageLayoutTransition(image, vk::ImageLayout::eShaderReadOnlyOptimal, cmdBuffer); }, nullptr); } + + void Core::prepareImageForStorage(const CommandStreamHandle cmdStream, const ImageHandle image) { + recordCommandsToStream(cmdStream, [image, this](const vk::CommandBuffer cmdBuffer) { + m_ImageManager->recordImageLayoutTransition(image, vk::ImageLayout::eGeneral, cmdBuffer); + }, nullptr); + } + + void Core::recordImageMemoryBarrier(const CommandStreamHandle cmdStream, const ImageHandle image) { + recordCommandsToStream(cmdStream, [image, this](const vk::CommandBuffer cmdBuffer) { + m_ImageManager->recordImageMemoryBarrier(image, cmdBuffer); + }, nullptr); + } + + void Core::recordBufferMemoryBarrier(const CommandStreamHandle cmdStream, const BufferHandle buffer) { + recordCommandsToStream(cmdStream, [buffer, this](const vk::CommandBuffer cmdBuffer) { + m_BufferManager->recordBufferMemoryBarrier(buffer, cmdBuffer); + }, nullptr); + } + + vk::ImageView Core::getSwapchainImageView() const { + return m_ImageManager->getVulkanImageView(vkcv::ImageHandle::createSwapchainImageHandle()); + } + } diff --git a/src/vkcv/DrawcallRecording.cpp b/src/vkcv/DrawcallRecording.cpp index 85b6eeb5fa413223b7b7f10f77b868252912041b..df7b7bbcb3fe278622cd160593eb750db00ec7b1 100644 --- a/src/vkcv/DrawcallRecording.cpp +++ b/src/vkcv/DrawcallRecording.cpp @@ -23,8 +23,6 @@ namespace vkcv { nullptr); } - cmdBuffer.bindIndexBuffer(drawcall.mesh.indexBuffer, 0, vk::IndexType::eUint16); //FIXME: choose proper size - const size_t drawcallPushConstantOffset = drawcallIndex * pushConstantData.sizePerDrawcall; // char* cast because void* does not support pointer arithmetic const void* drawcallPushConstantData = drawcallPushConstantOffset + (char*)pushConstantData.data; @@ -36,6 +34,12 @@ namespace vkcv { pushConstantData.sizePerDrawcall, drawcallPushConstantData); - cmdBuffer.drawIndexed(drawcall.mesh.indexCount, 1, 0, 0, {}); + if (drawcall.mesh.indexBuffer) { + cmdBuffer.bindIndexBuffer(drawcall.mesh.indexBuffer, 0, vk::IndexType::eUint16); //FIXME: choose proper size + cmdBuffer.drawIndexed(drawcall.mesh.indexCount, 1, 0, 0, {}); + } + else { + cmdBuffer.draw(drawcall.mesh.indexCount, 1, 0, 0, {}); + } } } \ No newline at end of file diff --git a/src/vkcv/Image.cpp b/src/vkcv/Image.cpp index f861daeb1cd7de9697e2f649de444666b8b0e63c..dca6358b84aa7bcd0f38e78d3fa7aa49fd11395d 100644 --- a/src/vkcv/Image.cpp +++ b/src/vkcv/Image.cpp @@ -19,9 +19,17 @@ namespace vkcv{ } } - Image Image::create(ImageManager* manager, vk::Format format, uint32_t width, uint32_t height, uint32_t depth) + Image Image::create( + ImageManager* manager, + vk::Format format, + uint32_t width, + uint32_t height, + uint32_t depth, + uint32_t mipCount, + bool supportStorage, + bool supportColorAttachment) { - return Image(manager, manager->createImage(width, height, depth, format)); + return Image(manager, manager->createImage(width, height, depth, format, mipCount, supportStorage, supportColorAttachment)); } vk::Format Image::getFormat() const { @@ -52,6 +60,10 @@ namespace vkcv{ void Image::fill(void *data, size_t size) { m_manager->fillImage(m_handle, data, size); } + + void Image::generateMipChainImmediate() { + m_manager->generateImageMipChainImmediate(m_handle); + } Image::Image(ImageManager* manager, const ImageHandle& handle) : m_manager(manager), diff --git a/src/vkcv/ImageLayoutTransitions.cpp b/src/vkcv/ImageLayoutTransitions.cpp index cb0f90a79d188cd80a5744d8c6ad7718e542d473..8d31c64ccbcbf33e259714f8c581c920738190b4 100644 --- a/src/vkcv/ImageLayoutTransitions.cpp +++ b/src/vkcv/ImageLayoutTransitions.cpp @@ -15,7 +15,7 @@ namespace vkcv { vk::ImageSubresourceRange imageSubresourceRange( aspectFlags, 0, - image.m_levels, + image.m_viewPerMip.size(), 0, image.m_layers ); diff --git a/src/vkcv/ImageManager.cpp b/src/vkcv/ImageManager.cpp index 1e3d19d02d7e86546d142bb64440364407e81824..dd54da39cfe1d832e006e4f673e6aa8e1eb7ee18 100644 --- a/src/vkcv/ImageManager.cpp +++ b/src/vkcv/ImageManager.cpp @@ -13,25 +13,23 @@ namespace vkcv { ImageManager::Image::Image( - vk::Image handle, - vk::DeviceMemory memory, - vk::ImageView view, - uint32_t width, - uint32_t height, - uint32_t depth, - vk::Format format, - uint32_t layers, - uint32_t levels) + vk::Image handle, + vk::DeviceMemory memory, + std::vector<vk::ImageView> views, + uint32_t width, + uint32_t height, + uint32_t depth, + vk::Format format, + uint32_t layers) : m_handle(handle), m_memory(memory), - m_view(view), + m_viewPerMip(views), m_width(width), m_height(height), m_depth(depth), m_format(format), - m_layers(layers), - m_levels(levels) + m_layers(layers) {} /** @@ -69,6 +67,11 @@ namespace vkcv { for (uint64_t id = 0; id < m_images.size(); id++) { destroyImageById(id); } + for (const auto swapchainImage : m_swapchainImages) { + for (const auto view : swapchainImage.m_viewPerMip) { + m_core->getContext().getDevice().destroy(view); + } + } } bool isDepthImageFormat(vk::Format format) { @@ -81,7 +84,14 @@ namespace vkcv { } } - ImageHandle ImageManager::createImage(uint32_t width, uint32_t height, uint32_t depth, vk::Format format) + ImageHandle ImageManager::createImage( + uint32_t width, + uint32_t height, + uint32_t depth, + vk::Format format, + uint32_t mipCount, + bool supportStorage, + bool supportColorAttachment) { const vk::PhysicalDevice& physicalDevice = m_core->getContext().getPhysicalDevice(); @@ -89,8 +99,14 @@ namespace vkcv { vk::ImageCreateFlags createFlags; vk::ImageUsageFlags imageUsageFlags = ( - vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst + vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eTransferSrc ); + if (supportStorage) { + imageUsageFlags |= vk::ImageUsageFlagBits::eStorage; + } + if (supportColorAttachment) { + imageUsageFlags |= vk::ImageUsageFlagBits::eColorAttachment; + } const bool isDepthFormat = isDepthImageFormat(format); @@ -127,11 +143,9 @@ namespace vkcv { imageTiling = vk::ImageTiling::eLinear; } - const vk::ImageFormatProperties imageFormatProperties = physicalDevice.getImageFormatProperties( - format, imageType, imageTiling, imageUsageFlags - ); + const vk::ImageFormatProperties imageFormatProperties = + physicalDevice.getImageFormatProperties(format, imageType, imageTiling, imageUsageFlags); - const uint32_t mipLevels = std::min<uint32_t>(1, imageFormatProperties.maxMipLevels); const uint32_t arrayLayers = std::min<uint32_t>(1, imageFormatProperties.maxArrayLayers); const vk::ImageCreateInfo imageCreateInfo( @@ -139,7 +153,7 @@ namespace vkcv { imageType, format, vk::Extent3D(width, height, depth), - mipLevels, + mipCount, arrayLayers, vk::SampleCountFlagBits::e1, imageTiling, @@ -172,30 +186,33 @@ namespace vkcv { aspectFlags = vk::ImageAspectFlagBits::eColor; } - const vk::ImageViewCreateInfo imageViewCreateInfo ( + std::vector<vk::ImageView> views; + for (int mip = 0; mip < mipCount; mip++) { + const vk::ImageViewCreateInfo imageViewCreateInfo( {}, image, imageViewType, format, vk::ComponentMapping( - vk::ComponentSwizzle::eIdentity, - vk::ComponentSwizzle::eIdentity, - vk::ComponentSwizzle::eIdentity, - vk::ComponentSwizzle::eIdentity + vk::ComponentSwizzle::eIdentity, + vk::ComponentSwizzle::eIdentity, + vk::ComponentSwizzle::eIdentity, + vk::ComponentSwizzle::eIdentity ), vk::ImageSubresourceRange( - aspectFlags, - 0, - mipLevels, - 0, - arrayLayers + aspectFlags, + mip, + mipCount - mip, + 0, + arrayLayers ) - ); - - vk::ImageView view = device.createImageView(imageViewCreateInfo); + ); + + views.push_back(device.createImageView(imageViewCreateInfo)); + } const uint64_t id = m_images.size(); - m_images.push_back(Image(image, memory, view, width, height, depth, format, arrayLayers, mipLevels)); + m_images.push_back(Image(image, memory, views, width, height, depth, format, arrayLayers)); return ImageHandle(id, [&](uint64_t id) { destroyImageById(id); }); } @@ -204,8 +221,12 @@ namespace vkcv { } vk::Image ImageManager::getVulkanImage(const ImageHandle &handle) const { + + if (handle.isSwapchainImage()) { + m_swapchainImages[m_currentSwapchainInputImage].m_handle; + } + const uint64_t id = handle.getId(); - if (id >= m_images.size()) { vkcv_log(LogLevel::ERROR, "Invalid handle"); return nullptr; @@ -217,8 +238,13 @@ namespace vkcv { } vk::DeviceMemory ImageManager::getVulkanDeviceMemory(const ImageHandle &handle) const { + + if (handle.isSwapchainImage()) { + vkcv_log(LogLevel::ERROR, "Swapchain image has no memory"); + return nullptr; + } + const uint64_t id = handle.getId(); - if (id >= m_images.size()) { vkcv_log(LogLevel::ERROR, "Invalid handle"); return nullptr; @@ -229,34 +255,45 @@ namespace vkcv { return image.m_memory; } - vk::ImageView ImageManager::getVulkanImageView(const ImageHandle &handle) const { - const uint64_t id = handle.getId(); + vk::ImageView ImageManager::getVulkanImageView(const ImageHandle &handle, const size_t mipLevel) const { + if (handle.isSwapchainImage()) { + return m_swapchainImages[m_currentSwapchainInputImage].m_viewPerMip[0]; + } + + const uint64_t id = handle.getId(); if (id >= m_images.size()) { vkcv_log(LogLevel::ERROR, "Invalid handle"); return nullptr; } - auto& image = m_images[id]; - - return image.m_view; + const auto& image = m_images[id]; + + if (mipLevel >= m_images.size()) { + vkcv_log(LogLevel::ERROR, "Image does not have requested mipLevel"); + return nullptr; + } + + return image.m_viewPerMip[mipLevel]; } void ImageManager::switchImageLayoutImmediate(const ImageHandle& handle, vk::ImageLayout newLayout) { - const uint64_t id = handle.getId(); + uint64_t id = handle.getId(); - if (id >= m_images.size()) { + const bool isSwapchainImage = handle.isSwapchainImage(); + + if (id >= m_images.size() && !isSwapchainImage) { vkcv_log(LogLevel::ERROR, "Invalid handle"); return; } - auto& image = m_images[id]; + auto& image = isSwapchainImage ? m_swapchainImages[m_currentSwapchainInputImage] : m_images[id]; const auto transitionBarrier = createImageLayoutTransitionBarrier(image, newLayout); SubmitInfo submitInfo; submitInfo.queueType = QueueType::Graphics; - m_core->recordAndSubmitCommands( + m_core->recordAndSubmitCommandsImmediate( submitInfo, [transitionBarrier](const vk::CommandBuffer& commandBuffer) { // TODO: precise PipelineStageFlagBits, will require a lot of context @@ -279,22 +316,57 @@ namespace vkcv { vk::CommandBuffer cmdBuffer) { const uint64_t id = handle.getId(); + const bool isSwapchainImage = handle.isSwapchainImage(); - if (id >= m_images.size()) { + if (id >= m_images.size() && !isSwapchainImage) { vkcv_log(LogLevel::ERROR, "Invalid handle"); return; } - auto& image = m_images[id]; + auto& image = isSwapchainImage ? m_swapchainImages[m_currentSwapchainInputImage] : m_images[id]; const auto transitionBarrier = createImageLayoutTransitionBarrier(image, newLayout); recordImageBarrier(cmdBuffer, transitionBarrier); image.m_layout = newLayout; } + + void ImageManager::recordImageMemoryBarrier( + const ImageHandle& handle, + vk::CommandBuffer cmdBuffer) { + + const uint64_t id = handle.getId(); + const bool isSwapchainImage = handle.isSwapchainImage(); + + if (id >= m_images.size() && !isSwapchainImage) { + std::cerr << "Error: ImageManager::recordImageMemoryBarrier invalid handle" << std::endl; + return; + } + + auto& image = isSwapchainImage ? m_swapchainImages[m_currentSwapchainInputImage] : m_images[id]; + const auto transitionBarrier = createImageLayoutTransitionBarrier(image, image.m_layout); + recordImageBarrier(cmdBuffer, transitionBarrier); + } + + constexpr uint32_t getChannelsByFormat(vk::Format format) { + switch (format) { + case vk::Format::eR8Unorm: + return 1; + case vk::Format::eR8G8B8A8Srgb: + return 4; + default: + std::cerr << "Check format instead of guessing, please!" << std::endl; + return 4; + } + } void ImageManager::fillImage(const ImageHandle& handle, void* data, size_t size) { const uint64_t id = handle.getId(); + if (handle.isSwapchainImage()) { + vkcv_log(LogLevel::ERROR, "Swapchain image cannot be filled"); + return; + } + if (id >= m_images.size()) { vkcv_log(LogLevel::ERROR, "Invalid handle"); return; @@ -306,7 +378,7 @@ namespace vkcv { handle, vk::ImageLayout::eTransferDstOptimal); - uint32_t channels = 4; // TODO: check image.m_format + uint32_t channels = getChannelsByFormat(image.m_format); const size_t image_size = ( image.m_width * image.m_height * image.m_depth * channels ); @@ -324,7 +396,7 @@ namespace vkcv { SubmitInfo submitInfo; submitInfo.queueType = QueueType::Transfer; - m_core->recordAndSubmitCommands( + m_core->recordAndSubmitCommandsImmediate( submitInfo, [&image, &stagingBuffer](const vk::CommandBuffer& commandBuffer) { vk::ImageAspectFlags aspectFlags; @@ -365,42 +437,113 @@ namespace vkcv { } ); } - + + void ImageManager::generateImageMipChainImmediate(const ImageHandle& handle) { + + const auto& device = m_core->getContext().getDevice(); + + SubmitInfo submitInfo; + submitInfo.queueType = QueueType::Graphics; + + if (handle.isSwapchainImage()) { + vkcv_log(vkcv::LogLevel::ERROR, "You cannot generate a mip chain for the swapchain, what are you smoking?"); + return; + } + + const auto id = handle.getId(); + if (id >= m_images.size()) { + vkcv_log(vkcv::LogLevel::ERROR, "Invalid image handle"); + return; + } + auto& image = m_images[id]; + switchImageLayoutImmediate(handle, vk::ImageLayout::eGeneral); + + const auto record = [&image, this, handle](const vk::CommandBuffer cmdBuffer) { + + vk::ImageAspectFlags aspectMask = isDepthImageFormat(image.m_format) ? + vk::ImageAspectFlagBits::eDepth : vk::ImageAspectFlagBits::eColor; + + uint32_t srcWidth = image.m_width; + uint32_t srcHeight = image.m_height; + uint32_t srcDepth = image.m_depth; + + auto half = [](uint32_t in) { + return std::max<uint32_t>(in / 2, 1); + }; + + uint32_t dstWidth = half(image.m_width); + uint32_t dstHeight = half(image.m_height); + uint32_t dstDepth = half(image.m_depth); + + for (uint32_t srcMip = 0; srcMip < image.m_viewPerMip.size() - 1; srcMip++) { + uint32_t dstMip = srcMip + 1; + vk::ImageBlit region( + vk::ImageSubresourceLayers(aspectMask, srcMip, 0, 1), + { vk::Offset3D(0, 0, 0), vk::Offset3D(srcWidth, srcHeight, srcDepth) }, + vk::ImageSubresourceLayers(aspectMask, dstMip, 0, 1), + { vk::Offset3D(0, 0, 0), vk::Offset3D(dstWidth, dstHeight, dstDepth) }); + + cmdBuffer.blitImage( + image.m_handle, + vk::ImageLayout::eGeneral, + image.m_handle, + vk::ImageLayout::eGeneral, + region, + vk::Filter::eLinear); + + srcWidth = dstWidth; + srcHeight = dstHeight; + srcDepth = dstDepth; + + dstWidth = half(dstWidth); + dstHeight = half(dstHeight); + dstDepth = half(dstDepth); + + recordImageMemoryBarrier(handle, cmdBuffer); + } + }; + + m_core->recordAndSubmitCommandsImmediate(submitInfo, record, nullptr); + } + uint32_t ImageManager::getImageWidth(const ImageHandle &handle) const { const uint64_t id = handle.getId(); - - if (id >= m_images.size()) { + const bool isSwapchainImage = handle.isSwapchainImage(); + + if (id >= m_images.size() && !isSwapchainImage) { vkcv_log(LogLevel::ERROR, "Invalid handle"); return 0; } - auto& image = m_images[id]; + auto& image = isSwapchainImage ? m_swapchainImages[m_currentSwapchainInputImage] : m_images[id]; return image.m_width; } uint32_t ImageManager::getImageHeight(const ImageHandle &handle) const { const uint64_t id = handle.getId(); + const bool isSwapchainImage = handle.isSwapchainImage(); - if (id >= m_images.size()) { + if (id >= m_images.size() && !isSwapchainImage) { vkcv_log(LogLevel::ERROR, "Invalid handle"); return 0; } - auto& image = m_images[id]; + auto& image = isSwapchainImage ? m_swapchainImages[m_currentSwapchainInputImage] : m_images[id]; return image.m_height; } uint32_t ImageManager::getImageDepth(const ImageHandle &handle) const { const uint64_t id = handle.getId(); - - if (id >= m_images.size()) { + const bool isSwapchainImage = handle.isSwapchainImage(); + + if (id >= m_images.size() && !isSwapchainImage) { vkcv_log(LogLevel::ERROR, "Invalid handle"); return 0; } - auto& image = m_images[id]; + auto& image = isSwapchainImage ? m_swapchainImages[m_currentSwapchainInputImage] : m_images[id]; return image.m_depth; } @@ -416,9 +559,11 @@ namespace vkcv { const vk::Device& device = m_core->getContext().getDevice(); - if (image.m_view) { - device.destroyImageView(image.m_view); - image.m_view = nullptr; + for (auto& view : image.m_viewPerMip) { + if (view) { + device.destroyImageView(view); + view = nullptr; + } } if (image.m_memory) { @@ -435,13 +580,35 @@ namespace vkcv { vk::Format ImageManager::getImageFormat(const ImageHandle& handle) const { const uint64_t id = handle.getId(); + const bool isSwapchainFormat = handle.isSwapchainImage(); - if (id >= m_images.size()) { + if (id >= m_images.size() && !isSwapchainFormat) { vkcv_log(LogLevel::ERROR, "Invalid handle"); return vk::Format::eUndefined; } - return m_images[id].m_format; + return isSwapchainFormat ? m_swapchainImages[m_currentSwapchainInputImage].m_format : m_images[id].m_format; + } + + void ImageManager::setCurrentSwapchainImageIndex(int index) { + m_currentSwapchainInputImage = index; + } + + void ImageManager::setSwapchainImages(const std::vector<vk::Image>& images, std::vector<vk::ImageView> views, + uint32_t width, uint32_t height, vk::Format format) { + + // destroy old views + for (auto image : m_swapchainImages) { + for (const auto& view : image.m_viewPerMip) { + m_core->getContext().getDevice().destroyImageView(view); + } + } + + assert(images.size() == views.size()); + m_swapchainImages.clear(); + for (int i = 0; i < images.size(); i++) { + m_swapchainImages.push_back(Image(images[i], nullptr, { views[i] }, width, height, 1, format, 1)); + } } } \ No newline at end of file diff --git a/src/vkcv/ImageManager.hpp b/src/vkcv/ImageManager.hpp index b9fccb25ec16bc1fd9569ab1a94627bd7ff06b18..69ab7943f34bcf3579a4384cbd59e78e5b7aacdf 100644 --- a/src/vkcv/ImageManager.hpp +++ b/src/vkcv/ImageManager.hpp @@ -18,29 +18,29 @@ namespace vkcv { public: struct Image { - vk::Image m_handle; - vk::DeviceMemory m_memory; - vk::ImageView m_view; - uint32_t m_width = 0; - uint32_t m_height = 0; - uint32_t m_depth = 0; - vk::Format m_format; - uint32_t m_layers = 1; - uint32_t m_levels = 1; - vk::ImageLayout m_layout = vk::ImageLayout::eUndefined; + vk::Image m_handle; + vk::DeviceMemory m_memory; + std::vector<vk::ImageView> m_viewPerMip; + uint32_t m_width = 0; + uint32_t m_height = 0; + uint32_t m_depth = 0; + vk::Format m_format; + uint32_t m_layers = 1; + vk::ImageLayout m_layout = vk::ImageLayout::eUndefined; private: // struct is public so utility functions can access members, but only ImageManager can create Image friend ImageManager; Image( - vk::Image handle, - vk::DeviceMemory memory, - vk::ImageView view, - uint32_t width, - uint32_t height, - uint32_t depth, - vk::Format format, - uint32_t layers, - uint32_t levels); + vk::Image handle, + vk::DeviceMemory memory, + std::vector<vk::ImageView> views, + uint32_t width, + uint32_t height, + uint32_t depth, + vk::Format format, + uint32_t layers); + + Image(); }; private: @@ -48,6 +48,8 @@ namespace vkcv { BufferManager& m_bufferManager; std::vector<Image> m_images; + std::vector<Image> m_swapchainImages; + int m_currentSwapchainInputImage; ImageManager(BufferManager& bufferManager) noexcept; @@ -67,7 +69,14 @@ namespace vkcv { ImageManager& operator=(ImageManager&& other) = delete; ImageManager& operator=(const ImageManager& other) = delete; - ImageHandle createImage(uint32_t width, uint32_t height, uint32_t depth, vk::Format format); + ImageHandle createImage( + uint32_t width, + uint32_t height, + uint32_t depth, + vk::Format format, + uint32_t mipCount, + bool supportStorage, + bool supportColorAttachment); ImageHandle createSwapchainImage(); @@ -78,7 +87,7 @@ namespace vkcv { vk::DeviceMemory getVulkanDeviceMemory(const ImageHandle& handle) const; [[nodiscard]] - vk::ImageView getVulkanImageView(const ImageHandle& handle) const; + vk::ImageView getVulkanImageView(const ImageHandle& handle, const size_t mipLevel = 0) const; void switchImageLayoutImmediate(const ImageHandle& handle, vk::ImageLayout newLayout); void recordImageLayoutTransition( @@ -86,7 +95,12 @@ namespace vkcv { vk::ImageLayout newLayout, vk::CommandBuffer cmdBuffer); + void recordImageMemoryBarrier( + const ImageHandle& handle, + vk::CommandBuffer cmdBuffer); + void fillImage(const ImageHandle& handle, void* data, size_t size); + void generateImageMipChainImmediate(const ImageHandle& handle); [[nodiscard]] uint32_t getImageWidth(const ImageHandle& handle) const; @@ -99,5 +113,10 @@ namespace vkcv { [[nodiscard]] vk::Format getImageFormat(const ImageHandle& handle) const; + + void setCurrentSwapchainImageIndex(int index); + void setSwapchainImages(const std::vector<vk::Image>& images, std::vector<vk::ImageView> views, + uint32_t width, uint32_t height, vk::Format format); + }; } \ No newline at end of file diff --git a/src/vkcv/PipelineConfig.cpp b/src/vkcv/PipelineConfig.cpp deleted file mode 100644 index 3bd2a68cb86f167afecc551dbd664dee8a63eb08..0000000000000000000000000000000000000000 --- a/src/vkcv/PipelineConfig.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @authors Mara Vogt, Mark Mints - * @file src/vkcv/Pipeline.cpp - * @brief Pipeline class to handle shader stages - */ - -#include "vkcv/PipelineConfig.hpp" - -namespace vkcv { - - PipelineConfig::PipelineConfig( - const ShaderProgram& shaderProgram, - uint32_t width, - uint32_t height, - const PassHandle &passHandle, - const VertexLayout &vertexLayout, - const std::vector<vk::DescriptorSetLayout> &descriptorLayouts, - bool useDynamicViewport) - : - m_ShaderProgram(shaderProgram), - m_Height(height), - m_Width(width), - m_PassHandle(passHandle), - m_VertexLayout(vertexLayout), - m_DescriptorLayouts(descriptorLayouts), - m_UseDynamicViewport(useDynamicViewport) - {} -} diff --git a/src/vkcv/PipelineManager.cpp b/src/vkcv/PipelineManager.cpp index 81b7525b160374915b1918c30870b05e619a30a4..df36442efc2992bf16b6e82245ef9753dad95e5d 100644 --- a/src/vkcv/PipelineManager.cpp +++ b/src/vkcv/PipelineManager.cpp @@ -7,8 +7,7 @@ namespace vkcv PipelineManager::PipelineManager(vk::Device device) noexcept : m_Device{device}, - m_Pipelines{}, - m_Configs{} + m_Pipelines{} {} PipelineManager::~PipelineManager() noexcept @@ -43,6 +42,15 @@ namespace vkcv } } + vk::PrimitiveTopology primitiveTopologyToVulkanPrimitiveTopology(const PrimitiveTopology topology) { + switch (topology) { + case(PrimitiveTopology::PointList): return vk::PrimitiveTopology::ePointList; + case(PrimitiveTopology::LineList): return vk::PrimitiveTopology::eLineList; + case(PrimitiveTopology::TriangleList): return vk::PrimitiveTopology::eTriangleList; + default: std::cout << "Error: Unknown primitive topology type" << std::endl; return vk::PrimitiveTopology::eTriangleList; + } + } + PipelineHandle PipelineManager::createPipeline(const PipelineConfig &config, PassManager& passManager) { const vk::RenderPass &pass = passManager.getVkPass(config.m_PassHandle); @@ -125,9 +133,9 @@ namespace vkcv // input assembly state vk::PipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateCreateInfo( - {}, - vk::PrimitiveTopology::eTriangleList, - false + {}, + primitiveTopologyToVulkanPrimitiveTopology(config.m_PrimitiveTopology), + false ); // viewport state @@ -149,6 +157,14 @@ namespace vkcv 0.f, 1.f ); + vk::PipelineRasterizationConservativeStateCreateInfoEXT conservativeRasterization; + if (config.m_UseConservativeRasterization) { + conservativeRasterization = vk::PipelineRasterizationConservativeStateCreateInfoEXT( + {}, + vk::ConservativeRasterizationModeEXT::eOverestimate, + 0.f); + pipelineRasterizationStateCreateInfo.pNext = &conservativeRasterization; + } // multisample state vk::PipelineMultisampleStateCreateInfo pipelineMultisampleStateCreateInfo( @@ -239,6 +255,20 @@ namespace vkcv // graphics pipeline create std::vector<vk::PipelineShaderStageCreateInfo> shaderStages = { pipelineVertexShaderStageInfo, pipelineFragmentShaderStageInfo }; + + const char *geometryShaderName = "main"; // outside of if to make sure it stays in scope + vk::ShaderModule geometryModule; + if (config.m_ShaderProgram.existsShader(ShaderStage::GEOMETRY)) { + const vkcv::Shader geometryShader = config.m_ShaderProgram.getShader(ShaderStage::GEOMETRY); + const auto& geometryCode = geometryShader.shaderCode; + const vk::ShaderModuleCreateInfo geometryModuleInfo({}, geometryCode.size(), reinterpret_cast<const uint32_t*>(geometryCode.data())); + if (m_Device.createShaderModule(&geometryModuleInfo, nullptr, &geometryModule) != vk::Result::eSuccess) { + return PipelineHandle(); + } + vk::PipelineShaderStageCreateInfo geometryStage({}, vk::ShaderStageFlagBits::eGeometry, geometryModule, geometryShaderName); + shaderStages.push_back(geometryStage); + } + const vk::GraphicsPipelineCreateInfo graphicsPipelineCreateInfo( {}, static_cast<uint32_t>(shaderStages.size()), @@ -264,15 +294,21 @@ namespace vkcv { m_Device.destroy(vertexModule); m_Device.destroy(fragmentModule); + if (geometryModule) { + m_Device.destroy(geometryModule); + } + m_Device.destroy(); return PipelineHandle(); } m_Device.destroy(vertexModule); m_Device.destroy(fragmentModule); + if (geometryModule) { + m_Device.destroy(geometryModule); + } const uint64_t id = m_Pipelines.size(); - m_Pipelines.push_back({ vkPipeline, vkPipelineLayout }); - m_Configs.push_back(config); + m_Pipelines.push_back({ vkPipeline, vkPipelineLayout, config }); return PipelineHandle(id, [&](uint64_t id) { destroyPipelineById(id); }); } @@ -320,10 +356,17 @@ namespace vkcv } } - const PipelineConfig &PipelineManager::getPipelineConfig(const PipelineHandle &handle) const + const PipelineConfig& PipelineManager::getPipelineConfig(const PipelineHandle &handle) const { const uint64_t id = handle.getId(); - return m_Configs.at(id); + + if (id >= m_Pipelines.size()) { + static PipelineConfig dummyConfig; + vkcv_log(LogLevel::ERROR, "Invalid handle"); + return dummyConfig; + } + + return m_Pipelines[id].m_config; } PipelineHandle PipelineManager::createComputePipeline( @@ -373,7 +416,7 @@ namespace vkcv m_Device.destroy(computeModule); const uint64_t id = m_Pipelines.size(); - m_Pipelines.push_back({ vkPipeline, vkPipelineLayout }); + m_Pipelines.push_back({ vkPipeline, vkPipelineLayout, PipelineConfig() }); return PipelineHandle(id, [&](uint64_t id) { destroyPipelineById(id); }); } diff --git a/src/vkcv/PipelineManager.hpp b/src/vkcv/PipelineManager.hpp index 634f5f4e6464532306e35fd10d9a1623df6ace16..b153eb4632b844e84b92953fe8abf6666a13e0c9 100644 --- a/src/vkcv/PipelineManager.hpp +++ b/src/vkcv/PipelineManager.hpp @@ -14,11 +14,11 @@ namespace vkcv struct Pipeline { vk::Pipeline m_handle; vk::PipelineLayout m_layout; + PipelineConfig m_config; }; vk::Device m_Device; std::vector<Pipeline> m_Pipelines; - std::vector<PipelineConfig> m_Configs; void destroyPipelineById(uint64_t id); diff --git a/src/vkcv/SamplerManager.cpp b/src/vkcv/SamplerManager.cpp index eb44356f2cbee1caaf4cb0635c8c8937890b06f9..a6ebb95b5e237dcd06ed8041b3f16489f7339d6a 100644 --- a/src/vkcv/SamplerManager.cpp +++ b/src/vkcv/SamplerManager.cpp @@ -87,7 +87,7 @@ namespace vkcv { false, vk::CompareOp::eAlways, 0.0f, - 1.0f, + 16.0f, vk::BorderColor::eIntOpaqueBlack, false ); diff --git a/src/vkcv/ShaderProgram.cpp b/src/vkcv/ShaderProgram.cpp index aa945bb18e7cf04513b41510f1ea993a02e1f46d..971797d9a42d071a1730ebf31a0b554f92fa361f 100644 --- a/src/vkcv/ShaderProgram.cpp +++ b/src/vkcv/ShaderProgram.cpp @@ -14,17 +14,21 @@ namespace vkcv { * @param[in] relative path to the shader code * @return vector of chars as a buffer for the code */ - std::vector<char> readShaderCode(const std::filesystem::path &shaderPath) - { - std::ifstream file(shaderPath.string(), std::ios::ate | std::ios::binary); + std::vector<char> readShaderCode(const std::filesystem::path &shaderPath) { + std::ifstream file (shaderPath.string(), std::ios::ate | std::ios::binary); + if (!file.is_open()) { vkcv_log(LogLevel::ERROR, "The file could not be opened"); return std::vector<char>{}; } + size_t fileSize = (size_t)file.tellg(); std::vector<char> buffer(fileSize); + file.seekg(0); file.read(buffer.data(), fileSize); + file.close(); + return buffer; } @@ -209,8 +213,7 @@ namespace vkcv { return m_VertexAttachments; } - const std::vector<std::vector<DescriptorBinding>> &ShaderProgram::getReflectedDescriptors() const - { + const std::vector<std::vector<DescriptorBinding>>& ShaderProgram::getReflectedDescriptors() const { return m_DescriptorSets; } diff --git a/src/vkcv/SwapChain.cpp b/src/vkcv/Swapchain.cpp similarity index 87% rename from src/vkcv/SwapChain.cpp rename to src/vkcv/Swapchain.cpp index b787536b66cfd802dfd435a773a584c875eeb391..33714adac7cec7c1b5e0013387424c4f865454ab 100644 --- a/src/vkcv/SwapChain.cpp +++ b/src/vkcv/Swapchain.cpp @@ -1,4 +1,4 @@ -#include <vkcv/SwapChain.hpp> +#include <vkcv/Swapchain.hpp> #include <utility> #define GLFW_INCLUDE_VULKAN @@ -27,44 +27,44 @@ namespace vkcv return vk::SurfaceKHR(surface); } - SwapChain::SwapChain(const Surface &surface, + Swapchain::Swapchain(const Surface &surface, vk::SwapchainKHR swapchain, vk::Format format, vk::ColorSpaceKHR colorSpace, vk::PresentModeKHR presentMode, uint32_t imageCount, vk::Extent2D extent) noexcept : - m_Surface(surface), - m_Swapchain(swapchain), - m_SwapchainFormat(format), - m_SwapchainColorSpace(colorSpace), - m_SwapchainPresentMode(presentMode), - m_SwapchainImageCount(imageCount), - m_Extent(extent), - m_RecreationRequired(false) + m_Surface(surface), + m_Swapchain(swapchain), + m_Format(format), + m_ColorSpace(colorSpace), + m_PresentMode(presentMode), + m_ImageCount(imageCount), + m_Extent(extent), + m_RecreationRequired(false) {} - SwapChain::SwapChain(const SwapChain &other) : + Swapchain::Swapchain(const Swapchain &other) : m_Surface(other.m_Surface), m_Swapchain(other.m_Swapchain), - m_SwapchainFormat(other.m_SwapchainFormat), - m_SwapchainColorSpace(other.m_SwapchainColorSpace), - m_SwapchainPresentMode(other.m_SwapchainPresentMode), - m_SwapchainImageCount(other.m_SwapchainImageCount), + m_Format(other.m_Format), + m_ColorSpace(other.m_ColorSpace), + m_PresentMode(other.m_PresentMode), + m_ImageCount(other.m_ImageCount), m_Extent(other.m_Extent), m_RecreationRequired(other.m_RecreationRequired.load()) {} - const vk::SwapchainKHR& SwapChain::getSwapchain() const { + const vk::SwapchainKHR& Swapchain::getSwapchain() const { return m_Swapchain; } - vk::SurfaceKHR SwapChain::getSurface() const { + vk::SurfaceKHR Swapchain::getSurface() const { return m_Surface.handle; } - vk::Format SwapChain::getSwapchainFormat() const{ - return m_SwapchainFormat; + vk::Format Swapchain::getFormat() const{ + return m_Format; } /** @@ -162,7 +162,7 @@ namespace vkcv * @param context that keeps instance, physicalDevice and a device. * @return swapchain */ - SwapChain SwapChain::create(const Window &window, const Context &context) { + Swapchain Swapchain::create(const Window &window, const Context &context) { const vk::Instance& instance = context.getInstance(); const vk::PhysicalDevice& physicalDevice = context.getPhysicalDevice(); const vk::Device& device = context.getDevice(); @@ -186,7 +186,7 @@ namespace vkcv chosenSurfaceFormat.colorSpace, // imageColorSpace chosenExtent, // imageExtent 1, // imageArrayLayers TODO: should we only allow non-stereoscopic applications? yes -> 1, no -> ? "must be greater than 0, less or equal to maxImageArrayLayers" - vk::ImageUsageFlagBits::eColorAttachment, // imageUsage TODO: what attachments? only color? depth? + vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eStorage, // imageUsage TODO: what attachments? only color? depth? vk::SharingMode::eExclusive, // imageSharingMode TODO: which sharing mode? "VK_SHARING_MODE_EXCLUSIV access exclusive to a single queue family, better performance", "VK_SHARING_MODE_CONCURRENT access from multiple queues" 0, // queueFamilyIndexCount, the number of queue families having access to the image(s) of the swapchain when imageSharingMode is VK_SHARING_MODE_CONCURRENT nullptr, // pQueueFamilyIndices, the pointer to an array of queue family indices having access to the images(s) of the swapchain when imageSharingMode is VK_SHARING_MODE_CONCURRENT @@ -199,7 +199,7 @@ namespace vkcv vk::SwapchainKHR swapchain = device.createSwapchainKHR(swapchainCreateInfo); - return SwapChain(surface, + return Swapchain(surface, swapchain, chosenSurfaceFormat.format, chosenSurfaceFormat.colorSpace, @@ -208,11 +208,11 @@ namespace vkcv chosenExtent); } - bool SwapChain::shouldUpdateSwapchain() const { + bool Swapchain::shouldUpdateSwapchain() const { return m_RecreationRequired; } - void SwapChain::updateSwapchain(const Context &context, const Window &window) { + void Swapchain::updateSwapchain(const Context &context, const Window &window) { if (!m_RecreationRequired.exchange(false)) return; @@ -222,18 +222,18 @@ namespace vkcv vk::SwapchainCreateInfoKHR swapchainCreateInfo( vk::SwapchainCreateFlagsKHR(), m_Surface.handle, - m_SwapchainImageCount, - m_SwapchainFormat, - m_SwapchainColorSpace, + m_ImageCount, + m_Format, + m_ColorSpace, extent2D, 1, - vk::ImageUsageFlagBits::eColorAttachment, + vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eStorage, vk::SharingMode::eExclusive, 0, nullptr, vk::SurfaceTransformFlagBitsKHR::eIdentity, vk::CompositeAlphaFlagBitsKHR::eOpaque, - m_SwapchainPresentMode, + m_PresentMode, true, oldSwapchain ); @@ -244,19 +244,19 @@ namespace vkcv m_Extent = extent2D; } - void SwapChain::signalSwapchainRecreation() { + void Swapchain::signalSwapchainRecreation() { m_RecreationRequired = true; } - const vk::Extent2D& SwapChain::getExtent() const { + const vk::Extent2D& Swapchain::getExtent() const { return m_Extent; } - SwapChain::~SwapChain() { + Swapchain::~Swapchain() { // needs to be destroyed by creator } - uint32_t SwapChain::getImageCount() { - return m_SwapchainImageCount; + uint32_t Swapchain::getImageCount() const { + return m_ImageCount; } } diff --git a/src/vkcv/Window.cpp b/src/vkcv/Window.cpp index c21271b78f7501721d5c0496d0344dd68e2e7e52..53761e12caa234a6c465d640cc178e5ac36134cd 100644 --- a/src/vkcv/Window.cpp +++ b/src/vkcv/Window.cpp @@ -5,64 +5,87 @@ */ #include <GLFW/glfw3.h> - #include "vkcv/Window.hpp" namespace vkcv { - static uint32_t s_WindowCount = 0; + static std::vector<GLFWwindow*> s_Windows; Window::Window(GLFWwindow *window) : m_window(window) { + glfwSetWindowUserPointer(m_window, this); + + this->e_mouseButton.lock(); + this->e_mouseMove.lock(); + this->e_resize.lock(); + this->e_key.lock(); + this->e_mouseScroll.lock(); + + // combine Callbacks with Events + glfwSetMouseButtonCallback(m_window, Window::onMouseButtonEvent); + glfwSetCursorPosCallback(m_window, Window::onMouseMoveEvent); + glfwSetWindowSizeCallback(m_window, Window::onResize); + glfwSetKeyCallback(m_window, Window::onKeyEvent); + glfwSetScrollCallback(m_window, Window::onMouseScrollEvent); + glfwSetCharCallback(m_window, Window::onCharEvent); + + glfwSetJoystickCallback(Window::onGamepadConnection); + glfwSetJoystickUserPointer(GLFW_JOYSTICK_1, this); } Window::~Window() { + s_Windows.erase(std::find(s_Windows.begin(), s_Windows.end(), m_window)); glfwDestroyWindow(m_window); - s_WindowCount--; - if(s_WindowCount == 0) { + if(s_Windows.empty()) { glfwTerminate(); } } Window Window::create( const char *windowTitle, int width, int height, bool resizable) { - if(s_WindowCount == 0) { - glfwInit(); - } - s_WindowCount++; - - width = std::max(width, 1); - height = std::max(height, 1); - - glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - glfwWindowHint(GLFW_RESIZABLE, resizable ? GLFW_TRUE : GLFW_FALSE); - GLFWwindow *window; - window = glfwCreateWindow(width, height, windowTitle, nullptr, nullptr); - - return Window(window); - } - - void Window::initEvents() { - glfwSetWindowUserPointer(m_window, this); - - // combine Callbacks with Events - glfwSetMouseButtonCallback(m_window, Window::onMouseButtonEvent); - - glfwSetCursorPosCallback(m_window, Window::onMouseMoveEvent); - - glfwSetWindowSizeCallback(m_window, Window::onResize); - - glfwSetKeyCallback(m_window, Window::onKeyEvent); - - glfwSetScrollCallback(m_window, Window::onMouseScrollEvent); + if(s_Windows.empty()) { + glfwInit(); + } + + width = std::max(width, 1); + height = std::max(height, 1); + + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + glfwWindowHint(GLFW_RESIZABLE, resizable ? GLFW_TRUE : GLFW_FALSE); + GLFWwindow *window = glfwCreateWindow(width, height, windowTitle, nullptr, nullptr); + + s_Windows.push_back(window); + + return Window(window); } void Window::pollEvents() { + onGamepadEvent(GLFW_JOYSTICK_1); + + for (auto glfwWindow : s_Windows) { + auto window = static_cast<Window *>(glfwGetWindowUserPointer(glfwWindow)); + + window->e_mouseButton.unlock(); + window->e_mouseMove.unlock(); + window->e_resize.unlock(); + window->e_key.unlock(); + window->e_mouseScroll.unlock(); + } + glfwPollEvents(); + + for (auto glfwWindow : s_Windows) { + auto window = static_cast<Window *>(glfwGetWindowUserPointer(glfwWindow)); + + window->e_mouseButton.lock(); + window->e_mouseMove.lock(); + window->e_resize.lock(); + window->e_key.lock(); + window->e_mouseScroll.lock(); + } } void Window::onMouseButtonEvent(GLFWwindow *callbackWindow, int button, int action, int mods) { - auto window = static_cast<Window *>(glfwGetWindowUserPointer(callbackWindow)); if (window != nullptr) { @@ -71,7 +94,6 @@ namespace vkcv { } void Window::onMouseMoveEvent(GLFWwindow *callbackWindow, double x, double y) { - auto window = static_cast<Window *>(glfwGetWindowUserPointer(callbackWindow)); if (window != nullptr) { @@ -88,7 +110,6 @@ namespace vkcv { } void Window::onResize(GLFWwindow *callbackWindow, int width, int height) { - auto window = static_cast<Window *>(glfwGetWindowUserPointer(callbackWindow)); if (window != nullptr) { @@ -97,13 +118,38 @@ namespace vkcv { } void Window::onKeyEvent(GLFWwindow *callbackWindow, int key, int scancode, int action, int mods) { - auto window = static_cast<Window *>(glfwGetWindowUserPointer(callbackWindow)); if (window != nullptr) { window->e_key(key, scancode, action, mods); } } + + void Window::onCharEvent(GLFWwindow *callbackWindow, unsigned int c) { + auto window = static_cast<Window *>(glfwGetWindowUserPointer(callbackWindow)); + + if (window != nullptr) { + window->e_char(c); + } + } + + void Window::onGamepadConnection(int gamepadIndex, int gamepadEvent) { + if (gamepadEvent == GLFW_CONNECTED) { + auto window = static_cast<Window *>(glfwGetWindowUserPointer(s_Windows[0])); // todo check for correct window + + if (window != nullptr) { + glfwSetJoystickUserPointer(gamepadIndex, window); + } + } + } + + void Window::onGamepadEvent(int gamepadIndex) { + auto window = static_cast<Window *>(glfwGetJoystickUserPointer(gamepadIndex)); + + if ( window != nullptr && glfwJoystickPresent(gamepadIndex)) { + window->e_gamepad(gamepadIndex); + } + } bool Window::isWindowOpen() const { return !glfwWindowShouldClose(m_window); @@ -124,4 +170,4 @@ namespace vkcv { GLFWwindow *Window::getWindow() const { return m_window; } -} \ No newline at end of file +}