diff --git a/01_HelloCoreSystemAsset/main.cpp b/01_HelloCoreSystemAsset/main.cpp index 6a9188344..7ca4badb4 100644 --- a/01_HelloCoreSystemAsset/main.cpp +++ b/01_HelloCoreSystemAsset/main.cpp @@ -2,8 +2,8 @@ // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h -// always include nabla first before std:: headers -#include "nabla.h" +// public interface and common examples API, always include first before std:: headers +#include "nbl/examples/examples.hpp" #include "nbl/system/IApplicationFramework.h" diff --git a/02_HelloCompute/main.cpp b/02_HelloCompute/main.cpp index 124cd7dc5..32812fb1a 100644 --- a/02_HelloCompute/main.cpp +++ b/02_HelloCompute/main.cpp @@ -94,9 +94,9 @@ class HelloComputeApp final : public nbl::application_templates::MonoSystemMonoL // The convention is that an `ICPU` object represents a potentially Mutable (and in the past, Serializable) recipe for creating an `IGPU` object, and later examples will show automated systems for doing that. // The Assets always form a Directed Acyclic Graph and our type system enforces that property at compile time (i.e. an `IBuffer` cannot reference an `IImageView` even indirectly). // Another reason for the 1:1 pairing of types is that one can use a CPU-to-GPU associative cache (asset manager has a default one) and use the pointers to the CPU objects as UUIDs. - // The ICPUShader is just a mutable container for source code (can be high level like HLSL needing compilation to SPIR-V or SPIR-V itself) held in an `nbl::asset::ICPUBuffer`. + // The IShader is just a mutable container for source code (can be high level like HLSL needing compilation to SPIR-V or SPIR-V itself) held in an `nbl::asset::ICPUBuffer`. // They can be created: from buffers of code, by compilation from some other source code, or loaded from files (next example will do that). - smart_refctd_ptr cpuShader; + smart_refctd_ptr cpuShader; { // Normally we'd use the ISystem and the IAssetManager to load shaders flexibly from (virtual) files for ease of development (syntax highlighting and Intellisense), // but I want to show the full process of assembling a shader from raw source code at least once. @@ -138,7 +138,7 @@ class HelloComputeApp final : public nbl::application_templates::MonoSystemMonoL } // Note how each ILogicalDevice method takes a smart-pointer r-value, so that the GPU objects refcount their dependencies - smart_refctd_ptr shader = device->createShader(cpuShader.get()); + smart_refctd_ptr shader = device->compileShader({.source = cpuShader.get()}); if (!shader) return logFail("Failed to create a GPU Shader, seems the Driver doesn't like the SPIR-V we're feeding it!\n"); diff --git a/03_DeviceSelectionAndSharedSources/Testers.h b/03_DeviceSelectionAndSharedSources/Testers.h index a76d4b668..f957e50a0 100644 --- a/03_DeviceSelectionAndSharedSources/Testers.h +++ b/03_DeviceSelectionAndSharedSources/Testers.h @@ -4,8 +4,7 @@ #ifndef _NBL_TESTERS_H_INCLUDED_ #define _NBL_TESTERS_H_INCLUDED_ -#include "nbl/application_templates/MonoDeviceApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" +#include "nbl/examples/examples.hpp" using namespace nbl; @@ -24,7 +23,7 @@ class IntrospectionTesterBase const std::string m_functionToTestName = ""; protected: - static std::pair, smart_refctd_ptr> compileHLSLShaderAndTestIntrospection( + static std::pair, smart_refctd_ptr> compileHLSLShaderAndTestIntrospection( video::IPhysicalDevice* physicalDevice, video::ILogicalDevice* device, system::ILogger* logger, asset::IAssetManager* assetMgr, const std::string& shaderPath, CSPIRVIntrospector& introspector) { IAssetLoader::SAssetLoadParams lp = {}; @@ -33,15 +32,18 @@ class IntrospectionTesterBase // this time we load a shader directly from a file auto assetBundle = assetMgr->getAsset(shaderPath, lp); const auto assets = assetBundle.getContents(); - if (assets.empty()) + const auto* metadata = assetBundle.getMetadata(); + if (assets.empty() || assetBundle.getAssetType() != IAsset::ET_SHADER) { logFail(logger, "Could not load shader!"); assert(0); } + const auto hlslMetadata = static_cast(metadata); + const auto shaderStage = hlslMetadata->shaderStages->front(); // It would be super weird if loading a shader from a file produced more than 1 asset assert(assets.size() == 1); - smart_refctd_ptr source = IAsset::castDown(assets[0]); + smart_refctd_ptr source = IAsset::castDown(assets[0]); smart_refctd_ptr introspection; { @@ -53,7 +55,7 @@ class IntrospectionTesterBase // The Shader Asset Loaders deduce the stage from the file extension, // if the extension is generic (.glsl or .hlsl) the stage is unknown. // But it can still be overriden from within the source with a `#pragma shader_stage` - options.stage = source->getStage() == IShader::E_SHADER_STAGE::ESS_COMPUTE ? source->getStage() : IShader::E_SHADER_STAGE::ESS_VERTEX; // TODO: do smth with it + options.stage = shaderStage == IShader::E_SHADER_STAGE::ESS_COMPUTE ? shaderStage : IShader::E_SHADER_STAGE::ESS_VERTEX; // TODO: do smth with it options.targetSpirvVersion = device->getPhysicalDevice()->getLimits().spirvVersion; // we need to perform an unoptimized compilation with source debug info or we'll lose names of variable sin the introspection options.spirvOptimizer = nullptr; @@ -186,7 +188,7 @@ class PredefinedLayoutTester final : public IntrospectionTesterBase constexpr uint32_t MERGE_TEST_SHADERS_CNT = mergeTestShadersPaths.size(); CSPIRVIntrospector introspector[MERGE_TEST_SHADERS_CNT]; - smart_refctd_ptr sources[MERGE_TEST_SHADERS_CNT]; + smart_refctd_ptr sources[MERGE_TEST_SHADERS_CNT]; for (uint32_t i = 0u; i < MERGE_TEST_SHADERS_CNT; ++i) { @@ -201,7 +203,7 @@ class PredefinedLayoutTester final : public IntrospectionTesterBase .binding = 0, .type = nbl::asset::IDescriptor::E_TYPE::ET_STORAGE_BUFFER, .createFlags = ICPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, - .stageFlags = ICPUShader::E_SHADER_STAGE::ESS_COMPUTE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, .count = 1, .immutableSamplers = nullptr } @@ -213,7 +215,7 @@ class PredefinedLayoutTester final : public IntrospectionTesterBase .binding = 0, .type = nbl::asset::IDescriptor::E_TYPE::ET_STORAGE_BUFFER, .createFlags = ICPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, - .stageFlags = ICPUShader::E_SHADER_STAGE::ESS_COMPUTE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, .count = 1, .immutableSamplers = nullptr }, @@ -221,7 +223,7 @@ class PredefinedLayoutTester final : public IntrospectionTesterBase .binding = 1, .type = nbl::asset::IDescriptor::E_TYPE::ET_STORAGE_BUFFER, .createFlags = ICPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, - .stageFlags = ICPUShader::E_SHADER_STAGE::ESS_COMPUTE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, .count = 2, .immutableSamplers = nullptr } @@ -251,9 +253,9 @@ class PredefinedLayoutTester final : public IntrospectionTesterBase bool pplnCreationSuccess[MERGE_TEST_SHADERS_CNT]; for (uint32_t i = 0u; i < MERGE_TEST_SHADERS_CNT; ++i) { - ICPUShader::SSpecInfo specInfo; + ICPUPipelineBase::SShaderSpecInfo specInfo; specInfo.entryPoint = "main"; - specInfo.shader = sources[i].get(); + specInfo.shader = sources[i]; pplnCreationSuccess[i] = static_cast(introspector[i].createApproximateComputePipelineFromIntrospection(specInfo, core::smart_refctd_ptr(predefinedPplnLayout))); } diff --git a/03_DeviceSelectionAndSharedSources/main.cpp b/03_DeviceSelectionAndSharedSources/main.cpp index be56791a1..c09228ce5 100644 --- a/03_DeviceSelectionAndSharedSources/main.cpp +++ b/03_DeviceSelectionAndSharedSources/main.cpp @@ -2,15 +2,20 @@ // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h -#include "nbl/application_templates/MonoDeviceApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" -#include "CommonPCH/PCH.hpp" + +#include "nbl/examples/examples.hpp" +// TODO: why isn't this in `nabla.h` ? +#include "nbl/asset/metadata/CHLSLMetadata.h" + using namespace nbl; -using namespace core; -using namespace system; -using namespace asset; -using namespace video; +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::examples; // TODO[Przemek]: update comments @@ -21,10 +26,10 @@ using namespace video; constexpr bool ENABLE_TESTS = false; // This time we create the device in the base class and also use a base class to give us an Asset Manager and an already mounted built-in resource archive -class DeviceSelectionAndSharedSourcesApp final : public application_templates::MonoDeviceApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +class DeviceSelectionAndSharedSourcesApp final : public application_templates::MonoDeviceApplication, public BuiltinResourcesApplication { using device_base_t = application_templates::MonoDeviceApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using asset_base_t = BuiltinResourcesApplication; public: // Yay thanks to multiple inheritance we cannot forward ctors anymore DeviceSelectionAndSharedSourcesApp(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) : @@ -60,9 +65,9 @@ class DeviceSelectionAndSharedSourcesApp final : public application_templates::M //shaderIntrospection->debugPrint(m_logger.get()); // We've now skipped the manual creation of a descriptor set layout, pipeline layout - ICPUShader::SSpecInfo specInfo; + ICPUPipelineBase::SShaderSpecInfo specInfo; specInfo.entryPoint = "main"; - specInfo.shader = source.get(); + specInfo.shader = source; smart_refctd_ptr cpuPipeline = introspector.createApproximateComputePipelineFromIntrospection(specInfo); @@ -236,7 +241,7 @@ class DeviceSelectionAndSharedSourcesApp final : public application_templates::M // Whether to keep invoking the above. In this example because its headless GPU compute, we do all the work in the app initialization. bool keepRunning() override { return false; } - std::pair, smart_refctd_ptr> compileShaderAndTestIntrospection( + std::pair, smart_refctd_ptr> compileShaderAndTestIntrospection( const std::string& shaderPath, CSPIRVIntrospector& introspector) { IAssetLoader::SAssetLoadParams lp = {}; @@ -245,15 +250,19 @@ class DeviceSelectionAndSharedSourcesApp final : public application_templates::M // this time we load a shader directly from a file auto assetBundle = m_assetMgr->getAsset(shaderPath, lp); const auto assets = assetBundle.getContents(); - if (assets.empty()) + if (assets.empty() || assetBundle.getAssetType() != IAsset::ET_SHADER) { logFail("Could not load shader!"); assert(0); } + const auto* metadata = assetBundle.getMetadata(); + const auto hlslMetadata = static_cast(metadata); + const auto shaderStage = hlslMetadata->shaderStages->front(); + // It would be super weird if loading a shader from a file produced more than 1 asset assert(assets.size() == 1); - smart_refctd_ptr source = IAsset::castDown(assets[0]); + smart_refctd_ptr source = IAsset::castDown(assets[0]); smart_refctd_ptr introspection; { @@ -265,7 +274,7 @@ class DeviceSelectionAndSharedSourcesApp final : public application_templates::M // The Shader Asset Loaders deduce the stage from the file extension, // if the extension is generic (.glsl or .hlsl) the stage is unknown. // But it can still be overriden from within the source with a `#pragma shader_stage` - options.stage = source->getStage() == IShader::E_SHADER_STAGE::ESS_COMPUTE ? source->getStage() : IShader::E_SHADER_STAGE::ESS_VERTEX; // TODO: do smth with it + options.stage = shaderStage == IShader::E_SHADER_STAGE::ESS_COMPUTE ? shaderStage : IShader::E_SHADER_STAGE::ESS_VERTEX; // TODO: do smth with it options.targetSpirvVersion = m_device->getPhysicalDevice()->getLimits().spirvVersion; // we need to perform an unoptimized compilation with source debug info or we'll lose names of variable sin the introspection options.spirvOptimizer = nullptr; @@ -277,7 +286,7 @@ class DeviceSelectionAndSharedSourcesApp final : public application_templates::M options.preprocessorOptions.includeFinder = compilerSet->getShaderCompiler(source->getContentType())->getDefaultIncludeFinder(); auto spirvUnspecialized = compilerSet->compileToSPIRV(source.get(), options); - const CSPIRVIntrospector::CStageIntrospectionData::SParams inspctParams = { .entryPoint = "main", .shader = spirvUnspecialized }; + const CSPIRVIntrospector::CStageIntrospectionData::SParams inspctParams = { .entryPoint = "main", .shader = spirvUnspecialized, .stage = shaderStage }; introspection = introspector.introspect(inspctParams); introspection->debugPrint(m_logger.get()); diff --git a/05_StreamingAndBufferDeviceAddressApp/app_resources/shader.comp.hlsl b/05_StreamingAndBufferDeviceAddressApp/app_resources/shader.comp.hlsl index 4aeef0e0f..af38ffada 100644 --- a/05_StreamingAndBufferDeviceAddressApp/app_resources/shader.comp.hlsl +++ b/05_StreamingAndBufferDeviceAddressApp/app_resources/shader.comp.hlsl @@ -10,6 +10,7 @@ template void dummyTraitTest() {} [numthreads(WorkgroupSize,1,1)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { dummyTraitTest(); diff --git a/05_StreamingAndBufferDeviceAddressApp/main.cpp b/05_StreamingAndBufferDeviceAddressApp/main.cpp index e8f7dbd33..a648acefb 100644 --- a/05_StreamingAndBufferDeviceAddressApp/main.cpp +++ b/05_StreamingAndBufferDeviceAddressApp/main.cpp @@ -5,7 +5,7 @@ // I've moved out a tiny part of this example into a shared header for reuse, please open and read it. #include "nbl/application_templates/MonoDeviceApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" +#include "nbl/examples/common/BuiltinResourcesApplication.hpp" using namespace nbl; @@ -20,10 +20,10 @@ using namespace video; // In this application we'll cover buffer streaming, Buffer Device Address (BDA) and push constants -class StreamingAndBufferDeviceAddressApp final : public application_templates::MonoDeviceApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +class StreamingAndBufferDeviceAddressApp final : public application_templates::MonoDeviceApplication, public examples::BuiltinResourcesApplication { using device_base_t = application_templates::MonoDeviceApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using asset_base_t = examples::BuiltinResourcesApplication; // This is the first example that submits multiple workloads in-flight. // What the shader does is it computes the minimum distance of each point against K other random input points. @@ -91,7 +91,7 @@ class StreamingAndBufferDeviceAddressApp final : public application_templates::M return false; // this time we load a shader directly from a file - smart_refctd_ptr shader; + smart_refctd_ptr shader; { IAssetLoader::SAssetLoadParams lp = {}; lp.logger = m_logger.get(); @@ -102,14 +102,10 @@ class StreamingAndBufferDeviceAddressApp final : public application_templates::M return logFail("Could not load shader!"); // lets go straight from ICPUSpecializedShader to IGPUSpecializedShader - auto source = IAsset::castDown(assets[0]); + const auto shaderSource = IAsset::castDown(assets[0]); + shader = m_device->compileShader({shaderSource.get()}); // The down-cast should not fail! - assert(source); - - // this time we skip the use of the asset converter since the ICPUShader->IGPUShader path is quick and simple - shader = m_device->createShader(source.get()); - if (!shader) - return logFail("Creation of a GPU Shader to from CPU Shader source failed!"); + assert(shader); } // The StreamingTransientDataBuffers are actually composed on top of another useful utility called `CAsyncSingleBufferSubAllocator` @@ -139,6 +135,7 @@ class StreamingAndBufferDeviceAddressApp final : public application_templates::M IGPUComputePipeline::SCreationParams params = {}; params.layout = layout.get(); params.shader.shader = shader.get(); + params.shader.entryPoint = "main"; if (!m_device->createComputePipelines(nullptr,{¶ms,1},&m_pipeline)) return logFail("Failed to create compute pipeline!\n"); } diff --git a/06_HelloGraphicsQueue/main.cpp b/06_HelloGraphicsQueue/main.cpp index dc2f3ebb4..07d6affd3 100644 --- a/06_HelloGraphicsQueue/main.cpp +++ b/06_HelloGraphicsQueue/main.cpp @@ -3,18 +3,20 @@ // For conditions of distribution and use, see copyright notice in nabla.h -// I've moved out a tiny part of this example into a shared header for reuse, please open and read it. -#include "nbl/application_templates/MonoDeviceApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" +#include "nbl/examples/examples.hpp" #include "nbl/ext/ScreenShot/ScreenShot.h" using namespace nbl; -using namespace core; -using namespace system; -using namespace asset; -using namespace video; +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::examples; + // Here we showcase the use of Graphics Queue only // Steps we take in this example: @@ -26,10 +28,10 @@ using namespace video; // - save the smallImg to disk // // all without using IUtilities. -class HelloGraphicsQueueApp final : public application_templates::MonoDeviceApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +class HelloGraphicsQueueApp final : public application_templates::MonoDeviceApplication, public BuiltinResourcesApplication { using device_base_t = application_templates::MonoDeviceApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using asset_base_t = BuiltinResourcesApplication; public: // Yay thanks to multiple inheritance we cannot forward ctors anymore. diff --git a/06_MeshLoaders/CMakeLists.txt b/06_MeshLoaders/CMakeLists.txt deleted file mode 100644 index 2f9218f93..000000000 --- a/06_MeshLoaders/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -include(common RESULT_VARIABLE RES) -if(NOT RES) - message(FATAL_ERROR "common.cmake not found. Should be in {repo_root}/cmake directory") -endif() - -nbl_create_executable_project("" "" "" "" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") \ No newline at end of file diff --git a/06_MeshLoaders/main.cpp b/06_MeshLoaders/main.cpp deleted file mode 100644 index 75135c033..000000000 --- a/06_MeshLoaders/main.cpp +++ /dev/null @@ -1,563 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -#define _NBL_STATIC_LIB_ -#include -#include -#include - -#include "CCamera.hpp" -#include "../common/CommonAPI.h" -#include "nbl/ext/ScreenShot/ScreenShot.h" - -using namespace nbl; -using namespace core; -using namespace ui; -/* - Uncomment for more detailed logging -*/ - -// #define NBL_MORE_LOGS - -class MeshLoadersApp : public ApplicationBase -{ - constexpr static uint32_t WIN_W = 1280; - constexpr static uint32_t WIN_H = 720; - constexpr static uint32_t SC_IMG_COUNT = 3u; - constexpr static uint32_t FRAMES_IN_FLIGHT = 5u; - constexpr static uint64_t MAX_TIMEOUT = 99999999999999ull; - constexpr static size_t NBL_FRAMES_TO_AVERAGE = 100ull; - - static_assert(FRAMES_IN_FLIGHT > SC_IMG_COUNT); -public: - nbl::core::smart_refctd_ptr windowManager; - nbl::core::smart_refctd_ptr window; - nbl::core::smart_refctd_ptr windowCb; - nbl::core::smart_refctd_ptr apiConnection; - nbl::core::smart_refctd_ptr surface; - nbl::core::smart_refctd_ptr utilities; - nbl::core::smart_refctd_ptr logicalDevice; - nbl::video::IPhysicalDevice* physicalDevice; - std::array queues; - nbl::core::smart_refctd_ptr swapchain; - nbl::core::smart_refctd_ptr renderpass; - nbl::core::smart_refctd_dynamic_array> fbo; - std::array, CommonAPI::InitOutput::MaxFramesInFlight>, CommonAPI::InitOutput::MaxQueuesCount> commandPools; - nbl::core::smart_refctd_ptr system; - nbl::core::smart_refctd_ptr assetManager; - nbl::video::IGPUObjectFromAssetConverter::SParams cpu2gpuParams; - nbl::core::smart_refctd_ptr logger; - nbl::core::smart_refctd_ptr inputSystem; - - nbl::video::IGPUObjectFromAssetConverter cpu2gpu; - - video::IDeviceMemoryBacked::SDeviceMemoryRequirements ubomemreq; - core::smart_refctd_ptr gpuubo; - core::smart_refctd_ptr gpuds1; - - core::smart_refctd_ptr occlusionQueryPool; - core::smart_refctd_ptr timestampQueryPool; - - asset::ICPUMesh* meshRaw = nullptr; - const asset::COBJMetadata* metaOBJ = nullptr; - - core::smart_refctd_ptr frameComplete[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr imageAcquire[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr renderFinished[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr commandBuffers[FRAMES_IN_FLIGHT]; - - CommonAPI::InputSystem::ChannelReader mouse; - CommonAPI::InputSystem::ChannelReader keyboard; - Camera camera = Camera(vectorSIMDf(0, 0, 0), vectorSIMDf(0, 0, 0), matrix4SIMD()); - - using RENDERPASS_INDEPENDENT_PIPELINE_ADRESS = size_t; - std::map> gpuPipelines; - core::smart_refctd_ptr gpumesh; - const asset::ICPUMeshBuffer* firstMeshBuffer; - const nbl::asset::COBJMetadata::CRenderpassIndependentPipeline* pipelineMetadata; - nbl::video::ISwapchain::SCreationParams m_swapchainCreationParams; - - uint32_t ds1UboBinding = 0; - int resourceIx; - uint32_t acquiredNextFBO = {}; - std::chrono::steady_clock::time_point lastTime; - bool frameDataFilled = false; - size_t frame_count = 0ull; - double time_sum = 0; - double dtList[NBL_FRAMES_TO_AVERAGE] = {}; - - video::CDumbPresentationOracle oracle; - - core::smart_refctd_ptr queryResultsBuffer; - - void setWindow(core::smart_refctd_ptr&& wnd) override - { - window = std::move(wnd); - } - void setSystem(core::smart_refctd_ptr&& s) override - { - system = std::move(s); - } - nbl::ui::IWindow* getWindow() override - { - return window.get(); - } - video::IAPIConnection* getAPIConnection() override - { - return apiConnection.get(); - } - video::ILogicalDevice* getLogicalDevice() override - { - return logicalDevice.get(); - } - video::IGPURenderpass* getRenderpass() override - { - return renderpass.get(); - } - void setSurface(core::smart_refctd_ptr&& s) override - { - surface = std::move(s); - } - void setFBOs(std::vector>& f) override - { - for (int i = 0; i < f.size(); i++) - { - fbo->begin()[i] = core::smart_refctd_ptr(f[i]); - } - } - void setSwapchain(core::smart_refctd_ptr&& s) override - { - swapchain = std::move(s); - } - uint32_t getSwapchainImageCount() override - { - return swapchain->getImageCount(); - } - virtual nbl::asset::E_FORMAT getDepthFormat() override - { - return nbl::asset::EF_D32_SFLOAT; - } - - void getAndLogQueryPoolResults() - { -#ifdef QUERY_POOL_LOGS - { - uint64_t samples_passed[4] = {}; - auto queryResultFlags = core::bitflag(video::IQueryPool::EQRF_WITH_AVAILABILITY_BIT) | video::IQueryPool::EQRF_64_BIT; - logicalDevice->getQueryPoolResults(occlusionQueryPool.get(), 0u, 2u, sizeof(samples_passed), samples_passed, sizeof(uint64_t) * 2, queryResultFlags); - logger->log("[AVAIL+64] SamplesPassed[0] = %d, SamplesPassed[1] = %d, Result Available = %d, %d", system::ILogger::ELL_INFO, samples_passed[0], samples_passed[2], samples_passed[1], samples_passed[3]); - } - { - uint64_t samples_passed[4] = {}; - auto queryResultFlags = core::bitflag(video::IQueryPool::EQRF_WITH_AVAILABILITY_BIT) | video::IQueryPool::EQRF_64_BIT | video::IQueryPool::EQRF_WAIT_BIT; - logicalDevice->getQueryPoolResults(occlusionQueryPool.get(), 0u, 2u, sizeof(samples_passed), samples_passed, sizeof(uint64_t) * 2, queryResultFlags); - logger->log("[WAIT+AVAIL+64] SamplesPassed[0] = %d, SamplesPassed[1] = %d, Result Available = %d, %d", system::ILogger::ELL_INFO, samples_passed[0], samples_passed[2], samples_passed[1], samples_passed[3]); - } - { - uint32_t samples_passed[2] = {}; - auto queryResultFlags = core::bitflag(video::IQueryPool::EQRF_WAIT_BIT); - logicalDevice->getQueryPoolResults(occlusionQueryPool.get(), 0u, 2u, sizeof(samples_passed), samples_passed, sizeof(uint32_t), queryResultFlags); - logger->log("[WAIT] SamplesPassed[0] = %d, SamplesPassed[1] = %d", system::ILogger::ELL_INFO, samples_passed[0], samples_passed[1]); - } - { - uint64_t timestamps[4] = {}; - auto queryResultFlags = core::bitflag(video::IQueryPool::EQRF_WAIT_BIT) | video::IQueryPool::EQRF_WITH_AVAILABILITY_BIT | video::IQueryPool::EQRF_64_BIT; - logicalDevice->getQueryPoolResults(timestampQueryPool.get(), 0u, 2u, sizeof(timestamps), timestamps, sizeof(uint64_t) * 2ull, queryResultFlags); - float timePassed = (timestamps[2] - timestamps[0]) * physicalDevice->getLimits().timestampPeriodInNanoSeconds; - logger->log("Time Passed (Seconds) = %f", system::ILogger::ELL_INFO, (timePassed * 1e-9)); - logger->log("Timestamps availablity: %d, %d", system::ILogger::ELL_INFO, timestamps[1], timestamps[3]); - } -#endif - } - - APP_CONSTRUCTOR(MeshLoadersApp) - void onAppInitialized_impl() override - { - const auto swapchainImageUsage = static_cast(asset::IImage::EUF_COLOR_ATTACHMENT_BIT | asset::IImage::EUF_TRANSFER_SRC_BIT); - CommonAPI::InitParams initParams; - initParams.window = core::smart_refctd_ptr(window); - initParams.apiType = video::EAT_VULKAN; - initParams.appName = { _NBL_APP_NAME_ }; - initParams.framesInFlight = FRAMES_IN_FLIGHT; - initParams.windowWidth = WIN_W; - initParams.windowHeight = WIN_H; - initParams.swapchainImageCount = SC_IMG_COUNT; - initParams.swapchainImageUsage = swapchainImageUsage; - initParams.depthFormat = nbl::asset::EF_D32_SFLOAT; - auto initOutput = CommonAPI::InitWithDefaultExt(std::move(initParams)); - - window = std::move(initParams.window); - windowCb = std::move(initParams.windowCb); - apiConnection = std::move(initOutput.apiConnection); - surface = std::move(initOutput.surface); - utilities = std::move(initOutput.utilities); - logicalDevice = std::move(initOutput.logicalDevice); - physicalDevice = initOutput.physicalDevice; - queues = std::move(initOutput.queues); - renderpass = std::move(initOutput.renderToSwapchainRenderpass); - commandPools = std::move(initOutput.commandPools); - system = std::move(initOutput.system); - assetManager = std::move(initOutput.assetManager); - cpu2gpuParams = std::move(initOutput.cpu2gpuParams); - logger = std::move(initOutput.logger); - inputSystem = std::move(initOutput.inputSystem); - m_swapchainCreationParams = std::move(initOutput.swapchainCreationParams); - - CommonAPI::createSwapchain(std::move(logicalDevice), m_swapchainCreationParams, WIN_W, WIN_H, swapchain); - assert(swapchain); - fbo = CommonAPI::createFBOWithSwapchainImages( - swapchain->getImageCount(), WIN_W, WIN_H, - logicalDevice, swapchain, renderpass, - nbl::asset::EF_D32_SFLOAT - ); - - // Occlusion Query - { - video::IQueryPool::SCreationParams queryPoolCreationParams = {}; - queryPoolCreationParams.queryType = video::IQueryPool::EQT_OCCLUSION; - queryPoolCreationParams.queryCount = 2u; - occlusionQueryPool = logicalDevice->createQueryPool(std::move(queryPoolCreationParams)); - } - - // Timestamp Query - video::IQueryPool::SCreationParams queryPoolCreationParams = {}; - { - video::IQueryPool::SCreationParams queryPoolCreationParams = {}; - queryPoolCreationParams.queryType = video::IQueryPool::EQT_TIMESTAMP; - queryPoolCreationParams.queryCount = 2u; - timestampQueryPool = logicalDevice->createQueryPool(std::move(queryPoolCreationParams)); - } - - { - // SAMPLES_PASSED_0 + AVAILABILIY_0 + SAMPLES_PASSED_1 + AVAILABILIY_1 (uint32_t) - const size_t queriesSize = sizeof(uint32_t) * 4; - video::IGPUBuffer::SCreationParams gpuuboCreationParams; - gpuuboCreationParams.size = queriesSize; - gpuuboCreationParams.usage = core::bitflag(asset::IBuffer::EUF_UNIFORM_BUFFER_BIT)|asset::IBuffer::EUF_TRANSFER_DST_BIT|asset::IBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF; - gpuuboCreationParams.queueFamilyIndexCount = 0u; - gpuuboCreationParams.queueFamilyIndices = nullptr; - - queryResultsBuffer = logicalDevice->createBuffer(std::move(gpuuboCreationParams)); - auto memReqs = queryResultsBuffer->getMemoryReqs(); - memReqs.memoryTypeBits &= physicalDevice->getDeviceLocalMemoryTypeBits(); - auto queriesMem = logicalDevice->allocate(memReqs, queryResultsBuffer.get()); - - queryResultsBuffer->setObjectDebugName("QueryResults"); - } - - nbl::video::IGPUObjectFromAssetConverter cpu2gpu; - { - auto* quantNormalCache = assetManager->getMeshManipulator()->getQuantNormalCache(); - quantNormalCache->loadCacheFromFile(system.get(), sharedOutputCWD / "normalCache101010.sse"); - - system::path archPath = sharedInputCWD / "sponza.zip"; - auto arch = system->openFileArchive(archPath); - // test no alias loading (TODO: fix loading from absolute paths) - system->mount(std::move(arch)); - asset::IAssetLoader::SAssetLoadParams loadParams; - loadParams.workingDirectory = sharedInputCWD; - loadParams.logger = logger.get(); - auto meshes_bundle = assetManager->getAsset((sharedInputCWD / "sponza.zip/sponza.obj").string(), loadParams); - assert(!meshes_bundle.getContents().empty()); - - metaOBJ = meshes_bundle.getMetadata()->selfCast(); - - auto cpuMesh = meshes_bundle.getContents().begin()[0]; - meshRaw = static_cast(cpuMesh.get()); - - quantNormalCache->saveCacheToFile(system.get(), sharedOutputCWD / "normalCache101010.sse"); - } - - // Fix FrontFace and BlendParams for meshBuffers - for (size_t i = 0ull; i < meshRaw->getMeshBuffers().size(); ++i) - { - auto& meshBuffer = meshRaw->getMeshBuffers().begin()[i]; - meshBuffer->getPipeline()->getRasterizationParams().frontFaceIsCCW = false; - } - - // we can safely assume that all meshbuffers within mesh loaded from OBJ has same DS1 layout (used for camera-specific data) - firstMeshBuffer = *meshRaw->getMeshBuffers().begin(); - pipelineMetadata = metaOBJ->getAssetSpecificMetadata(firstMeshBuffer->getPipeline()); - - // so we can create just one DS - const asset::ICPUDescriptorSetLayout* ds1layout = firstMeshBuffer->getPipeline()->getLayout()->getDescriptorSetLayout(1u); - ds1UboBinding = ds1layout->getDescriptorRedirect(asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER).getBinding(asset::ICPUDescriptorSetLayout::CBindingRedirect::storage_range_index_t{ 0 }).data; - - size_t neededDS1UBOsz = 0ull; - { - for (const auto& shdrIn : pipelineMetadata->m_inputSemantics) - if (shdrIn.descriptorSection.type == asset::IRenderpassIndependentPipelineMetadata::ShaderInput::E_TYPE::ET_UNIFORM_BUFFER && shdrIn.descriptorSection.uniformBufferObject.set == 1u && shdrIn.descriptorSection.uniformBufferObject.binding == ds1UboBinding) - neededDS1UBOsz = std::max(neededDS1UBOsz, shdrIn.descriptorSection.uniformBufferObject.relByteoffset + shdrIn.descriptorSection.uniformBufferObject.bytesize); - } - - core::smart_refctd_ptr gpuds1layout; - { - auto gpu_array = cpu2gpu.getGPUObjectsFromAssets(&ds1layout, &ds1layout + 1, cpu2gpuParams); - if (!gpu_array || gpu_array->size() < 1u || !(*gpu_array)[0]) - assert(false); - - gpuds1layout = (*gpu_array)[0]; - } - - core::smart_refctd_ptr descriptorPool = nullptr; - { - video::IDescriptorPool::SCreateInfo createInfo = {}; - createInfo.maxSets = 1u; - createInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER)] = 1u; - descriptorPool = logicalDevice->createDescriptorPool(std::move(createInfo)); - } - - video::IGPUBuffer::SCreationParams gpuuboCreationParams; - gpuuboCreationParams.size = neededDS1UBOsz; - gpuuboCreationParams.usage = core::bitflag(asset::IBuffer::EUF_UNIFORM_BUFFER_BIT) | asset::IBuffer::EUF_TRANSFER_DST_BIT | asset::IBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF; - gpuuboCreationParams.queueFamilyIndexCount = 0u; - gpuuboCreationParams.queueFamilyIndices = nullptr; - - gpuubo = logicalDevice->createBuffer(std::move(gpuuboCreationParams)); - auto gpuuboMemReqs = gpuubo->getMemoryReqs(); - gpuuboMemReqs.memoryTypeBits &= physicalDevice->getDeviceLocalMemoryTypeBits(); - auto uboMemoryOffset = logicalDevice->allocate(gpuuboMemReqs, gpuubo.get(), video::IDeviceMemoryAllocation::E_MEMORY_ALLOCATE_FLAGS::EMAF_NONE); - - gpuds1 = descriptorPool->createDescriptorSet(std::move(gpuds1layout)); - - { - video::IGPUDescriptorSet::SWriteDescriptorSet write; - write.dstSet = gpuds1.get(); - write.binding = ds1UboBinding; - write.count = 1u; - write.arrayElement = 0u; - write.descriptorType = asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER; - video::IGPUDescriptorSet::SDescriptorInfo info; - { - info.desc = gpuubo; - info.info.buffer.offset = 0ull; - info.info.buffer.size = neededDS1UBOsz; - } - write.info = &info; - logicalDevice->updateDescriptorSets(1u, &write, 0u, nullptr); - } - { - cpu2gpuParams.beginCommandBuffers(); - - auto gpu_array = cpu2gpu.getGPUObjectsFromAssets(&meshRaw, &meshRaw + 1, cpu2gpuParams); - if (!gpu_array || gpu_array->size() < 1u || !(*gpu_array)[0]) - assert(false); - - cpu2gpuParams.waitForCreationToComplete(false); - - gpumesh = (*gpu_array)[0]; - } - - { - for (size_t i = 0; i < gpumesh->getMeshBuffers().size(); ++i) - { - auto gpuIndependentPipeline = gpumesh->getMeshBuffers().begin()[i]->getPipeline(); - - nbl::video::IGPUGraphicsPipeline::SCreationParams graphicsPipelineParams; - graphicsPipelineParams.renderpassIndependent = core::smart_refctd_ptr(const_cast(gpuIndependentPipeline)); - graphicsPipelineParams.renderpass = core::smart_refctd_ptr(renderpass); - - const RENDERPASS_INDEPENDENT_PIPELINE_ADRESS adress = reinterpret_cast(graphicsPipelineParams.renderpassIndependent.get()); - gpuPipelines[adress] = logicalDevice->createGraphicsPipeline(nullptr, std::move(graphicsPipelineParams)); - } - } - - core::vectorSIMDf cameraPosition(-250.0f,177.0f,1.69f); - core::vectorSIMDf cameraTarget(50.0f,125.0f,-3.0f); - matrix4SIMD projectionMatrix = matrix4SIMD::buildProjectionMatrixPerspectiveFovLH(core::radians(60.0f), video::ISurface::getTransformedAspectRatio(swapchain->getPreTransform(), WIN_W, WIN_H), 0.1, 10000); - camera = Camera(cameraPosition, cameraTarget, projectionMatrix, 10.f, 1.f); - lastTime = std::chrono::steady_clock::now(); - - for (size_t i = 0ull; i < NBL_FRAMES_TO_AVERAGE; ++i) - dtList[i] = 0.0; - - oracle.reportBeginFrameRecord(); - - - const auto& graphicsCommandPools = commandPools[CommonAPI::InitOutput::EQT_GRAPHICS]; - for (uint32_t i = 0u; i < FRAMES_IN_FLIGHT; i++) - { - logicalDevice->createCommandBuffers(graphicsCommandPools[i].get(), video::IGPUCommandBuffer::EL_PRIMARY, 1, commandBuffers+i); - imageAcquire[i] = logicalDevice->createSemaphore(); - renderFinished[i] = logicalDevice->createSemaphore(); - } - - constexpr uint64_t MAX_TIMEOUT = 99999999999999ull; - uint32_t acquiredNextFBO = {}; - resourceIx = -1; - } - void onAppTerminated_impl() override - { - const auto& fboCreationParams = fbo->begin()[acquiredNextFBO]->getCreationParameters(); - auto gpuSourceImageView = fboCreationParams.attachments[0]; - - bool status = ext::ScreenShot::createScreenShot( - logicalDevice.get(), - queues[CommonAPI::InitOutput::EQT_TRANSFER_DOWN], - renderFinished[resourceIx].get(), - gpuSourceImageView.get(), - assetManager.get(), - "ScreenShot.png", - asset::IImage::EL_PRESENT_SRC, - asset::EAF_NONE); - - assert(status); - logicalDevice->waitIdle(); - } - void workLoopBody() override - { - ++resourceIx; - if (resourceIx >= FRAMES_IN_FLIGHT) - resourceIx = 0; - - auto& commandBuffer = commandBuffers[resourceIx]; - auto& fence = frameComplete[resourceIx]; - if (fence) - logicalDevice->blockForFences(1u, &fence.get()); - else - fence = logicalDevice->createFence(static_cast(0)); - - commandBuffer->reset(nbl::video::IGPUCommandBuffer::ERF_RELEASE_RESOURCES_BIT); - commandBuffer->begin(nbl::video::IGPUCommandBuffer::EU_NONE); - - const auto nextPresentationTimestamp = oracle.acquireNextImage(swapchain.get(), imageAcquire[resourceIx].get(), nullptr, &acquiredNextFBO); - { - inputSystem->getDefaultMouse(&mouse); - inputSystem->getDefaultKeyboard(&keyboard); - - camera.beginInputProcessing(nextPresentationTimestamp); - mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void { camera.mouseProcess(events); }, logger.get()); - keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void { camera.keyboardProcess(events); }, logger.get()); - camera.endInputProcessing(nextPresentationTimestamp); - } - - const auto& viewMatrix = camera.getViewMatrix(); - const auto& viewProjectionMatrix = matrix4SIMD::concatenateBFollowedByAPrecisely( - video::ISurface::getSurfaceTransformationMatrix(swapchain->getPreTransform()), - camera.getConcatenatedMatrix() - ); - - asset::SViewport viewport; - viewport.minDepth = 1.f; - viewport.maxDepth = 0.f; - viewport.x = 0u; - viewport.y = 0u; - viewport.width = WIN_W; - viewport.height = WIN_H; - commandBuffer->setViewport(0u, 1u, &viewport); - - VkRect2D scissor = {}; - scissor.offset = { 0, 0 }; - scissor.extent = { WIN_W, WIN_H }; - commandBuffer->setScissor(0u, 1u, &scissor); - - core::matrix3x4SIMD modelMatrix; - modelMatrix.setTranslation(nbl::core::vectorSIMDf(0, 0, 0, 0)); - core::matrix4SIMD mvp = core::concatenateBFollowedByA(viewProjectionMatrix, modelMatrix); - - const size_t uboSize = gpuubo->getSize(); - core::vector uboData(uboSize); - for (const auto& shdrIn : pipelineMetadata->m_inputSemantics) - { - if (shdrIn.descriptorSection.type == asset::IRenderpassIndependentPipelineMetadata::ShaderInput::E_TYPE::ET_UNIFORM_BUFFER && shdrIn.descriptorSection.uniformBufferObject.set == 1u && shdrIn.descriptorSection.uniformBufferObject.binding == ds1UboBinding) - { - switch (shdrIn.type) - { - case asset::IRenderpassIndependentPipelineMetadata::ECSI_WORLD_VIEW_PROJ: - { - memcpy(uboData.data() + shdrIn.descriptorSection.uniformBufferObject.relByteoffset, mvp.pointer(), shdrIn.descriptorSection.uniformBufferObject.bytesize); - } break; - - case asset::IRenderpassIndependentPipelineMetadata::ECSI_WORLD_VIEW: - { - memcpy(uboData.data() + shdrIn.descriptorSection.uniformBufferObject.relByteoffset, viewMatrix.pointer(), shdrIn.descriptorSection.uniformBufferObject.bytesize); - } break; - - case asset::IRenderpassIndependentPipelineMetadata::ECSI_WORLD_VIEW_INVERSE_TRANSPOSE: - { - memcpy(uboData.data() + shdrIn.descriptorSection.uniformBufferObject.relByteoffset, viewMatrix.pointer(), shdrIn.descriptorSection.uniformBufferObject.bytesize); - } break; - } - } - } - commandBuffer->updateBuffer(gpuubo.get(), 0ull, uboSize, uboData.data()); - - nbl::video::IGPUCommandBuffer::SRenderpassBeginInfo beginInfo; - { - VkRect2D area; - area.offset = { 0,0 }; - area.extent = { WIN_W, WIN_H }; - asset::SClearValue clear[2] = {}; - clear[0].color.float32[0] = 1.f; - clear[0].color.float32[1] = 1.f; - clear[0].color.float32[2] = 1.f; - clear[0].color.float32[3] = 1.f; - clear[1].depthStencil.depth = 0.f; - - beginInfo.clearValueCount = 2u; - beginInfo.framebuffer = fbo->begin()[acquiredNextFBO]; - beginInfo.renderpass = renderpass; - beginInfo.renderArea = area; - beginInfo.clearValues = clear; - } - - commandBuffer->resetQueryPool(occlusionQueryPool.get(), 0u, 2u); - commandBuffer->resetQueryPool(timestampQueryPool.get(), 0u, 2u); - commandBuffer->beginRenderPass(&beginInfo, nbl::asset::ESC_INLINE); - - commandBuffer->writeTimestamp(asset::E_PIPELINE_STAGE_FLAGS::EPSF_TOP_OF_PIPE_BIT, timestampQueryPool.get(), 0u); - for (size_t i = 0; i < gpumesh->getMeshBuffers().size(); ++i) - { - if(i < 2) - commandBuffer->beginQuery(occlusionQueryPool.get(), i); - auto gpuMeshBuffer = gpumesh->getMeshBuffers().begin()[i]; - auto gpuGraphicsPipeline = gpuPipelines[reinterpret_cast(gpuMeshBuffer->getPipeline())]; - - const video::IGPURenderpassIndependentPipeline* gpuRenderpassIndependentPipeline = gpuMeshBuffer->getPipeline(); - const video::IGPUDescriptorSet* ds3 = gpuMeshBuffer->getAttachedDescriptorSet(); - - commandBuffer->bindGraphicsPipeline(gpuGraphicsPipeline.get()); - - const video::IGPUDescriptorSet* gpuds1_ptr = gpuds1.get(); - commandBuffer->bindDescriptorSets(asset::EPBP_GRAPHICS, gpuRenderpassIndependentPipeline->getLayout(), 1u, 1u, &gpuds1_ptr); - const video::IGPUDescriptorSet* gpuds3_ptr = gpuMeshBuffer->getAttachedDescriptorSet(); - if (gpuds3_ptr) - commandBuffer->bindDescriptorSets(asset::EPBP_GRAPHICS, gpuRenderpassIndependentPipeline->getLayout(), 3u, 1u, &gpuds3_ptr); - commandBuffer->pushConstants(gpuRenderpassIndependentPipeline->getLayout(), asset::IShader::ESS_FRAGMENT, 0u, gpuMeshBuffer->MAX_PUSH_CONSTANT_BYTESIZE, gpuMeshBuffer->getPushConstantsDataPtr()); - - commandBuffer->drawMeshBuffer(gpuMeshBuffer); - - if(i < 2) - commandBuffer->endQuery(occlusionQueryPool.get(), i); - } - commandBuffer->writeTimestamp(asset::E_PIPELINE_STAGE_FLAGS::EPSF_BOTTOM_OF_PIPE_BIT, timestampQueryPool.get(), 1u); - - commandBuffer->endRenderPass(); - - auto queryResultFlags = core::bitflag(video::IQueryPool::EQRF_WAIT_BIT) | video::IQueryPool::EQRF_WITH_AVAILABILITY_BIT; - commandBuffer->copyQueryPoolResults(occlusionQueryPool.get(), 0, 2, queryResultsBuffer.get(), 0u, sizeof(uint32_t) * 2, queryResultFlags); - - commandBuffer->end(); - - logicalDevice->resetFences(1, &fence.get()); - CommonAPI::Submit( - logicalDevice.get(), - commandBuffer.get(), - queues[CommonAPI::InitOutput::EQT_COMPUTE], - imageAcquire[resourceIx].get(), - renderFinished[resourceIx].get(), - fence.get()); - CommonAPI::Present(logicalDevice.get(), - swapchain.get(), - queues[CommonAPI::InitOutput::EQT_GRAPHICS], renderFinished[resourceIx].get(), acquiredNextFBO); - - getAndLogQueryPoolResults(); - } - bool keepRunning() override - { - return windowCb->isWindowOpen(); - } -}; - -NBL_COMMON_API_MAIN(MeshLoadersApp) diff --git a/07_StagingAndMultipleQueues/main.cpp b/07_StagingAndMultipleQueues/main.cpp index 658a28a35..fc6bf4551 100644 --- a/07_StagingAndMultipleQueues/main.cpp +++ b/07_StagingAndMultipleQueues/main.cpp @@ -3,26 +3,24 @@ // For conditions of distribution and use, see copyright notice in nabla.h // I've moved out a tiny part of this example into a shared header for reuse, please open and read it. - -#include "nbl/application_templates/BasicMultiQueueApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" - -// get asset converter -#include "CommonPCH/PCH.hpp" +#include "nbl/examples/examples.hpp" using namespace nbl; -using namespace core; -using namespace system; -using namespace asset; -using namespace video; +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::examples; #include "app_resources/common.hlsl" // This time we let the new base class score and pick queue families, as well as initialize `nbl::video::IUtilities` for us -class StagingAndMultipleQueuesApp final : public application_templates::BasicMultiQueueApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +class StagingAndMultipleQueuesApp final : public application_templates::BasicMultiQueueApplication, public BuiltinResourcesApplication { using device_base_t = application_templates::BasicMultiQueueApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using asset_base_t = BuiltinResourcesApplication; // TODO: would be cool if we used `system::ISystem::listItemsInDirectory(sharedInputCWD/"GLI")` as our dataset static constexpr std::array imagesToLoad = { @@ -246,7 +244,7 @@ class StagingAndMultipleQueuesApp final : public application_templates::BasicMul .binding = 0, .type = nbl::asset::IDescriptor::E_TYPE::ET_SAMPLED_IMAGE, .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, - .stageFlags = IGPUShader::E_SHADER_STAGE::ESS_COMPUTE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, .count = 1, .immutableSamplers = nullptr }, @@ -254,7 +252,7 @@ class StagingAndMultipleQueuesApp final : public application_templates::BasicMul .binding = 1, .type = nbl::asset::IDescriptor::E_TYPE::ET_STORAGE_BUFFER, .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, - .stageFlags = IGPUShader::E_SHADER_STAGE::ESS_COMPUTE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, .count = 1, .immutableSamplers = nullptr } @@ -281,18 +279,17 @@ class StagingAndMultipleQueuesApp final : public application_templates::BasicMul } // LOAD SHADER FROM FILE - smart_refctd_ptr source; + smart_refctd_ptr source; { - source = loadFistAssetInBundle("../app_resources/comp_shader.hlsl"); - source->setShaderStage(IShader::E_SHADER_STAGE::ESS_COMPUTE); // can also be done via a #pragma in the shader + source = loadFistAssetInBundle("../app_resources/comp_shader.hlsl"); } if (!source) logFailAndTerminate("Could not create a CPU shader!"); - core::smart_refctd_ptr shader = m_device->createShader(source.get()); + core::smart_refctd_ptr shader = m_device->compileShader({ source.get() }); if(!shader) - logFailAndTerminate("Could not create a GPU shader!"); + logFailAndTerminate("Could not compile shader to spirv!"); // CREATE COMPUTE PIPELINE SPushConstantRange pc[1]; @@ -432,15 +429,16 @@ class StagingAndMultipleQueuesApp final : public application_templates::BasicMul submitInfo[0].waitSemaphores = waitSemaphoreSubmitInfo; // there's no save to wait on, or need to prevent signal-after-submit because Renderdoc freezes because it // starts capturing immediately upon a submit and can't defer a capture till semaphores signal. - if (imageToProcessIdisRunningInRenderdoc()) + const bool isRunningInRenderdoc = m_api->runningInGraphicsDebugger()==IAPIConnection::EDebuggerType::Renderdoc; + if (imageToProcessIdisRunningInRenderdoc() && imageToProcessId>=SUBMITS_IN_FLIGHT) + if (isRunningInRenderdoc && imageToProcessId>=SUBMITS_IN_FLIGHT) for (auto old = histogramsSaved.load(); old < histogramSaveWaitSemaphoreValue; old = histogramsSaved.load()) histogramsSaved.wait(old); // Some Devices like all of the Intel GPUs do not have enough queues for us to allocate different queues to compute and transfers, // so our `BasicMultiQueueApplication` will "alias" a single queue to both usages. Normally you don't need to care, but here we're // attempting to do "out-of-order" "submit-before-signal" so we need to "hold back" submissions if the queues are aliased! - if (getTransferUpQueue()==computeQueue || m_api->isRunningInRenderdoc()) + if (getTransferUpQueue()==computeQueue || isRunningInRenderdoc) for (auto old = transfersSubmitted.load(); old <= imageToProcessId; old = transfersSubmitted.load()) transfersSubmitted.wait(old); computeQueue->submit(submitInfo); diff --git a/08_HelloSwapchain/main.cpp b/08_HelloSwapchain/main.cpp index 9137fe77a..cd294b0d2 100644 --- a/08_HelloSwapchain/main.cpp +++ b/08_HelloSwapchain/main.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2018-2024 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h -#include "SimpleWindowedApplication.hpp" +#include "nbl/examples/examples.hpp" // #include "nbl/video/surface/CSurfaceVulkan.h" diff --git a/09_GeometryCreator/CMakeLists.txt b/09_GeometryCreator/CMakeLists.txt index 928ef5761..2dd253226 100644 --- a/09_GeometryCreator/CMakeLists.txt +++ b/09_GeometryCreator/CMakeLists.txt @@ -2,5 +2,7 @@ set(NBL_INCLUDE_SERACH_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/include" ) -nbl_create_executable_project("" "" "${NBL_INCLUDE_SERACH_DIRECTORIES}" "" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") -LINK_BUILTIN_RESOURCES_TO_TARGET(${EXECUTABLE_NAME} geometryCreatorSpirvBRD) \ No newline at end of file + # TODO; Arek I removed `NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET` from the last parameter here, doesn't this macro have 4 arguments anyway !? +nbl_create_executable_project("" "" "${NBL_INCLUDE_SERACH_DIRECTORIES}" "" "") +# TODO: Arek temporarily disabled cause I haven't figured out how to make this target yet +# LINK_BUILTIN_RESOURCES_TO_TARGET(${EXECUTABLE_NAME} nblExamplesGeometrySpirvBRD) \ No newline at end of file diff --git a/09_GeometryCreator/include/common.hpp b/09_GeometryCreator/include/common.hpp index 3661e5697..84cd8118a 100644 --- a/09_GeometryCreator/include/common.hpp +++ b/09_GeometryCreator/include/common.hpp @@ -1,20 +1,8 @@ -#ifndef __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ -#define __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ +#ifndef _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ +#define _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ -#include -#include "nbl/asset/utils/CGeometryCreator.h" -#include "SimpleWindowedApplication.hpp" -#include "InputSystem.hpp" -#include "CEventCallback.hpp" - -#include "CCamera.hpp" -#include "SBasicViewParameters.hlsl" - -#include "geometry/creator/spirv/builtin/CArchive.h" -#include "geometry/creator/spirv/builtin/builtinResources.h" - -#include "CGeomtryCreatorScene.hpp" +#include "nbl/examples/examples.hpp" using namespace nbl; using namespace core; @@ -24,6 +12,7 @@ using namespace asset; using namespace ui; using namespace video; using namespace scene; -using namespace geometrycreator; +using namespace nbl::examples; + #endif // __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ \ No newline at end of file diff --git a/09_GeometryCreator/main.cpp b/09_GeometryCreator/main.cpp index 4ac527e08..900d827b7 100644 --- a/09_GeometryCreator/main.cpp +++ b/09_GeometryCreator/main.cpp @@ -1,146 +1,25 @@ -// Copyright (C) 2018-2024 - DevSH Graphics Programming Sp. z O.O. +// Copyright (C) 2018-2025 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h -#include "common.hpp" - -class CSwapchainFramebuffersAndDepth final : public nbl::video::CDefaultSwapchainFramebuffers -{ - using base_t = CDefaultSwapchainFramebuffers; - -public: - template - inline CSwapchainFramebuffersAndDepth(ILogicalDevice* device, const asset::E_FORMAT _desiredDepthFormat, Args&&... args) : CDefaultSwapchainFramebuffers(device, std::forward(args)...) - { - const IPhysicalDevice::SImageFormatPromotionRequest req = { - .originalFormat = _desiredDepthFormat, - .usages = {IGPUImage::EUF_RENDER_ATTACHMENT_BIT} - }; - m_depthFormat = m_device->getPhysicalDevice()->promoteImageFormat(req, IGPUImage::TILING::OPTIMAL); - - const static IGPURenderpass::SCreationParams::SDepthStencilAttachmentDescription depthAttachments[] = { - {{ - { - .format = m_depthFormat, - .samples = IGPUImage::ESCF_1_BIT, - .mayAlias = false - }, - /*.loadOp = */{IGPURenderpass::LOAD_OP::CLEAR}, - /*.storeOp = */{IGPURenderpass::STORE_OP::STORE}, - /*.initialLayout = */{IGPUImage::LAYOUT::UNDEFINED}, // because we clear we don't care about contents - /*.finalLayout = */{IGPUImage::LAYOUT::ATTACHMENT_OPTIMAL} // transition to presentation right away so we can skip a barrier - }}, - IGPURenderpass::SCreationParams::DepthStencilAttachmentsEnd - }; - m_params.depthStencilAttachments = depthAttachments; - - static IGPURenderpass::SCreationParams::SSubpassDescription subpasses[] = { - m_params.subpasses[0], - IGPURenderpass::SCreationParams::SubpassesEnd - }; - subpasses[0].depthStencilAttachment.render = { .attachmentIndex = 0,.layout = IGPUImage::LAYOUT::ATTACHMENT_OPTIMAL }; - m_params.subpasses = subpasses; - } - -protected: - inline bool onCreateSwapchain_impl(const uint8_t qFam) override - { - auto device = const_cast(m_renderpass->getOriginDevice()); - const auto depthFormat = m_renderpass->getCreationParameters().depthStencilAttachments[0].format; - const auto& sharedParams = getSwapchain()->getCreationParameters().sharedParams; - auto image = device->createImage({ IImage::SCreationParams{ - .type = IGPUImage::ET_2D, - .samples = IGPUImage::ESCF_1_BIT, - .format = depthFormat, - .extent = {sharedParams.width,sharedParams.height,1}, - .mipLevels = 1, - .arrayLayers = 1, - .depthUsage = IGPUImage::EUF_RENDER_ATTACHMENT_BIT - } }); - - device->allocate(image->getMemoryReqs(), image.get()); - - m_depthBuffer = device->createImageView({ - .flags = IGPUImageView::ECF_NONE, - .subUsages = IGPUImage::EUF_RENDER_ATTACHMENT_BIT, - .image = std::move(image), - .viewType = IGPUImageView::ET_2D, - .format = depthFormat, - .subresourceRange = {IGPUImage::EAF_DEPTH_BIT,0,1,0,1} - }); - - const auto retval = base_t::onCreateSwapchain_impl(qFam); - m_depthBuffer = nullptr; - return retval; - } - - inline smart_refctd_ptr createFramebuffer(IGPUFramebuffer::SCreationParams&& params) override - { - params.depthStencilAttachments = &m_depthBuffer.get(); - return m_device->createFramebuffer(std::move(params)); - } +#include "common.hpp" - E_FORMAT m_depthFormat; - // only used to pass a parameter from `onCreateSwapchain_impl` to `createFramebuffer` - smart_refctd_ptr m_depthBuffer; -}; -class GeometryCreatorApp final : public examples::SimpleWindowedApplication +class GeometryCreatorApp final : public MonoWindowApplication, public BuiltinResourcesApplication { - using device_base_t = examples::SimpleWindowedApplication; - using clock_t = std::chrono::steady_clock; - - constexpr static inline uint32_t WIN_W = 1280, WIN_H = 720; - - // Maximum frames which can be simultaneously submitted, used to cycle through our per-frame resources like command buffers - constexpr static inline uint32_t MaxFramesInFlight = 3u; - - constexpr static inline clock_t::duration DisplayImageDuration = std::chrono::milliseconds(900); + using device_base_t = MonoWindowApplication; + using asset_base_t = BuiltinResourcesApplication; public: - inline GeometryCreatorApp(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) - : IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) {} - - virtual SPhysicalDeviceFeatures getRequiredDeviceFeatures() const override - { - auto retval = device_base_t::getRequiredDeviceFeatures(); - retval.geometryShader = true; - return retval; - } - - inline core::vector getSurfaces() const override - { - if (!m_surface) - { - { - auto windowCallback = core::make_smart_refctd_ptr(smart_refctd_ptr(m_inputSystem), smart_refctd_ptr(m_logger)); - IWindow::SCreationParams params = {}; - params.callback = core::make_smart_refctd_ptr(); - params.width = WIN_W; - params.height = WIN_H; - params.x = 32; - params.y = 32; - params.flags = ui::IWindow::ECF_HIDDEN | IWindow::ECF_BORDERLESS | IWindow::ECF_RESIZABLE; - params.windowCaption = "GeometryCreatorApp"; - params.callback = windowCallback; - const_cast&>(m_window) = m_winMgr->createWindow(std::move(params)); - } - - auto surface = CSurfaceVulkanWin32::create(smart_refctd_ptr(m_api), smart_refctd_ptr_static_cast(m_window)); - const_cast&>(m_surface) = nbl::video::CSimpleResizeSurface::create(std::move(surface)); - } - - if (m_surface) - return { {m_surface->getSurface()/*,EQF_NONE*/} }; - - return {}; - } + GeometryCreatorApp(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) + : IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD), + device_base_t({1280,720}, EF_D16_UNORM, _localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) {} inline bool onAppInitialized(smart_refctd_ptr&& system) override { - m_inputSystem = make_smart_refctd_ptr(logger_opt_smart_ptr(smart_refctd_ptr(m_logger))); - + if (!asset_base_t::onAppInitialized(smart_refctd_ptr(system))) + return false; if (!device_base_t::onAppInitialized(smart_refctd_ptr(system))) return false; @@ -148,58 +27,7 @@ class GeometryCreatorApp final : public examples::SimpleWindowedApplication if (!m_semaphore) return logFail("Failed to Create a Semaphore!"); - ISwapchain::SCreationParams swapchainParams = { .surface = m_surface->getSurface() }; - if (!swapchainParams.deduceFormat(m_physicalDevice)) - return logFail("Could not choose a Surface Format for the Swapchain!"); - - // Subsequent submits don't wait for each other, hence its important to have External Dependencies which prevent users of the depth attachment overlapping. - const static IGPURenderpass::SCreationParams::SSubpassDependency dependencies[] = { - // wipe-transition of Color to ATTACHMENT_OPTIMAL - { - .srcSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, - .dstSubpass = 0, - .memoryBarrier = { - // last place where the depth can get modified in previous frame - .srcStageMask = PIPELINE_STAGE_FLAGS::LATE_FRAGMENT_TESTS_BIT, - // only write ops, reads can't be made available - .srcAccessMask = ACCESS_FLAGS::DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - // destination needs to wait as early as possible - .dstStageMask = PIPELINE_STAGE_FLAGS::EARLY_FRAGMENT_TESTS_BIT, - // because of depth test needing a read and a write - .dstAccessMask = ACCESS_FLAGS::DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | ACCESS_FLAGS::DEPTH_STENCIL_ATTACHMENT_READ_BIT - } - // leave view offsets and flags default - }, - // color from ATTACHMENT_OPTIMAL to PRESENT_SRC - { - .srcSubpass = 0, - .dstSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, - .memoryBarrier = { - // last place where the depth can get modified - .srcStageMask = PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, - // only write ops, reads can't be made available - .srcAccessMask = ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT - // spec says nothing is needed when presentation is the destination - } - // leave view offsets and flags default - }, - IGPURenderpass::SCreationParams::DependenciesEnd - }; - - // TODO: promote the depth format if D16 not supported, or quote the spec if there's guaranteed support for it - auto scResources = std::make_unique(m_device.get(), EF_D16_UNORM, swapchainParams.surfaceFormat.format, dependencies); - - auto* renderpass = scResources->getRenderpass(); - - if (!renderpass) - return logFail("Failed to create Renderpass!"); - - auto gQueue = getGraphicsQueue(); - if (!m_surface || !m_surface->init(gQueue, std::move(scResources), swapchainParams.sharedParams)) - return logFail("Could not create Window & Surface or initialize the Surface!"); - - auto pool = m_device->createCommandPool(gQueue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); - + auto pool = m_device->createCommandPool(getGraphicsQueue()->getFamilyIndex(),IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); for (auto i = 0u; i < MaxFramesInFlight; i++) { if (!pool) @@ -208,80 +36,58 @@ class GeometryCreatorApp final : public examples::SimpleWindowedApplication return logFail("Couldn't create Command Buffer!"); } - m_winMgr->setWindowSize(m_window.get(), WIN_W, WIN_H); - m_surface->recreateSwapchain(); - - auto assetManager = make_smart_refctd_ptr(smart_refctd_ptr(system)); - auto* geometry = assetManager->getGeometryCreator(); - - //using Builder = typename CScene::CreateResourcesDirectlyWithDevice::Builder; - using Builder = typename CScene::CreateResourcesWithAssetConverter::Builder; - auto oneRunCmd = CScene::createCommandBuffer(m_utils->getLogicalDevice(), m_utils->getLogger(), gQueue->getFamilyIndex()); - Builder builder(m_utils.get(), oneRunCmd.get(), m_logger.get(), geometry); - - // gpu resources - if (builder.build()) + const uint32_t addtionalBufferOwnershipFamilies[] = {getGraphicsQueue()->getFamilyIndex()}; + m_scene = CGeometryCreatorScene::create( + { + .transferQueue = getTransferUpQueue(), + .utilities = m_utils.get(), + .logger = m_logger.get(), + .addtionalBufferOwnershipFamilies = addtionalBufferOwnershipFamilies + }, + CSimpleDebugRenderer::DefaultPolygonGeometryPatch // we want to use the vertex data through UTBs + ); + + auto scRes = static_cast(m_surface->getSwapchainResources()); + const auto& geometries = m_scene->getInitParams().geometries; + m_renderer = CSimpleDebugRenderer::create(m_assetMgr.get(),scRes->getRenderpass(),0,{&geometries.front().get(),geometries.size()}); + if (!m_renderer || m_renderer->getGeometries().size() != geometries.size()) + return logFail("Could not create Renderer!"); + // special case { - if (!builder.finalize(resources, gQueue)) - m_logger->log("Could not finalize resource objects to gpu objects!", ILogger::ELL_ERROR); + const auto& pipelines = m_renderer->getInitParams().pipelines; + auto ix = 0u; + for (const auto& name : m_scene->getInitParams().geometryNames) + { + if (name=="Cone") + m_renderer->getGeometry(ix).pipeline = pipelines[CSimpleDebugRenderer::SInitParams::PipelineType::Cone]; + ix++; + } } - else - m_logger->log("Could not build resource objects!", ILogger::ELL_ERROR); + m_renderer->m_instances.resize(1); + m_renderer->m_instances[0].world = float32_t3x4( + float32_t4(1,0,0,0), + float32_t4(0,1,0,0), + float32_t4(0,0,1,0) + ); // camera { core::vectorSIMDf cameraPosition(-5.81655884, 2.58630896, -4.23974705); core::vectorSIMDf cameraTarget(-0.349590302, -0.213266611, 0.317821503); - matrix4SIMD projectionMatrix = matrix4SIMD::buildProjectionMatrixPerspectiveFovLH(core::radians(60.0f), float(WIN_W) / WIN_H, 0.1, 10000); + matrix4SIMD projectionMatrix = matrix4SIMD::buildProjectionMatrixPerspectiveFovLH(core::radians(60.0f), float(m_initialResolution.x)/float(m_initialResolution.y), 0.1, 10000); camera = Camera(cameraPosition, cameraTarget, projectionMatrix, 1.069f, 0.4f); } - m_winMgr->show(m_window.get()); - oracle.reportBeginFrameRecord(); - + onAppInitializedFinish(); return true; } - inline void workLoopBody() override + inline IQueue::SSubmitInfo::SSemaphoreInfo renderFrame(const std::chrono::microseconds nextPresentationTimestamp) override { - // framesInFlight: ensuring safe execution of command buffers and acquires, `framesInFlight` only affect semaphore waits, don't use this to index your resources because it can change with swapchain recreation. - const uint32_t framesInFlight = core::min(MaxFramesInFlight, m_surface->getMaxAcquiresInFlight()); - // We block for semaphores for 2 reasons here: - // A) Resource: Can't use resource like a command buffer BEFORE previous use is finished! [MaxFramesInFlight] - // B) Acquire: Can't have more acquires in flight than a certain threshold returned by swapchain or your surface helper class. [MaxAcquiresInFlight] - if (m_realFrameIx >= framesInFlight) - { - const ISemaphore::SWaitInfo cbDonePending[] = - { - { - .semaphore = m_semaphore.get(), - .value = m_realFrameIx + 1 - framesInFlight - } - }; - if (m_device->blockForSemaphores(cbDonePending) != ISemaphore::WAIT_RESULT::SUCCESS) - return; - } - - const auto resourceIx = m_realFrameIx % MaxFramesInFlight; - m_inputSystem->getDefaultMouse(&mouse); m_inputSystem->getDefaultKeyboard(&keyboard); - auto updatePresentationTimestamp = [&]() - { - m_currentImageAcquire = m_surface->acquireNextImage(); - - oracle.reportEndFrameRecord(); - const auto timestamp = oracle.getNextPresentationTimeStamp(); - oracle.reportBeginFrameRecord(); - - return timestamp; - }; - - const auto nextPresentationTimestamp = updatePresentationTimestamp(); - - if (!m_currentImageAcquire) - return; + const auto resourceIx = m_realFrameIx % device_base_t::MaxFramesInFlight; auto* const cb = m_cmdBufs.data()[resourceIx].get(); cb->reset(IGPUCommandBuffer::RESET_FLAGS::RELEASE_RESOURCES_BIT); @@ -292,40 +98,8 @@ class GeometryCreatorApp final : public examples::SimpleWindowedApplication mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void { camera.mouseProcess(events); mouseProcess(events); }, m_logger.get()); keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void { camera.keyboardProcess(events); }, m_logger.get()); camera.endInputProcessing(nextPresentationTimestamp); - - const auto type = static_cast(gcIndex); - const auto& [gpu, meta] = resources.objects[type]; - - object.meta.type = type; - object.meta.name = meta.name; - } - - const auto viewMatrix = camera.getViewMatrix(); - const auto viewProjectionMatrix = camera.getConcatenatedMatrix(); - - core::matrix3x4SIMD modelMatrix; - modelMatrix.setTranslation(nbl::core::vectorSIMDf(0, 0, 0, 0)); - modelMatrix.setRotation(quaternion(0, 0, 0)); - - core::matrix3x4SIMD modelViewMatrix = core::concatenateBFollowedByA(viewMatrix, modelMatrix); - core::matrix4SIMD modelViewProjectionMatrix = core::concatenateBFollowedByA(viewProjectionMatrix, modelMatrix); - - core::matrix3x4SIMD normalMatrix; - modelViewMatrix.getSub3x3InverseTranspose(normalMatrix); - - SBasicViewParameters uboData; - memcpy(uboData.MVP, modelViewProjectionMatrix.pointer(), sizeof(uboData.MVP)); - memcpy(uboData.MV, modelViewMatrix.pointer(), sizeof(uboData.MV)); - memcpy(uboData.NormalMat, normalMatrix.pointer(), sizeof(uboData.NormalMat)); - { - SBufferRange range; - range.buffer = core::smart_refctd_ptr(resources.ubo.buffer); - range.size = resources.ubo.buffer->getSize(); - - cb->updateBuffer(range, &uboData); } - auto* queue = getGraphicsQueue(); asset::SViewport viewport; { @@ -352,12 +126,12 @@ class GeometryCreatorApp final : public examples::SimpleWindowedApplication .extent = {m_window->getWidth(),m_window->getHeight()} }; - const IGPUCommandBuffer::SClearColorValue clearValue = { .float32 = {0.f,0.f,0.f,1.f} }; + const IGPUCommandBuffer::SClearColorValue clearValue = { .float32 = {1.f,0.f,1.f,1.f} }; const IGPUCommandBuffer::SClearDepthStencilValue depthValue = { .depth = 0.f }; auto scRes = static_cast(m_surface->getSwapchainResources()); const IGPUCommandBuffer::SRenderpassBeginInfo info = { - .framebuffer = scRes->getFramebuffer(m_currentImageAcquire.imageIndex), + .framebuffer = scRes->getFramebuffer(device_base_t::getCurrentAcquire().imageIndex), .colorClearValues = &clearValue, .depthStencilClearValues = &depthValue, .renderArea = currentRenderArea @@ -366,112 +140,120 @@ class GeometryCreatorApp final : public examples::SimpleWindowedApplication cb->beginRenderPass(info, IGPUCommandBuffer::SUBPASS_CONTENTS::INLINE); } - const auto& [hook, meta] = resources.objects[object.meta.type]; - auto* rawPipeline = hook.pipeline.get(); - - SBufferBinding vertex = hook.bindings.vertex, index = hook.bindings.index; - - cb->bindGraphicsPipeline(rawPipeline); - cb->bindDescriptorSets(EPBP_GRAPHICS, rawPipeline->getLayout(), 1, 1, &resources.descriptorSet.get()); - cb->bindVertexBuffers(0, 1, &vertex); - - if (index.buffer && hook.indexType != EIT_UNKNOWN) + float32_t3x4 viewMatrix; + float32_t4x4 viewProjMatrix; + // TODO: get rid of legacy matrices { - cb->bindIndexBuffer(index, hook.indexType); - cb->drawIndexed(hook.indexCount, 1, 0, 0, 0); + memcpy(&viewMatrix,camera.getViewMatrix().pointer(),sizeof(viewMatrix)); + memcpy(&viewProjMatrix,camera.getConcatenatedMatrix().pointer(),sizeof(viewProjMatrix)); } - else - cb->draw(hook.indexCount, 1, 0, 0); + const auto viewParams = CSimpleDebugRenderer::SViewParams(viewMatrix,viewProjMatrix); + + // tear down scene every frame + m_renderer->m_instances[0].packedGeo = m_renderer->getGeometries().data()+gcIndex; + m_renderer->render(cb,viewParams); cb->endRenderPass(); + cb->endDebugMarker(); cb->end(); + + IQueue::SSubmitInfo::SSemaphoreInfo retval = { - const IQueue::SSubmitInfo::SSemaphoreInfo rendered[] = - { - { - .semaphore = m_semaphore.get(), - .value = ++m_realFrameIx, - .stageMask = PIPELINE_STAGE_FLAGS::ALL_GRAPHICS_BITS - } - }; + .semaphore = m_semaphore.get(), + .value = ++m_realFrameIx, + .stageMask = PIPELINE_STAGE_FLAGS::ALL_GRAPHICS_BITS + }; + const IQueue::SSubmitInfo::SCommandBufferInfo commandBuffers[] = + { + {.cmdbuf = cb } + }; + const IQueue::SSubmitInfo::SSemaphoreInfo acquired[] = { { - { - const IQueue::SSubmitInfo::SCommandBufferInfo commandBuffers[] = - { - {.cmdbuf = cb } - }; - - const IQueue::SSubmitInfo::SSemaphoreInfo acquired[] = - { - { - .semaphore = m_currentImageAcquire.semaphore, - .value = m_currentImageAcquire.acquireCount, - .stageMask = PIPELINE_STAGE_FLAGS::NONE - } - }; - const IQueue::SSubmitInfo infos[] = - { - { - .waitSemaphores = acquired, - .commandBuffers = commandBuffers, - .signalSemaphores = rendered - } - }; - - if (queue->submit(infos) == IQueue::RESULT::SUCCESS) - { - const nbl::video::ISemaphore::SWaitInfo waitInfos[] = - { { - .semaphore = m_semaphore.get(), - .value = m_realFrameIx - } }; - - m_device->blockForSemaphores(waitInfos); // this is not solution, quick wa to not throw validation errors - } - else - --m_realFrameIx; - } + .semaphore = device_base_t::getCurrentAcquire().semaphore, + .value = device_base_t::getCurrentAcquire().acquireCount, + .stageMask = PIPELINE_STAGE_FLAGS::NONE } - - std::string caption = "[Nabla Engine] Geometry Creator"; + }; + const IQueue::SSubmitInfo infos[] = + { { - caption += ", displaying [" + std::string(object.meta.name.data()) + "]"; - m_window->setCaption(caption); + .waitSemaphores = acquired, + .commandBuffers = commandBuffers, + .signalSemaphores = {&retval,1} } - m_surface->present(m_currentImageAcquire.imageIndex, rendered); - } - } + }; - inline bool keepRunning() override - { - if (m_surface->irrecoverable()) - return false; + if (getGraphicsQueue()->submit(infos) != IQueue::RESULT::SUCCESS) + { + retval.semaphore = nullptr; // so that we don't wait on semaphore that will never signal + m_realFrameIx--; + } - return true; + std::string caption = "[Nabla Engine] Geometry Creator"; + { + caption += ", displaying ["; + caption += m_scene->getInitParams().geometryNames[gcIndex]; + caption += "]"; + m_window->setCaption(caption); + } + return retval; } - - inline bool onAppTerminated() override + + protected: + const video::IGPURenderpass::SCreationParams::SSubpassDependency* getDefaultSubpassDependencies() const override { - return device_base_t::onAppTerminated(); + // Subsequent submits don't wait for each other, hence its important to have External Dependencies which prevent users of the depth attachment overlapping. + const static IGPURenderpass::SCreationParams::SSubpassDependency dependencies[] = { + // wipe-transition of Color to ATTACHMENT_OPTIMAL and depth + { + .srcSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .dstSubpass = 0, + .memoryBarrier = { + // last place where the depth can get modified in previous frame, `COLOR_ATTACHMENT_OUTPUT_BIT` is implicitly later + .srcStageMask = PIPELINE_STAGE_FLAGS::LATE_FRAGMENT_TESTS_BIT, + // don't want any writes to be available, we'll clear + .srcAccessMask = ACCESS_FLAGS::NONE, + // destination needs to wait as early as possible + // TODO: `COLOR_ATTACHMENT_OUTPUT_BIT` shouldn't be needed, because its a logically later stage, see TODO in `ECommonEnums.h` + .dstStageMask = PIPELINE_STAGE_FLAGS::EARLY_FRAGMENT_TESTS_BIT | PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + // because depth and color get cleared first no read mask + .dstAccessMask = ACCESS_FLAGS::DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + } + // leave view offsets and flags default + }, + // color from ATTACHMENT_OPTIMAL to PRESENT_SRC + { + .srcSubpass = 0, + .dstSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .memoryBarrier = { + // last place where the color can get modified, depth is implicitly earlier + .srcStageMask = PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + // only write ops, reads can't be made available + .srcAccessMask = ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + // spec says nothing is needed when presentation is the destination + } + // leave view offsets and flags default + }, + IGPURenderpass::SCreationParams::DependenciesEnd + }; + return dependencies; } private: - smart_refctd_ptr m_window; - smart_refctd_ptr> m_surface; + // + smart_refctd_ptr m_scene; + smart_refctd_ptr m_renderer; + // smart_refctd_ptr m_semaphore; uint64_t m_realFrameIx = 0; - std::array, MaxFramesInFlight> m_cmdBufs; - ISimpleManagedSurface::SAcquireResult m_currentImageAcquire = {}; - - core::smart_refctd_ptr m_inputSystem; + std::array,device_base_t::MaxFramesInFlight> m_cmdBufs; + // InputSystem::ChannelReader mouse; InputSystem::ChannelReader keyboard; + // Camera camera = Camera(core::vectorSIMDf(0, 0, 0), core::vectorSIMDf(0, 0, 0), core::matrix4SIMD()); - video::CDumbPresentationOracle oracle; - ResourcesBundle resources; - ObjectDrawHookCpu object; uint16_t gcIndex = {}; void mouseProcess(const nbl::ui::IMouseEventChannel::range_t& events) @@ -480,8 +262,11 @@ class GeometryCreatorApp final : public examples::SimpleWindowedApplication { auto ev = *eventIt; - if (ev.type == nbl::ui::SMouseEvent::EET_SCROLL) - gcIndex = std::clamp(int16_t(gcIndex) + int16_t(core::sign(ev.scrollEvent.verticalScroll)), int64_t(0), int64_t(OT_COUNT - (uint8_t)1u)); + if (ev.type==nbl::ui::SMouseEvent::EET_SCROLL && m_renderer) + { + gcIndex += int16_t(core::sign(ev.scrollEvent.verticalScroll)); + gcIndex = core::clamp(gcIndex,0ull,m_renderer->getGeometries().size()-1); + } } } }; diff --git a/10_CountingSort/app_resources/prefix_sum_shader.comp.hlsl b/10_CountingSort/app_resources/prefix_sum_shader.comp.hlsl index 1e5d2510e..b0301fc3f 100644 --- a/10_CountingSort/app_resources/prefix_sum_shader.comp.hlsl +++ b/10_CountingSort/app_resources/prefix_sum_shader.comp.hlsl @@ -4,6 +4,7 @@ [[vk::push_constant]] CountingPushData pushData; [numthreads(WorkgroupSize,1,1)] +[shader("compute")] void main(uint32_t3 ID : SV_GroupThreadID, uint32_t3 GroupID : SV_GroupID) { sort::CountingParameters < uint32_t > params; diff --git a/10_CountingSort/app_resources/scatter_shader.comp.hlsl b/10_CountingSort/app_resources/scatter_shader.comp.hlsl index fa502726f..ddecfca2b 100644 --- a/10_CountingSort/app_resources/scatter_shader.comp.hlsl +++ b/10_CountingSort/app_resources/scatter_shader.comp.hlsl @@ -6,6 +6,7 @@ using DoublePtrAccessor = DoubleBdaAccessor; [numthreads(WorkgroupSize, 1, 1)] +[shader("compute")] void main(uint32_t3 ID : SV_GroupThreadID, uint32_t3 GroupID : SV_GroupID) { sort::CountingParameters params; diff --git a/10_CountingSort/main.cpp b/10_CountingSort/main.cpp index 4d0c93516..d51650919 100644 --- a/10_CountingSort/main.cpp +++ b/10_CountingSort/main.cpp @@ -1,20 +1,21 @@ -#include "nbl/application_templates/MonoDeviceApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" -#include "CommonPCH/PCH.hpp" +#include "nbl/examples/examples.hpp" using namespace nbl; -using namespace core; -using namespace system; -using namespace asset; -using namespace video; +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::examples; #include "app_resources/common.hlsl" #include "nbl/builtin/hlsl/bit.hlsl" -class CountingSortApp final : public application_templates::MonoDeviceApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +class CountingSortApp final : public application_templates::MonoDeviceApplication, public BuiltinResourcesApplication { using device_base_t = application_templates::MonoDeviceApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using asset_base_t = BuiltinResourcesApplication; public: // Yay thanks to multiple inheritance we cannot forward ctors anymore @@ -37,7 +38,7 @@ class CountingSortApp final : public application_templates::MonoDeviceApplicatio const uint32_t bucket_count = std::min((uint32_t)3000, MaxBucketCount); const uint32_t elements_per_thread = ceil((float)ceil((float)element_count / limits.computeUnits) / WorkgroupSize); - auto prepShader = [&](const core::string& path) -> smart_refctd_ptr + auto prepShader = [&](const core::string& path) -> smart_refctd_ptr { // this time we load a shader directly from a file IAssetLoader::SAssetLoadParams lp = {}; @@ -51,7 +52,7 @@ class CountingSortApp final : public application_templates::MonoDeviceApplicatio return nullptr; } - auto source = IAsset::castDown(assets[0]); + auto source = IAsset::castDown(assets[0]); // The down-cast should not fail! assert(source); @@ -63,8 +64,8 @@ class CountingSortApp final : public application_templates::MonoDeviceApplicatio WorkgroupSize, bucket_count ); - // this time we skip the use of the asset converter since the ICPUShader->IGPUShader path is quick and simple - auto shader = m_device->createShader(overrideSource.get()); + // this time we skip the use of the asset converter since the IShader->IGPUShader path is quick and simple + auto shader = m_device->compileShader({ overrideSource.get() }); if (!shader) { logFail("Creation of Prefix Sum Shader from CPU Shader source failed!"); @@ -93,8 +94,8 @@ class CountingSortApp final : public application_templates::MonoDeviceApplicatio params.shader.shader = prefixSumShader.get(); params.shader.entryPoint = "main"; params.shader.entries = nullptr; - params.shader.requireFullSubgroups = true; - params.shader.requiredSubgroupSize = static_cast(5); + params.shader.requiredSubgroupSize = static_cast(5); + params.cached.requireFullSubgroups = true; if (!m_device->createComputePipelines(nullptr, { ¶ms,1 }, &prefixSumPipeline)) return logFail("Failed to create compute pipeline!\n"); params.shader.shader = scatterShader.get(); diff --git a/11_FFT/app_resources/shader.comp.hlsl b/11_FFT/app_resources/shader.comp.hlsl index ecbf4f092..7c86f50b4 100644 --- a/11_FFT/app_resources/shader.comp.hlsl +++ b/11_FFT/app_resources/shader.comp.hlsl @@ -14,13 +14,13 @@ uint32_t3 glsl::gl_WorkGroupSize() { return uint32_t3(uint32_t(ConstevalParamete struct SharedMemoryAccessor { - template + template void set(IndexType idx, AccessType value) { sharedmem[idx] = value; } - template + template void get(IndexType idx, NBL_REF_ARG(AccessType) value) { value = sharedmem[idx]; @@ -44,14 +44,14 @@ struct Accessor } // TODO: can't use our own BDA yet, because it doesn't support the types `workgroup::FFT` will invoke these templates with - template - void get(const uint32_t index, NBL_REF_ARG(AccessType) value) + template + void get(const IndexType index, NBL_REF_ARG(AccessType) value) { value = vk::RawBufferLoad(address + index * sizeof(AccessType)); } - template - void set(const uint32_t index, const AccessType value) + template + void set(const IndexType index, const AccessType value) { vk::RawBufferStore(address + index * sizeof(AccessType), value); } @@ -60,6 +60,7 @@ struct Accessor }; [numthreads(ConstevalParameters::WorkgroupSize,1,1)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { Accessor accessor = Accessor::create(pushConstants.deviceBufferAddress); diff --git a/11_FFT/main.cpp b/11_FFT/main.cpp index 80f5f856c..3829e8481 100644 --- a/11_FFT/main.cpp +++ b/11_FFT/main.cpp @@ -3,17 +3,16 @@ // For conditions of distribution and use, see copyright notice in nabla.h -// I've moved out a tiny part of this example into a shared header for reuse, please open and read it. -#include "nbl/application_templates/MonoDeviceApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" - +#include "nbl/examples/examples.hpp" using namespace nbl; -using namespace core; -using namespace system; -using namespace asset; -using namespace video; - +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::examples; #include "app_resources/common.hlsl" #include "nbl/builtin/hlsl/bit.hlsl" @@ -21,10 +20,10 @@ using namespace video; // Simple showcase of how to run FFT on a 1D array -class FFT_Test final : public application_templates::MonoDeviceApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +class FFT_Test final : public application_templates::MonoDeviceApplication, public BuiltinResourcesApplication { using device_base_t = application_templates::MonoDeviceApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using asset_base_t = BuiltinResourcesApplication; smart_refctd_ptr m_pipeline; @@ -46,13 +45,13 @@ class FFT_Test final : public application_templates::MonoDeviceApplication, publ smart_refctd_ptr m_timeline; uint64_t semaphorValue = 0; - inline core::smart_refctd_ptr createShader( + inline core::smart_refctd_ptr createShader( const char* includeMainName) { std::string prelude = "#include \""; - auto CPUShader = core::make_smart_refctd_ptr((prelude + includeMainName + "\"\n").c_str(), IShader::E_SHADER_STAGE::ESS_COMPUTE, IShader::E_CONTENT_TYPE::ECT_HLSL, includeMainName); - assert(CPUShader); - return m_device->createShader(CPUShader.get()); + auto hlslShader = core::make_smart_refctd_ptr((prelude + includeMainName + "\"\n").c_str(), IShader::E_CONTENT_TYPE::ECT_HLSL, includeMainName); + assert(hlslShader); + return m_device->compileShader({ hlslShader.get() }); } public: @@ -70,7 +69,7 @@ class FFT_Test final : public application_templates::MonoDeviceApplication, publ return false; // this time we load a shader directly from a file - smart_refctd_ptr shader; + smart_refctd_ptr shader; /* { IAssetLoader::SAssetLoadParams lp = {}; lp.logger = m_logger.get(); @@ -81,14 +80,14 @@ class FFT_Test final : public application_templates::MonoDeviceApplication, publ return logFail("Could not load shader!"); // Cast down the asset to its proper type - auto source = IAsset::castDown(assets[0]); + auto source = IAsset::castDown(assets[0]); // The down-cast should not fail! assert(source); - // Compile directly to IGPUShader - shader = m_device->createShader(source.get()); + // Compile directly to SPIR-V Shader + shader = m_device->compileShader({ source.get() }); if (!shader) - return logFail("Creation of a GPU Shader to from CPU Shader source failed!"); + return logFail("Creation of a SPIR-V Shader from HLSL Shader source failed!"); }*/ shader = createShader("app_resources/shader.comp.hlsl"); @@ -132,8 +131,9 @@ class FFT_Test final : public application_templates::MonoDeviceApplication, publ IGPUComputePipeline::SCreationParams params = {}; params.layout = layout.get(); params.shader.shader = shader.get(); - params.shader.requiredSubgroupSize = static_cast(hlsl::findMSB(m_physicalDevice->getLimits().maxSubgroupSize)); - params.shader.requireFullSubgroups = true; + params.shader.entryPoint = "main"; + params.shader.requiredSubgroupSize = static_cast(hlsl::findMSB(m_physicalDevice->getLimits().maxSubgroupSize)); + params.cached.requireFullSubgroups = true; if (!m_device->createComputePipelines(nullptr, { ¶ms,1 }, &m_pipeline)) return logFail("Failed to create compute pipeline!\n"); } diff --git a/12_MeshLoaders/CMakeLists.txt b/12_MeshLoaders/CMakeLists.txt new file mode 100644 index 000000000..2dd253226 --- /dev/null +++ b/12_MeshLoaders/CMakeLists.txt @@ -0,0 +1,8 @@ +set(NBL_INCLUDE_SERACH_DIRECTORIES + "${CMAKE_CURRENT_SOURCE_DIR}/include" +) + + # TODO; Arek I removed `NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET` from the last parameter here, doesn't this macro have 4 arguments anyway !? +nbl_create_executable_project("" "" "${NBL_INCLUDE_SERACH_DIRECTORIES}" "" "") +# TODO: Arek temporarily disabled cause I haven't figured out how to make this target yet +# LINK_BUILTIN_RESOURCES_TO_TARGET(${EXECUTABLE_NAME} nblExamplesGeometrySpirvBRD) \ No newline at end of file diff --git a/12_MeshLoaders/README.md b/12_MeshLoaders/README.md new file mode 100644 index 000000000..6330f4673 --- /dev/null +++ b/12_MeshLoaders/README.md @@ -0,0 +1,2 @@ +https://github.com/user-attachments/assets/6f779700-e6d4-4e11-95fb-7a7fddc47255 + diff --git a/06_MeshLoaders/config.json.template b/12_MeshLoaders/config.json.template similarity index 100% rename from 06_MeshLoaders/config.json.template rename to 12_MeshLoaders/config.json.template diff --git a/12_MeshLoaders/include/common.hpp b/12_MeshLoaders/include/common.hpp new file mode 100644 index 000000000..84cd8118a --- /dev/null +++ b/12_MeshLoaders/include/common.hpp @@ -0,0 +1,18 @@ +#ifndef _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ +#define _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ + + +#include "nbl/examples/examples.hpp" + +using namespace nbl; +using namespace core; +using namespace hlsl; +using namespace system; +using namespace asset; +using namespace ui; +using namespace video; +using namespace scene; +using namespace nbl::examples; + + +#endif // __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ \ No newline at end of file diff --git a/12_MeshLoaders/main.cpp b/12_MeshLoaders/main.cpp new file mode 100644 index 000000000..14da9f0d6 --- /dev/null +++ b/12_MeshLoaders/main.cpp @@ -0,0 +1,371 @@ +// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. +// This file is part of the "Nabla Engine". +// For conditions of distribution and use, see copyright notice in nabla.h +#include "common.hpp" + +#include "../3rdparty/portable-file-dialogs/portable-file-dialogs.h" + + +class MeshLoadersApp final : public MonoWindowApplication, public BuiltinResourcesApplication +{ + using device_base_t = MonoWindowApplication; + using asset_base_t = BuiltinResourcesApplication; + + public: + inline MeshLoadersApp(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) + : IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD), + device_base_t({1280,720}, EF_UNKNOWN, _localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) {} + + inline bool onAppInitialized(smart_refctd_ptr&& system) override + { + if (!asset_base_t::onAppInitialized(smart_refctd_ptr(system))) + return false; + if (!device_base_t::onAppInitialized(smart_refctd_ptr(system))) + return false; + + m_semaphore = m_device->createSemaphore(m_realFrameIx); + if (!m_semaphore) + return logFail("Failed to Create a Semaphore!"); + + auto pool = m_device->createCommandPool(getGraphicsQueue()->getFamilyIndex(),IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); + for (auto i=0u; icreateCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY,{m_cmdBufs.data()+i,1})) + return logFail("Couldn't create Command Buffer!"); + } + + //! cache results -- speeds up mesh generation on second run + m_qnc = make_smart_refctd_ptr(); + m_qnc->loadCacheFromFile(m_system.get(),sharedOutputCWD/"../../tmp/normalCache888.sse"); + + auto scRes = static_cast(m_surface->getSwapchainResources()); + m_renderer = CSimpleDebugRenderer::create(m_assetMgr.get(),scRes->getRenderpass(),0,{}); + if (!m_renderer) + return logFail("Failed to create renderer!"); + + // + if (!reloadModel()) + return false; + + camera.mapKeysToArrows(); + + onAppInitializedFinish(); + return true; + } + + inline IQueue::SSubmitInfo::SSemaphoreInfo renderFrame(const std::chrono::microseconds nextPresentationTimestamp) override + { + m_inputSystem->getDefaultMouse(&mouse); + m_inputSystem->getDefaultKeyboard(&keyboard); + + // + const auto resourceIx = m_realFrameIx % MaxFramesInFlight; + + auto* const cb = m_cmdBufs.data()[resourceIx].get(); + cb->reset(IGPUCommandBuffer::RESET_FLAGS::RELEASE_RESOURCES_BIT); + cb->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + // clear to black for both things + { + // begin renderpass + { + auto scRes = static_cast(m_surface->getSwapchainResources()); + auto* framebuffer = scRes->getFramebuffer(device_base_t::getCurrentAcquire().imageIndex); + const IGPUCommandBuffer::SClearColorValue clearValue = { .float32 = {1.f,0.f,1.f,1.f} }; + const IGPUCommandBuffer::SClearDepthStencilValue depthValue = { .depth = 0.f }; + const VkRect2D currentRenderArea = + { + .offset = {0,0}, + .extent = {framebuffer->getCreationParameters().width,framebuffer->getCreationParameters().height} + }; + const IGPUCommandBuffer::SRenderpassBeginInfo info = + { + .framebuffer = framebuffer, + .colorClearValues = &clearValue, + .depthStencilClearValues = &depthValue, + .renderArea = currentRenderArea + }; + cb->beginRenderPass(info,IGPUCommandBuffer::SUBPASS_CONTENTS::INLINE); + + const SViewport viewport = { + .x = static_cast(currentRenderArea.offset.x), + .y = static_cast(currentRenderArea.offset.y), + .width = static_cast(currentRenderArea.extent.width), + .height = static_cast(currentRenderArea.extent.height) + }; + cb->setViewport(0u,1u,&viewport); + + cb->setScissor(0u,1u,¤tRenderArea); + } + // late latch input + { + camera.beginInputProcessing(nextPresentationTimestamp); + mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void { camera.mouseProcess(events); }, m_logger.get()); + keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void + { + camera.keyboardProcess(events); + }, + m_logger.get() + ); + camera.endInputProcessing(nextPresentationTimestamp); + } + // draw scene + { + float32_t3x4 viewMatrix; + float32_t4x4 viewProjMatrix; + // TODO: get rid of legacy matrices + { + memcpy(&viewMatrix,camera.getViewMatrix().pointer(),sizeof(viewMatrix)); + memcpy(&viewProjMatrix,camera.getConcatenatedMatrix().pointer(),sizeof(viewProjMatrix)); + } + m_renderer->render(cb,CSimpleDebugRenderer::SViewParams(viewMatrix,viewProjMatrix)); + } + cb->endRenderPass(); + } + cb->end(); + + IQueue::SSubmitInfo::SSemaphoreInfo retval = + { + .semaphore = m_semaphore.get(), + .value = ++m_realFrameIx, + .stageMask = PIPELINE_STAGE_FLAGS::ALL_GRAPHICS_BITS + }; + const IQueue::SSubmitInfo::SCommandBufferInfo commandBuffers[] = + { + {.cmdbuf = cb } + }; + const IQueue::SSubmitInfo::SSemaphoreInfo acquired[] = { + { + .semaphore = device_base_t::getCurrentAcquire().semaphore, + .value = device_base_t::getCurrentAcquire().acquireCount, + .stageMask = PIPELINE_STAGE_FLAGS::NONE + } + }; + const IQueue::SSubmitInfo infos[] = + { + { + .waitSemaphores = acquired, + .commandBuffers = commandBuffers, + .signalSemaphores = {&retval,1} + } + }; + + if (getGraphicsQueue()->submit(infos) != IQueue::RESULT::SUCCESS) + { + retval.semaphore = nullptr; // so that we don't wait on semaphore that will never signal + m_realFrameIx--; + } + + std::string caption = "[Nabla Engine] Mesh Loaders"; + { + caption += ", displaying ["; + caption += m_modelPath; + caption += "]"; + m_window->setCaption(caption); + } + return retval; + } + + protected: + const video::IGPURenderpass::SCreationParams::SSubpassDependency* getDefaultSubpassDependencies() const override + { + // Subsequent submits don't wait for each other, hence its important to have External Dependencies which prevent users of the depth attachment overlapping. + const static IGPURenderpass::SCreationParams::SSubpassDependency dependencies[] = { + // wipe-transition of Color to ATTACHMENT_OPTIMAL and depth + { + .srcSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .dstSubpass = 0, + .memoryBarrier = { + // last place where the depth can get modified in previous frame, `COLOR_ATTACHMENT_OUTPUT_BIT` is implicitly later + .srcStageMask = PIPELINE_STAGE_FLAGS::LATE_FRAGMENT_TESTS_BIT, + // don't want any writes to be available, we'll clear + .srcAccessMask = ACCESS_FLAGS::NONE, + // destination needs to wait as early as possible + // TODO: `COLOR_ATTACHMENT_OUTPUT_BIT` shouldn't be needed, because its a logically later stage, see TODO in `ECommonEnums.h` + .dstStageMask = PIPELINE_STAGE_FLAGS::EARLY_FRAGMENT_TESTS_BIT | PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + // because depth and color get cleared first no read mask + .dstAccessMask = ACCESS_FLAGS::DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + } + // leave view offsets and flags default + }, + // color from ATTACHMENT_OPTIMAL to PRESENT_SRC + { + .srcSubpass = 0, + .dstSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .memoryBarrier = { + // last place where the color can get modified, depth is implicitly earlier + .srcStageMask = PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + // only write ops, reads can't be made available + .srcAccessMask = ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + // spec says nothing is needed when presentation is the destination + } + // leave view offsets and flags default + }, + IGPURenderpass::SCreationParams::DependenciesEnd + }; + return dependencies; + } + + private: + // TODO: standardise this across examples, and take from `argv` + bool m_nonInteractiveTest = true; + + inline bool reloadModel() + { + if (m_nonInteractiveTest) // TODO: maybe also take from argv and argc + m_modelPath = (sharedInputCWD/"ply/Spanner-ply.ply").string(); + else + { + pfd::open_file file("Choose a supported Model File", sharedInputCWD.string(), + { + "All Supported Formats", "*.ply *.stl *.serialized *.obj", + "TODO (.ply)", "*.ply", + "TODO (.stl)", "*.stl", + "Mitsuba 0.6 Serialized (.serialized)", "*.serialized", + "Wavefront Object (.obj)", "*.obj" + }, + false + ); + if (file.result().empty()) + return false; + m_modelPath = file.result()[0]; + } + + // free up + m_renderer->m_instances.clear(); + m_renderer->clearGeometries({.semaphore=m_semaphore.get(),.value=m_realFrameIx}); + m_assetMgr->clearAllAssetCache(); + + //! load the geometry + IAssetLoader::SAssetLoadParams params = {}; + params.meshManipulatorOverride = nullptr; // TODO + auto bundle = m_assetMgr->getAsset(m_modelPath,params); + if (bundle.getContents().empty()) + return false; + + // + core::vector> geometries; + switch (bundle.getAssetType()) + { + case IAsset::E_TYPE::ET_GEOMETRY: + for (const auto& item : bundle.getContents()) + if (auto polyGeo=IAsset::castDown(item); polyGeo) + geometries.push_back(polyGeo); + break; + default: + m_logger->log("Asset loaded but not a supported type (ET_GEOMETRY,ET_GEOMETRY_COLLECTION)",ILogger::ELL_ERROR); + break; + } + if (geometries.empty()) + return false; + + //! cache results -- speeds up mesh generation on second run + m_qnc->saveCacheToFile(m_system.get(),sharedOutputCWD/"../../tmp/normalCache888.sse"); + + // convert the geometries + { + smart_refctd_ptr converter = CAssetConverter::create({.device=m_device.get()}); + + const auto transferFamily = getTransferUpQueue()->getFamilyIndex(); + + struct SInputs : CAssetConverter::SInputs + { + virtual inline std::span getSharedOwnershipQueueFamilies(const size_t groupCopyID, const asset::ICPUBuffer* buffer, const CAssetConverter::patch_t& patch) const + { + return sharedBufferOwnership; + } + + core::vector sharedBufferOwnership; + } inputs = {}; + core::vector> patches(geometries.size(),CSimpleDebugRenderer::DefaultPolygonGeometryPatch); + { + inputs.logger = m_logger.get(); + std::get>(inputs.assets) = {&geometries.front().get(),geometries.size()}; + std::get>(inputs.patches) = patches; + // set up shared ownership so we don't have to + core::unordered_set families; + families.insert(transferFamily); + families.insert(getGraphicsQueue()->getFamilyIndex()); + if (families.size()>1) + for (const auto fam : families) + inputs.sharedBufferOwnership.push_back(fam); + } + + // reserve + auto reservation = converter->reserve(inputs); + if (!reservation) + { + m_logger->log("Failed to reserve GPU objects for CPU->GPU conversion!",ILogger::ELL_ERROR); + return false; + } + + // convert + { + auto semaphore = m_device->createSemaphore(0u); + + constexpr auto MultiBuffering = 2; + std::array,MultiBuffering> commandBuffers = {}; + { + auto pool = m_device->createCommandPool(transferFamily,IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT|IGPUCommandPool::CREATE_FLAGS::TRANSIENT_BIT); + pool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY,commandBuffers,smart_refctd_ptr(m_logger)); + } + commandBuffers.front()->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + + std::array commandBufferSubmits; + for (auto i=0; ilog("Failed to await submission feature!", ILogger::ELL_ERROR); + return false; + } + } + + const auto& converted = reservation.getGPUObjects(); + if (!m_renderer->addGeometries({ &converted.front().get(),converted.size() })) + return false; + } + +// TODO: get scene bounds and reset camera + + // TODO: write out the geometry + + return true; + } + + // Maximum frames which can be simultaneously submitted, used to cycle through our per-frame resources like command buffers + constexpr static inline uint32_t MaxFramesInFlight = 3u; + // + smart_refctd_ptr m_qnc; + smart_refctd_ptr m_renderer; + // + smart_refctd_ptr m_semaphore; + uint64_t m_realFrameIx = 0; + std::array,MaxFramesInFlight> m_cmdBufs; + // + InputSystem::ChannelReader mouse; + InputSystem::ChannelReader keyboard; + // + Camera camera = Camera(core::vectorSIMDf(0, 0, 0), core::vectorSIMDf(0, 0, 0), core::matrix4SIMD()); + // mutables + std::string m_modelPath; +}; + +NBL_MAIN_FUNC(MeshLoadersApp) \ No newline at end of file diff --git a/56_RayQuery/pipeline.groovy b/12_MeshLoaders/pipeline.groovy similarity index 87% rename from 56_RayQuery/pipeline.groovy rename to 12_MeshLoaders/pipeline.groovy index beba797c3..7b7c9702a 100644 --- a/56_RayQuery/pipeline.groovy +++ b/12_MeshLoaders/pipeline.groovy @@ -2,9 +2,9 @@ import org.DevshGraphicsProgramming.Agent import org.DevshGraphicsProgramming.BuilderInfo import org.DevshGraphicsProgramming.IBuilder -class CRayQueryBuilder extends IBuilder +class CUIBuilder extends IBuilder { - public CRayQueryBuilder(Agent _agent, _info) + public CUIBuilder(Agent _agent, _info) { super(_agent, _info) } @@ -44,7 +44,7 @@ class CRayQueryBuilder extends IBuilder def create(Agent _agent, _info) { - return new CRayQueryBuilder(_agent, _info) + return new CUIBuilder(_agent, _info) } return this \ No newline at end of file diff --git a/22_CppCompat/CIntrinsicsTester.h b/22_CppCompat/CIntrinsicsTester.h index 77aa2c1ca..d053977c0 100644 --- a/22_CppCompat/CIntrinsicsTester.h +++ b/22_CppCompat/CIntrinsicsTester.h @@ -1,12 +1,13 @@ #ifndef _NBL_EXAMPLES_TESTS_22_CPP_COMPAT_C_INTRINSICS_TESTER_INCLUDED_ #define _NBL_EXAMPLES_TESTS_22_CPP_COMPAT_C_INTRINSICS_TESTER_INCLUDED_ -#include + +#include "nbl/examples/examples.hpp" + #include "app_resources/common.hlsl" -#include "nbl/application_templates/MonoDeviceApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" #include "ITester.h" + using namespace nbl; class CIntrinsicsTester final : public ITester diff --git a/22_CppCompat/CTgmathTester.h b/22_CppCompat/CTgmathTester.h index 6d2b23c73..63b0e483e 100644 --- a/22_CppCompat/CTgmathTester.h +++ b/22_CppCompat/CTgmathTester.h @@ -1,12 +1,13 @@ #ifndef _NBL_EXAMPLES_TESTS_22_CPP_COMPAT_C_TGMATH_TESTER_INCLUDED_ #define _NBL_EXAMPLES_TESTS_22_CPP_COMPAT_C_TGMATH_TESTER_INCLUDED_ -#include + +#include "nbl/examples/examples.hpp" + #include "app_resources/common.hlsl" -#include "nbl/application_templates/MonoDeviceApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" #include "ITester.h" + using namespace nbl; class CTgmathTester final : public ITester diff --git a/22_CppCompat/ITester.h b/22_CppCompat/ITester.h index a216fbf40..9f2353c95 100644 --- a/22_CppCompat/ITester.h +++ b/22_CppCompat/ITester.h @@ -1,10 +1,12 @@ #ifndef _NBL_EXAMPLES_TESTS_22_CPP_COMPAT_I_TESTER_INCLUDED_ #define _NBL_EXAMPLES_TESTS_22_CPP_COMPAT_I_TESTER_INCLUDED_ -#include + +#include "nbl/examples/examples.hpp" + #include "app_resources/common.hlsl" -#include "nbl/application_templates/MonoDeviceApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" +#include "nbl/asset/metadata/CHLSLMetadata.h" + using namespace nbl; @@ -45,14 +47,15 @@ class ITester logFail("Failed to create Command Buffers!\n"); // Load shaders, set up pipeline - core::smart_refctd_ptr shader; + core::smart_refctd_ptr shader; + auto shaderStage = ESS_UNKNOWN; { asset::IAssetLoader::SAssetLoadParams lp = {}; lp.logger = m_logger.get(); lp.workingDirectory = ""; // virtual root auto assetBundle = m_assetMgr->getAsset(pipleineSetupData.testShaderPath, lp); const auto assets = assetBundle.getContents(); - if (assets.empty()) + if (assets.empty() || assetBundle.getAssetType() != asset::IAsset::ET_SHADER) { logFail("Could not load shader!"); assert(0); @@ -60,12 +63,14 @@ class ITester // It would be super weird if loading a shader from a file produced more than 1 asset assert(assets.size() == 1); - core::smart_refctd_ptr source = asset::IAsset::castDown(assets[0]); + core::smart_refctd_ptr source = asset::IAsset::castDown(assets[0]); + const auto hlslMetadata = static_cast(assetBundle.getMetadata()); + shaderStage = hlslMetadata->shaderStages->front(); auto* compilerSet = m_assetMgr->getCompilerSet(); asset::IShaderCompiler::SCompilerOptions options = {}; - options.stage = source->getStage(); + options.stage = shaderStage; options.targetSpirvVersion = m_device->getPhysicalDevice()->getLimits().spirvVersion; options.spirvOptimizer = nullptr; options.debugInfoFlags |= asset::IShaderCompiler::E_DEBUG_INFO_FLAGS::EDIF_SOURCE_BIT; @@ -73,11 +78,7 @@ class ITester options.preprocessorOptions.logger = m_logger.get(); options.preprocessorOptions.includeFinder = compilerSet->getShaderCompiler(source->getContentType())->getDefaultIncludeFinder(); - auto spirv = compilerSet->compileToSPIRV(source.get(), options); - - video::ILogicalDevice::SShaderCreationParameters params{}; - params.cpushader = spirv.get(); - shader = m_device->createShader(params); + shader = compilerSet->compileToSPIRV(source.get(), options); } if (!shader) diff --git a/22_CppCompat/main.cpp b/22_CppCompat/main.cpp index 7fa2556c4..70c8d7b3a 100644 --- a/22_CppCompat/main.cpp +++ b/22_CppCompat/main.cpp @@ -1,26 +1,26 @@ // Copyright (C) 2018-2024 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h -#include -#include -#include -#include -#include "nbl/application_templates/MonoDeviceApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" #include "app_resources/common.hlsl" #include "CTgmathTester.h" #include "CIntrinsicsTester.h" +#include +#include +#include + + +using namespace nbl; using namespace nbl::core; using namespace nbl::hlsl; using namespace nbl::system; using namespace nbl::asset; +using namespace nbl::ui; using namespace nbl::video; -using namespace nbl::application_templates; - +using namespace nbl::examples; //using namespace glm; @@ -43,10 +43,10 @@ struct T float32_t4 h; }; -class CompatibilityTest final : public MonoDeviceApplication, public MonoAssetManagerAndBuiltinResourceApplication +class CompatibilityTest final : public application_templates::MonoDeviceApplication, public BuiltinResourcesApplication { - using device_base_t = MonoDeviceApplication; - using asset_base_t = MonoAssetManagerAndBuiltinResourceApplication; + using device_base_t = application_templates::MonoDeviceApplication; + using asset_base_t = BuiltinResourcesApplication; public: CompatibilityTest(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) : IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) {} @@ -84,7 +84,7 @@ class CompatibilityTest final : public MonoDeviceApplication, public MonoAssetMa m_commandPool = m_device->createCommandPool(m_queue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); m_commandPool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY, { &m_cmdbuf,1 }, smart_refctd_ptr(m_logger)); - smart_refctd_ptr shader; + smart_refctd_ptr shader; { IAssetLoader::SAssetLoadParams lp = {}; lp.logger = m_logger.get(); @@ -94,14 +94,12 @@ class CompatibilityTest final : public MonoDeviceApplication, public MonoAssetMa if (assets.empty()) return logFail("Could not load shader!"); - // lets go straight from ICPUSpecializedShader to IGPUSpecializedShader - auto source = IAsset::castDown(assets[0]); + auto source = IAsset::castDown(assets[0]); // The down-cast should not fail! assert(source); - assert(source->getStage() == IShader::E_SHADER_STAGE::ESS_COMPUTE); // this time we skip the use of the asset converter since the ICPUShader->IGPUShader path is quick and simple - shader = m_device->createShader(source.get()); + shader = m_device->compileShader({ source.get() }); if (!shader) return logFail("Creation of a GPU Shader to from CPU Shader source failed!"); } @@ -129,6 +127,7 @@ class CompatibilityTest final : public MonoDeviceApplication, public MonoAssetMa IGPUComputePipeline::SCreationParams params = {}; params.layout = layout.get(); params.shader.shader = shader.get(); + params.shader.entryPoint = "main"; if (!m_device->createComputePipelines(nullptr, { ¶ms,1 }, &m_pipeline)) return logFail("Failed to create compute pipeline!\n"); } diff --git a/23_ArithmeticUnitTest/CMakeLists.txt b/23_Arithmetic2UnitTest/CMakeLists.txt similarity index 100% rename from 23_ArithmeticUnitTest/CMakeLists.txt rename to 23_Arithmetic2UnitTest/CMakeLists.txt diff --git a/23_ArithmeticUnitTest/app_resources/common.hlsl b/23_Arithmetic2UnitTest/app_resources/common.hlsl similarity index 89% rename from 23_ArithmeticUnitTest/app_resources/common.hlsl rename to 23_Arithmetic2UnitTest/app_resources/common.hlsl index 10892a2b9..6654645cf 100644 --- a/23_ArithmeticUnitTest/app_resources/common.hlsl +++ b/23_Arithmetic2UnitTest/app_resources/common.hlsl @@ -1,15 +1,14 @@ #include "nbl/builtin/hlsl/cpp_compat.hlsl" #include "nbl/builtin/hlsl/functional.hlsl" -template -struct Output +struct PushConstantData { - NBL_CONSTEXPR_STATIC_INLINE uint32_t ScanElementCount = kScanElementCount; - - uint32_t subgroupSize; - uint32_t data[ScanElementCount]; + uint64_t pInputBuf; + uint64_t pOutputBuf[8]; }; +namespace arithmetic +{ // Thanks to our unified HLSL/C++ STD lib we're able to remove a whole load of code template struct bit_and : nbl::hlsl::bit_and @@ -92,5 +91,6 @@ struct ballot : nbl::hlsl::plus static inline constexpr const char* name = "bitcount"; #endif }; +} -#include "nbl/builtin/hlsl/subgroup/basic.hlsl" \ No newline at end of file +#include "nbl/builtin/hlsl/glsl_compat/subgroup_basic.hlsl" diff --git a/23_Arithmetic2UnitTest/app_resources/shaderCommon.hlsl b/23_Arithmetic2UnitTest/app_resources/shaderCommon.hlsl new file mode 100644 index 000000000..3793b08f8 --- /dev/null +++ b/23_Arithmetic2UnitTest/app_resources/shaderCommon.hlsl @@ -0,0 +1,19 @@ +#include "common.hlsl" + +using namespace nbl; +using namespace hlsl; + +[[vk::push_constant]] PushConstantData pc; + +struct device_capabilities +{ +#ifdef TEST_NATIVE + NBL_CONSTEXPR_STATIC_INLINE bool shaderSubgroupArithmetic = true; +#else + NBL_CONSTEXPR_STATIC_INLINE bool shaderSubgroupArithmetic = false; +#endif +}; + +#ifndef OPERATION +#error "Define OPERATION!" +#endif diff --git a/23_Arithmetic2UnitTest/app_resources/testSubgroup.comp.hlsl b/23_Arithmetic2UnitTest/app_resources/testSubgroup.comp.hlsl new file mode 100644 index 000000000..3105aec56 --- /dev/null +++ b/23_Arithmetic2UnitTest/app_resources/testSubgroup.comp.hlsl @@ -0,0 +1,55 @@ +#pragma shader_stage(compute) + +#define operation_t nbl::hlsl::OPERATION + +#include "nbl/builtin/hlsl/glsl_compat/core.hlsl" +#include "nbl/builtin/hlsl/glsl_compat/subgroup_basic.hlsl" +#include "nbl/builtin/hlsl/subgroup2/arithmetic_portability.hlsl" +#include "nbl/builtin/hlsl/subgroup2/arithmetic_params.hlsl" + +#include "shaderCommon.hlsl" +#include "nbl/builtin/hlsl/workgroup2/basic.hlsl" + +template +using params_t = SUBGROUP_CONFIG_T; + +typedef vector::base_t, device_capabilities>::ItemsPerInvocation> type_t; + +uint32_t globalIndex() +{ + return glsl::gl_WorkGroupID().x*WORKGROUP_SIZE+workgroup::SubgroupContiguousIndex(); +} + +template +static void subtest(NBL_CONST_REF_ARG(type_t) sourceVal) +{ + const uint64_t outputBufAddr = pc.pOutputBuf[Binop::BindingIndex]; + + assert(glsl::gl_SubgroupSize() == params_t::config_t::Size) + + operation_t > func; + type_t val = func(sourceVal); + + vk::RawBufferStore(outputBufAddr + sizeof(type_t) * globalIndex(), val, sizeof(uint32_t)); +} + +type_t test() +{ + const uint32_t idx = globalIndex(); + type_t sourceVal = vk::RawBufferLoad(pc.pInputBuf + idx * sizeof(type_t)); + + subtest >(sourceVal); + subtest >(sourceVal); + subtest >(sourceVal); + subtest >(sourceVal); + subtest >(sourceVal); + subtest >(sourceVal); + subtest >(sourceVal); + return sourceVal; +} + +[numthreads(WORKGROUP_SIZE,1,1)] +void main() +{ + test(); +} diff --git a/23_Arithmetic2UnitTest/app_resources/testWorkgroup.comp.hlsl b/23_Arithmetic2UnitTest/app_resources/testWorkgroup.comp.hlsl new file mode 100644 index 000000000..a3e70b8ff --- /dev/null +++ b/23_Arithmetic2UnitTest/app_resources/testWorkgroup.comp.hlsl @@ -0,0 +1,75 @@ +#pragma shader_stage(compute) + +#include "nbl/builtin/hlsl/glsl_compat/core.hlsl" +#include "nbl/builtin/hlsl/glsl_compat/subgroup_basic.hlsl" +#include "nbl/builtin/hlsl/subgroup2/arithmetic_portability.hlsl" +#include "nbl/builtin/hlsl/workgroup2/arithmetic.hlsl" + +using config_t = WORKGROUP_CONFIG_T; + +#include "shaderCommon.hlsl" + +typedef vector type_t; + +// final (level 1/2) scan needs to fit in one subgroup exactly +groupshared uint32_t scratch[mpl::max_v]; + +#include "nbl/examples/workgroup/DataAccessors.hlsl" +using namespace nbl::hlsl::examples::workgroup; + +static ScratchProxy arithmeticAccessor; + +template +struct operation_t +{ + using binop_base_t = typename Binop::base_t; + using otype_t = typename Binop::type_t; + + // workgroup reduction returns the value of the reduction + // workgroup scans do no return anything, but use the data accessor to do the storing directly + void operator()() + { + using data_proxy_t = PreloadedDataProxy; + data_proxy_t dataAccessor = data_proxy_t::create(pc.pInputBuf, pc.pOutputBuf[Binop::BindingIndex]); + dataAccessor.preload(); +#if IS_REDUCTION + otype_t value = +#endif + OPERATION::template __call(dataAccessor,arithmeticAccessor); + // we barrier before because we alias the accessors for Binop + arithmeticAccessor.workgroupExecutionAndMemoryBarrier(); +#if IS_REDUCTION + [unroll] + for (uint32_t i = 0; i < data_proxy_t::PreloadedDataCount; i++) + dataAccessor.preloaded[i] = value; +#endif + dataAccessor.unload(); + } +}; + + +template +static void subtest() +{ + assert(glsl::gl_SubgroupSize() == config_t::SubgroupSize) + + operation_t func; + func(); +} + +void test() +{ + subtest >(); + subtest >(); + subtest >(); + subtest >(); + subtest >(); + subtest >(); + subtest >(); +} + +[numthreads(config_t::WorkgroupSize,1,1)] +void main() +{ + test(); +} \ No newline at end of file diff --git a/23_ArithmeticUnitTest/config.json.template b/23_Arithmetic2UnitTest/config.json.template similarity index 100% rename from 23_ArithmeticUnitTest/config.json.template rename to 23_Arithmetic2UnitTest/config.json.template diff --git a/23_Arithmetic2UnitTest/main.cpp b/23_Arithmetic2UnitTest/main.cpp new file mode 100644 index 000000000..3939fd443 --- /dev/null +++ b/23_Arithmetic2UnitTest/main.cpp @@ -0,0 +1,509 @@ +// TODO: copyright notice + + +#include "nbl/examples/examples.hpp" + +#include "app_resources/common.hlsl" +#include "nbl/builtin/hlsl/workgroup2/arithmetic_config.hlsl" +#include "nbl/builtin/hlsl/subgroup2/arithmetic_params.hlsl" + + +using namespace nbl; +using namespace core; +using namespace asset; +using namespace system; +using namespace video; + +// method emulations on the CPU, to verify the results of the GPU methods +template +struct emulatedReduction +{ + using type_t = typename Binop::type_t; + + static inline void impl(type_t* out, const type_t* in, const uint32_t itemCount) + { + const type_t red = std::reduce(in,in+itemCount,Binop::identity,Binop()); + std::fill(out,out+itemCount,red); + } + + static inline constexpr const char* name = "reduction"; +}; +template +struct emulatedScanInclusive +{ + using type_t = typename Binop::type_t; + + static inline void impl(type_t* out, const type_t* in, const uint32_t itemCount) + { + std::inclusive_scan(in,in+itemCount,out,Binop()); + } + static inline constexpr const char* name = "inclusive_scan"; +}; +template +struct emulatedScanExclusive +{ + using type_t = typename Binop::type_t; + + static inline void impl(type_t* out, const type_t* in, const uint32_t itemCount) + { + std::exclusive_scan(in,in+itemCount,out,Binop::identity,Binop()); + } + static inline constexpr const char* name = "exclusive_scan"; +}; + +class Workgroup2ScanTestApp final : public application_templates::BasicMultiQueueApplication, public examples::BuiltinResourcesApplication +{ + using device_base_t = application_templates::BasicMultiQueueApplication; + using asset_base_t = examples::BuiltinResourcesApplication; + +public: + Workgroup2ScanTestApp(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) : + system::IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) {} + + bool onAppInitialized(smart_refctd_ptr&& system) override + { + if (!device_base_t::onAppInitialized(std::move(system))) + return false; + if (!asset_base_t::onAppInitialized(std::move(system))) + return false; + + transferDownQueue = getTransferDownQueue(); + computeQueue = getComputeQueue(); + + // TODO: get the element count from argv + const uint32_t elementCount = 1024 * 1024; + // populate our random data buffer on the CPU and create a GPU copy + inputData = new uint32_t[elementCount]; + smart_refctd_ptr gpuinputDataBuffer; + { + std::mt19937 randGenerator(0xdeadbeefu); + for (uint32_t i = 0u; i < elementCount; i++) + inputData[i] = randGenerator(); // TODO: change to using xoroshiro, then we can skip having the input buffer at all + + IGPUBuffer::SCreationParams inputDataBufferCreationParams = {}; + inputDataBufferCreationParams.size = sizeof(uint32_t) * elementCount; + inputDataBufferCreationParams.usage = IGPUBuffer::EUF_STORAGE_BUFFER_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; + m_utils->createFilledDeviceLocalBufferOnDedMem( + SIntendedSubmitInfo{.queue=getTransferUpQueue()}, + std::move(inputDataBufferCreationParams), + inputData + ).move_into(gpuinputDataBuffer); + } + + // create 8 buffers for 8 operations + for (auto i=0u; igetSize(); + params.usage = bitflag(IGPUBuffer::EUF_STORAGE_BUFFER_BIT) | IGPUBuffer::EUF_TRANSFER_SRC_BIT | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; + + outputBuffers[i] = m_device->createBuffer(std::move(params)); + auto mreq = outputBuffers[i]->getMemoryReqs(); + mreq.memoryTypeBits &= m_physicalDevice->getDeviceLocalMemoryTypeBits(); + assert(mreq.memoryTypeBits); + + auto bufferMem = m_device->allocate(mreq, outputBuffers[i].get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); + assert(bufferMem.isValid()); + } + pc.pInputBuf = gpuinputDataBuffer->getDeviceAddress(); + for (uint32_t i = 0; i < OutputBufferCount; i++) + pc.pOutputBuf[i] = outputBuffers[i]->getDeviceAddress(); + + // create Pipeline Layout + { + SPushConstantRange pcRange = { .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, .offset = 0,.size = sizeof(PushConstantData) }; + pipelineLayout = m_device->createPipelineLayout({&pcRange, 1}); + } + + const auto spirv_isa_cache_path = localOutputCWD / "spirv_isa_cache.bin"; + // enclose to make sure file goes out of scope and we can reopen it + { + smart_refctd_ptr spirv_isa_cache_input; + // try to load SPIR-V to ISA cache + { + ISystem::future_t> fileCreate; + m_system->createFile(fileCreate, spirv_isa_cache_path, IFile::ECF_READ | IFile::ECF_MAPPABLE | IFile::ECF_COHERENT); + if (auto lock = fileCreate.acquire()) + spirv_isa_cache_input = *lock; + } + // create the cache + { + std::span spirv_isa_cache_data = {}; + if (spirv_isa_cache_input) + spirv_isa_cache_data = { reinterpret_cast(spirv_isa_cache_input->getMappedPointer()),spirv_isa_cache_input->getSize() }; + else + m_logger->log("Failed to load SPIR-V 2 ISA cache!", ILogger::ELL_PERFORMANCE); + // Normally we'd deserialize a `ICPUPipelineCache` properly and pass that instead + m_spirv_isa_cache = m_device->createPipelineCache(spirv_isa_cache_data); + } + } + { + // TODO: rename `deleteDirectory` to just `delete`? and a `IFile::setSize()` ? + m_system->deleteDirectory(spirv_isa_cache_path); + ISystem::future_t> fileCreate; + m_system->createFile(fileCreate, spirv_isa_cache_path, IFile::ECF_WRITE); + // I can be relatively sure I'll succeed to acquire the future, the pointer to created file might be null though. + m_spirv_isa_cache_output = *fileCreate.acquire(); + if (!m_spirv_isa_cache_output) + logFail("Failed to Create SPIR-V to ISA cache file."); + } + + // load shader source from file + auto getShaderSource = [&](const char* filePath) -> auto + { + IAssetLoader::SAssetLoadParams lparams = {}; + lparams.logger = m_logger.get(); + lparams.workingDirectory = ""; + auto bundle = m_assetMgr->getAsset(filePath, lparams); + if (bundle.getContents().empty() || bundle.getAssetType()!=IAsset::ET_SHADER) + { + m_logger->log("Shader %s not found!", ILogger::ELL_ERROR, filePath); + exit(-1); + } + auto firstAssetInBundle = bundle.getContents()[0]; + return smart_refctd_ptr_static_cast(firstAssetInBundle); + }; + + auto subgroupTestSource = getShaderSource("app_resources/testSubgroup.comp.hlsl"); + auto workgroupTestSource = getShaderSource("app_resources/testWorkgroup.comp.hlsl"); + // now create or retrieve final resources to run our tests + sema = m_device->createSemaphore(timelineValue); + resultsBuffer = ICPUBuffer::create({ outputBuffers[0]->getSize() }); + { + smart_refctd_ptr cmdpool = m_device->createCommandPool(computeQueue->getFamilyIndex(),IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); + if (!cmdpool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY,{&cmdbuf,1})) + { + logFail("Failed to create Command Buffers!\n"); + return false; + } + } + + const auto MaxWorkgroupSize = m_physicalDevice->getLimits().maxComputeWorkGroupInvocations; + const auto MinSubgroupSize = m_physicalDevice->getLimits().minSubgroupSize; + const auto MaxSubgroupSize = m_physicalDevice->getLimits().maxSubgroupSize; + for (uint32_t useNative = 0; useNative <= uint32_t(m_physicalDevice->getProperties().limits.shaderSubgroupArithmetic); useNative++) + { + if (useNative) + m_logger->log("Testing with native subgroup arithmetic", ILogger::ELL_INFO); + else + m_logger->log("Testing with emulated subgroup arithmetic", ILogger::ELL_INFO); + + for (auto subgroupSize = MinSubgroupSize; subgroupSize <= MaxSubgroupSize; subgroupSize *= 2u) + { + const uint8_t subgroupSizeLog2 = hlsl::findMSB(subgroupSize); + for (uint32_t workgroupSize = subgroupSize; workgroupSize <= MaxWorkgroupSize; workgroupSize *= 2u) + { + // make sure renderdoc captures everything for debugging + m_api->startCapture(); + m_logger->log("Testing Workgroup Size %u with Subgroup Size %u", ILogger::ELL_INFO, workgroupSize, subgroupSize); + + for (uint32_t j = 0; j < ItemsPerInvocations.size(); j++) + { + const uint32_t itemsPerInvocation = ItemsPerInvocations[j]; + uint32_t itemsPerWG = workgroupSize * itemsPerInvocation; + m_logger->log("Testing Items per Invocation %u", ILogger::ELL_INFO, itemsPerInvocation); + bool passed = true; + passed = runTest(subgroupTestSource, elementCount, subgroupSizeLog2, workgroupSize, bool(useNative), itemsPerWG, itemsPerInvocation) && passed; + logTestOutcome(passed, itemsPerWG); + passed = runTest(subgroupTestSource, elementCount, subgroupSizeLog2, workgroupSize, bool(useNative), itemsPerWG, itemsPerInvocation) && passed; + logTestOutcome(passed, itemsPerWG); + passed = runTest(subgroupTestSource, elementCount, subgroupSizeLog2, workgroupSize, bool(useNative), itemsPerWG, itemsPerInvocation) && passed; + logTestOutcome(passed, itemsPerWG); + + hlsl::workgroup2::SArithmeticConfiguration wgConfig; + wgConfig.init(hlsl::findMSB(workgroupSize), subgroupSizeLog2, itemsPerInvocation); + itemsPerWG = wgConfig.VirtualWorkgroupSize * wgConfig.ItemsPerInvocation_0; + m_logger->log("Testing Item Count %u", ILogger::ELL_INFO, itemsPerWG); + passed = runTest(workgroupTestSource, elementCount, subgroupSizeLog2, workgroupSize, bool(useNative), itemsPerWG, itemsPerInvocation) && passed; + logTestOutcome(passed, itemsPerWG); + passed = runTest(workgroupTestSource, elementCount, subgroupSizeLog2, workgroupSize, bool(useNative), itemsPerWG, itemsPerInvocation) && passed; + logTestOutcome(passed, itemsPerWG); + passed = runTest(workgroupTestSource, elementCount, subgroupSizeLog2, workgroupSize, bool(useNative), itemsPerWG, itemsPerInvocation) && passed; + logTestOutcome(passed, itemsPerWG); + } + m_api->endCapture(); + + // save cache every now and then + { + auto cpu = m_spirv_isa_cache->convertToCPUCache(); + // Normally we'd beautifully JSON serialize the thing, allow multiple devices & drivers + metadata + auto bin = cpu->getEntries().begin()->second.bin; + IFile::success_t success; + m_spirv_isa_cache_output->write(success, bin->data(), 0ull, bin->size()); + if (!success) + logFail("Could not write Create SPIR-V to ISA cache to disk!"); + } + } + } + } + + return true; + } + + virtual bool onAppTerminated() override + { + m_logger->log("==========Result==========", ILogger::ELL_INFO); + m_logger->log("Fail Count: %u", ILogger::ELL_INFO, totalFailCount); + delete[] inputData; + return true; + } + + // the unit test is carried out on init + void workLoopBody() override {} + + // + bool keepRunning() override { return false; } + +private: + void logTestOutcome(bool passed, uint32_t workgroupSize) + { + if (passed) + m_logger->log("Passed test #%u", ILogger::ELL_INFO, workgroupSize); + else + { + totalFailCount++; + m_logger->log("Failed test #%u", ILogger::ELL_ERROR, workgroupSize); + } + } + + // create pipeline (specialized every test) [TODO: turn into a future/async] + smart_refctd_ptr createPipeline(const IShader* overridenUnspecialized, const uint8_t subgroupSizeLog2) + { + auto shader = m_device->compileShader({ overridenUnspecialized }); + IGPUComputePipeline::SCreationParams params = {}; + params.layout = pipelineLayout.get(); + params.shader = { + .shader = shader.get(), + .entryPoint = "main", + .requiredSubgroupSize = static_cast(subgroupSizeLog2), + .entries = nullptr, + }; + params.cached.requireFullSubgroups = true; + core::smart_refctd_ptr pipeline; + if (!m_device->createComputePipelines(m_spirv_isa_cache.get(),{¶ms,1},&pipeline)) + return nullptr; + return pipeline; + } + + template class Arithmetic, bool WorkgroupTest> + bool runTest(const smart_refctd_ptr& source, const uint32_t elementCount, const uint8_t subgroupSizeLog2, const uint32_t workgroupSize, bool useNative, uint32_t itemsPerWG, uint32_t itemsPerInvoc = 1u) + { + std::string arith_name = Arithmetic>::name; + const uint32_t workgroupSizeLog2 = hlsl::findMSB(workgroupSize); + + auto compiler = make_smart_refctd_ptr(smart_refctd_ptr(m_system)); + CHLSLCompiler::SOptions options = {}; + options.stage = IShader::E_SHADER_STAGE::ESS_COMPUTE; + options.targetSpirvVersion = m_device->getPhysicalDevice()->getLimits().spirvVersion; + options.spirvOptimizer = nullptr; +#ifndef _NBL_DEBUG + ISPIRVOptimizer::E_OPTIMIZER_PASS optPasses = ISPIRVOptimizer::EOP_STRIP_DEBUG_INFO; + auto opt = make_smart_refctd_ptr(std::span(&optPasses, 1)); + options.spirvOptimizer = opt.get(); +#else + options.debugInfoFlags |= IShaderCompiler::E_DEBUG_INFO_FLAGS::EDIF_LINE_BIT; +#endif + options.preprocessorOptions.sourceIdentifier = source->getFilepathHint(); + options.preprocessorOptions.logger = m_logger.get(); + + auto* includeFinder = compiler->getDefaultIncludeFinder(); + options.preprocessorOptions.includeFinder = includeFinder; + + smart_refctd_ptr overriddenUnspecialized; + if constexpr (WorkgroupTest) + { + hlsl::workgroup2::SArithmeticConfiguration wgConfig; + wgConfig.init(hlsl::findMSB(workgroupSize), subgroupSizeLog2, itemsPerInvoc); + + const std::string definitions[3] = { + "workgroup2::" + arith_name, + wgConfig.getConfigTemplateStructString(), + std::to_string(arith_name=="reduction") + }; + + const IShaderCompiler::SMacroDefinition defines[4] = { + { "OPERATION", definitions[0] }, + { "WORKGROUP_CONFIG_T", definitions[1] }, + { "IS_REDUCTION", definitions[2] }, + { "TEST_NATIVE", "1" } + }; + if (useNative) + options.preprocessorOptions.extraDefines = { defines, defines + 4 }; + else + options.preprocessorOptions.extraDefines = { defines, defines + 3 }; + + overriddenUnspecialized = compiler->compileToSPIRV((const char*)source->getContent()->getPointer(), options); + } + else + { + hlsl::subgroup2::SArithmeticParams sgParams; + sgParams.init(subgroupSizeLog2, itemsPerInvoc); + + const std::string definitions[3] = { + "subgroup2::" + arith_name, + std::to_string(workgroupSize), + sgParams.getParamTemplateStructString() + }; + + const IShaderCompiler::SMacroDefinition defines[4] = { + { "OPERATION", definitions[0] }, + { "WORKGROUP_SIZE", definitions[1] }, + { "SUBGROUP_CONFIG_T", definitions[2] }, + { "TEST_NATIVE", "1" } + }; + if (useNative) + options.preprocessorOptions.extraDefines = { defines, defines + 4 }; + else + options.preprocessorOptions.extraDefines = { defines, defines + 3 }; + + overriddenUnspecialized = compiler->compileToSPIRV((const char*)source->getContent()->getPointer(), options); + } + + auto pipeline = createPipeline(overriddenUnspecialized.get(),subgroupSizeLog2); + + // TODO: overlap dispatches with memory readbacks (requires multiple copies of `buffers`) + uint32_t workgroupCount = 1;// min(elementCount / itemsPerWG, m_physicalDevice->getLimits().maxComputeWorkGroupCount[0]); + + cmdbuf->begin(IGPUCommandBuffer::USAGE::NONE); + cmdbuf->bindComputePipeline(pipeline.get()); + cmdbuf->pushConstants(pipelineLayout.get(), IShader::E_SHADER_STAGE::ESS_COMPUTE, 0, sizeof(PushConstantData), &pc); + cmdbuf->dispatch(workgroupCount, 1, 1); + { + IGPUCommandBuffer::SPipelineBarrierDependencyInfo::buffer_barrier_t memoryBarrier[OutputBufferCount]; + for (auto i=0u; igetSize(),outputBuffers[i]} + }; + } + IGPUCommandBuffer::SPipelineBarrierDependencyInfo info = {.memBarriers={},.bufBarriers=memoryBarrier}; + cmdbuf->pipelineBarrier(asset::E_DEPENDENCY_FLAGS::EDF_NONE,info); + } + cmdbuf->end(); + + const IQueue::SSubmitInfo::SSemaphoreInfo signal[1] = {{.semaphore=sema.get(),.value=++timelineValue}}; + const IQueue::SSubmitInfo::SCommandBufferInfo cmdbufs[1] = {{.cmdbuf=cmdbuf.get()}}; + const IQueue::SSubmitInfo submits[1] = {{.commandBuffers=cmdbufs,.signalSemaphores=signal}}; + computeQueue->submit(submits); + const ISemaphore::SWaitInfo wait[1] = {{.semaphore=sema.get(),.value=timelineValue}}; + m_device->blockForSemaphores(wait); + + const uint32_t subgroupSize = 1u << subgroupSizeLog2; + // check results + bool passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount, subgroupSize, itemsPerInvoc); + passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount, subgroupSize, itemsPerInvoc) && passed; + passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount, subgroupSize, itemsPerInvoc) && passed; + passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount, subgroupSize, itemsPerInvoc) && passed; + passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount, subgroupSize, itemsPerInvoc) && passed; + passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount, subgroupSize, itemsPerInvoc) && passed; + passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount, subgroupSize, itemsPerInvoc) && passed; + + return passed; + } + + //returns true if result matches + template class Arithmetic, class Binop, bool WorkgroupTest> + bool validateResults(const uint32_t itemsPerWG, const uint32_t workgroupCount, const uint32_t subgroupSize, const uint32_t itemsPerInvoc) + { + bool success = true; + + // download data + const SBufferRange bufferRange = {0u, resultsBuffer->getSize(), outputBuffers[Binop::BindingIndex]}; + m_utils->downloadBufferRangeViaStagingBufferAutoSubmit(SIntendedSubmitInfo{.queue=transferDownQueue},bufferRange,resultsBuffer->getPointer()); + + using type_t = typename Binop::type_t; + const auto testData = reinterpret_cast(resultsBuffer->getPointer()); + + // TODO: parallel for (the temporary values need to be threadlocal or what?) + // now check if the data obtained has valid values + type_t* tmp = new type_t[itemsPerWG]; + for (uint32_t workgroupID = 0u; success && workgroupID < workgroupCount; workgroupID++) + { + if constexpr (WorkgroupTest) + { + const auto workgroupOffset = workgroupID * itemsPerWG; + Arithmetic::impl(tmp, inputData + workgroupOffset, itemsPerWG); + + for (uint32_t localInvocationIndex = 0u; localInvocationIndex < itemsPerWG; localInvocationIndex++) + { + const auto globalInvocationIndex = workgroupOffset + localInvocationIndex; + const auto cpuVal = tmp[localInvocationIndex]; + const auto gpuVal = testData[globalInvocationIndex]; + if (cpuVal != gpuVal) + { + m_logger->log( + "Failed test #%d (%s) (%s) Expected %u got %u for workgroup %d and localinvoc %d", + ILogger::ELL_ERROR, itemsPerWG, WorkgroupTest ? "workgroup" : "subgroup", Binop::name, + cpuVal, gpuVal, workgroupID, localInvocationIndex + ); + success = false; + break; + } + } + } + else + { + const auto workgroupOffset = workgroupID * itemsPerWG; + const auto workgroupSize = itemsPerWG / itemsPerInvoc; + for (uint32_t pseudoSubgroupID = 0u; pseudoSubgroupID < workgroupSize; pseudoSubgroupID += subgroupSize) + Arithmetic::impl(tmp + pseudoSubgroupID * itemsPerInvoc, inputData + workgroupOffset + pseudoSubgroupID * itemsPerInvoc, subgroupSize * itemsPerInvoc); + + for (uint32_t localInvocationIndex = 0u; localInvocationIndex < workgroupSize; localInvocationIndex++) + { + const auto localOffset = localInvocationIndex * itemsPerInvoc; + const auto globalInvocationIndex = workgroupOffset + localOffset; + + for (uint32_t itemInvocationIndex = 0u; itemInvocationIndex < itemsPerInvoc; itemInvocationIndex++) + { + const auto cpuVal = tmp[localOffset + itemInvocationIndex]; + const auto gpuVal = testData[globalInvocationIndex + itemInvocationIndex]; + if (cpuVal != gpuVal) + { + m_logger->log( + "Failed test #%d (%s) (%s) Expected %u got %u for workgroup %d and localinvoc %d and iteminvoc %d", + ILogger::ELL_ERROR, itemsPerWG, WorkgroupTest ? "workgroup" : "subgroup", Binop::name, + cpuVal, gpuVal, workgroupID, localInvocationIndex, itemInvocationIndex + ); + success = false; + break; + } + } + } + } + } + delete[] tmp; + + return success; + } + + IQueue* transferDownQueue; + IQueue* computeQueue; + smart_refctd_ptr m_spirv_isa_cache; + smart_refctd_ptr m_spirv_isa_cache_output; + + uint32_t* inputData = nullptr; + constexpr static inline uint32_t OutputBufferCount = 8u; + smart_refctd_ptr outputBuffers[OutputBufferCount]; + smart_refctd_ptr pipelineLayout; + PushConstantData pc; + + smart_refctd_ptr sema; + uint64_t timelineValue = 0; + smart_refctd_ptr cmdbuf; + smart_refctd_ptr resultsBuffer; + + uint32_t totalFailCount = 0; + + constexpr static inline std::array ItemsPerInvocations = { 1, 2, 3, 4 }; +}; + +NBL_MAIN_FUNC(Workgroup2ScanTestApp) \ No newline at end of file diff --git a/23_ArithmeticUnitTest/pipeline.groovy b/23_Arithmetic2UnitTest/pipeline.groovy similarity index 100% rename from 23_ArithmeticUnitTest/pipeline.groovy rename to 23_Arithmetic2UnitTest/pipeline.groovy diff --git a/23_ArithmeticUnitTest/app_resources/shaderCommon.hlsl b/23_ArithmeticUnitTest/app_resources/shaderCommon.hlsl deleted file mode 100644 index 13ee8d21e..000000000 --- a/23_ArithmeticUnitTest/app_resources/shaderCommon.hlsl +++ /dev/null @@ -1,55 +0,0 @@ -#include "common.hlsl" - -#include "nbl/builtin/hlsl/glsl_compat/core.hlsl" -#include "nbl/builtin/hlsl/subgroup/basic.hlsl" -#include "nbl/builtin/hlsl/subgroup/arithmetic_portability.hlsl" - -#include "nbl/builtin/hlsl/jit/device_capabilities.hlsl" - -// https://github.com/microsoft/DirectXShaderCompiler/issues/6144 -uint32_t3 nbl::hlsl::glsl::gl_WorkGroupSize() {return uint32_t3(WORKGROUP_SIZE,1,1);} - -// unfortunately DXC chokes on descriptors as static members -// https://github.com/microsoft/DirectXShaderCompiler/issues/5940 -[[vk::binding(0, 0)]] StructuredBuffer inputValue; -[[vk::binding(1, 0)]] RWByteAddressBuffer output[8]; - -// because subgroups don't match `gl_LocalInvocationIndex` snake curve addressing, we also can't load inputs that way -uint32_t globalIndex(); -// since we test ITEMS_PER_WG class binop> -static void subtest(NBL_CONST_REF_ARG(type_t) sourceVal) -{ - if (globalIndex()==0u) - output[binop::BindingIndex].template Store(0,nbl::hlsl::glsl::gl_SubgroupSize()); - - operation_t::base_t,nbl::hlsl::jit::device_capabilities> func; - if (canStore()) - output[binop::BindingIndex].template Store(sizeof(uint32_t)+sizeof(type_t)*globalIndex(),func(sourceVal)); -} - - -type_t test() -{ - const type_t sourceVal = inputValue[globalIndex()]; - - subtest(sourceVal); - subtest(sourceVal); - subtest(sourceVal); - subtest(sourceVal); - subtest(sourceVal); - subtest(sourceVal); - subtest(sourceVal); - return sourceVal; -} - -#include "nbl/builtin/hlsl/workgroup/basic.hlsl" \ No newline at end of file diff --git a/23_ArithmeticUnitTest/app_resources/testSubgroup.comp.hlsl b/23_ArithmeticUnitTest/app_resources/testSubgroup.comp.hlsl deleted file mode 100644 index 479265d73..000000000 --- a/23_ArithmeticUnitTest/app_resources/testSubgroup.comp.hlsl +++ /dev/null @@ -1,18 +0,0 @@ -#pragma shader_stage(compute) - -#define operation_t nbl::hlsl::OPERATION - -#include "shaderCommon.hlsl" - -uint32_t globalIndex() -{ - return nbl::hlsl::glsl::gl_WorkGroupID().x*WORKGROUP_SIZE+nbl::hlsl::workgroup::SubgroupContiguousIndex(); -} - -bool canStore() {return true;} - -[numthreads(WORKGROUP_SIZE,1,1)] -void main() -{ - test(); -} \ No newline at end of file diff --git a/23_ArithmeticUnitTest/app_resources/testWorkgroup.comp.hlsl b/23_ArithmeticUnitTest/app_resources/testWorkgroup.comp.hlsl deleted file mode 100644 index 9bafae47f..000000000 --- a/23_ArithmeticUnitTest/app_resources/testWorkgroup.comp.hlsl +++ /dev/null @@ -1,107 +0,0 @@ -#pragma shader_stage(compute) - - -#include "nbl/builtin/hlsl/workgroup/scratch_size.hlsl" - -static const uint32_t ArithmeticSz = nbl::hlsl::workgroup::scratch_size_arithmetic::value; -static const uint32_t BallotSz = nbl::hlsl::workgroup::scratch_size_ballot::value; -static const uint32_t ScratchSz = ArithmeticSz+BallotSz; - -// TODO: Can we make it a static variable in the ScratchProxy struct? -groupshared uint32_t scratch[ScratchSz]; - - -#include "nbl/builtin/hlsl/workgroup/arithmetic.hlsl" - - -template -struct ScratchProxy -{ - void get(const uint32_t ix, NBL_REF_ARG(uint32_t) value) - { - value = scratch[ix+offset]; - } - void set(const uint32_t ix, const uint32_t value) - { - scratch[ix+offset] = value; - } - - uint32_t atomicOr(const uint32_t ix, const uint32_t value) - { - return nbl::hlsl::glsl::atomicOr(scratch[ix],value); - } - - void workgroupExecutionAndMemoryBarrier() - { - nbl::hlsl::glsl::barrier(); - //nbl::hlsl::glsl::memoryBarrierShared(); implied by the above - } -}; - -static ScratchProxy<0> arithmeticAccessor; - - -#include "nbl/builtin/hlsl/workgroup/broadcast.hlsl" - - -template -struct operation_t -{ - using type_t = typename Binop::type_t; - - type_t operator()(type_t value) - { - type_t retval = nbl::hlsl::OPERATION::template __call >(value,arithmeticAccessor); - // we barrier before because we alias the accessors for Binop - arithmeticAccessor.workgroupExecutionAndMemoryBarrier(); - return retval; - } -}; - - -#include "shaderCommon.hlsl" - -static ScratchProxy ballotAccessor; - - -uint32_t globalIndex() -{ - return nbl::hlsl::glsl::gl_WorkGroupID().x*ITEMS_PER_WG+nbl::hlsl::workgroup::SubgroupContiguousIndex(); -} - -bool canStore() -{ - return nbl::hlsl::workgroup::SubgroupContiguousIndex()::BindingIndex].template Store(0,nbl::hlsl::glsl::gl_SubgroupSize()); - - // we can only ballot booleans, so low bit - nbl::hlsl::workgroup::ballot >(bool(sourceVal & 0x1u), ballotAccessor); - // need to barrier between ballot and usages of a ballot by myself - ballotAccessor.workgroupExecutionAndMemoryBarrier(); - - uint32_t destVal = 0xdeadbeefu; -#define CONSTEXPR_OP_TYPE_TEST(IS_OP) nbl::hlsl::is_same,0x45>,nbl::hlsl::workgroup::IS_OP,0x45> >::value -#define BALLOT_TEMPLATE_ARGS ITEMS_PER_WG,decltype(ballotAccessor),decltype(arithmeticAccessor),nbl::hlsl::jit::device_capabilities - if (CONSTEXPR_OP_TYPE_TEST(reduction)) - destVal = nbl::hlsl::workgroup::ballotBitCount(ballotAccessor,arithmeticAccessor); - else if (CONSTEXPR_OP_TYPE_TEST(inclusive_scan)) - destVal = nbl::hlsl::workgroup::ballotInclusiveBitCount(ballotAccessor,arithmeticAccessor); - else if (CONSTEXPR_OP_TYPE_TEST(exclusive_scan)) - destVal = nbl::hlsl::workgroup::ballotExclusiveBitCount(ballotAccessor,arithmeticAccessor); - else - { - assert(false); - } -#undef BALLOT_TEMPLATE_ARGS -#undef CONSTEXPR_OP_TYPE_TEST - - if (canStore()) - output[ballot::BindingIndex].template Store(sizeof(uint32_t)+sizeof(type_t)*globalIndex(),destVal); -} \ No newline at end of file diff --git a/23_ArithmeticUnitTest/main.cpp b/23_ArithmeticUnitTest/main.cpp deleted file mode 100644 index 147d231e2..000000000 --- a/23_ArithmeticUnitTest/main.cpp +++ /dev/null @@ -1,462 +0,0 @@ -#include "nbl/application_templates/BasicMultiQueueApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" -#include "app_resources/common.hlsl" - -using namespace nbl; -using namespace core; -using namespace asset; -using namespace system; -using namespace video; - -// method emulations on the CPU, to verify the results of the GPU methods -template -struct emulatedReduction -{ - using type_t = typename Binop::type_t; - - static inline void impl(type_t* out, const type_t* in, const uint32_t itemCount) - { - const type_t red = std::reduce(in,in+itemCount,Binop::identity,Binop()); - std::fill(out,out+itemCount,red); - } - - static inline constexpr const char* name = "reduction"; -}; -template -struct emulatedScanInclusive -{ - using type_t = typename Binop::type_t; - - static inline void impl(type_t* out, const type_t* in, const uint32_t itemCount) - { - std::inclusive_scan(in,in+itemCount,out,Binop()); - } - static inline constexpr const char* name = "inclusive_scan"; -}; -template -struct emulatedScanExclusive -{ - using type_t = typename Binop::type_t; - - static inline void impl(type_t* out, const type_t* in, const uint32_t itemCount) - { - std::exclusive_scan(in,in+itemCount,out,Binop::identity,Binop()); - } - static inline constexpr const char* name = "exclusive_scan"; -}; - -class ArithmeticUnitTestApp final : public application_templates::BasicMultiQueueApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication -{ - using device_base_t = application_templates::BasicMultiQueueApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; - -public: - ArithmeticUnitTestApp(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) : - system::IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) {} - - bool onAppInitialized(smart_refctd_ptr&& system) override - { - if (!device_base_t::onAppInitialized(std::move(system))) - return false; - if (!asset_base_t::onAppInitialized(std::move(system))) - return false; - - transferDownQueue = getTransferDownQueue(); - computeQueue = getComputeQueue(); - - // TODO: get the element count from argv - const uint32_t elementCount = Output<>::ScanElementCount; - // populate our random data buffer on the CPU and create a GPU copy - inputData = new uint32_t[elementCount]; - smart_refctd_ptr gpuinputDataBuffer; - { - std::mt19937 randGenerator(0xdeadbeefu); - for (uint32_t i = 0u; i < elementCount; i++) - inputData[i] = randGenerator(); // TODO: change to using xoroshiro, then we can skip having the input buffer at all - - IGPUBuffer::SCreationParams inputDataBufferCreationParams = {}; - inputDataBufferCreationParams.size = sizeof(Output<>::data[0]) * elementCount; - inputDataBufferCreationParams.usage = IGPUBuffer::EUF_STORAGE_BUFFER_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT; - m_utils->createFilledDeviceLocalBufferOnDedMem( - SIntendedSubmitInfo{.queue=getTransferUpQueue()}, - std::move(inputDataBufferCreationParams), - inputData - ).move_into(gpuinputDataBuffer); - } - - // create 8 buffers for 8 operations - for (auto i=0u; igetSize(); - params.usage = bitflag(IGPUBuffer::EUF_STORAGE_BUFFER_BIT) | IGPUBuffer::EUF_TRANSFER_SRC_BIT; - - outputBuffers[i] = m_device->createBuffer(std::move(params)); - auto mreq = outputBuffers[i]->getMemoryReqs(); - mreq.memoryTypeBits &= m_physicalDevice->getDeviceLocalMemoryTypeBits(); - assert(mreq.memoryTypeBits); - - auto bufferMem = m_device->allocate(mreq, outputBuffers[i].get()); - assert(bufferMem.isValid()); - } - - // create Descriptor Set and Pipeline Layout - { - // create Descriptor Set Layout - smart_refctd_ptr dsLayout; - { - IGPUDescriptorSetLayout::SBinding binding[2]; - for (uint32_t i = 0u; i < 2; i++) - binding[i] = {{},i,IDescriptor::E_TYPE::ET_STORAGE_BUFFER,IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE,IShader::E_SHADER_STAGE::ESS_COMPUTE,1u,nullptr }; - binding[1].count = OutputBufferCount; - dsLayout = m_device->createDescriptorSetLayout(binding); - } - - // set and transient pool - auto descPool = m_device->createDescriptorPoolForDSLayouts(IDescriptorPool::ECF_NONE,{&dsLayout.get(),1}); - descriptorSet = descPool->createDescriptorSet(smart_refctd_ptr(dsLayout)); - { - IGPUDescriptorSet::SDescriptorInfo infos[1+OutputBufferCount]; - infos[0].desc = gpuinputDataBuffer; - infos[0].info.buffer = { 0u,gpuinputDataBuffer->getSize() }; - for (uint32_t i = 1u; i <= OutputBufferCount; i++) - { - auto buff = outputBuffers[i - 1]; - infos[i].info.buffer = { 0u,buff->getSize() }; - infos[i].desc = std::move(buff); // save an atomic in the refcount - - } - - IGPUDescriptorSet::SWriteDescriptorSet writes[2]; - for (uint32_t i=0u; i<2; i++) - writes[i] = {descriptorSet.get(),i,0u,1u,infos+i}; - writes[1].count = OutputBufferCount; - - m_device->updateDescriptorSets(2, writes, 0u, nullptr); - } - - pipelineLayout = m_device->createPipelineLayout({},std::move(dsLayout)); - } - - const auto spirv_isa_cache_path = localOutputCWD/"spirv_isa_cache.bin"; - // enclose to make sure file goes out of scope and we can reopen it - { - smart_refctd_ptr spirv_isa_cache_input; - // try to load SPIR-V to ISA cache - { - ISystem::future_t> fileCreate; - m_system->createFile(fileCreate,spirv_isa_cache_path,IFile::ECF_READ|IFile::ECF_MAPPABLE|IFile::ECF_COHERENT); - if (auto lock=fileCreate.acquire()) - spirv_isa_cache_input = *lock; - } - // create the cache - { - std::span spirv_isa_cache_data = {}; - if (spirv_isa_cache_input) - spirv_isa_cache_data = {reinterpret_cast(spirv_isa_cache_input->getMappedPointer()),spirv_isa_cache_input->getSize()}; - else - m_logger->log("Failed to load SPIR-V 2 ISA cache!",ILogger::ELL_PERFORMANCE); - // Normally we'd deserialize a `ICPUPipelineCache` properly and pass that instead - m_spirv_isa_cache = m_device->createPipelineCache(spirv_isa_cache_data); - } - } - { - // TODO: rename `deleteDirectory` to just `delete`? and a `IFile::setSize()` ? - m_system->deleteDirectory(spirv_isa_cache_path); - ISystem::future_t> fileCreate; - m_system->createFile(fileCreate,spirv_isa_cache_path,IFile::ECF_WRITE); - // I can be relatively sure I'll succeed to acquire the future, the pointer to created file might be null though. - m_spirv_isa_cache_output=*fileCreate.acquire(); - if (!m_spirv_isa_cache_output) - logFail("Failed to Create SPIR-V to ISA cache file."); - } - - // load shader source from file - auto getShaderSource = [&](const char* filePath) -> auto - { - IAssetLoader::SAssetLoadParams lparams = {}; - lparams.logger = m_logger.get(); - lparams.workingDirectory = ""; - auto bundle = m_assetMgr->getAsset(filePath, lparams); - if (bundle.getContents().empty() || bundle.getAssetType()!=IAsset::ET_SHADER) - { - m_logger->log("Shader %s not found!", ILogger::ELL_ERROR, filePath); - exit(-1); - } - auto firstAssetInBundle = bundle.getContents()[0]; - return smart_refctd_ptr_static_cast(firstAssetInBundle); - }; - - auto subgroupTestSource = getShaderSource("app_resources/testSubgroup.comp.hlsl"); - auto workgroupTestSource = getShaderSource("app_resources/testWorkgroup.comp.hlsl"); - // now create or retrieve final resources to run our tests - sema = m_device->createSemaphore(timelineValue); - resultsBuffer = ICPUBuffer::create({ outputBuffers[0]->getSize() }); - { - smart_refctd_ptr cmdpool = m_device->createCommandPool(computeQueue->getFamilyIndex(),IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); - if (!cmdpool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY,{&cmdbuf,1})) - { - logFail("Failed to create Command Buffers!\n"); - return false; - } - } - - const auto MaxWorkgroupSize = m_physicalDevice->getLimits().maxComputeWorkGroupInvocations; - const auto MinSubgroupSize = m_physicalDevice->getLimits().minSubgroupSize; - const auto MaxSubgroupSize = m_physicalDevice->getLimits().maxSubgroupSize; - for (auto subgroupSize=MinSubgroupSize; subgroupSize <= MaxSubgroupSize; subgroupSize *= 2u) - { - const uint8_t subgroupSizeLog2 = hlsl::findMSB(subgroupSize); - for (uint32_t workgroupSize = subgroupSize; workgroupSize <= MaxWorkgroupSize; workgroupSize += subgroupSize) - { - // make sure renderdoc captures everything for debugging - m_api->startCapture(); - m_logger->log("Testing Workgroup Size %u with Subgroup Size %u", ILogger::ELL_INFO, workgroupSize, subgroupSize); - - bool passed = true; - // TODO async the testing - passed = runTest(subgroupTestSource, elementCount, subgroupSizeLog2, workgroupSize) && passed; - logTestOutcome(passed, workgroupSize); - passed = runTest(subgroupTestSource, elementCount, subgroupSizeLog2, workgroupSize) && passed; - logTestOutcome(passed, workgroupSize); - passed = runTest(subgroupTestSource, elementCount, subgroupSizeLog2, workgroupSize) && passed; - logTestOutcome(passed, workgroupSize); - for (uint32_t itemsPerWG = workgroupSize; itemsPerWG > workgroupSize - subgroupSize; itemsPerWG--) - { - m_logger->log("Testing Item Count %u", ILogger::ELL_INFO, itemsPerWG); - passed = runTest(workgroupTestSource, elementCount, subgroupSizeLog2, workgroupSize, itemsPerWG) && passed; - logTestOutcome(passed, itemsPerWG); - passed = runTest(workgroupTestSource, elementCount, subgroupSizeLog2, workgroupSize, itemsPerWG) && passed; - logTestOutcome(passed, itemsPerWG); - passed = runTest(workgroupTestSource, elementCount, subgroupSizeLog2, workgroupSize, itemsPerWG) && passed; - logTestOutcome(passed, itemsPerWG); - } - m_api->endCapture(); - - // save cache every now and then - { - auto cpu = m_spirv_isa_cache->convertToCPUCache(); - // Normally we'd beautifully JSON serialize the thing, allow multiple devices & drivers + metadata - auto bin = cpu->getEntries().begin()->second.bin; - IFile::success_t success; - m_spirv_isa_cache_output->write(success,bin->data(),0ull,bin->size()); - if (!success) - logFail("Could not write Create SPIR-V to ISA cache to disk!"); - } - } - } - - return true; - } - - virtual bool onAppTerminated() override - { - m_logger->log("==========Result==========", ILogger::ELL_INFO); - m_logger->log("Fail Count: %u", ILogger::ELL_INFO, totalFailCount); - delete[] inputData; - return true; - } - - // the unit test is carried out on init - void workLoopBody() override {} - - // - bool keepRunning() override { return false; } - -private: - void logTestOutcome(bool passed, uint32_t workgroupSize) - { - if (passed) - m_logger->log("Passed test #%u", ILogger::ELL_INFO, workgroupSize); - else - { - totalFailCount++; - m_logger->log("Failed test #%u", ILogger::ELL_ERROR, workgroupSize); - } - } - - // create pipeline (specialized every test) [TODO: turn into a future/async] - smart_refctd_ptr createPipeline(const ICPUShader* overridenUnspecialized, const uint8_t subgroupSizeLog2) - { - auto shader = m_device->createShader(overridenUnspecialized); - IGPUComputePipeline::SCreationParams params = {}; - params.layout = pipelineLayout.get(); - params.shader = { - .entryPoint = "main", - .shader = shader.get(), - .entries = nullptr, - .requiredSubgroupSize = static_cast(subgroupSizeLog2), - .requireFullSubgroups = true - }; - core::smart_refctd_ptr pipeline; - if (!m_device->createComputePipelines(m_spirv_isa_cache.get(),{¶ms,1},&pipeline)) - return nullptr; - return pipeline; - } - - /*template class Arithmetic, bool WorkgroupTest> - bool runTest(const smart_refctd_ptr& source, const uint32_t elementCount, const uint32_t workgroupSize, uint32_t itemsPerWG = ~0u) - { - return true; - }*/ - - template class Arithmetic, bool WorkgroupTest> - bool runTest(const smart_refctd_ptr& source, const uint32_t elementCount, const uint8_t subgroupSizeLog2, const uint32_t workgroupSize, uint32_t itemsPerWG = ~0u) - { - std::string arith_name = Arithmetic>::name; - - smart_refctd_ptr overridenUnspecialized; - if constexpr (WorkgroupTest) - { - overridenUnspecialized = CHLSLCompiler::createOverridenCopy( - source.get(), "#define OPERATION %s\n#define WORKGROUP_SIZE %d\n#define ITEMS_PER_WG %d\n", - (("workgroup::") + arith_name).c_str(), workgroupSize, itemsPerWG - ); - } - else - { - itemsPerWG = workgroupSize; - overridenUnspecialized = CHLSLCompiler::createOverridenCopy( - source.get(), "#define OPERATION %s\n#define WORKGROUP_SIZE %d\n", - (("subgroup::") + arith_name).c_str(), workgroupSize - ); - } - auto pipeline = createPipeline(overridenUnspecialized.get(),subgroupSizeLog2); - - // TODO: overlap dispatches with memory readbacks (requires multiple copies of `buffers`) - const uint32_t workgroupCount = elementCount / itemsPerWG; - cmdbuf->begin(IGPUCommandBuffer::USAGE::NONE); - cmdbuf->bindComputePipeline(pipeline.get()); - cmdbuf->bindDescriptorSets(EPBP_COMPUTE, pipeline->getLayout(), 0u, 1u, &descriptorSet.get()); - cmdbuf->dispatch(workgroupCount, 1, 1); - { - IGPUCommandBuffer::SPipelineBarrierDependencyInfo::buffer_barrier_t memoryBarrier[OutputBufferCount]; - for (auto i=0u; igetSize(),outputBuffers[i]} - }; - } - IGPUCommandBuffer::SPipelineBarrierDependencyInfo info = {.memBarriers={},.bufBarriers=memoryBarrier}; - cmdbuf->pipelineBarrier(asset::E_DEPENDENCY_FLAGS::EDF_NONE,info); - } - cmdbuf->end(); - - const IQueue::SSubmitInfo::SSemaphoreInfo signal[1] = {{.semaphore=sema.get(),.value=++timelineValue}}; - const IQueue::SSubmitInfo::SCommandBufferInfo cmdbufs[1] = {{.cmdbuf=cmdbuf.get()}}; - const IQueue::SSubmitInfo submits[1] = {{.commandBuffers=cmdbufs,.signalSemaphores=signal}}; - computeQueue->submit(submits); - const ISemaphore::SWaitInfo wait[1] = {{.semaphore=sema.get(),.value=timelineValue}}; - m_device->blockForSemaphores(wait); - - // check results - bool passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount); - passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount) && passed; - passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount) && passed; - passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount) && passed; - passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount) && passed; - passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount) && passed; - passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount) && passed; - if constexpr (WorkgroupTest) - passed = validateResults, WorkgroupTest>(itemsPerWG, workgroupCount) && passed; - - return passed; - } - - //returns true if result matches - template class Arithmetic, class Binop, bool WorkgroupTest> - bool validateResults(const uint32_t itemsPerWG, const uint32_t workgroupCount) - { - bool success = true; - - // download data - const SBufferRange bufferRange = {0u, resultsBuffer->getSize(), outputBuffers[Binop::BindingIndex]}; - m_utils->downloadBufferRangeViaStagingBufferAutoSubmit(SIntendedSubmitInfo{.queue=transferDownQueue},bufferRange,resultsBuffer->getPointer()); - - using type_t = typename Binop::type_t; - const auto dataFromBuffer = reinterpret_cast(resultsBuffer->getPointer()); - const auto subgroupSize = dataFromBuffer[0]; - if (subgroupSizenbl::hlsl::subgroup::MaxSubgroupSize) - { - m_logger->log("Unexpected Subgroup Size %u", ILogger::ELL_ERROR, subgroupSize); - return false; - } - - const auto testData = reinterpret_cast(dataFromBuffer + 1); - // TODO: parallel for (the temporary values need to be threadlocal or what?) - // now check if the data obtained has valid values - type_t* tmp = new type_t[itemsPerWG]; - type_t* ballotInput = new type_t[itemsPerWG]; - for (uint32_t workgroupID = 0u; success && workgroupID < workgroupCount; workgroupID++) - { - const auto workgroupOffset = workgroupID * itemsPerWG; - - if constexpr (WorkgroupTest) - { - if constexpr (std::is_same_v, Binop>) - { - for (auto i = 0u; i < itemsPerWG; i++) - ballotInput[i] = inputData[i + workgroupOffset] & 0x1u; - Arithmetic::impl(tmp, ballotInput, itemsPerWG); - } - else - Arithmetic::impl(tmp, inputData + workgroupOffset, itemsPerWG); - } - else - { - for (uint32_t pseudoSubgroupID = 0u; pseudoSubgroupID < itemsPerWG; pseudoSubgroupID += subgroupSize) - Arithmetic::impl(tmp + pseudoSubgroupID, inputData + workgroupOffset + pseudoSubgroupID, subgroupSize); - } - - for (uint32_t localInvocationIndex = 0u; localInvocationIndex < itemsPerWG; localInvocationIndex++) - { - const auto globalInvocationIndex = workgroupOffset + localInvocationIndex; - const auto cpuVal = tmp[localInvocationIndex]; - const auto gpuVal = testData[globalInvocationIndex]; - if (cpuVal != gpuVal) - { - m_logger->log( - "Failed test #%d (%s) (%s) Expected %u got %u for workgroup %d and localinvoc %d", - ILogger::ELL_ERROR, itemsPerWG, WorkgroupTest ? "workgroup" : "subgroup", Binop::name, - cpuVal, gpuVal, workgroupID, localInvocationIndex - ); - success = false; - break; - } - } - } - delete[] ballotInput; - delete[] tmp; - - return success; - } - - IQueue* transferDownQueue; - IQueue* computeQueue; - smart_refctd_ptr m_spirv_isa_cache; - smart_refctd_ptr m_spirv_isa_cache_output; - - uint32_t* inputData = nullptr; - constexpr static inline uint32_t OutputBufferCount = 8u; - smart_refctd_ptr outputBuffers[OutputBufferCount]; - smart_refctd_ptr descriptorSet; - smart_refctd_ptr pipelineLayout; - - smart_refctd_ptr sema; - uint64_t timelineValue = 0; - smart_refctd_ptr cmdbuf; - smart_refctd_ptr resultsBuffer; - - uint32_t totalFailCount = 0; -}; - -NBL_MAIN_FUNC(ArithmeticUnitTestApp) \ No newline at end of file diff --git a/24_ColorSpaceTest/main.cpp b/24_ColorSpaceTest/main.cpp index 844f058fe..84c55ef3a 100644 --- a/24_ColorSpaceTest/main.cpp +++ b/24_ColorSpaceTest/main.cpp @@ -1,10 +1,8 @@ // Copyright (C) 2018-2024 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" -#include "SimpleWindowedApplication.hpp" +#include "nbl/examples/examples.hpp" -#include "nbl/video/surface/CSurfaceVulkan.h" #include "nbl/ext/FullScreenTriangle/FullScreenTriangle.h" #include "nlohmann/json.hpp" @@ -19,14 +17,15 @@ using namespace system; using namespace asset; using namespace ui; using namespace video; +using namespace nbl::examples; // defines for sampler tests can be found in the file below #include "app_resources/push_constants.hlsl" -class ColorSpaceTestSampleApp final : public examples::SimpleWindowedApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +class ColorSpaceTestSampleApp final : public SimpleWindowedApplication, public BuiltinResourcesApplication { - using device_base_t = examples::SimpleWindowedApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using device_base_t = SimpleWindowedApplication; + using asset_base_t = BuiltinResourcesApplication; using clock_t = std::chrono::steady_clock; using perf_clock_resolution_t = std::chrono::milliseconds; @@ -161,7 +160,7 @@ class ColorSpaceTestSampleApp final : public examples::SimpleWindowedApplication return logFail("Failed to create Full Screen Triangle protopipeline or load its vertex shader!"); // Load Custom Shader - auto loadCompileAndCreateShader = [&](const std::string& relPath) -> smart_refctd_ptr + auto loadCompileAndCreateShader = [&](const std::string& relPath) -> smart_refctd_ptr { IAssetLoader::SAssetLoadParams lp = {}; lp.logger = m_logger.get(); @@ -172,11 +171,11 @@ class ColorSpaceTestSampleApp final : public examples::SimpleWindowedApplication return nullptr; // lets go straight from ICPUSpecializedShader to IGPUSpecializedShader - auto source = IAsset::castDown(assets[0]); + auto source = IAsset::castDown(assets[0]); if (!source) return nullptr; - return m_device->createShader(source.get()); + return m_device->compileShader({ source.get() }); }; auto fragmentShader = loadCompileAndCreateShader("app_resources/present.frag.hlsl"); if (!fragmentShader) @@ -255,14 +254,14 @@ class ColorSpaceTestSampleApp final : public examples::SimpleWindowedApplication // Now create the pipeline { const asset::SPushConstantRange range = { - .stageFlags = IShader::E_SHADER_STAGE::ESS_FRAGMENT, + .stageFlags = ESS_FRAGMENT, .offset = 0, .size = sizeof(push_constants_t) }; auto layout = m_device->createPipelineLayout({ &range,1 }, nullptr, nullptr, nullptr, core::smart_refctd_ptr(dsLayout)); - const IGPUShader::SSpecInfo fragSpec = { + const IGPUPipelineBase::SShaderSpecInfo fragSpec = { + .shader = fragmentShader.get(), .entryPoint = "main", - .shader = fragmentShader.get() }; m_pipeline = fsTriProtoPPln.createPipeline(fragSpec, layout.get(), scResources->getRenderpass()/*,default is subpass 0*/); if (!m_pipeline) @@ -796,7 +795,7 @@ class ColorSpaceTestSampleApp final : public examples::SimpleWindowedApplication cmdbuf->beginRenderPass(info,IGPUCommandBuffer::SUBPASS_CONTENTS::INLINE); } cmdbuf->bindGraphicsPipeline(m_pipeline.get()); - cmdbuf->pushConstants(m_pipeline->getLayout(),IGPUShader::E_SHADER_STAGE::ESS_FRAGMENT,0,sizeof(push_constants_t),&pc); + cmdbuf->pushConstants(m_pipeline->getLayout(),hlsl::ShaderStage::ESS_FRAGMENT,0,sizeof(push_constants_t),&pc); cmdbuf->bindDescriptorSets(nbl::asset::EPBP_GRAPHICS,m_pipeline->getLayout(),3,1,&ds); ext::FullScreenTriangle::recordDrawCall(cmdbuf); cmdbuf->endRenderPass(); diff --git a/25_FilterTest/main.cpp b/25_FilterTest/main.cpp index a66227225..4ce68d66c 100644 --- a/25_FilterTest/main.cpp +++ b/25_FilterTest/main.cpp @@ -868,7 +868,7 @@ class BlitFilterTestApp final : public virtual application_templates::BasicMulti logger->log("Failed to fit the preload region in shared memory even for 1x1x1 workgroup!",ILogger::ELL_ERROR); return false; } - cmdbuf->pushConstants(layout,IGPUShader::E_SHADER_STAGE::ESS_COMPUTE,0,sizeof(params),¶ms); + cmdbuf->pushConstants(layout,hlsl::ShaderStage::ESS_COMPUTE,0,sizeof(params),¶ms); cmdbuf->dispatch(params.perWG.getWorkgroupCount(outExtent16)); if (m_alphaSemantic==IBlitUtilities::EAS_REFERENCE_OR_COVERAGE) { diff --git a/26_Blur/app_resources/shader.comp.hlsl b/26_Blur/app_resources/shader.comp.hlsl index 94baa8d2a..99e876ccc 100644 --- a/26_Blur/app_resources/shader.comp.hlsl +++ b/26_Blur/app_resources/shader.comp.hlsl @@ -131,6 +131,7 @@ struct ScanSharedMemoryProxy }; [numthreads(WORKGROUP_SIZE, 1, 1)] +[shader("compute")] void main() { ScanSharedMemoryProxy scanSmemAccessor; diff --git a/26_Blur/main.cpp b/26_Blur/main.cpp index 8217c4e51..83cf140d6 100644 --- a/26_Blur/main.cpp +++ b/26_Blur/main.cpp @@ -1,28 +1,29 @@ // Copyright (C) 2024-2025 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h + + +#include "nbl/examples/examples.hpp" + #include #include -#include "nabla.h" -#include "SimpleWindowedApplication.hpp" -#include "InputSystem.hpp" -#include "CEventCallback.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" - using namespace nbl; using namespace nbl::core; using namespace nbl::system; using namespace nbl::asset; using namespace nbl::ui; using namespace nbl::video; +using namespace nbl::examples; #include "app_resources/common.hlsl" -class BlurApp final : public examples::SimpleWindowedApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication + + +class BlurApp final : public SimpleWindowedApplication, public BuiltinResourcesApplication { - using device_base_t = examples::SimpleWindowedApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using device_base_t = SimpleWindowedApplication; + using asset_base_t = BuiltinResourcesApplication; using clock_t = std::chrono::steady_clock; public: @@ -225,7 +226,7 @@ class BlurApp final : public examples::SimpleWindowedApplication, public applica if (!m_vertImg || !m_device->allocate(reqs, m_vertImg.get()).isValid()) return logFail("Could not create HDR Image"); - smart_refctd_ptr shader; + smart_refctd_ptr shader; { IAssetLoader::SAssetLoadParams lp = {}; lp.logger = m_logger.get(); @@ -236,10 +237,10 @@ class BlurApp final : public examples::SimpleWindowedApplication, public applica return logFail("Failed to load shader from disk"); // lets go straight from ICPUSpecializedShader to IGPUSpecializedShader - auto sourceRaw = IAsset::castDown(assets[0]); + auto sourceRaw = IAsset::castDown(assets[0]); if (!sourceRaw) return logFail("Failed to load shader from disk"); - smart_refctd_ptr source = CHLSLCompiler::createOverridenCopy( + smart_refctd_ptr source = CHLSLCompiler::createOverridenCopy( sourceRaw.get(), "static const uint16_t WORKGROUP_SIZE = %d;\n" "static const uint16_t MAX_SCANLINE_SIZE = %d;\n" @@ -262,9 +263,9 @@ class BlurApp final : public examples::SimpleWindowedApplication, public applica ISPIRVOptimizer::EOP_LOCAL_MULTI_STORE_ELIM }; auto opt = make_smart_refctd_ptr(optPasses); - shader = m_device->createShader(source.get(), opt.get()); + shader = m_device->compileShader({ source.get(),opt.get() }); #else - shader = m_device->createShader(source.get()); + shader = m_device->compileShader({ source.get() }); #endif if (!shader) return false; @@ -272,26 +273,18 @@ class BlurApp final : public examples::SimpleWindowedApplication, public applica { const asset::SPushConstantRange ranges[] = { { - .stageFlags = IGPUShader::E_SHADER_STAGE::ESS_COMPUTE, + .stageFlags = hlsl::ShaderStage::ESS_COMPUTE, .offset = 0, .size = sizeof(PushConstants) } }; auto layout = m_device->createPipelineLayout(ranges, smart_refctd_ptr(dsLayout)); - const IGPUComputePipeline::SCreationParams params[] = { { - { - .layout = layout.get() - }, - {}, - IGPUComputePipeline::SCreationParams::FLAGS::NONE, - { - .entryPoint = "main", - .shader = shader.get(), - .entries = nullptr, - .requiredSubgroupSize = static_cast(hlsl::findMSB(m_physicalDevice->getLimits().maxSubgroupSize)), - .requireFullSubgroups = true - } - }}; - if (!m_device->createComputePipelines(nullptr, params, &m_ppln)) + + IGPUComputePipeline::SCreationParams params = {}; + params.layout = layout.get(); + params.shader.shader = shader.get(); + params.shader.entryPoint = "main"; + params.cached.requireFullSubgroups = true; + if (!m_device->createComputePipelines(nullptr, { ¶ms, 1 }, &m_ppln)) return logFail("Failed to create Pipeline"); } @@ -626,7 +619,7 @@ class BlurApp final : public examples::SimpleWindowedApplication, public applica cb->pipelineBarrier(E_DEPENDENCY_FLAGS::EDF_NONE, { .memBarriers = {}, .bufBarriers = {},.imgBarriers = {&vertImgBarrier,1} }); cb->bindDescriptorSets(E_PIPELINE_BIND_POINT::EPBP_COMPUTE, layout, 0, 1, &m_ds0.get()); PushConstants pc = { .radius = blurRadius, .activeAxis = 0, .edgeWrapMode = blurEdgeWrapMode }; - cb->pushConstants(layout, IGPUShader::E_SHADER_STAGE::ESS_COMPUTE, 0, sizeof(pc), &pc); + cb->pushConstants(layout, hlsl::ShaderStage::ESS_COMPUTE, 0, sizeof(pc), &pc); cb->dispatch(image_params.extent.height, 1, 1); image_memory_barrier_t horzImgBarrier = { @@ -646,7 +639,7 @@ class BlurApp final : public examples::SimpleWindowedApplication, public applica cb->pipelineBarrier(E_DEPENDENCY_FLAGS::EDF_NONE, { .memBarriers = {}, .bufBarriers = {},.imgBarriers = {&horzImgBarrier,1} }); cb->bindDescriptorSets(E_PIPELINE_BIND_POINT::EPBP_COMPUTE, layout, 0, 1, &m_ds1.get()); pc.activeAxis = 1; - cb->pushConstants(layout, IGPUShader::E_SHADER_STAGE::ESS_COMPUTE, 0, sizeof(pc), &pc); + cb->pushConstants(layout, hlsl::ShaderStage::ESS_COMPUTE, 0, sizeof(pc), &pc); cb->dispatch(image_params.extent.width, 1, 1); } diff --git a/27_MPMCScheduler/app_resources/shader.comp.hlsl b/27_MPMCScheduler/app_resources/shader.comp.hlsl index c49ad018c..966963761 100644 --- a/27_MPMCScheduler/app_resources/shader.comp.hlsl +++ b/27_MPMCScheduler/app_resources/shader.comp.hlsl @@ -305,6 +305,7 @@ uint32_t3 gl_WorkGroupSize() {return uint32_t3(WorkgroupSizeX*WorkgroupSizeY,1,1 } } [numthreads(WorkgroupSizeX*WorkgroupSizeY,1,1)] +[shader("compute")] void main() { // manually push an explicit workload diff --git a/27_MPMCScheduler/main.cpp b/27_MPMCScheduler/main.cpp index c380bf3c6..580335a35 100644 --- a/27_MPMCScheduler/main.cpp +++ b/27_MPMCScheduler/main.cpp @@ -1,9 +1,9 @@ // Copyright (C) 2024-2025 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h -#include "nabla.h" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" -#include "SimpleWindowedApplication.hpp" + + +#include "nbl/examples/examples.hpp" using namespace nbl; using namespace nbl::core; @@ -11,13 +11,15 @@ using namespace nbl::system; using namespace nbl::asset; using namespace nbl::ui; using namespace nbl::video; +using namespace nbl::examples; #include "app_resources/common.hlsl" -class MPMCSchedulerApp final : public examples::SimpleWindowedApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication + +class MPMCSchedulerApp final : public SimpleWindowedApplication, public BuiltinResourcesApplication { - using device_base_t = examples::SimpleWindowedApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using device_base_t = SimpleWindowedApplication; + using asset_base_t = BuiltinResourcesApplication; using clock_t = std::chrono::steady_clock; constexpr static inline uint32_t WIN_W = 1280, WIN_H = 720; @@ -69,7 +71,7 @@ class MPMCSchedulerApp final : public examples::SimpleWindowedApplication, publi if (!asset_base_t::onAppInitialized(std::move(system))) return false; - smart_refctd_ptr shader; + smart_refctd_ptr shader; { IAssetLoader::SAssetLoadParams lp = {}; lp.logger = m_logger.get(); @@ -80,11 +82,11 @@ class MPMCSchedulerApp final : public examples::SimpleWindowedApplication, publi return logFail("Failed to load shader from disk"); // lets go straight from ICPUSpecializedShader to IGPUSpecializedShader - auto source = IAsset::castDown(assets[0]); + auto source = IAsset::castDown(assets[0]); if (!source) return logFail("Failed to load shader from disk"); - shader = m_device->createShader(source.get()); + shader = m_device->compileShader({ source.get() }); if (!shader) return false; } @@ -106,26 +108,17 @@ class MPMCSchedulerApp final : public examples::SimpleWindowedApplication, publi { const asset::SPushConstantRange ranges[] = {{ - .stageFlags = IGPUShader::E_SHADER_STAGE::ESS_COMPUTE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, .offset = 0, .size = sizeof(PushConstants) }}; auto layout = m_device->createPipelineLayout(ranges,smart_refctd_ptr(dsLayout)); - const IGPUComputePipeline::SCreationParams params[] = { { - { - .layout = layout.get() - }, - {}, - IGPUComputePipeline::SCreationParams::FLAGS::NONE, - { - .entryPoint = "main", - .shader = shader.get(), - .entries = nullptr, - .requiredSubgroupSize = IGPUShader::SSpecInfo::SUBGROUP_SIZE::UNKNOWN, - .requireFullSubgroups = true - } - }}; - if (!m_device->createComputePipelines(nullptr,params,&m_ppln)) + IGPUComputePipeline::SCreationParams params; + params.layout = layout.get(); + params.shader.shader = shader.get(); + params.shader.entryPoint = "main"; + params.cached.requireFullSubgroups = true; + if (!m_device->createComputePipelines(nullptr, { ¶ms, 1 }, &m_ppln)) return logFail("Failed to create Pipeline"); } @@ -306,7 +299,7 @@ class MPMCSchedulerApp final : public examples::SimpleWindowedApplication, publi .sharedAcceptableIdleCount = 0, .globalAcceptableIdleCount = 0 }; - cb->pushConstants(layout,IGPUShader::E_SHADER_STAGE::ESS_COMPUTE,0,sizeof(pc),&pc); + cb->pushConstants(layout,hlsl::ShaderStage::ESS_COMPUTE,0,sizeof(pc),&pc); cb->dispatch(WIN_W/WorkgroupSizeX,WIN_H/WorkgroupSizeY,1); } diff --git a/27_PLYSTLDemo/CMakeLists.txt b/27_PLYSTLDemo/CMakeLists.txt deleted file mode 100644 index a476b6203..000000000 --- a/27_PLYSTLDemo/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ - -include(common RESULT_VARIABLE RES) -if(NOT RES) - message(FATAL_ERROR "common.cmake not found. Should be in {repo_root}/cmake directory") -endif() - -nbl_create_executable_project("" "" "" "" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") \ No newline at end of file diff --git a/27_PLYSTLDemo/config.json.template b/27_PLYSTLDemo/config.json.template deleted file mode 100644 index cb1b3b7a7..000000000 --- a/27_PLYSTLDemo/config.json.template +++ /dev/null @@ -1,28 +0,0 @@ -{ - "enableParallelBuild": true, - "threadsPerBuildProcess" : 2, - "isExecuted": false, - "scriptPath": "", - "cmake": { - "configurations": [ "Release", "Debug", "RelWithDebInfo" ], - "buildModes": [], - "requiredOptions": [ "NBL_BUILD_MITSUBA_LOADER", "NBL_BUILD_OPTIX" ] - }, - "profiles": [ - { - "backend": "vulkan", - "platform": "windows", - "buildModes": [], - "runConfiguration": "Release", - "gpuArchitectures": [] - } - ], - "dependencies": [], - "data": [ - { - "dependencies": [], - "command": [""], - "outputs": [] - } - ] -} \ No newline at end of file diff --git a/27_PLYSTLDemo/main.cpp b/27_PLYSTLDemo/main.cpp deleted file mode 100644 index 1e6d470e2..000000000 --- a/27_PLYSTLDemo/main.cpp +++ /dev/null @@ -1,579 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -#define _NBL_STATIC_LIB_ -#include -#include -#include - -#include "CCamera.hpp" -#include "../common/CommonAPI.h" -#include "nbl/ext/ScreenShot/ScreenShot.h" - -using namespace nbl; -using namespace core; - -/* - Uncomment for more detailed logging -*/ - -// #define NBL_MORE_LOGS - -/* - Uncomment for writing assets -*/ - -#define WRITE_ASSETS - -class PLYSTLDemo : public ApplicationBase -{ - static constexpr uint32_t WIN_W = 1280; - static constexpr uint32_t WIN_H = 720; - static constexpr uint32_t SC_IMG_COUNT = 3u; - static constexpr uint32_t FRAMES_IN_FLIGHT = 5u; - static constexpr uint64_t MAX_TIMEOUT = 99999999999999ull; - static constexpr size_t NBL_FRAMES_TO_AVERAGE = 100ull; - static_assert(FRAMES_IN_FLIGHT > SC_IMG_COUNT); - - using RENDERPASS_INDEPENDENT_PIPELINE_ADRESS = size_t; - using GPU_PIPELINE_HASH_CONTAINER = std::map>; - using DependentDrawData = std::tuple, core::smart_refctd_ptr, core::smart_refctd_ptr, uint32_t, const asset::IRenderpassIndependentPipelineMetadata*>; - -public: - nbl::core::smart_refctd_ptr windowManager; - nbl::core::smart_refctd_ptr window; - nbl::core::smart_refctd_ptr windowCallback; - nbl::core::smart_refctd_ptr gl; - nbl::core::smart_refctd_ptr surface; - nbl::core::smart_refctd_ptr utilities; - nbl::core::smart_refctd_ptr logicalDevice; - nbl::video::IPhysicalDevice* gpuPhysicalDevice; - std::array queues = { nullptr, nullptr, nullptr, nullptr }; - nbl::core::smart_refctd_ptr swapchain; - nbl::core::smart_refctd_ptr renderpass; - nbl::core::smart_refctd_dynamic_array> fbos; - std::array, CommonAPI::InitOutput::MaxFramesInFlight>, CommonAPI::InitOutput::MaxQueuesCount> commandPools; - nbl::core::smart_refctd_ptr system; - nbl::core::smart_refctd_ptr assetManager; - nbl::video::IGPUObjectFromAssetConverter::SParams cpu2gpuParams; - nbl::core::smart_refctd_ptr logger; - nbl::core::smart_refctd_ptr inputSystem; - - nbl::core::smart_refctd_ptr gpuTransferFence; - nbl::core::smart_refctd_ptr gpuComputeFence; - nbl::video::IGPUObjectFromAssetConverter cpu2gpu; - - uint32_t acquiredNextFBO = {}; - int resourceIx = -1; - - core::smart_refctd_ptr commandBuffers[FRAMES_IN_FLIGHT]; - - core::smart_refctd_ptr frameComplete[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr imageAcquire[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr renderFinished[FRAMES_IN_FLIGHT] = { nullptr }; - - nbl::video::ISwapchain::SCreationParams m_swapchainCreationParams; - - std::chrono::system_clock::time_point lastTime; - bool frameDataFilled = false; - size_t frame_count = 0ull; - double time_sum = 0; - double dtList[NBL_FRAMES_TO_AVERAGE] = {}; - - CommonAPI::InputSystem::ChannelReader mouse; - CommonAPI::InputSystem::ChannelReader keyboard; - - Camera camera = Camera(core::vectorSIMDf(0, 0, 0), core::vectorSIMDf(0, 0, 0), core::matrix4SIMD()); - - GPU_PIPELINE_HASH_CONTAINER gpuPipelinesPly; - GPU_PIPELINE_HASH_CONTAINER gpuPipelinesStl; - - DependentDrawData plyDrawData; - DependentDrawData stlDrawData; - - void setWindow(core::smart_refctd_ptr&& wnd) override - { - window = std::move(wnd); - } - nbl::ui::IWindow* getWindow() override - { - return window.get(); - } - void setSystem(core::smart_refctd_ptr&& s) override - { - system = std::move(s); - } - video::IAPIConnection* getAPIConnection() override - { - return gl.get(); - } - video::ILogicalDevice* getLogicalDevice() override - { - return logicalDevice.get(); - } - video::IGPURenderpass* getRenderpass() override - { - return renderpass.get(); - } - void setSurface(core::smart_refctd_ptr&& s) override - { - surface = std::move(s); - } - void setFBOs(std::vector>& f) override - { - for (int i = 0; i < f.size(); i++) - { - fbos->begin()[i] = core::smart_refctd_ptr(f[i]); - } - } - void setSwapchain(core::smart_refctd_ptr&& s) override - { - swapchain = std::move(s); - } - uint32_t getSwapchainImageCount() override - { - return swapchain->getImageCount(); - } - virtual nbl::asset::E_FORMAT getDepthFormat() override - { - return nbl::asset::EF_D32_SFLOAT; - } - -APP_CONSTRUCTOR(PLYSTLDemo) - - void onAppInitialized_impl() override - { - const auto swapchainImageUsage = static_cast(asset::IImage::EUF_COLOR_ATTACHMENT_BIT); - CommonAPI::InitParams initParams; - initParams.window = core::smart_refctd_ptr(window); - initParams.apiType = video::EAT_VULKAN; - initParams.appName = { _NBL_APP_NAME_ }; - initParams.framesInFlight = FRAMES_IN_FLIGHT; - initParams.windowWidth = WIN_W; - initParams.windowHeight = WIN_H; - initParams.swapchainImageCount = SC_IMG_COUNT; - initParams.swapchainImageUsage = swapchainImageUsage; - initParams.depthFormat = nbl::asset::EF_D32_SFLOAT; - auto initOutput = CommonAPI::InitWithDefaultExt(std::move(initParams)); - - window = std::move(initParams.window); - gl = std::move(initOutput.apiConnection); - surface = std::move(initOutput.surface); - gpuPhysicalDevice = std::move(initOutput.physicalDevice); - logicalDevice = std::move(initOutput.logicalDevice); - queues = std::move(initOutput.queues); - renderpass = std::move(initOutput.renderToSwapchainRenderpass); - commandPools = std::move(initOutput.commandPools); - assetManager = std::move(initOutput.assetManager); - logger = std::move(initOutput.logger); - inputSystem = std::move(initOutput.inputSystem); - system = std::move(initOutput.system); - windowCallback = std::move(initParams.windowCb); - utilities = std::move(initOutput.utilities); - m_swapchainCreationParams = std::move(initOutput.swapchainCreationParams); - - CommonAPI::createSwapchain(std::move(logicalDevice), m_swapchainCreationParams, WIN_W, WIN_H, swapchain); - assert(swapchain); - fbos = CommonAPI::createFBOWithSwapchainImages( - swapchain->getImageCount(), WIN_W, WIN_H, - logicalDevice, swapchain, renderpass, - nbl::asset::EF_D32_SFLOAT - ); - - auto defaultComputeCommandPool = commandPools[CommonAPI::InitOutput::EQT_COMPUTE][0]; - auto defaultTransferUpCommandPool = commandPools[CommonAPI::InitOutput::EQT_TRANSFER_UP][0]; - - nbl::video::IGPUObjectFromAssetConverter cpu2gpu; - nbl::video::IGPUObjectFromAssetConverter::SParams cpu2gpuParams; - - nbl::core::smart_refctd_ptr gpuTransferFence; - nbl::core::smart_refctd_ptr gpuTransferSemaphore; - - nbl::core::smart_refctd_ptr gpuComputeFence; - nbl::core::smart_refctd_ptr gpuComputeSemaphore; - - { - gpuTransferFence = logicalDevice->createFence(static_cast(0)); - gpuTransferSemaphore = logicalDevice->createSemaphore(); - - gpuComputeFence = logicalDevice->createFence(static_cast(0)); - gpuComputeSemaphore = logicalDevice->createSemaphore(); - - cpu2gpuParams.utilities = utilities.get(); - cpu2gpuParams.device = logicalDevice.get(); - cpu2gpuParams.assetManager = assetManager.get(); - cpu2gpuParams.pipelineCache = nullptr; - cpu2gpuParams.limits = gpuPhysicalDevice->getLimits(); - cpu2gpuParams.finalQueueFamIx = queues[decltype(initOutput)::EQT_GRAPHICS]->getFamilyIndex(); - - logicalDevice->createCommandBuffers(defaultTransferUpCommandPool.get(),video::IGPUCommandBuffer::EL_PRIMARY,1u,&cpu2gpuParams.perQueue[nbl::video::IGPUObjectFromAssetConverter::EQU_TRANSFER].cmdbuf); - cpu2gpuParams.perQueue[nbl::video::IGPUObjectFromAssetConverter::EQU_TRANSFER].queue = queues[decltype(initOutput)::EQT_TRANSFER_UP]; - cpu2gpuParams.perQueue[nbl::video::IGPUObjectFromAssetConverter::EQU_TRANSFER].semaphore = &gpuTransferSemaphore; - - logicalDevice->createCommandBuffers(defaultComputeCommandPool.get(),video::IGPUCommandBuffer::EL_PRIMARY,1u,&cpu2gpuParams.perQueue[nbl::video::IGPUObjectFromAssetConverter::EQU_COMPUTE].cmdbuf); - cpu2gpuParams.perQueue[nbl::video::IGPUObjectFromAssetConverter::EQU_COMPUTE].queue = queues[decltype(initOutput)::EQT_COMPUTE]; - cpu2gpuParams.perQueue[nbl::video::IGPUObjectFromAssetConverter::EQU_COMPUTE].semaphore = &gpuComputeSemaphore; - - cpu2gpuParams.beginCommandBuffers(); - } - - auto loadAndGetCpuMesh = [&](system::path path) -> std::pair, const asset::IAssetMetadata*> - { - auto meshes_bundle = assetManager->getAsset(path.string(), {}); - { - bool status = !meshes_bundle.getContents().empty(); - assert(status); - } - - auto mesh = core::smart_refctd_ptr_static_cast(meshes_bundle.getContents().begin()[0]); - auto metadata = meshes_bundle.getMetadata(); - return std::make_pair(mesh, metadata); - //return std::make_pair(core::smart_refctd_ptr_static_cast(meshes_bundle.getContents().begin()[0]), meshes_bundle.getMetadata()); - }; - - auto cpuBundlePLYData = loadAndGetCpuMesh(sharedInputCWD / "ply/Spanner-ply.ply"); - auto cpuBundleSTLData = loadAndGetCpuMesh(sharedInputCWD / "extrusionLogo_TEST_fixed.stl"); - - core::smart_refctd_ptr cpuMeshPly = cpuBundlePLYData.first; - auto metadataPly = cpuBundlePLYData.second->selfCast(); - - core::smart_refctd_ptr cpuMeshStl = cpuBundleSTLData.first; - auto metadataStl = cpuBundleSTLData.second->selfCast(); - -#ifdef WRITE_ASSETS - { - asset::IAssetWriter::SAssetWriteParams wp(cpuMeshPly.get()); - bool status = assetManager->writeAsset("Spanner_ply.ply", wp); - assert(status); - } - - { - asset::IAssetWriter::SAssetWriteParams wp(cpuMeshStl.get()); - bool status = assetManager->writeAsset("extrusionLogo_TEST_fixedTest.stl", wp); - assert(status); - } -#endif // WRITE_ASSETS - - /* - For the testing puposes we can safely assume all meshbuffers within mesh loaded from PLY & STL has same DS1 layout (used for camera-specific data) - */ - - auto getMeshDependentDrawData = [&](core::smart_refctd_ptr cpuMesh, bool isPLY) -> DependentDrawData - { - const asset::ICPUMeshBuffer* const firstMeshBuffer = cpuMesh->getMeshBuffers().begin()[0]; - const asset::ICPUDescriptorSetLayout* ds1layout = firstMeshBuffer->getPipeline()->getLayout()->getDescriptorSetLayout(1u); //! DS1 - const asset::IRenderpassIndependentPipelineMetadata* pipelineMetadata; - { - if (isPLY) - pipelineMetadata = metadataPly->getAssetSpecificMetadata(firstMeshBuffer->getPipeline()); - else - pipelineMetadata = metadataStl->getAssetSpecificMetadata(firstMeshBuffer->getPipeline()); - } - - /* - So we can create just one DescriptorSet - */ - - const uint32_t ds1UboBinding = ds1layout->getDescriptorRedirect(asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER).getBinding(asset::ICPUDescriptorSetLayout::CBindingRedirect::storage_range_index_t{ 0 }).data; - - auto getNeededDS1UboByteSize = [&]() - { - size_t neededDS1UboSize = 0ull; - { - for (const auto& shaderInputs : pipelineMetadata->m_inputSemantics) - if (shaderInputs.descriptorSection.type == asset::IRenderpassIndependentPipelineMetadata::ShaderInput::E_TYPE::ET_UNIFORM_BUFFER && shaderInputs.descriptorSection.uniformBufferObject.set == 1u && shaderInputs.descriptorSection.uniformBufferObject.binding == ds1UboBinding) - neededDS1UboSize = std::max(neededDS1UboSize, shaderInputs.descriptorSection.uniformBufferObject.relByteoffset + shaderInputs.descriptorSection.uniformBufferObject.bytesize); - } - return neededDS1UboSize; - }; - - const uint64_t uboDS1ByteSize = getNeededDS1UboByteSize(); - - core::smart_refctd_ptr gpuds1layout; - { - auto gpu_array = cpu2gpu.getGPUObjectsFromAssets(&ds1layout, &ds1layout + 1, cpu2gpuParams); - if (!gpu_array || gpu_array->size() < 1u || !(*gpu_array)[0]) - assert(false); - - gpuds1layout = (*gpu_array)[0]; - } - - const uint32_t setCount = 1; - auto gpuUBODescriptorPool = logicalDevice->createDescriptorPoolForDSLayouts(video::IDescriptorPool::ECF_NONE, &gpuds1layout.get(), &gpuds1layout.get()+1ull, &setCount); - - video::IGPUBuffer::SCreationParams creationParams; - creationParams.usage = asset::IBuffer::E_USAGE_FLAGS(asset::IBuffer::EUF_UNIFORM_BUFFER_BIT | asset::IBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF); - creationParams.queueFamilyIndices = 0u; - creationParams.queueFamilyIndices = nullptr; - creationParams.size = uboDS1ByteSize; - - auto gpuubo = logicalDevice->createBuffer(std::move(creationParams)); - auto gpuuboMemReqs = gpuubo->getMemoryReqs(); - gpuuboMemReqs.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - logicalDevice->allocate(gpuuboMemReqs, gpuubo.get()); - - auto gpuds1 = gpuUBODescriptorPool->createDescriptorSet(std::move(gpuds1layout)); - { - video::IGPUDescriptorSet::SWriteDescriptorSet write; - write.dstSet = gpuds1.get(); - write.binding = ds1UboBinding; - write.count = 1u; - write.arrayElement = 0u; - write.descriptorType = asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER; - video::IGPUDescriptorSet::SDescriptorInfo info; - { - info.desc = gpuubo; - info.info.buffer.offset = 0ull; - info.info.buffer.size = uboDS1ByteSize; - } - write.info = &info; - logicalDevice->updateDescriptorSets(1u, &write, 0u, nullptr); - } - - core::smart_refctd_ptr gpumesh; - { - auto gpu_array = cpu2gpu.getGPUObjectsFromAssets(&cpuMesh.get(), &cpuMesh.get() + 1, cpu2gpuParams); - cpu2gpuParams.waitForCreationToComplete(true); - cpu2gpuParams.beginCommandBuffers(); - if (!gpu_array || gpu_array->size() < 1u || !(*gpu_array)[0]) - assert(false); - - gpumesh = (*gpu_array)[0]; - } - - return std::make_tuple(gpumesh, gpuubo, gpuds1, ds1UboBinding, pipelineMetadata); - }; - - plyDrawData = getMeshDependentDrawData(cpuMeshPly, true); - stlDrawData = getMeshDependentDrawData(cpuMeshStl, false); - - { - auto fillGpuPipeline = [&](GPU_PIPELINE_HASH_CONTAINER& container, video::IGPUMesh* gpuMesh) - { - for (size_t i = 0; i < gpuMesh->getMeshBuffers().size(); ++i) - { - auto gpuIndependentPipeline = gpuMesh->getMeshBuffers().begin()[i]->getPipeline(); - - nbl::video::IGPUGraphicsPipeline::SCreationParams graphicsPipelineParams; - graphicsPipelineParams.renderpassIndependent = core::smart_refctd_ptr(const_cast(gpuIndependentPipeline)); - graphicsPipelineParams.renderpass = core::smart_refctd_ptr(renderpass); - - const RENDERPASS_INDEPENDENT_PIPELINE_ADRESS adress = reinterpret_cast(graphicsPipelineParams.renderpassIndependent.get()); - container[adress] = logicalDevice->createGraphicsPipeline(nullptr, std::move(graphicsPipelineParams)); - } - }; - - fillGpuPipeline(gpuPipelinesPly, std::get>(plyDrawData).get()); - fillGpuPipeline(gpuPipelinesStl, std::get>(stlDrawData).get()); - } - - core::vectorSIMDf cameraPosition(0, 5, -10); - matrix4SIMD projectionMatrix = matrix4SIMD::buildProjectionMatrixPerspectiveFovLH(core::radians(60.0f), video::ISurface::getTransformedAspectRatio(swapchain->getPreTransform(), WIN_W, WIN_H), 0.001, 1000); - camera = Camera(cameraPosition, core::vectorSIMDf(0, 0, 0), projectionMatrix, 0.01f, 1.f); - lastTime = std::chrono::system_clock::now(); - - for (size_t i = 0ull; i < NBL_FRAMES_TO_AVERAGE; ++i) - dtList[i] = 0.0; - - const auto& graphicsCommandPools = commandPools[CommonAPI::InitOutput::EQT_GRAPHICS]; - for (uint32_t i = 0u; i < FRAMES_IN_FLIGHT; i++) - { - logicalDevice->createCommandBuffers(graphicsCommandPools[i].get(), video::IGPUCommandBuffer::EL_PRIMARY, 1, commandBuffers+i); - imageAcquire[i] = logicalDevice->createSemaphore(); - renderFinished[i] = logicalDevice->createSemaphore(); - } - } - - void onAppTerminated_impl() override - { - const auto& fboCreationParams = fbos->begin()[acquiredNextFBO]->getCreationParameters(); - auto gpuSourceImageView = fboCreationParams.attachments[0]; - - //TODO: - bool status = ext::ScreenShot::createScreenShot( - logicalDevice.get(), - queues[CommonAPI::InitOutput::EQT_TRANSFER_UP], - renderFinished[resourceIx].get(), - gpuSourceImageView.get(), - assetManager.get(), - "ScreenShot.png", - asset::IImage::EL_PRESENT_SRC, - asset::EAF_NONE); - assert(status); - } - - void workLoopBody() override - { - ++resourceIx; - if (resourceIx >= FRAMES_IN_FLIGHT) - resourceIx = 0; - - auto& commandBuffer = commandBuffers[resourceIx]; - auto& fence = frameComplete[resourceIx]; - - if (fence) - while (logicalDevice->waitForFences(1u, &fence.get(), false, MAX_TIMEOUT) == video::IGPUFence::ES_TIMEOUT) {} - else - fence = logicalDevice->createFence(static_cast(0)); - - auto renderStart = std::chrono::system_clock::now(); - const auto renderDt = std::chrono::duration_cast(renderStart - lastTime).count(); - lastTime = renderStart; - { // Calculate Simple Moving Average for FrameTime - time_sum -= dtList[frame_count]; - time_sum += renderDt; - dtList[frame_count] = renderDt; - frame_count++; - if (frame_count >= NBL_FRAMES_TO_AVERAGE) - { - frameDataFilled = true; - frame_count = 0; - } - - } - const double averageFrameTime = frameDataFilled ? (time_sum / (double)NBL_FRAMES_TO_AVERAGE) : (time_sum / frame_count); - -#ifdef NBL_MORE_LOGS - logger->log("renderDt = %f ------ averageFrameTime = %f", system::ILogger::ELL_INFO, renderDt, averageFrameTime); -#endif // NBL_MORE_LOGS - - auto averageFrameTimeDuration = std::chrono::duration(averageFrameTime); - auto nextPresentationTime = renderStart + averageFrameTimeDuration; - auto nextPresentationTimeStamp = std::chrono::duration_cast(nextPresentationTime.time_since_epoch()); - - inputSystem->getDefaultMouse(&mouse); - inputSystem->getDefaultKeyboard(&keyboard); - - camera.beginInputProcessing(nextPresentationTimeStamp); - mouse.consumeEvents([&](const ui::IMouseEventChannel::range_t& events) -> void { camera.mouseProcess(events); }, logger.get()); - keyboard.consumeEvents([&](const ui::IKeyboardEventChannel::range_t& events) -> void { camera.keyboardProcess(events); }, logger.get()); - camera.endInputProcessing(nextPresentationTimeStamp); - - const auto& viewMatrix = camera.getViewMatrix(); - const auto& viewProjectionMatrix = matrix4SIMD::concatenateBFollowedByAPrecisely( - video::ISurface::getSurfaceTransformationMatrix(swapchain->getPreTransform()), - camera.getConcatenatedMatrix() - ); - - commandBuffer->reset(nbl::video::IGPUCommandBuffer::ERF_RELEASE_RESOURCES_BIT); - commandBuffer->begin(video::IGPUCommandBuffer::EU_ONE_TIME_SUBMIT_BIT); // TODO: Reset Frame's CommandPool - - asset::SViewport viewport; - viewport.minDepth = 1.f; - viewport.maxDepth = 0.f; - viewport.x = 0u; - viewport.y = 0u; - viewport.width = WIN_W; - viewport.height = WIN_H; - commandBuffer->setViewport(0u, 1u, &viewport); - - swapchain->acquireNextImage(MAX_TIMEOUT, imageAcquire[resourceIx].get(), nullptr, &acquiredNextFBO); - - nbl::video::IGPUCommandBuffer::SRenderpassBeginInfo beginInfo; - { - VkRect2D area; - area.offset = { 0,0 }; - area.extent = { WIN_W, WIN_H }; - asset::SClearValue clear[2] = {}; - clear[0].color.float32[0] = 1.f; - clear[0].color.float32[1] = 1.f; - clear[0].color.float32[2] = 1.f; - clear[0].color.float32[3] = 1.f; - clear[1].depthStencil.depth = 0.f; - - beginInfo.clearValueCount = 2u; - beginInfo.framebuffer = fbos->begin()[acquiredNextFBO]; - beginInfo.renderpass = renderpass; - beginInfo.renderArea = area; - beginInfo.clearValues = clear; - } - - commandBuffer->beginRenderPass(&beginInfo, nbl::asset::ESC_INLINE); - - auto renderMesh = [&](GPU_PIPELINE_HASH_CONTAINER& gpuPipelines, DependentDrawData& drawData, uint32_t index) - { - auto gpuMesh = std::get>(drawData); - auto gpuubo = std::get>(drawData); - auto gpuds1 = std::get>(drawData); - auto ds1UboBinding = std::get(drawData); - const auto* pipelineMetadata = std::get(drawData); - - core::matrix3x4SIMD modelMatrix; - - if (index == 1) - modelMatrix.setScale(core::vectorSIMDf(10, 10, 10)); - modelMatrix.setTranslation(nbl::core::vectorSIMDf(index * 150, 0, 0, 0)); - - core::matrix4SIMD mvp = core::concatenateBFollowedByA(viewProjectionMatrix, modelMatrix); - - core::vector uboData(gpuubo->getSize()); - for (const auto& shaderInputs : pipelineMetadata->m_inputSemantics) - { - if (shaderInputs.descriptorSection.type == asset::IRenderpassIndependentPipelineMetadata::ShaderInput::E_TYPE::ET_UNIFORM_BUFFER && shaderInputs.descriptorSection.uniformBufferObject.set == 1u && shaderInputs.descriptorSection.uniformBufferObject.binding == ds1UboBinding) - { - switch (shaderInputs.type) - { - case asset::IRenderpassIndependentPipelineMetadata::ECSI_WORLD_VIEW_PROJ: - { - memcpy(uboData.data() + shaderInputs.descriptorSection.uniformBufferObject.relByteoffset, mvp.pointer(), shaderInputs.descriptorSection.uniformBufferObject.bytesize); - } break; - - case asset::IRenderpassIndependentPipelineMetadata::ECSI_WORLD_VIEW: - { - memcpy(uboData.data() + shaderInputs.descriptorSection.uniformBufferObject.relByteoffset, viewMatrix.pointer(), shaderInputs.descriptorSection.uniformBufferObject.bytesize); - } break; - - case asset::IRenderpassIndependentPipelineMetadata::ECSI_WORLD_VIEW_INVERSE_TRANSPOSE: - { - memcpy(uboData.data() + shaderInputs.descriptorSection.uniformBufferObject.relByteoffset, viewMatrix.pointer(), shaderInputs.descriptorSection.uniformBufferObject.bytesize); - } break; - } - } - } - - commandBuffer->updateBuffer(gpuubo.get(), 0ull, gpuubo->getSize(), uboData.data()); - - for (auto gpuMeshBuffer : gpuMesh->getMeshBuffers()) - { - auto gpuGraphicsPipeline = gpuPipelines[reinterpret_cast(gpuMeshBuffer->getPipeline())]; - - const video::IGPURenderpassIndependentPipeline* gpuRenderpassIndependentPipeline = gpuMeshBuffer->getPipeline(); - const video::IGPUDescriptorSet* ds3 = gpuMeshBuffer->getAttachedDescriptorSet(); - - commandBuffer->bindGraphicsPipeline(gpuGraphicsPipeline.get()); - - const video::IGPUDescriptorSet* gpuds1_ptr = gpuds1.get(); - commandBuffer->bindDescriptorSets(asset::EPBP_GRAPHICS, gpuRenderpassIndependentPipeline->getLayout(), 1u, 1u, &gpuds1_ptr, 0u); - const video::IGPUDescriptorSet* gpuds3_ptr = gpuMeshBuffer->getAttachedDescriptorSet(); - - if (gpuds3_ptr) - commandBuffer->bindDescriptorSets(asset::EPBP_GRAPHICS, gpuRenderpassIndependentPipeline->getLayout(), 3u, 1u, &gpuds3_ptr, 0u); - if (gpuRenderpassIndependentPipeline->getLayout()->m_pushConstantRanges) - commandBuffer->pushConstants(gpuRenderpassIndependentPipeline->getLayout(), video::IGPUShader::ESS_FRAGMENT, 0u, gpuMeshBuffer->MAX_PUSH_CONSTANT_BYTESIZE, gpuMeshBuffer->getPushConstantsDataPtr()); - - commandBuffer->drawMeshBuffer(gpuMeshBuffer); - } - }; - - /* - Record PLY and STL rendering commands - */ - - renderMesh(gpuPipelinesPly, plyDrawData, 0); - renderMesh(gpuPipelinesStl, stlDrawData, 1); - - commandBuffer->endRenderPass(); - commandBuffer->end(); - - CommonAPI::Submit(logicalDevice.get(), commandBuffer.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS], imageAcquire[resourceIx].get(), renderFinished[resourceIx].get(), fence.get()); - CommonAPI::Present(logicalDevice.get(), swapchain.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS], renderFinished[resourceIx].get(), acquiredNextFBO); - } - - bool keepRunning() override - { - return windowCallback->isWindowOpen(); - } -}; - -NBL_COMMON_API_MAIN(PLYSTLDemo) \ No newline at end of file diff --git a/28_FFTBloom/app_resources/fft_common.hlsl b/28_FFTBloom/app_resources/fft_common.hlsl index 41f8821cc..9f2be1432 100644 --- a/28_FFTBloom/app_resources/fft_common.hlsl +++ b/28_FFTBloom/app_resources/fft_common.hlsl @@ -5,13 +5,13 @@ groupshared uint32_t sharedmem[FFTParameters::SharedMemoryDWORDs]; struct SharedMemoryAccessor { - template + template void set(IndexType idx, AccessType value) { sharedmem[idx] = value; } - template + template void get(IndexType idx, NBL_REF_ARG(AccessType) value) { value = sharedmem[idx]; @@ -36,14 +36,14 @@ struct PreloadedAccessorCommonBase struct PreloadedAccessorBase : PreloadedAccessorCommonBase { - template - void set(uint32_t idx, AccessType value) + template + void set(IndexType idx, AccessType value) { preloaded[idx >> WorkgroupSizeLog2] = value; } - template - void get(uint32_t idx, NBL_REF_ARG(AccessType) value) + template + void get(IndexType idx, NBL_REF_ARG(AccessType) value) { value = preloaded[idx >> WorkgroupSizeLog2]; } @@ -54,14 +54,14 @@ struct PreloadedAccessorBase : PreloadedAccessorCommonBase // In the case for preloading all channels at once we make it stateful so we track which channel we're running FFT on struct MultiChannelPreloadedAccessorBase : PreloadedAccessorCommonBase { - template - void set(uint32_t idx, AccessType value) + template + void set(IndexType idx, AccessType value) { preloaded[currentChannel][idx >> WorkgroupSizeLog2] = value; } - template - void get(uint32_t idx, NBL_REF_ARG(AccessType) value) + template + void get(IndexType idx, NBL_REF_ARG(AccessType) value) { value = preloaded[currentChannel][idx >> WorkgroupSizeLog2]; } diff --git a/28_FFTBloom/app_resources/fft_convolve_ifft.hlsl b/28_FFTBloom/app_resources/fft_convolve_ifft.hlsl index 73d9d7850..07c2ec8cf 100644 --- a/28_FFTBloom/app_resources/fft_convolve_ifft.hlsl +++ b/28_FFTBloom/app_resources/fft_convolve_ifft.hlsl @@ -223,6 +223,7 @@ NBL_CONSTEXPR_STATIC_INLINE float32_t2 PreloadedSecondAxisAccessor::KernelHalfPi NBL_CONSTEXPR_STATIC_INLINE vector PreloadedSecondAxisAccessor::One = {1.0f, 0.f}; [numthreads(FFTParameters::WorkgroupSize, 1, 1)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { SharedMemoryAccessor sharedmemAccessor; diff --git a/28_FFTBloom/app_resources/image_fft_first_axis.hlsl b/28_FFTBloom/app_resources/image_fft_first_axis.hlsl index 864c64b1e..f1478a8d6 100644 --- a/28_FFTBloom/app_resources/image_fft_first_axis.hlsl +++ b/28_FFTBloom/app_resources/image_fft_first_axis.hlsl @@ -76,6 +76,7 @@ struct PreloadedFirstAxisAccessor : MultiChannelPreloadedAccessorBase }; [numthreads(FFTParameters::WorkgroupSize, 1, 1)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { SharedMemoryAccessor sharedmemAccessor; diff --git a/28_FFTBloom/app_resources/image_ifft_first_axis.hlsl b/28_FFTBloom/app_resources/image_ifft_first_axis.hlsl index 9146073dd..b3bef3510 100644 --- a/28_FFTBloom/app_resources/image_ifft_first_axis.hlsl +++ b/28_FFTBloom/app_resources/image_ifft_first_axis.hlsl @@ -136,6 +136,7 @@ struct PreloadedFirstAxisAccessor : MultiChannelPreloadedAccessorMirrorTradeBase }; [numthreads(FFTParameters::WorkgroupSize, 1, 1)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { SharedMemoryAccessor sharedmemAccessor; diff --git a/28_FFTBloom/app_resources/kernel_fft_first_axis.hlsl b/28_FFTBloom/app_resources/kernel_fft_first_axis.hlsl index 51f514c4a..741bac7db 100644 --- a/28_FFTBloom/app_resources/kernel_fft_first_axis.hlsl +++ b/28_FFTBloom/app_resources/kernel_fft_first_axis.hlsl @@ -68,6 +68,7 @@ struct PreloadedFirstAxisAccessor : MultiChannelPreloadedAccessorBase }; [numthreads(FFTParameters::WorkgroupSize, 1, 1)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { SharedMemoryAccessor sharedmemAccessor; diff --git a/28_FFTBloom/app_resources/kernel_fft_second_axis.hlsl b/28_FFTBloom/app_resources/kernel_fft_second_axis.hlsl index ab7216da2..eaecb5d0f 100644 --- a/28_FFTBloom/app_resources/kernel_fft_second_axis.hlsl +++ b/28_FFTBloom/app_resources/kernel_fft_second_axis.hlsl @@ -200,6 +200,7 @@ struct PreloadedSecondAxisAccessor : MultiChannelPreloadedAccessorMirrorTradeBas }; [numthreads(FFTParameters::WorkgroupSize, 1, 1)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { SharedMemoryAccessor sharedmemAccessor; diff --git a/28_FFTBloom/app_resources/kernel_spectrum_normalize.hlsl b/28_FFTBloom/app_resources/kernel_spectrum_normalize.hlsl index f2ef207d3..efe406301 100644 --- a/28_FFTBloom/app_resources/kernel_spectrum_normalize.hlsl +++ b/28_FFTBloom/app_resources/kernel_spectrum_normalize.hlsl @@ -2,6 +2,7 @@ [[vk::binding(2, 0)]] RWTexture2DArray kernelChannels; [numthreads(8, 8, 1)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { const scalar_t powerReciprocal = vk::RawBufferLoad(pushConstants.rowMajorBufferAddress); diff --git a/28_FFTBloom/main.cpp b/28_FFTBloom/main.cpp index cc312c3be..049bbd581 100644 --- a/28_FFTBloom/main.cpp +++ b/28_FFTBloom/main.cpp @@ -2,27 +2,31 @@ // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h -#include "SimpleWindowedApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" + +#include "nbl/examples/examples.hpp" using namespace nbl; -using namespace core; -using namespace system; -using namespace asset; -using namespace video; -using namespace ui; +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::examples; #include "app_resources/common.hlsl" #include "nbl/builtin/hlsl/bit.hlsl" + + // Defaults that match this example's image constexpr uint32_t WIN_W = 1280; constexpr uint32_t WIN_H = 720; -class FFTBloomApp final : public examples::SimpleWindowedApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +class FFTBloomApp final : public SimpleWindowedApplication, public BuiltinResourcesApplication { - using device_base_t = examples::SimpleWindowedApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using device_base_t = SimpleWindowedApplication; + using asset_base_t = BuiltinResourcesApplication; using clock_t = std::chrono::steady_clock; // Windowed App members @@ -169,7 +173,7 @@ class FFTBloomApp final : public examples::SimpleWindowedApplication, public app float32_t totalSizeReciprocal; }; - inline core::smart_refctd_ptr createShader(const char* includeMainName, const SShaderConstevalParameters& shaderConstants) + inline core::smart_refctd_ptr createShader(const char* includeMainName, const SShaderConstevalParameters& shaderConstants) { // The annoying "const static member field must be initialized outside of struct" bug strikes again std::ostringstream kernelHalfPixelSizeStream; @@ -204,18 +208,17 @@ class FFTBloomApp final : public examples::SimpleWindowedApplication, public app - auto CPUShader = core::make_smart_refctd_ptr((prelude+"\n#include \"" + includeMainName + "\"\n").c_str(), - IShader::E_SHADER_STAGE::ESS_COMPUTE, + auto HLSLShader = core::make_smart_refctd_ptr((prelude+"\n#include \"" + includeMainName + "\"\n").c_str(), IShader::E_CONTENT_TYPE::ECT_HLSL, includeMainName); - assert(CPUShader); + assert(HLSLShader); #ifndef _NBL_DEBUG ISPIRVOptimizer::E_OPTIMIZER_PASS optPasses = ISPIRVOptimizer::EOP_STRIP_DEBUG_INFO; auto opt = make_smart_refctd_ptr(std::span(&optPasses, 1)); - return m_device->createShader({ CPUShader.get(), opt.get(), m_readCache.get(), m_writeCache.get()}); + return m_device->compileShader({ HLSLShader.get(), opt.get(), m_readCache.get(), m_writeCache.get()}); #else - return m_device->createShader({ CPUShader.get(), nullptr, m_readCache.get(), m_writeCache.get() }); + return m_device->compileShader({ HLSLShader.get(), nullptr, m_readCache.get(), m_writeCache.get() }); #endif } @@ -709,7 +712,7 @@ class FFTBloomApp final : public examples::SimpleWindowedApplication, public app // Normalization shader needs this info uint16_t secondAxisFFTHalfLengthLog2 = elementsPerInvocationLog2 + workgroupSizeLog2 - 1; // Create shaders - smart_refctd_ptr shaders[3]; + smart_refctd_ptr shaders[3]; uint16_t2 kernelDimensions = { kerDim.width, kerDim.height }; SShaderConstevalParameters::SShaderConstevalParametersCreateInfo shaderConstevalInfo = { .useHalfFloats = m_useHalfFloats, .elementsPerInvocationLog2 = elementsPerInvocationLog2, .workgroupSizeLog2 = workgroupSizeLog2, .numWorkgroupsLog2 = secondAxisFFTHalfLengthLog2, .previousWorkgroupSizeLog2 = workgroupSizeLog2 }; SShaderConstevalParameters shaderConstevalParameters(shaderConstevalInfo); @@ -722,11 +725,11 @@ class FFTBloomApp final : public examples::SimpleWindowedApplication, public app for (auto i = 0u; i < 3; i++) { params[i].layout = pipelineLayout.get(); - params[i].shader.entryPoint = "main"; params[i].shader.shader = shaders[i].get(); + params[i].shader.entryPoint = "main"; // Normalization doesn't require full subgroups - params[i].shader.requireFullSubgroups = bool(2-i); - params[i].shader.requiredSubgroupSize = static_cast(hlsl::findMSB(deviceLimits.maxSubgroupSize)); + params[i].cached.requireFullSubgroups = bool(2-i); + params[i].shader.requiredSubgroupSize = static_cast(hlsl::findMSB(deviceLimits.maxSubgroupSize)); } smart_refctd_ptr pipelines[3]; @@ -884,7 +887,7 @@ class FFTBloomApp final : public examples::SimpleWindowedApplication, public app uint16_t firstAxisFFTHalfLengthLog2; uint16_t firstAxisFFTElementsPerInvocationLog2; uint16_t firstAxisFFTWorkgroupSizeLog2; - smart_refctd_ptr shaders[3]; + smart_refctd_ptr shaders[3]; { auto [elementsPerInvocationLog2, workgroupSizeLog2] = workgroup::fft::optimalFFTParameters(deviceLimits.maxOptimallyResidentWorkgroupInvocations, m_marginSrcDim.height, deviceLimits.maxSubgroupSize); SShaderConstevalParameters::SShaderConstevalParametersCreateInfo shaderConstevalInfo = { .useHalfFloats = m_useHalfFloats, .elementsPerInvocationLog2 = elementsPerInvocationLog2, .workgroupSizeLog2 = workgroupSizeLog2 }; @@ -926,10 +929,10 @@ class FFTBloomApp final : public examples::SimpleWindowedApplication, public app IGPUComputePipeline::SCreationParams params[3] = {}; for (auto i = 0u; i < 3; i++) { params[i].layout = pipelineLayout.get(); - params[i].shader.entryPoint = "main"; params[i].shader.shader = shaders[i].get(); - params[i].shader.requiredSubgroupSize = static_cast(hlsl::findMSB(deviceLimits.maxSubgroupSize)); - params[i].shader.requireFullSubgroups = true; + params[i].shader.entryPoint = "main"; + params[i].shader.requiredSubgroupSize = static_cast(hlsl::findMSB(deviceLimits.maxSubgroupSize)); + params[i].cached.requireFullSubgroups = true; } smart_refctd_ptr pipelines[3]; diff --git a/29_Arithmetic2Bench/CMakeLists.txt b/29_Arithmetic2Bench/CMakeLists.txt new file mode 100644 index 000000000..0724366c9 --- /dev/null +++ b/29_Arithmetic2Bench/CMakeLists.txt @@ -0,0 +1,25 @@ + +include(common RESULT_VARIABLE RES) +if(NOT RES) + message(FATAL_ERROR "common.cmake not found. Should be in {repo_root}/cmake directory") +endif() + +nbl_create_executable_project("" "" "" "" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") + +if(NBL_EMBED_BUILTIN_RESOURCES) + set(_BR_TARGET_ ${EXECUTABLE_NAME}_builtinResourceData) + set(RESOURCE_DIR "app_resources") + + get_filename_component(_SEARCH_DIRECTORIES_ "${CMAKE_CURRENT_SOURCE_DIR}" ABSOLUTE) + get_filename_component(_OUTPUT_DIRECTORY_SOURCE_ "${CMAKE_CURRENT_BINARY_DIR}/src" ABSOLUTE) + get_filename_component(_OUTPUT_DIRECTORY_HEADER_ "${CMAKE_CURRENT_BINARY_DIR}/include" ABSOLUTE) + + file(GLOB_RECURSE BUILTIN_RESOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/${RESOURCE_DIR}" CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${RESOURCE_DIR}/*") + foreach(RES_FILE ${BUILTIN_RESOURCE_FILES}) + LIST_BUILTIN_RESOURCE(RESOURCES_TO_EMBED "${RES_FILE}") + endforeach() + + ADD_CUSTOM_BUILTIN_RESOURCES(${_BR_TARGET_} RESOURCES_TO_EMBED "${_SEARCH_DIRECTORIES_}" "${RESOURCE_DIR}" "nbl::this_example::builtin" "${_OUTPUT_DIRECTORY_HEADER_}" "${_OUTPUT_DIRECTORY_SOURCE_}") + + LINK_BUILTIN_RESOURCES_TO_TARGET(${EXECUTABLE_NAME} ${_BR_TARGET_}) +endif() \ No newline at end of file diff --git a/29_Arithmetic2Bench/app_resources/benchmarkSubgroup.comp.hlsl b/29_Arithmetic2Bench/app_resources/benchmarkSubgroup.comp.hlsl new file mode 100644 index 000000000..f6ad3e678 --- /dev/null +++ b/29_Arithmetic2Bench/app_resources/benchmarkSubgroup.comp.hlsl @@ -0,0 +1,57 @@ +#pragma shader_stage(compute) + +#define operation_t nbl::hlsl::OPERATION + +#include "nbl/builtin/hlsl/glsl_compat/core.hlsl" +#include "nbl/builtin/hlsl/glsl_compat/subgroup_basic.hlsl" +#include "nbl/builtin/hlsl/subgroup2/arithmetic_params.hlsl" +#include "nbl/builtin/hlsl/subgroup2/arithmetic_portability.hlsl" +#include "nbl/builtin/hlsl/random/xoroshiro.hlsl" + +#include "shaderCommon.hlsl" +#include "nbl/builtin/hlsl/workgroup2/basic.hlsl" + +template +using params_t = SUBGROUP_CONFIG_T; + +NBL_CONSTEXPR_STATIC_INLINE uint32_t ItemsPerInvocation = params_t::base_t, device_capabilities>::ItemsPerInvocation; + +typedef vector type_t; + +uint32_t globalIndex() +{ + return glsl::gl_WorkGroupID().x*WORKGROUP_SIZE+workgroup::SubgroupContiguousIndex(); +} + +template +static void subbench(NBL_CONST_REF_ARG(type_t) sourceVal) +{ + type_t value = sourceVal; + + const uint64_t outputBufAddr = pc.pOutputBuf[Binop::BindingIndex]; + + operation_t > func; + // [unroll] + for (uint32_t i = 0; i < NUM_LOOPS; i++) + value = func(value); + + vk::RawBufferStore(outputBufAddr + sizeof(type_t) * globalIndex(), value, sizeof(uint32_t)); +} + +void benchmark() +{ + const uint32_t invocationIndex = globalIndex(); + type_t sourceVal; + Xoroshiro64Star xoroshiro = Xoroshiro64Star::construct(uint32_t2(invocationIndex,invocationIndex+1)); + [unroll] + for (uint16_t i = 0; i < ItemsPerInvocation; i++) + sourceVal[i] = xoroshiro(); + + subbench >(sourceVal); +} + +[numthreads(WORKGROUP_SIZE,1,1)] +void main() +{ + benchmark(); +} diff --git a/29_Arithmetic2Bench/app_resources/benchmarkWorkgroup.comp.hlsl b/29_Arithmetic2Bench/app_resources/benchmarkWorkgroup.comp.hlsl new file mode 100644 index 000000000..58912691f --- /dev/null +++ b/29_Arithmetic2Bench/app_resources/benchmarkWorkgroup.comp.hlsl @@ -0,0 +1,125 @@ +#pragma shader_stage(compute) + +#include "nbl/builtin/hlsl/glsl_compat/core.hlsl" +#include "nbl/builtin/hlsl/glsl_compat/subgroup_basic.hlsl" +#include "nbl/builtin/hlsl/subgroup2/arithmetic_portability.hlsl" +#include "nbl/builtin/hlsl/workgroup2/arithmetic.hlsl" +#include "nbl/builtin/hlsl/random/xoroshiro.hlsl" + +using config_t = WORKGROUP_CONFIG_T; + +#include "shaderCommon.hlsl" + +typedef vector type_t; + +// final (level 1/2) scan needs to fit in one subgroup exactly +groupshared uint32_t scratch[mpl::max_v]; + +#include "nbl/examples/workgroup/DataAccessors.hlsl" +using namespace nbl::hlsl::examples::workgroup; + +template +struct RandomizedInputDataProxy +{ + using dtype_t = vector; + + NBL_CONSTEXPR_STATIC_INLINE uint16_t WorkgroupSize = uint16_t(1u) << WorkgroupSizeLog2; + NBL_CONSTEXPR_STATIC_INLINE uint16_t PreloadedDataCount = VirtualWorkgroupSize / WorkgroupSize; + + static RandomizedInputDataProxy create(uint64_t inputBuf, uint64_t outputBuf) + { + RandomizedInputDataProxy retval; + retval.data = DataProxy::create(inputBuf, outputBuf); + return retval; + } + + template + void get(const IndexType ix, NBL_REF_ARG(AccessType) value) + { + value = preloaded[ix>>WorkgroupSizeLog2]; + } + template + void set(const IndexType ix, const AccessType value) + { + preloaded[ix>>WorkgroupSizeLog2] = value; + } + + void preload() + { + const uint16_t invocationIndex = workgroup::SubgroupContiguousIndex(); + Xoroshiro64Star xoroshiro = Xoroshiro64Star::construct(uint32_t2(invocationIndex,invocationIndex+1)); + [unroll] + for (uint16_t idx = 0; idx < PreloadedDataCount; idx++) + [unroll] + for (uint16_t i = 0; i < ItemsPerInvocation; i++) + preloaded[idx][i] = xoroshiro(); + } + void unload() + { + const uint16_t invocationIndex = workgroup::SubgroupContiguousIndex(); + [unroll] + for (uint16_t idx = 0; idx < PreloadedDataCount; idx++) + data.template set(idx * WorkgroupSize + invocationIndex, preloaded[idx]); + } + + void workgroupExecutionAndMemoryBarrier() + { + glsl::barrier(); + //glsl::memoryBarrierShared(); implied by the above + } + + DataProxy data; + dtype_t preloaded[PreloadedDataCount]; +}; + +static ScratchProxy arithmeticAccessor; + +using data_proxy_t = RandomizedInputDataProxy; + +template +struct operation_t +{ + using binop_base_t = typename Binop::base_t; + using otype_t = typename Binop::type_t; + + void operator()(data_proxy_t dataAccessor) + { +#if IS_REDUCTION + otype_t value = +#endif + OPERATION::template __call(dataAccessor,arithmeticAccessor); + // we barrier before because we alias the accessors for Binop + arithmeticAccessor.workgroupExecutionAndMemoryBarrier(); +#if IS_REDUCTION + [unroll] + for (uint32_t i = 0; i < data_proxy_t::PreloadedDataCount; i++) + dataAccessor.preloaded[i] = value; +#endif + } +}; + +template +static void subbench() +{ + data_proxy_t dataAccessor = data_proxy_t::create(0, pc.pOutputBuf[Binop::BindingIndex]); + dataAccessor.preload(); + + operation_t func; + for (uint32_t i = 0; i < NUM_LOOPS; i++) + func(dataAccessor); + + dataAccessor.unload(); +} + +void benchmark() +{ + // only benchmark plus op + subbench >(); +} + + +[numthreads(config_t::WorkgroupSize,1,1)] +void main() +{ + benchmark(); +} diff --git a/29_Arithmetic2Bench/app_resources/common.hlsl b/29_Arithmetic2Bench/app_resources/common.hlsl new file mode 100644 index 000000000..cca5af987 --- /dev/null +++ b/29_Arithmetic2Bench/app_resources/common.hlsl @@ -0,0 +1,34 @@ +#include "nbl/builtin/hlsl/cpp_compat.hlsl" +#include "nbl/builtin/hlsl/functional.hlsl" + +struct PushConstantData +{ + uint64_t pOutputBuf[2]; +}; + +namespace arithmetic +{ +template +struct plus : nbl::hlsl::plus +{ + using base_t = nbl::hlsl::plus; + + NBL_CONSTEXPR_STATIC_INLINE uint16_t BindingIndex = 0; +#ifndef __HLSL_VERSION + static inline constexpr const char* name = "plus"; +#endif +}; + +template +struct ballot : nbl::hlsl::plus +{ + using base_t = nbl::hlsl::plus; + + NBL_CONSTEXPR_STATIC_INLINE uint16_t BindingIndex = 1; +#ifndef __HLSL_VERSION + static inline constexpr const char* name = "bitcount"; +#endif +}; +} + +#include "nbl/builtin/hlsl/glsl_compat/subgroup_basic.hlsl" diff --git a/29_Arithmetic2Bench/app_resources/shaderCommon.hlsl b/29_Arithmetic2Bench/app_resources/shaderCommon.hlsl new file mode 100644 index 000000000..242ededd8 --- /dev/null +++ b/29_Arithmetic2Bench/app_resources/shaderCommon.hlsl @@ -0,0 +1,26 @@ +#include "common.hlsl" + +using namespace nbl; +using namespace hlsl; + +[[vk::push_constant]] PushConstantData pc; + +struct device_capabilities +{ +#ifdef TEST_NATIVE + NBL_CONSTEXPR_STATIC_INLINE bool shaderSubgroupArithmetic = true; +#else + NBL_CONSTEXPR_STATIC_INLINE bool shaderSubgroupArithmetic = false; +#endif +}; + +#ifndef OPERATION +#error "Define OPERATION!" +#endif + +#ifndef NUM_LOOPS +#error "Define NUM_LOOPS!" +#endif + +// NOTE added dummy output image to be able to profile with Nsight, which still doesn't support profiling headless compute shaders +[[vk::binding(2, 0)]] RWTexture2D outImage; // dummy diff --git a/29_SpecializationConstants/config.json.template b/29_Arithmetic2Bench/config.json.template similarity index 100% rename from 29_SpecializationConstants/config.json.template rename to 29_Arithmetic2Bench/config.json.template diff --git a/29_Arithmetic2Bench/main.cpp b/29_Arithmetic2Bench/main.cpp new file mode 100644 index 000000000..75f483db0 --- /dev/null +++ b/29_Arithmetic2Bench/main.cpp @@ -0,0 +1,689 @@ +#include "nbl/examples/examples.hpp" +#include "app_resources/common.hlsl" +#include "nbl/builtin/hlsl/workgroup2/arithmetic_config.hlsl" +#include "nbl/builtin/hlsl/subgroup2/arithmetic_params.hlsl" + +using namespace nbl; +using namespace nbl::core; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::examples; + + +template requires std::is_base_of_v +class CExplicitSurfaceFormatResizeSurface final : public ISimpleManagedSurface +{ +public: + using this_t = CExplicitSurfaceFormatResizeSurface; + + // Factory method so we can fail, requires a `_surface` created from a window and with a callback that inherits from `ICallback` declared just above + template requires std::is_base_of_v, Surface> + static inline core::smart_refctd_ptr create(core::smart_refctd_ptr&& _surface) + { + if (!_surface) + return nullptr; + + auto _window = _surface->getWindow(); + ICallback* cb = nullptr; + if (_window) + cb = dynamic_cast(_window->getEventCallback()); + + return core::smart_refctd_ptr(new this_t(std::move(_surface), cb), core::dont_grab); + } + + // Factory method so we can fail, requires a `_surface` created from a native surface + template requires std::is_base_of_v, Surface> + static inline core::smart_refctd_ptr create(core::smart_refctd_ptr&& _surface, ICallback* cb) + { + if (!_surface) + return nullptr; + + return core::smart_refctd_ptr(new this_t(std::move(_surface), cb), core::dont_grab); + } + + // + inline bool init(CThreadSafeQueueAdapter* queue, std::unique_ptr&& scResources, const ISwapchain::SSharedCreationParams& sharedParams = {}) + { + if (!scResources || !base_init(queue)) + return init_fail(); + + m_sharedParams = sharedParams; + if (!m_sharedParams.deduce(queue->getOriginDevice()->getPhysicalDevice(), getSurface())) + return init_fail(); + + m_swapchainResources = std::move(scResources); + return true; + } + + // Can be public because we don't need to worry about mutexes unlike the Smooth Resize class + inline ISwapchainResources* getSwapchainResources() override { return m_swapchainResources.get(); } + + // need to see if the swapchain is invalidated (e.g. because we're starting from 0-area old Swapchain) and try to recreate the swapchain + inline SAcquireResult acquireNextImage() + { + if (!isWindowOpen()) + { + becomeIrrecoverable(); + return {}; + } + + if (!m_swapchainResources || (m_swapchainResources->getStatus() != ISwapchainResources::STATUS::USABLE && !recreateSwapchain(m_surfaceFormat))) + return {}; + + return ISimpleManagedSurface::acquireNextImage(); + } + + // its enough to just foward though + inline bool present(const uint8_t imageIndex, const std::span waitSemaphores) + { + return ISimpleManagedSurface::present(imageIndex, waitSemaphores); + } + + // + inline bool recreateSwapchain(const ISurface::SFormat& explicitSurfaceFormat) + { + assert(m_swapchainResources); + // dont assign straight to `m_swapchainResources` because of complex refcounting and cycles + core::smart_refctd_ptr newSwapchain; + // TODO: This block of code could be rolled up into `ISimpleManagedSurface::ISwapchainResources` eventually + { + auto* surface = getSurface(); + auto device = const_cast(getAssignedQueue()->getOriginDevice()); + // 0s are invalid values, so they indicate we want them deduced + m_sharedParams.width = 0; + m_sharedParams.height = 0; + // Question: should we re-query the supported queues, formats, present modes, etc. just-in-time?? + auto* swapchain = m_swapchainResources->getSwapchain(); + if (swapchain ? swapchain->deduceRecreationParams(m_sharedParams) : m_sharedParams.deduce(device->getPhysicalDevice(), surface)) + { + // super special case, we can't re-create the swapchain but its possible to recover later on + if (m_sharedParams.width == 0 || m_sharedParams.height == 0) + { + // we need to keep the old-swapchain around, but can drop the rest + m_swapchainResources->invalidate(); + return false; + } + // now lets try to create a new swapchain + if (swapchain) + newSwapchain = swapchain->recreate(m_sharedParams); + else + { + ISwapchain::SCreationParams params = { + .surface = core::smart_refctd_ptr(surface), + .surfaceFormat = explicitSurfaceFormat, + .sharedParams = m_sharedParams + // we're not going to support concurrent sharing in this simple class + }; + m_surfaceFormat = explicitSurfaceFormat; + newSwapchain = CVulkanSwapchain::create(core::smart_refctd_ptr(device), std::move(params)); + } + } + else // parameter deduction failed + return false; + } + + if (newSwapchain) + { + m_swapchainResources->invalidate(); + return m_swapchainResources->onCreateSwapchain(getAssignedQueue()->getFamilyIndex(), std::move(newSwapchain)); + } + else + becomeIrrecoverable(); + + return false; + } + +protected: + using ISimpleManagedSurface::ISimpleManagedSurface; + + // + inline void deinit_impl() override final + { + becomeIrrecoverable(); + } + + // + inline void becomeIrrecoverable() override { m_swapchainResources = nullptr; } + + // gets called when OUT_OF_DATE upon an acquire + inline SAcquireResult handleOutOfDate() override final + { + // recreate swapchain and try to acquire again + if (recreateSwapchain(m_surfaceFormat)) + return ISimpleManagedSurface::acquireNextImage(); + return {}; + } + +private: + // Because the surface can start minimized (extent={0,0}) we might not be able to create the swapchain right away, so store creation parameters until we can create it. + ISwapchain::SSharedCreationParams m_sharedParams = {}; + // The swapchain might not be possible to create or recreate right away, so this might be + // either nullptr before the first successful acquire or the old to-be-retired swapchain. + std::unique_ptr m_swapchainResources = {}; + + ISurface::SFormat m_surfaceFormat = {}; +}; + +// NOTE added swapchain + drawing frames to be able to profile with Nsight, which still doesn't support profiling headless compute shaders +class ArithmeticBenchApp final : public examples::SimpleWindowedApplication, public examples::BuiltinResourcesApplication +{ + using device_base_t = examples::SimpleWindowedApplication; + using asset_base_t = examples::BuiltinResourcesApplication; + + constexpr static inline uint32_t WIN_W = 1280; + constexpr static inline uint32_t WIN_H = 720; + constexpr static inline uint32_t MaxFramesInFlight = 5; + +public: + ArithmeticBenchApp(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) : + system::IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) {} + + inline core::vector getSurfaces() const override + { + if (!m_surface) + { + { + auto windowCallback = core::make_smart_refctd_ptr(smart_refctd_ptr(m_inputSystem), smart_refctd_ptr(m_logger)); + IWindow::SCreationParams params = {}; + params.callback = core::make_smart_refctd_ptr(); + params.width = WIN_W; + params.height = WIN_H; + params.x = 32; + params.y = 32; + params.flags = ui::IWindow::ECF_HIDDEN | IWindow::ECF_BORDERLESS | IWindow::ECF_RESIZABLE; + params.windowCaption = "ArithmeticBenchApp"; + params.callback = windowCallback; + const_cast&>(m_window) = m_winMgr->createWindow(std::move(params)); + } + + auto surface = CSurfaceVulkanWin32::create(smart_refctd_ptr(m_api), smart_refctd_ptr_static_cast(m_window)); + const_cast&>(m_surface) = CExplicitSurfaceFormatResizeSurface::create(std::move(surface)); + } + + if (m_surface) + return { {m_surface->getSurface()/*,EQF_NONE*/} }; + + return {}; + } + + bool onAppInitialized(smart_refctd_ptr&& system) override + { + m_inputSystem = make_smart_refctd_ptr(logger_opt_smart_ptr(smart_refctd_ptr(m_logger))); + + if (!device_base_t::onAppInitialized(std::move(system))) + return false; + if (!asset_base_t::onAppInitialized(std::move(system))) + return false; + + m_semaphore = m_device->createSemaphore(m_realFrameIx); + if (!m_semaphore) + return logFail("Failed to Create a Semaphore!"); + + ISwapchain::SCreationParams swapchainParams = { .surface = m_surface->getSurface() }; + asset::E_FORMAT preferredFormats[] = { asset::EF_R8G8B8A8_UNORM }; + if (!swapchainParams.deduceFormat(m_physicalDevice, preferredFormats)) + return logFail("Could not choose a Surface Format for the Swapchain!"); + + swapchainParams.sharedParams.imageUsage = IGPUImage::E_USAGE_FLAGS::EUF_RENDER_ATTACHMENT_BIT | IGPUImage::E_USAGE_FLAGS::EUF_STORAGE_BIT; + + auto graphicsQueue = getGraphicsQueue(); + if (!m_surface || !m_surface->init(graphicsQueue, std::make_unique(), swapchainParams.sharedParams)) + return logFail("Could not create Window & Surface or initialize the Surface!"); + + auto pool = m_device->createCommandPool(graphicsQueue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); + + for (auto i = 0u; i < MaxFramesInFlight; i++) + { + if (!pool) + return logFail("Couldn't create Command Pool!"); + if (!pool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY, { m_cmdBufs.data() + i, 1 })) + return logFail("Couldn't create Command Buffer!"); + } + + m_winMgr->setWindowSize(m_window.get(), WIN_W, WIN_H); + m_surface->recreateSwapchain(swapchainParams.surfaceFormat); + + transferDownQueue = getTransferDownQueue(); + computeQueue = getComputeQueue(); + + // create 2 buffers for 2 operations + for (auto i=0u; icreateBuffer(std::move(params)); + auto mreq = outputBuffers[i]->getMemoryReqs(); + mreq.memoryTypeBits &= m_physicalDevice->getDeviceLocalMemoryTypeBits(); + assert(mreq.memoryTypeBits); + + auto bufferMem = m_device->allocate(mreq, outputBuffers[i].get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); + assert(bufferMem.isValid()); + } + for (auto i = 0u; i < OutputBufferCount; i++) + pc.pOutputBuf[i] = outputBuffers[i]->getDeviceAddress(); + + // create image views for swapchain images + for (uint32_t i = 0; i < ISwapchain::MaxImages; i++) + { + IGPUImage* scImg = m_surface->getSwapchainResources()->getImage(i); + if (scImg == nullptr) + continue; + IGPUImageView::SCreationParams viewParams = { + .flags = IGPUImageView::ECF_NONE, + .subUsages = IGPUImage::E_USAGE_FLAGS::EUF_STORAGE_BIT, + .image = smart_refctd_ptr(scImg), + .viewType = IGPUImageView::ET_2D, + .format = scImg->getCreationParameters().format + }; + swapchainImageViews[i] = m_device->createImageView(std::move(viewParams)); + } + + // create Descriptor Sets and Pipeline Layouts + smart_refctd_ptr benchPplnLayout; + { + // set and transient pool + smart_refctd_ptr benchLayout; + { + IGPUDescriptorSetLayout::SBinding binding[1]; + binding[0] = { {},2,IDescriptor::E_TYPE::ET_STORAGE_IMAGE,IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_UPDATE_AFTER_BIND_BIT,IShader::E_SHADER_STAGE::ESS_COMPUTE,1u,nullptr }; + benchLayout = m_device->createDescriptorSetLayout(binding); + } + + const uint32_t setCount = ISwapchain::MaxImages; + benchPool = m_device->createDescriptorPoolForDSLayouts(IDescriptorPool::ECF_UPDATE_AFTER_BIND_BIT, { &benchLayout.get(),1 }, &setCount); + for (auto i = 0u; i < ISwapchain::MaxImages; i++) + { + benchDs[i] = benchPool->createDescriptorSet(smart_refctd_ptr(benchLayout)); + if (!benchDs[i]) + return logFail("Could not create Descriptor Set!"); + } + + SPushConstantRange pcRange = { .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, .offset = 0,.size = sizeof(PushConstantData) }; + benchPplnLayout = m_device->createPipelineLayout({ &pcRange, 1 }, std::move(benchLayout)); + } + if (UseNativeArithmetic && !m_physicalDevice->getProperties().limits.shaderSubgroupArithmetic) + { + logFail("UseNativeArithmetic is true but device does not support shaderSubgroupArithmetic!"); + return false; + } + + IGPUDescriptorSet::SWriteDescriptorSet dsWrites[ISwapchain::MaxImages]; + for (auto i = 0u; i < ISwapchain::MaxImages; i++) + { + if (swapchainImageViews[i].get() == nullptr) + continue; + + video::IGPUDescriptorSet::SDescriptorInfo dsInfo; + dsInfo.info.image.imageLayout = IImage::LAYOUT::GENERAL; + dsInfo.desc = swapchainImageViews[i]; + + dsWrites[i] = + { + .dstSet = benchDs[i].get(), + .binding = 2u, + .arrayElement = 0u, + .count = 1u, + .info = &dsInfo, + }; + m_device->updateDescriptorSets(1u, &dsWrites[i], 0u, nullptr); + } + + + // load shader source from file + auto getShaderSource = [&](const char* filePath) -> auto + { + IAssetLoader::SAssetLoadParams lparams = {}; + lparams.logger = m_logger.get(); + lparams.workingDirectory = ""; + auto bundle = m_assetMgr->getAsset(filePath, lparams); + if (bundle.getContents().empty() || bundle.getAssetType()!=IAsset::ET_SHADER) + { + m_logger->log("Shader %s not found!", ILogger::ELL_ERROR, filePath); + exit(-1); + } + auto firstAssetInBundle = bundle.getContents()[0]; + return smart_refctd_ptr_static_cast(firstAssetInBundle); + }; + + // for each workgroup size (manually adjust items per invoc, operation else uses up a lot of ram) + const auto MaxSubgroupSize = m_physicalDevice->getLimits().maxSubgroupSize; + smart_refctd_ptr shaderSource; + if constexpr (DoWorkgroupBenchmarks) + shaderSource = getShaderSource("app_resources/benchmarkWorkgroup.comp.hlsl"); + else + shaderSource = getShaderSource("app_resources/benchmarkSubgroup.comp.hlsl"); + + for (uint32_t op = 0; op < arithmeticOperations.size(); op++) + for (uint32_t i = 0; i < workgroupSizes.size(); i++) + benchSets[op*workgroupSizes.size()+i] = createBenchmarkPipelines(shaderSource, benchPplnLayout.get(), ElementCount, arithmeticOperations[op], hlsl::findMSB(MaxSubgroupSize), workgroupSizes[i], ItemsPerInvocation, NumLoops); + + m_winMgr->show(m_window.get()); + + return true; + } + + virtual bool onAppTerminated() override + { + return true; + } + + // the unit test is carried out on init + void workLoopBody() override + { + const auto resourceIx = m_realFrameIx % MaxFramesInFlight; + + const uint32_t framesInFlight = core::min(MaxFramesInFlight, m_surface->getMaxAcquiresInFlight()); + + if (m_realFrameIx >= framesInFlight) + { + const ISemaphore::SWaitInfo cbDonePending[] = + { + { + .semaphore = m_semaphore.get(), + .value = m_realFrameIx + 1 - framesInFlight + } + }; + if (m_device->blockForSemaphores(cbDonePending) != ISemaphore::WAIT_RESULT::SUCCESS) + return; + } + + m_currentImageAcquire = m_surface->acquireNextImage(); + if (!m_currentImageAcquire) + return; + + auto* const cmdbuf = m_cmdBufs.data()[resourceIx].get(); + cmdbuf->reset(IGPUCommandBuffer::RESET_FLAGS::RELEASE_RESOURCES_BIT); + cmdbuf->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + + const auto MaxSubgroupSize = m_physicalDevice->getLimits().maxSubgroupSize; + const auto SubgroupSizeLog2 = hlsl::findMSB(MaxSubgroupSize); + + cmdbuf->bindDescriptorSets(EPBP_COMPUTE, benchSets[0].pipeline->getLayout(), 0u, 1u, &benchDs[m_currentImageAcquire.imageIndex].get()); + cmdbuf->pushConstants(benchSets[0].pipeline->getLayout(), IShader::E_SHADER_STAGE::ESS_COMPUTE, 0, sizeof(PushConstantData), &pc); + + for (uint32_t i = 0; i < benchSets.size(); i++) + runBenchmark(cmdbuf, benchSets[i], ElementCount, SubgroupSizeLog2); + + // barrier transition to PRESENT + { + IGPUCommandBuffer::SPipelineBarrierDependencyInfo::image_barrier_t imageBarriers[1]; + imageBarriers[0].barrier = { + .dep = { + .srcStageMask = PIPELINE_STAGE_FLAGS::COMPUTE_SHADER_BIT, + .srcAccessMask = ACCESS_FLAGS::SHADER_WRITE_BITS, + .dstStageMask = PIPELINE_STAGE_FLAGS::NONE, + .dstAccessMask = ACCESS_FLAGS::NONE + } + }; + imageBarriers[0].image = m_surface->getSwapchainResources()->getImage(m_currentImageAcquire.imageIndex); + imageBarriers[0].subresourceRange = { + .aspectMask = IImage::EAF_COLOR_BIT, + .baseMipLevel = 0u, + .levelCount = 1u, + .baseArrayLayer = 0u, + .layerCount = 1u + }; + imageBarriers[0].oldLayout = IImage::LAYOUT::UNDEFINED; + imageBarriers[0].newLayout = IImage::LAYOUT::PRESENT_SRC; + + cmdbuf->pipelineBarrier(E_DEPENDENCY_FLAGS::EDF_NONE, { .imgBarriers = imageBarriers }); + } + + cmdbuf->end(); + + // submit + { + auto* queue = getGraphicsQueue(); + const IQueue::SSubmitInfo::SSemaphoreInfo rendered[] = + { + { + .semaphore = m_semaphore.get(), + .value = ++m_realFrameIx, + .stageMask = PIPELINE_STAGE_FLAGS::ALL_TRANSFER_BITS + } + }; + { + { + const IQueue::SSubmitInfo::SCommandBufferInfo commandBuffers[] = + { + {.cmdbuf = cmdbuf } + }; + + const IQueue::SSubmitInfo::SSemaphoreInfo acquired[] = + { + { + .semaphore = m_currentImageAcquire.semaphore, + .value = m_currentImageAcquire.acquireCount, + .stageMask = PIPELINE_STAGE_FLAGS::NONE + } + }; + const IQueue::SSubmitInfo infos[] = + { + { + .waitSemaphores = acquired, + .commandBuffers = commandBuffers, + .signalSemaphores = rendered + } + }; + + if (queue->submit(infos) == IQueue::RESULT::SUCCESS) + { + const nbl::video::ISemaphore::SWaitInfo waitInfos[] = + { { + .semaphore = m_semaphore.get(), + .value = m_realFrameIx + } }; + + m_device->blockForSemaphores(waitInfos); // this is not solution, quick wa to not throw validation errors + } + else + --m_realFrameIx; + } + } + + m_surface->present(m_currentImageAcquire.imageIndex, rendered); + } + + numSubmits++; + } + + // + bool keepRunning() override { return numSubmits < MaxNumSubmits; } + +private: + // create pipeline (specialized every test) [TODO: turn into a future/async] + smart_refctd_ptr createPipeline(const IShader* overridenUnspecialized, const IGPUPipelineLayout* layout, const uint8_t subgroupSizeLog2) + { + auto shader = m_device->compileShader({ overridenUnspecialized }); + IGPUComputePipeline::SCreationParams params = {}; + params.layout = layout; + params.shader = { + .shader = shader.get(), + .entryPoint = "main", + .requiredSubgroupSize = static_cast(subgroupSizeLog2), + .entries = nullptr, + }; + params.cached.requireFullSubgroups = true; + core::smart_refctd_ptr pipeline; + if (!m_device->createComputePipelines(nullptr,{¶ms,1},&pipeline)) + return nullptr; + return pipeline; + } + + struct BenchmarkSet + { + smart_refctd_ptr pipeline; + uint32_t workgroupSize; + uint32_t itemsPerInvocation; + }; + + template + BenchmarkSet createBenchmarkPipelines(const smart_refctd_ptr&source, const IGPUPipelineLayout* layout, const uint32_t elementCount, const std::string& arith_name, const uint8_t subgroupSizeLog2, const uint32_t workgroupSize, uint32_t itemsPerInvoc = 1u, uint32_t numLoops = 8u) + { + auto compiler = make_smart_refctd_ptr(smart_refctd_ptr(m_system)); + CHLSLCompiler::SOptions options = {}; + options.stage = IShader::E_SHADER_STAGE::ESS_COMPUTE; + options.targetSpirvVersion = m_device->getPhysicalDevice()->getLimits().spirvVersion; + options.spirvOptimizer = nullptr; +#ifndef _NBL_DEBUG + ISPIRVOptimizer::E_OPTIMIZER_PASS optPasses = ISPIRVOptimizer::EOP_STRIP_DEBUG_INFO; + auto opt = make_smart_refctd_ptr(std::span(&optPasses, 1)); + options.spirvOptimizer = opt.get(); +#else + options.debugInfoFlags |= IShaderCompiler::E_DEBUG_INFO_FLAGS::EDIF_LINE_BIT; +#endif + options.preprocessorOptions.sourceIdentifier = source->getFilepathHint(); + options.preprocessorOptions.logger = m_logger.get(); + + auto* includeFinder = compiler->getDefaultIncludeFinder(); + options.preprocessorOptions.includeFinder = includeFinder; + + const uint32_t subgroupSize = 0x1u << subgroupSizeLog2; + const uint32_t workgroupSizeLog2 = hlsl::findMSB(workgroupSize); + hlsl::workgroup2::SArithmeticConfiguration wgConfig; + wgConfig.init(workgroupSizeLog2, subgroupSizeLog2, itemsPerInvoc); + const uint32_t itemsPerWG = wgConfig.VirtualWorkgroupSize * wgConfig.ItemsPerInvocation_0; + smart_refctd_ptr overriddenUnspecialized; + if constexpr (WorkgroupBench) + { + const std::string definitions[4] = { + "workgroup2::" + arith_name, + wgConfig.getConfigTemplateStructString(), + std::to_string(numLoops), + std::to_string(arith_name=="reduction") + }; + + const IShaderCompiler::SMacroDefinition defines[5] = { + { "OPERATION", definitions[0] }, + { "WORKGROUP_CONFIG_T", definitions[1] }, + { "NUM_LOOPS", definitions[2] }, + { "IS_REDUCTION", definitions[3] }, + { "TEST_NATIVE", "1" } + }; + if (UseNativeArithmetic) + options.preprocessorOptions.extraDefines = { defines, defines + 5 }; + else + options.preprocessorOptions.extraDefines = { defines, defines + 4 }; + + overriddenUnspecialized = compiler->compileToSPIRV((const char*)source->getContent()->getPointer(), options); + } + else + { + hlsl::subgroup2::SArithmeticParams sgParams; + sgParams.init(subgroupSizeLog2, itemsPerInvoc); + + const std::string definitions[4] = { + "subgroup2::" + arith_name, + std::to_string(workgroupSize), + sgParams.getParamTemplateStructString(), + std::to_string(numLoops) + }; + + const IShaderCompiler::SMacroDefinition defines[5] = { + { "OPERATION", definitions[0] }, + { "WORKGROUP_SIZE", definitions[1] }, + { "SUBGROUP_CONFIG_T", definitions[2] }, + { "NUM_LOOPS", definitions[3] }, + { "TEST_NATIVE", "1" } + }; + if (UseNativeArithmetic) + options.preprocessorOptions.extraDefines = { defines, defines + 5 }; + else + options.preprocessorOptions.extraDefines = { defines, defines + 4 }; + + overriddenUnspecialized = compiler->compileToSPIRV((const char*)source->getContent()->getPointer(), options); + } + + BenchmarkSet set; + set.pipeline = createPipeline(overriddenUnspecialized.get(), layout, subgroupSizeLog2); + if constexpr (WorkgroupBench) + { + set.workgroupSize = itemsPerWG; + } + else + { + set.workgroupSize = workgroupSize; + } + set.itemsPerInvocation = itemsPerInvoc; + + return set; + }; + + template + void runBenchmark(IGPUCommandBuffer* cmdbuf, const BenchmarkSet& set, const uint32_t elementCount, const uint8_t subgroupSizeLog2) + { + uint32_t workgroupCount; + if constexpr (WorkgroupBench) + workgroupCount = elementCount / set.workgroupSize; + else + workgroupCount = elementCount / (set.workgroupSize * set.itemsPerInvocation); + + cmdbuf->bindComputePipeline(set.pipeline.get()); + cmdbuf->dispatch(workgroupCount, 1, 1); + { + IGPUCommandBuffer::SPipelineBarrierDependencyInfo::buffer_barrier_t memoryBarrier[OutputBufferCount]; + for (auto i = 0u; i < OutputBufferCount; i++) + { + memoryBarrier[i] = { + .barrier = { + .dep = { + .srcStageMask = PIPELINE_STAGE_FLAGS::COMPUTE_SHADER_BIT, + .srcAccessMask = ACCESS_FLAGS::SHADER_WRITE_BITS, + // in theory we don't need the HOST BITS cause we block on a semaphore but might as well add them + .dstStageMask = PIPELINE_STAGE_FLAGS::COMPUTE_SHADER_BIT | PIPELINE_STAGE_FLAGS::HOST_BIT, + .dstAccessMask = ACCESS_FLAGS::SHADER_WRITE_BITS | ACCESS_FLAGS::HOST_READ_BIT + } + }, + .range = {0ull,outputBuffers[i]->getSize(),outputBuffers[i]} + }; + } + IGPUCommandBuffer::SPipelineBarrierDependencyInfo info = { .memBarriers = {},.bufBarriers = memoryBarrier }; + cmdbuf->pipelineBarrier(asset::E_DEPENDENCY_FLAGS::EDF_NONE, info); + } + } + + IQueue* transferDownQueue; + IQueue* computeQueue; + + smart_refctd_ptr m_window; + smart_refctd_ptr> m_surface; + smart_refctd_ptr m_semaphore; + uint64_t m_realFrameIx = 0; + std::array, MaxFramesInFlight> m_cmdBufs; + ISimpleManagedSurface::SAcquireResult m_currentImageAcquire = {}; + + smart_refctd_ptr m_inputSystem; + + std::array, ISwapchain::MaxImages> swapchainImageViews; + + constexpr static inline uint32_t MaxNumSubmits = 30; + uint32_t numSubmits = 0; + constexpr static inline uint32_t ElementCount = 1024 * 1024; + + /* PARAMETERS TO CHANGE FOR DIFFERENT BENCHMARKS */ + constexpr static inline bool DoWorkgroupBenchmarks = true; + constexpr static inline bool UseNativeArithmetic = true; + uint32_t ItemsPerInvocation = 4u; + constexpr static inline uint32_t NumLoops = 1000u; + constexpr static inline uint32_t NumBenchmarks = 6u; + std::array workgroupSizes = { 32, 64, 128, 256, 512, 1024 }; + std::array arithmeticOperations = { "reduction", "inclusive_scan", "exclusive_scan" }; + + + std::array benchSets; + smart_refctd_ptr benchPool; + std::array, ISwapchain::MaxImages> benchDs; + + constexpr static inline uint32_t OutputBufferCount = 2u; + smart_refctd_ptr outputBuffers[OutputBufferCount]; + smart_refctd_ptr gpuOutputAddressesBuffer; + PushConstantData pc; + + uint64_t timelineValue = 0; +}; + +NBL_MAIN_FUNC(ArithmeticBenchApp) \ No newline at end of file diff --git a/old_to_refactor/49_ComputeFFT/pipeline.groovy b/29_Arithmetic2Bench/pipeline.groovy similarity index 85% rename from old_to_refactor/49_ComputeFFT/pipeline.groovy rename to 29_Arithmetic2Bench/pipeline.groovy index 64874da2a..7ea9947e0 100644 --- a/old_to_refactor/49_ComputeFFT/pipeline.groovy +++ b/29_Arithmetic2Bench/pipeline.groovy @@ -2,9 +2,9 @@ import org.DevshGraphicsProgramming.Agent import org.DevshGraphicsProgramming.BuilderInfo import org.DevshGraphicsProgramming.IBuilder -class CComputeFFTBuilder extends IBuilder +class CArithemticUnitTestBuilder extends IBuilder { - public CComputeFFTBuilder(Agent _agent, _info) + public CArithemticUnitTestBuilder(Agent _agent, _info) { super(_agent, _info) } @@ -44,7 +44,7 @@ class CComputeFFTBuilder extends IBuilder def create(Agent _agent, _info) { - return new CComputeFFTBuilder(_agent, _info) + return new CArithemticUnitTestBuilder(_agent, _info) } return this \ No newline at end of file diff --git a/29_MeshLoaders/CMakeLists.txt b/29_MeshLoaders/CMakeLists.txt new file mode 100644 index 000000000..07b0fd396 --- /dev/null +++ b/29_MeshLoaders/CMakeLists.txt @@ -0,0 +1,37 @@ +include(common RESULT_VARIABLE RES) +if(NOT RES) + message(FATAL_ERROR "common.cmake not found. Should be in {repo_root}/cmake directory") +endif() + +if(NBL_BUILD_IMGUI) + set(NBL_INCLUDE_SERACH_DIRECTORIES + "${CMAKE_CURRENT_SOURCE_DIR}/include" + ) + + list(APPEND NBL_LIBRARIES + imtestengine + "${NBL_EXT_IMGUI_UI_LIB}" + ) + + nbl_create_executable_project("" "" "${NBL_INCLUDE_SERACH_DIRECTORIES}" "${NBL_LIBRARIES}" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") + + if(NBL_EMBED_BUILTIN_RESOURCES) + set(_BR_TARGET_ ${EXECUTABLE_NAME}_builtinResourceData) + set(RESOURCE_DIR "app_resources") + + get_filename_component(_SEARCH_DIRECTORIES_ "${CMAKE_CURRENT_SOURCE_DIR}" ABSOLUTE) + get_filename_component(_OUTPUT_DIRECTORY_SOURCE_ "${CMAKE_CURRENT_BINARY_DIR}/src" ABSOLUTE) + get_filename_component(_OUTPUT_DIRECTORY_HEADER_ "${CMAKE_CURRENT_BINARY_DIR}/include" ABSOLUTE) + + file(GLOB_RECURSE BUILTIN_RESOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/${RESOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/${RESOURCE_DIR}/*") + foreach(RES_FILE ${BUILTIN_RESOURCE_FILES}) + LIST_BUILTIN_RESOURCE(RESOURCES_TO_EMBED "${RES_FILE}") + endforeach() + + ADD_CUSTOM_BUILTIN_RESOURCES(${_BR_TARGET_} RESOURCES_TO_EMBED "${_SEARCH_DIRECTORIES_}" "${RESOURCE_DIR}" "nbl::this_example::builtin" "${_OUTPUT_DIRECTORY_HEADER_}" "${_OUTPUT_DIRECTORY_SOURCE_}") + + LINK_BUILTIN_RESOURCES_TO_TARGET(${EXECUTABLE_NAME} ${_BR_TARGET_}) + endif() +endif() + + diff --git a/56_RayQuery/config.json.template b/29_MeshLoaders/config.json.template similarity index 90% rename from 56_RayQuery/config.json.template rename to 29_MeshLoaders/config.json.template index f961745c1..2c42b001d 100644 --- a/56_RayQuery/config.json.template +++ b/29_MeshLoaders/config.json.template @@ -6,7 +6,7 @@ "cmake": { "configurations": [ "Release", "Debug", "RelWithDebInfo" ], "buildModes": [], - "requiredOptions": [] + "requiredOptions": [ "NBL_BUILD_MITSUBA_LOADER" ] }, "profiles": [ { diff --git a/29_MeshLoaders/main.cpp b/29_MeshLoaders/main.cpp new file mode 100644 index 000000000..6afb74a5c --- /dev/null +++ b/29_MeshLoaders/main.cpp @@ -0,0 +1,1404 @@ +// Copyright (C) 2018-2024 - DevSH Graphics Programming Sp. z O.O. +// This file is part of the "Nabla Engine". +// For conditions of distribution and use, see copyright notice in nabla.h + +#include +#include "nbl/asset/utils/CGeometryCreator.h" +#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" + +#include +#include + +using namespace nbl; +using namespace core; +using namespace hlsl; +using namespace system; +using namespace asset; +using namespace ui; +using namespace video; + + +class MeshLoadersApp final : public examples::SimpleWindowedApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +{ + using device_base_t = examples::SimpleWindowedApplication; + using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + + constexpr static inline uint32_t WIN_W = 1280, WIN_H = 720; + constexpr static inline uint32_t MaxFramesInFlight = 3u; + constexpr static inline uint8_t MaxUITextureCount = 1u; + + + public: + inline MeshLoadersApp(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) + : IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) + { + } + + inline SPhysicalDeviceFeatures getPreferredDeviceFeatures() const override + { + auto retval = device_base_t::getPreferredDeviceFeatures(); + retval.accelerationStructure = true; + retval.rayQuery = true; + return retval; + } + + inline core::vector getSurfaces() const override + { + if (!m_surface) + { + { + auto windowCallback = core::make_smart_refctd_ptr(smart_refctd_ptr(m_inputSystem), smart_refctd_ptr(m_logger)); + IWindow::SCreationParams params = {}; + params.callback = core::make_smart_refctd_ptr(); + params.width = WIN_W; + params.height = WIN_H; + params.x = 32; + params.y = 32; + params.flags = ui::IWindow::ECF_HIDDEN | IWindow::ECF_BORDERLESS | IWindow::ECF_RESIZABLE; + params.windowCaption = "MeshLoadersApp"; + params.callback = windowCallback; + const_cast&>(m_window) = m_winMgr->createWindow(std::move(params)); + } + + auto surface = CSurfaceVulkanWin32::create(smart_refctd_ptr(m_api), smart_refctd_ptr_static_cast(m_window)); + const_cast&>(m_surface) = CSimpleResizeSurface::create(std::move(surface)); + } + + if (m_surface) + return { {m_surface->getSurface()/*,EQF_NONE*/} }; + + return {}; + } + + // so that we can use the same queue for asset converter and rendering + inline core::vector getQueueRequirements() const override + { + auto reqs = device_base_t::getQueueRequirements(); + reqs.front().requiredFlags |= IQueue::FAMILY_FLAGS::TRANSFER_BIT; + reqs.front().requiredFlags |= IQueue::FAMILY_FLAGS::COMPUTE_BIT; + return reqs; + } + + inline bool onAppInitialized(smart_refctd_ptr&& system) override + { + m_inputSystem = make_smart_refctd_ptr(logger_opt_smart_ptr(smart_refctd_ptr(m_logger))); + + if (!device_base_t::onAppInitialized(smart_refctd_ptr(system))) + return false; + + if (!asset_base_t::onAppInitialized(smart_refctd_ptr(system))) + return false; + +#if 0 + // Load Custom Shader + auto loadCompileAndCreateShader = [&](const std::string& relPath) -> smart_refctd_ptr + { + IAssetLoader::SAssetLoadParams lp = {}; + lp.logger = m_logger.get(); + lp.workingDirectory = ""; // virtual root + auto assetBundle = m_assetMgr->getAsset(relPath, lp); + const auto assets = assetBundle.getContents(); + if (assets.empty()) + return nullptr; + + // lets go straight from ICPUSpecializedShader to IGPUSpecializedShader + auto sourceRaw = IAsset::castDown(assets[0]); + if (!sourceRaw) + return nullptr; + + return m_device->createShader({ sourceRaw.get(), nullptr, shaderReadCache.get(), shaderWriteCache.get() }); + }; + + // load shaders + const auto raygenShader = loadCompileAndCreateShader("app_resources/raytrace.rgen.hlsl"); + const auto closestHitShader = loadCompileAndCreateShader("app_resources/raytrace.rchit.hlsl"); + const auto proceduralClosestHitShader = loadCompileAndCreateShader("app_resources/raytrace_procedural.rchit.hlsl"); + const auto intersectionHitShader = loadCompileAndCreateShader("app_resources/raytrace.rint.hlsl"); + const auto anyHitShaderColorPayload = loadCompileAndCreateShader("app_resources/raytrace.rahit.hlsl"); + const auto anyHitShaderShadowPayload = loadCompileAndCreateShader("app_resources/raytrace_shadow.rahit.hlsl"); + const auto missShader = loadCompileAndCreateShader("app_resources/raytrace.rmiss.hlsl"); + const auto missShadowShader = loadCompileAndCreateShader("app_resources/raytrace_shadow.rmiss.hlsl"); + const auto directionalLightCallShader = loadCompileAndCreateShader("app_resources/light_directional.rcall.hlsl"); + const auto pointLightCallShader = loadCompileAndCreateShader("app_resources/light_point.rcall.hlsl"); + const auto spotLightCallShader = loadCompileAndCreateShader("app_resources/light_spot.rcall.hlsl"); + const auto fragmentShader = loadCompileAndCreateShader("app_resources/present.frag.hlsl"); +#endif + + m_semaphore = m_device->createSemaphore(m_realFrameIx); + if (!m_semaphore) + return logFail("Failed to Create a Semaphore!"); + + auto gQueue = getGraphicsQueue(); + + // Create renderpass and init surface + nbl::video::IGPURenderpass* renderpass; + { + ISwapchain::SCreationParams swapchainParams = { .surface = smart_refctd_ptr(m_surface->getSurface()) }; + if (!swapchainParams.deduceFormat(m_physicalDevice)) + return logFail("Could not choose a Surface Format for the Swapchain!"); + + const static IGPURenderpass::SCreationParams::SSubpassDependency dependencies[] = + { + { + .srcSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .dstSubpass = 0, + .memoryBarrier = + { + .srcStageMask = asset::PIPELINE_STAGE_FLAGS::COPY_BIT, + .srcAccessMask = asset::ACCESS_FLAGS::TRANSFER_WRITE_BIT, + .dstStageMask = asset::PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + .dstAccessMask = asset::ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + } + }, + { + .srcSubpass = 0, + .dstSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .memoryBarrier = + { + .srcStageMask = asset::PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = asset::ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + } + }, + IGPURenderpass::SCreationParams::DependenciesEnd + }; + + auto scResources = std::make_unique(m_device.get(), swapchainParams.surfaceFormat.format, dependencies); + renderpass = scResources->getRenderpass(); + + if (!renderpass) + return logFail("Failed to create Renderpass!"); + + if (!m_surface || !m_surface->init(gQueue, std::move(scResources), swapchainParams.sharedParams)) + return logFail("Could not create Window & Surface or initialize the Surface!"); + } +#if 0 + auto pool = m_device->createCommandPool(gQueue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); + + m_converter = CAssetConverter::create({ .device = m_device.get(), .optimizer = {} }); + + for (auto i = 0u; i < MaxFramesInFlight; i++) + { + if (!pool) + return logFail("Couldn't create Command Pool!"); + if (!pool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY, { m_cmdBufs.data() + i, 1 })) + return logFail("Couldn't create Command Buffer!"); + } +#endif + m_winMgr->setWindowSize(m_window.get(), WIN_W, WIN_H); + m_surface->recreateSwapchain(); + +#if 0 + // create output images + m_hdrImage = m_device->createImage({ + { + .type = IGPUImage::ET_2D, + .samples = ICPUImage::ESCF_1_BIT, + .format = EF_R16G16B16A16_SFLOAT, + .extent = {WIN_W, WIN_H, 1}, + .mipLevels = 1, + .arrayLayers = 1, + .flags = IImage::ECF_NONE, + .usage = bitflag(IImage::EUF_STORAGE_BIT) | IImage::EUF_TRANSFER_SRC_BIT | IImage::EUF_SAMPLED_BIT + } + }); + + if (!m_hdrImage || !m_device->allocate(m_hdrImage->getMemoryReqs(), m_hdrImage.get()).isValid()) + return logFail("Could not create HDR Image"); + + m_hdrImageView = m_device->createImageView({ + .flags = IGPUImageView::ECF_NONE, + .subUsages = IGPUImage::E_USAGE_FLAGS::EUF_STORAGE_BIT | IGPUImage::E_USAGE_FLAGS::EUF_SAMPLED_BIT, + .image = m_hdrImage, + .viewType = IGPUImageView::E_TYPE::ET_2D, + .format = asset::EF_R16G16B16A16_SFLOAT + }); + + + + // ray trace pipeline and descriptor set layout setup + { + const IGPUDescriptorSetLayout::SBinding bindings[] = { + { + .binding = 0, + .type = asset::IDescriptor::E_TYPE::ET_ACCELERATION_STRUCTURE, + .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_RAYGEN, + .count = 1, + }, + { + .binding = 1, + .type = asset::IDescriptor::E_TYPE::ET_STORAGE_IMAGE, + .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_RAYGEN, + .count = 1, + } + }; + const auto descriptorSetLayout = m_device->createDescriptorSetLayout(bindings); + + const std::array dsLayoutPtrs = { descriptorSetLayout.get() }; + m_rayTracingDsPool = m_device->createDescriptorPoolForDSLayouts(IDescriptorPool::ECF_UPDATE_AFTER_BIND_BIT, std::span(dsLayoutPtrs.begin(), dsLayoutPtrs.end())); + m_rayTracingDs = m_rayTracingDsPool->createDescriptorSet(descriptorSetLayout); + + const SPushConstantRange pcRange = { + .stageFlags = IShader::E_SHADER_STAGE::ESS_ALL_RAY_TRACING, + .offset = 0u, + .size = sizeof(SPushConstants), + }; + const auto pipelineLayout = m_device->createPipelineLayout({ &pcRange, 1 }, smart_refctd_ptr(descriptorSetLayout), nullptr, nullptr, nullptr); + + IGPURayTracingPipeline::SCreationParams params = {}; + + enum RtDemoShader + { + RTDS_RAYGEN, + RTDS_MISS, + RTDS_MISS_SHADOW, + RTDS_CLOSEST_HIT, + RTDS_SPHERE_CLOSEST_HIT, + RTDS_ANYHIT_PRIMARY, + RTDS_ANYHIT_SHADOW, + RTDS_INTERSECTION, + RTDS_DIRECTIONAL_CALL, + RTDS_POINT_CALL, + RTDS_SPOT_CALL, + RTDS_COUNT + }; + + IGPUShader::SSpecInfo shaders[RTDS_COUNT]; + shaders[RTDS_RAYGEN] = { .shader = raygenShader.get() }; + shaders[RTDS_MISS] = { .shader = missShader.get() }; + shaders[RTDS_MISS_SHADOW] = { .shader = missShadowShader.get() }; + shaders[RTDS_CLOSEST_HIT] = { .shader = closestHitShader.get() }; + shaders[RTDS_SPHERE_CLOSEST_HIT] = { .shader = proceduralClosestHitShader.get() }; + shaders[RTDS_ANYHIT_PRIMARY] = { .shader = anyHitShaderColorPayload.get() }; + shaders[RTDS_ANYHIT_SHADOW] = { .shader = anyHitShaderShadowPayload.get() }; + shaders[RTDS_INTERSECTION] = { .shader = intersectionHitShader.get() }; + shaders[RTDS_DIRECTIONAL_CALL] = { .shader = directionalLightCallShader.get() }; + shaders[RTDS_POINT_CALL] = { .shader = pointLightCallShader.get() }; + shaders[RTDS_SPOT_CALL] = { .shader = spotLightCallShader.get() }; + + params.layout = pipelineLayout.get(); + params.shaders = std::span(shaders); + using RayTracingFlags = IGPURayTracingPipeline::SCreationParams::FLAGS; + params.flags = core::bitflag(RayTracingFlags::NO_NULL_MISS_SHADERS) | + RayTracingFlags::NO_NULL_INTERSECTION_SHADERS | + RayTracingFlags::NO_NULL_ANY_HIT_SHADERS; + + auto& shaderGroups = params.shaderGroups; + + shaderGroups.raygen = { .index = RTDS_RAYGEN }; + + IRayTracingPipelineBase::SGeneralShaderGroup missGroups[EMT_COUNT]; + missGroups[EMT_PRIMARY] = { .index = RTDS_MISS }; + missGroups[EMT_OCCLUSION] = { .index = RTDS_MISS_SHADOW }; + shaderGroups.misses = missGroups; + + auto getHitGroupIndex = [](E_GEOM_TYPE geomType, E_RAY_TYPE rayType) + { + return geomType * ERT_COUNT + rayType; + }; + IRayTracingPipelineBase::SHitShaderGroup hitGroups[E_RAY_TYPE::ERT_COUNT * E_GEOM_TYPE::EGT_COUNT]; + hitGroups[getHitGroupIndex(EGT_TRIANGLES, ERT_PRIMARY)] = { + .closestHit = RTDS_CLOSEST_HIT, + .anyHit = RTDS_ANYHIT_PRIMARY, + }; + hitGroups[getHitGroupIndex(EGT_TRIANGLES, ERT_OCCLUSION)] = { + .closestHit = IGPURayTracingPipeline::SGeneralShaderGroup::Unused, + .anyHit = RTDS_ANYHIT_SHADOW, + }; + hitGroups[getHitGroupIndex(EGT_PROCEDURAL, ERT_PRIMARY)] = { + .closestHit = RTDS_SPHERE_CLOSEST_HIT, + .anyHit = RTDS_ANYHIT_PRIMARY, + .intersection = RTDS_INTERSECTION, + }; + hitGroups[getHitGroupIndex(EGT_PROCEDURAL, ERT_OCCLUSION)] = { + .closestHit = IGPURayTracingPipeline::SGeneralShaderGroup::Unused, + .anyHit = RTDS_ANYHIT_SHADOW, + .intersection = RTDS_INTERSECTION, + }; + shaderGroups.hits = hitGroups; + + IRayTracingPipelineBase::SGeneralShaderGroup callableGroups[ELT_COUNT]; + callableGroups[ELT_DIRECTIONAL] = { .index = RTDS_DIRECTIONAL_CALL }; + callableGroups[ELT_POINT] = { .index = RTDS_POINT_CALL }; + callableGroups[ELT_SPOT] = { .index = RTDS_SPOT_CALL }; + shaderGroups.callables = callableGroups; + + params.cached.maxRecursionDepth = 1; + params.cached.dynamicStackSize = true; + + if (!m_device->createRayTracingPipelines(nullptr, { ¶ms, 1 }, &m_rayTracingPipeline)) + return logFail("Failed to create ray tracing pipeline"); + + calculateRayTracingStackSize(m_rayTracingPipeline); + + if (!createShaderBindingTable(m_rayTracingPipeline)) + return logFail("Could not create shader binding table"); + + } + + auto assetManager = make_smart_refctd_ptr(smart_refctd_ptr(system)); + auto* geometryCreator = assetManager->getGeometryCreator(); + + if (!createIndirectBuffer()) + return logFail("Could not create indirect buffer"); + + if (!createAccelerationStructuresFromGeometry(geometryCreator)) + return logFail("Could not create acceleration structures from geometry creator"); + + ISampler::SParams samplerParams = { + .AnisotropicFilter = 0 + }; + auto defaultSampler = m_device->createSampler(samplerParams); + + { + const IGPUDescriptorSetLayout::SBinding bindings[] = { + { + .binding = 0u, + .type = nbl::asset::IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER, + .createFlags = ICPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_FRAGMENT, + .count = 1u, + .immutableSamplers = &defaultSampler + } + }; + auto gpuPresentDescriptorSetLayout = m_device->createDescriptorSetLayout(bindings); + const video::IGPUDescriptorSetLayout* const layouts[] = { gpuPresentDescriptorSetLayout.get() }; + const uint32_t setCounts[] = { 1u }; + m_presentDsPool = m_device->createDescriptorPoolForDSLayouts(IDescriptorPool::E_CREATE_FLAGS::ECF_NONE, layouts, setCounts); + m_presentDs = m_presentDsPool->createDescriptorSet(gpuPresentDescriptorSetLayout); + + auto scRes = static_cast(m_surface->getSwapchainResources()); + ext::FullScreenTriangle::ProtoPipeline fsTriProtoPPln(m_assetMgr.get(), m_device.get(), m_logger.get()); + if (!fsTriProtoPPln) + return logFail("Failed to create Full Screen Triangle protopipeline or load its vertex shader!"); + + const IGPUShader::SSpecInfo fragSpec = { + .entryPoint = "main", + .shader = fragmentShader.get() + }; + + auto presentLayout = m_device->createPipelineLayout( + {}, + core::smart_refctd_ptr(gpuPresentDescriptorSetLayout), + nullptr, + nullptr, + nullptr + ); + m_presentPipeline = fsTriProtoPPln.createPipeline(fragSpec, presentLayout.get(), scRes->getRenderpass()); + if (!m_presentPipeline) + return logFail("Could not create Graphics Pipeline!"); + } + + // write descriptors + IGPUDescriptorSet::SDescriptorInfo infos[3]; + infos[0].desc = m_gpuTlas; + + infos[1].desc = m_hdrImageView; + if (!infos[1].desc) + return logFail("Failed to create image view"); + infos[1].info.image.imageLayout = IImage::LAYOUT::GENERAL; + + infos[2].desc = m_hdrImageView; + infos[2].info.image.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; + + IGPUDescriptorSet::SWriteDescriptorSet writes[] = { + {.dstSet = m_rayTracingDs.get(), .binding = 0, .arrayElement = 0, .count = 1, .info = &infos[0]}, + {.dstSet = m_rayTracingDs.get(), .binding = 1, .arrayElement = 0, .count = 1, .info = &infos[1]}, + {.dstSet = m_presentDs.get(), .binding = 0, .arrayElement = 0, .count = 1, .info = &infos[2] }, + }; + m_device->updateDescriptorSets(std::span(writes), {}); + + // gui descriptor setup + { + using binding_flags_t = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS; + { + IGPUSampler::SParams params; + params.AnisotropicFilter = 1u; + params.TextureWrapU = ETC_REPEAT; + params.TextureWrapV = ETC_REPEAT; + params.TextureWrapW = ETC_REPEAT; + + m_ui.samplers.gui = m_device->createSampler(params); + m_ui.samplers.gui->setObjectDebugName("Nabla IMGUI UI Sampler"); + } + + std::array, 69u> immutableSamplers; + for (auto& it : immutableSamplers) + it = smart_refctd_ptr(m_ui.samplers.scene); + + immutableSamplers[nbl::ext::imgui::UI::FontAtlasTexId] = smart_refctd_ptr(m_ui.samplers.gui); + + nbl::ext::imgui::UI::SCreationParameters params; + + params.resources.texturesInfo = { .setIx = 0u, .bindingIx = 0u }; + params.resources.samplersInfo = { .setIx = 0u, .bindingIx = 1u }; + params.assetManager = m_assetMgr; + params.pipelineCache = nullptr; + params.pipelineLayout = nbl::ext::imgui::UI::createDefaultPipelineLayout(m_utils->getLogicalDevice(), params.resources.texturesInfo, params.resources.samplersInfo, MaxUITextureCount); + params.renderpass = smart_refctd_ptr(renderpass); + params.streamingBuffer = nullptr; + params.subpassIx = 0u; + params.transfer = getGraphicsQueue(); + params.utilities = m_utils; + { + m_ui.manager = ext::imgui::UI::create(std::move(params)); + + // note that we use default layout provided by our extension, but you are free to create your own by filling nbl::ext::imgui::UI::S_CREATION_PARAMETERS::resources + const auto* descriptorSetLayout = m_ui.manager->getPipeline()->getLayout()->getDescriptorSetLayout(0u); + const auto& params = m_ui.manager->getCreationParameters(); + + IDescriptorPool::SCreateInfo descriptorPoolInfo = {}; + descriptorPoolInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_SAMPLER)] = (uint32_t)nbl::ext::imgui::UI::DefaultSamplerIx::COUNT; + descriptorPoolInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_SAMPLED_IMAGE)] = MaxUITextureCount; + descriptorPoolInfo.maxSets = 1u; + descriptorPoolInfo.flags = IDescriptorPool::E_CREATE_FLAGS::ECF_UPDATE_AFTER_BIND_BIT; + + m_guiDescriptorSetPool = m_device->createDescriptorPool(std::move(descriptorPoolInfo)); + assert(m_guiDescriptorSetPool); + + m_guiDescriptorSetPool->createDescriptorSets(1u, &descriptorSetLayout, &m_ui.descriptorSet); + assert(m_ui.descriptorSet); + } + } + + m_ui.manager->registerListener( + [this]() -> void { + ImGuiIO& io = ImGui::GetIO(); + + m_camera.setProjectionMatrix([&]() + { + static matrix4SIMD projection; + + projection = matrix4SIMD::buildProjectionMatrixPerspectiveFovRH( + core::radians(m_cameraSetting.fov), + io.DisplaySize.x / io.DisplaySize.y, + m_cameraSetting.zNear, + m_cameraSetting.zFar); + + return projection; + }()); + + ImGui::SetNextWindowPos(ImVec2(1024, 100), ImGuiCond_Appearing); + ImGui::SetNextWindowSize(ImVec2(256, 256), ImGuiCond_Appearing); + + // create a window and insert the inspector + ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_Appearing); + ImGui::SetNextWindowSize(ImVec2(320, 340), ImGuiCond_Appearing); + ImGui::Begin("Controls"); + + ImGui::SameLine(); + + ImGui::Text("Camera"); + + ImGui::SliderFloat("Move speed", &m_cameraSetting.moveSpeed, 0.1f, 10.f); + ImGui::SliderFloat("Rotate speed", &m_cameraSetting.rotateSpeed, 0.1f, 10.f); + ImGui::SliderFloat("Fov", &m_cameraSetting.fov, 20.f, 150.f); + ImGui::SliderFloat("zNear", &m_cameraSetting.zNear, 0.1f, 100.f); + ImGui::SliderFloat("zFar", &m_cameraSetting.zFar, 110.f, 10000.f); + Light m_oldLight = m_light; + int light_type = m_light.type; + ImGui::ListBox("LightType", &light_type, s_lightTypeNames, ELT_COUNT); + m_light.type = static_cast(light_type); + if (m_light.type == ELT_DIRECTIONAL) + { + ImGui::SliderFloat3("Light Direction", &m_light.direction.x, -1.f, 1.f); + } + else if (m_light.type == ELT_POINT) + { + ImGui::SliderFloat3("Light Position", &m_light.position.x, -20.f, 20.f); + } + else if (m_light.type == ELT_SPOT) + { + ImGui::SliderFloat3("Light Direction", &m_light.direction.x, -1.f, 1.f); + ImGui::SliderFloat3("Light Position", &m_light.position.x, -20.f, 20.f); + + float32_t dOuterCutoff = hlsl::degrees(acos(m_light.outerCutoff)); + if (ImGui::SliderFloat("Light Outer Cutoff", &dOuterCutoff, 0.0f, 45.0f)) + { + m_light.outerCutoff = cos(hlsl::radians(dOuterCutoff)); + } + } + ImGui::Checkbox("Use Indirect Command", &m_useIndirectCommand); + if (m_light != m_oldLight) + { + m_frameAccumulationCounter = 0; + } + + ImGui::Text("X: %f Y: %f", io.MousePos.x, io.MousePos.y); + + ImGui::End(); + } + ); +#endif + // Set Camera + { + core::vectorSIMDf cameraPosition(0, 5, -10); + matrix4SIMD proj = matrix4SIMD::buildProjectionMatrixPerspectiveFovRH( + core::radians(60.0f), + WIN_W / WIN_H, + 0.01f, + 500.0f + ); + m_camera = Camera(cameraPosition, core::vectorSIMDf(0, 0, 0), proj); + } + + m_winMgr->setWindowSize(m_window.get(), WIN_W, WIN_H); + m_surface->recreateSwapchain(); + m_winMgr->show(m_window.get()); + m_oracle.reportBeginFrameRecord(); + m_camera.mapKeysToWASD(); + + return true; + } + + bool updateGUIDescriptorSet() + { + // texture atlas, note we don't create info & write pair for the font sampler because UI extension's is immutable and baked into DS layout + static std::array descriptorInfo; + static IGPUDescriptorSet::SWriteDescriptorSet writes[MaxUITextureCount]; + + descriptorInfo[ext::imgui::UI::FontAtlasTexId].info.image.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; + descriptorInfo[ext::imgui::UI::FontAtlasTexId].desc = smart_refctd_ptr(m_ui.manager->getFontAtlasView()); + + for (uint32_t i = 0; i < descriptorInfo.size(); ++i) + { + writes[i].dstSet = m_ui.descriptorSet.get(); + writes[i].binding = 0u; + writes[i].arrayElement = i; + writes[i].count = 1u; + } + writes[ext::imgui::UI::FontAtlasTexId].info = descriptorInfo.data() + ext::imgui::UI::FontAtlasTexId; + + return m_device->updateDescriptorSets(writes, {}); + } + + inline void workLoopBody() override + { + // framesInFlight: ensuring safe execution of command buffers and acquires, `framesInFlight` only affect semaphore waits, don't use this to index your resources because it can change with swapchain recreation. + const uint32_t framesInFlight = core::min(MaxFramesInFlight, m_surface->getMaxAcquiresInFlight()); + // We block for semaphores for 2 reasons here: + // A) Resource: Can't use resource like a command buffer BEFORE previous use is finished! [MaxFramesInFlight] + // B) Acquire: Can't have more acquires in flight than a certain threshold returned by swapchain or your surface helper class. [MaxAcquiresInFlight] + if (m_realFrameIx >= framesInFlight) + { + const ISemaphore::SWaitInfo cbDonePending[] = + { + { + .semaphore = m_semaphore.get(), + .value = m_realFrameIx + 1 - framesInFlight + } + }; + if (m_device->blockForSemaphores(cbDonePending) != ISemaphore::WAIT_RESULT::SUCCESS) + return; + } + const auto resourceIx = m_realFrameIx % MaxFramesInFlight; + + m_api->startCapture(); + +// update(); + + auto queue = getGraphicsQueue(); + auto cmdbuf = m_cmdBufs[resourceIx].get(); + + if (!keepRunning()) + return; + + cmdbuf->reset(IGPUCommandBuffer::RESET_FLAGS::RELEASE_RESOURCES_BIT); + cmdbuf->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + cmdbuf->beginDebugMarker("Frame"); +#if 0 + const auto viewMatrix = m_camera.getViewMatrix(); + const auto projectionMatrix = m_camera.getProjectionMatrix(); + const auto viewProjectionMatrix = m_camera.getConcatenatedMatrix(); + + core::matrix3x4SIMD modelMatrix; + modelMatrix.setTranslation(nbl::core::vectorSIMDf(0, 0, 0, 0)); + modelMatrix.setRotation(quaternion(0, 0, 0)); + + core::matrix4SIMD invModelViewProjectionMatrix; + modelViewProjectionMatrix.getInverseTransform(invModelViewProjectionMatrix); + + { + IGPUCommandBuffer::SPipelineBarrierDependencyInfo::image_barrier_t imageBarriers[1]; + imageBarriers[0].barrier = { + .dep = { + .srcStageMask = PIPELINE_STAGE_FLAGS::FRAGMENT_SHADER_BIT, // previous frame read from framgent shader + .srcAccessMask = ACCESS_FLAGS::SHADER_READ_BITS, + .dstStageMask = PIPELINE_STAGE_FLAGS::RAY_TRACING_SHADER_BIT, + .dstAccessMask = ACCESS_FLAGS::SHADER_WRITE_BITS + } + }; + imageBarriers[0].image = m_hdrImage.get(); + imageBarriers[0].subresourceRange = { + .aspectMask = IImage::EAF_COLOR_BIT, + .baseMipLevel = 0u, + .levelCount = 1u, + .baseArrayLayer = 0u, + .layerCount = 1u + }; + imageBarriers[0].oldLayout = m_frameAccumulationCounter == 0 ? IImage::LAYOUT::UNDEFINED : IImage::LAYOUT::READ_ONLY_OPTIMAL; + imageBarriers[0].newLayout = IImage::LAYOUT::GENERAL; + cmdbuf->pipelineBarrier(E_DEPENDENCY_FLAGS::EDF_NONE, { .imgBarriers = imageBarriers }); + } + + // Trace Rays Pass + { + SPushConstants pc; + pc.light = m_light; + pc.proceduralGeomInfoBuffer = m_proceduralGeomInfoBuffer->getDeviceAddress(); + pc.triangleGeomInfoBuffer = m_triangleGeomInfoBuffer->getDeviceAddress(); + pc.frameCounter = m_frameAccumulationCounter; + const core::vector3df camPos = m_camera.getPosition().getAsVector3df(); + pc.camPos = { camPos.X, camPos.Y, camPos.Z }; + memcpy(&pc.invMVP, invModelViewProjectionMatrix.pointer(), sizeof(pc.invMVP)); + + cmdbuf->bindRayTracingPipeline(m_rayTracingPipeline.get()); + cmdbuf->setRayTracingPipelineStackSize(m_rayTracingStackSize); + cmdbuf->pushConstants(m_rayTracingPipeline->getLayout(), IShader::E_SHADER_STAGE::ESS_ALL_RAY_TRACING, 0, sizeof(SPushConstants), &pc); + cmdbuf->bindDescriptorSets(EPBP_RAY_TRACING, m_rayTracingPipeline->getLayout(), 0, 1, &m_rayTracingDs.get()); + if (m_useIndirectCommand) + { + cmdbuf->traceRaysIndirect( + SBufferBinding{ + .offset = 0, + .buffer = m_indirectBuffer, + }); + } + else + { + cmdbuf->traceRays( + m_shaderBindingTable.raygenGroupRange, + m_shaderBindingTable.missGroupsRange, m_shaderBindingTable.missGroupsStride, + m_shaderBindingTable.hitGroupsRange, m_shaderBindingTable.hitGroupsStride, + m_shaderBindingTable.callableGroupsRange, m_shaderBindingTable.callableGroupsStride, + WIN_W, WIN_H, 1); + } + } + + // pipeline barrier + { + IGPUCommandBuffer::SPipelineBarrierDependencyInfo::image_barrier_t imageBarriers[1]; + imageBarriers[0].barrier = { + .dep = { + .srcStageMask = PIPELINE_STAGE_FLAGS::RAY_TRACING_SHADER_BIT, + .srcAccessMask = ACCESS_FLAGS::SHADER_WRITE_BITS, + .dstStageMask = PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + .dstAccessMask = ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + } + }; + imageBarriers[0].image = m_hdrImage.get(); + imageBarriers[0].subresourceRange = { + .aspectMask = IImage::EAF_COLOR_BIT, + .baseMipLevel = 0u, + .levelCount = 1u, + .baseArrayLayer = 0u, + .layerCount = 1u + }; + imageBarriers[0].oldLayout = IImage::LAYOUT::GENERAL; + imageBarriers[0].newLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; + + cmdbuf->pipelineBarrier(E_DEPENDENCY_FLAGS::EDF_NONE, { .imgBarriers = imageBarriers }); + } + + { + asset::SViewport viewport; + { + viewport.minDepth = 1.f; + viewport.maxDepth = 0.f; + viewport.x = 0u; + viewport.y = 0u; + viewport.width = WIN_W; + viewport.height = WIN_H; + } + cmdbuf->setViewport(0u, 1u, &viewport); + + + VkRect2D defaultScisors[] = { {.offset = {(int32_t)viewport.x, (int32_t)viewport.y}, .extent = {(uint32_t)viewport.width, (uint32_t)viewport.height}} }; + cmdbuf->setScissor(defaultScisors); + + auto scRes = static_cast(m_surface->getSwapchainResources()); + const VkRect2D currentRenderArea = + { + .offset = {0,0}, + .extent = {m_window->getWidth(),m_window->getHeight()} + }; + const IGPUCommandBuffer::SClearColorValue clearColor = { .float32 = {0.f,0.f,0.f,1.f} }; + const IGPUCommandBuffer::SRenderpassBeginInfo info = + { + .framebuffer = scRes->getFramebuffer(m_currentImageAcquire.imageIndex), + .colorClearValues = &clearColor, + .depthStencilClearValues = nullptr, + .renderArea = currentRenderArea + }; + nbl::video::ISemaphore::SWaitInfo waitInfo = { .semaphore = m_semaphore.get(), .value = m_realFrameIx + 1u }; + + cmdbuf->beginRenderPass(info, IGPUCommandBuffer::SUBPASS_CONTENTS::INLINE); + + cmdbuf->bindGraphicsPipeline(m_presentPipeline.get()); + cmdbuf->bindDescriptorSets(EPBP_GRAPHICS, m_presentPipeline->getLayout(), 0, 1u, &m_presentDs.get()); + ext::FullScreenTriangle::recordDrawCall(cmdbuf); + + const auto uiParams = m_ui.manager->getCreationParameters(); + auto* uiPipeline = m_ui.manager->getPipeline(); + cmdbuf->bindGraphicsPipeline(uiPipeline); + cmdbuf->bindDescriptorSets(EPBP_GRAPHICS, uiPipeline->getLayout(), uiParams.resources.texturesInfo.setIx, 1u, &m_ui.descriptorSet.get()); + m_ui.manager->render(cmdbuf, waitInfo); + + cmdbuf->endRenderPass(); + + } +#endif + cmdbuf->endDebugMarker(); + cmdbuf->end(); + + { + const IQueue::SSubmitInfo::SSemaphoreInfo rendered[] = + { + { + .semaphore = m_semaphore.get(), + .value = ++m_realFrameIx, + .stageMask = PIPELINE_STAGE_FLAGS::ALL_TRANSFER_BITS + } + }; + { + { + const IQueue::SSubmitInfo::SCommandBufferInfo commandBuffers[] = + { + {.cmdbuf = cmdbuf } + }; + + const IQueue::SSubmitInfo::SSemaphoreInfo acquired[] = + { + { + .semaphore = m_currentImageAcquire.semaphore, + .value = m_currentImageAcquire.acquireCount, + .stageMask = PIPELINE_STAGE_FLAGS::NONE + } + }; + const IQueue::SSubmitInfo infos[] = + { + { + .waitSemaphores = acquired, + .commandBuffers = commandBuffers, + .signalSemaphores = rendered + } + }; + +// updateGUIDescriptorSet(); + + if (queue->submit(infos) != IQueue::RESULT::SUCCESS) + m_realFrameIx--; + } + } + + m_window->setCaption("[Nabla Engine] Ray Tracing Pipeline"); + m_surface->present(m_currentImageAcquire.imageIndex, rendered); + } + m_api->endCapture(); + m_frameAccumulationCounter++; + } +#if 0 + inline void update() + { + m_camera.setMoveSpeed(m_cameraSetting.moveSpeed); + m_camera.setRotateSpeed(m_cameraSetting.rotateSpeed); + + static std::chrono::microseconds previousEventTimestamp{}; + + m_inputSystem->getDefaultMouse(&m_mouse); + m_inputSystem->getDefaultKeyboard(&m_keyboard); + + auto updatePresentationTimestamp = [&]() + { + m_currentImageAcquire = m_surface->acquireNextImage(); + + m_oracle.reportEndFrameRecord(); + const auto timestamp = m_oracle.getNextPresentationTimeStamp(); + m_oracle.reportBeginFrameRecord(); + + return timestamp; + }; + + const auto nextPresentationTimestamp = updatePresentationTimestamp(); + + struct + { + std::vector mouse{}; + std::vector keyboard{}; + } capturedEvents; + + m_camera.beginInputProcessing(nextPresentationTimestamp); + { + const auto& io = ImGui::GetIO(); + m_mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void + { + if (!io.WantCaptureMouse) + m_camera.mouseProcess(events); // don't capture the events, only let camera handle them with its impl + + for (const auto& e : events) // here capture + { + if (e.timeStamp < previousEventTimestamp) + continue; + + previousEventTimestamp = e.timeStamp; + capturedEvents.mouse.emplace_back(e); + + } + }, m_logger.get()); + + m_keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void + { + if (!io.WantCaptureKeyboard) + m_camera.keyboardProcess(events); // don't capture the events, only let camera handle them with its impl + + for (const auto& e : events) // here capture + { + if (e.timeStamp < previousEventTimestamp) + continue; + + previousEventTimestamp = e.timeStamp; + capturedEvents.keyboard.emplace_back(e); + } + }, m_logger.get()); + + } + m_camera.endInputProcessing(nextPresentationTimestamp); + + const core::SRange mouseEvents(capturedEvents.mouse.data(), capturedEvents.mouse.data() + capturedEvents.mouse.size()); + const core::SRange keyboardEvents(capturedEvents.keyboard.data(), capturedEvents.keyboard.data() + capturedEvents.keyboard.size()); + const auto cursorPosition = m_window->getCursorControl()->getPosition(); + const auto mousePosition = float32_t2(cursorPosition.x, cursorPosition.y) - float32_t2(m_window->getX(), m_window->getY()); + + const ext::imgui::UI::SUpdateParameters params = + { + .mousePosition = mousePosition, + .displaySize = { m_window->getWidth(), m_window->getHeight() }, + .mouseEvents = mouseEvents, + .keyboardEvents = keyboardEvents + }; + + m_ui.manager->update(params); + } +#endif + inline bool keepRunning() override + { + if (m_surface->irrecoverable()) + return false; + + return true; + } + + inline bool onAppTerminated() override + { + return device_base_t::onAppTerminated(); + } + + private: +#if 0 + bool createAccelerationStructuresFromGeometry(const IGeometryCreator* gc) + { + auto queue = getGraphicsQueue(); + // get geometries into ICPUBuffers + auto pool = m_device->createCommandPool(queue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); + if (!pool) + return logFail("Couldn't create Command Pool for geometry creation!"); + + const auto defaultMaterial = Material{ + .ambient = {0.2, 0.1, 0.1}, + .diffuse = {0.8, 0.3, 0.3}, + .specular = {0.8, 0.8, 0.8}, + .shininess = 1.0f, + .alpha = 1.0f, + }; + + auto getTranslationMatrix = [](float32_t x, float32_t y, float32_t z) + { + core::matrix3x4SIMD transform; + transform.setTranslation(nbl::core::vectorSIMDf(x, y, z, 0)); + return transform; + }; + + core::matrix3x4SIMD planeTransform; + planeTransform.setRotation(quaternion::fromAngleAxis(core::radians(-90.0f), vector3df_SIMD{ 1, 0, 0 })); + + // triangles geometries + const auto cpuObjects = std::array{ + ReferenceObjectCpu { + .meta = {.type = OT_RECTANGLE, .name = "Plane Mesh"}, + .data = gc->createRectangleMesh(nbl::core::vector2df_SIMD(10, 10)), + .material = defaultMaterial, + .transform = planeTransform, + }, + ReferenceObjectCpu { + .meta = {.type = OT_CUBE, .name = "Cube Mesh"}, + .data = gc->createCubeMesh(nbl::core::vector3df(1, 1, 1)), + .material = defaultMaterial, + .transform = getTranslationMatrix(0, 0.5f, 0), + }, + ReferenceObjectCpu { + .meta = {.type = OT_CUBE, .name = "Cube Mesh 2"}, + .data = gc->createCubeMesh(nbl::core::vector3df(1.5, 1.5, 1.5)), + .material = Material{ + .ambient = {0.1, 0.1, 0.2}, + .diffuse = {0.2, 0.2, 0.8}, + .specular = {0.8, 0.8, 0.8}, + .shininess = 1.0f, + }, + .transform = getTranslationMatrix(-5.0f, 1.0f, 0), + }, + ReferenceObjectCpu { + .meta = {.type = OT_CUBE, .name = "Transparent Cube Mesh"}, + .data = gc->createCubeMesh(nbl::core::vector3df(1.5, 1.5, 1.5)), + .material = Material{ + .ambient = {0.1, 0.2, 0.1}, + .diffuse = {0.2, 0.8, 0.2}, + .specular = {0.8, 0.8, 0.8}, + .shininess = 1.0f, + .alpha = 0.2, + }, + .transform = getTranslationMatrix(5.0f, 1.0f, 0), + }, + }; + + struct CPUTriBufferBindings + { + nbl::asset::SBufferBinding vertex, index; + }; + std::array cpuTriBuffers; + + for (uint32_t i = 0; i < cpuObjects.size(); i++) + { + const auto& cpuObject = cpuObjects[i]; + + auto vBuffer = smart_refctd_ptr(cpuObject.data.bindings[0].buffer); // no offset + auto vUsage = bitflag(IGPUBuffer::EUF_STORAGE_BUFFER_BIT) | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF | + IGPUBuffer::EUF_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; + vBuffer->addUsageFlags(vUsage); + vBuffer->setContentHash(vBuffer->computeContentHash()); + + auto iBuffer = smart_refctd_ptr(cpuObject.data.indexBuffer.buffer); // no offset + auto iUsage = bitflag(IGPUBuffer::EUF_STORAGE_BUFFER_BIT) | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF | + IGPUBuffer::EUF_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; + + if (cpuObject.data.indexType != EIT_UNKNOWN) + if (iBuffer) + { + iBuffer->addUsageFlags(iUsage); + iBuffer->setContentHash(iBuffer->computeContentHash()); + } + + cpuTriBuffers[i] = { + .vertex = {.offset = 0, .buffer = vBuffer}, + .index = {.offset = 0, .buffer = iBuffer}, + }; + + } + + // procedural geometries + using Aabb = IGPUBottomLevelAccelerationStructure::AABB_t; + + smart_refctd_ptr cpuProcBuffer; + { + ICPUBuffer::SCreationParams params; + params.size = NumberOfProceduralGeometries * sizeof(Aabb); + cpuProcBuffer = ICPUBuffer::create(std::move(params)); + } + + core::vector proceduralGeoms; + proceduralGeoms.reserve(NumberOfProceduralGeometries); + auto proceduralGeometries = reinterpret_cast(cpuProcBuffer->getPointer()); + for (int32_t i = 0; i < NumberOfProceduralGeometries; i++) + { + const auto middle_i = NumberOfProceduralGeometries / 2.0; + SProceduralGeomInfo sphere = { + .material = hlsl::_static_cast(Material{ + .ambient = {0.1, 0.05 * i, 0.1}, + .diffuse = {0.3, 0.2 * i, 0.3}, + .specular = {0.8, 0.8, 0.8}, + .shininess = 1.0f, + }), + .center = float32_t3((i - middle_i) * 4.0, 2, 5.0), + .radius = 1, + }; + + proceduralGeoms.push_back(sphere); + const auto sphereMin = sphere.center - sphere.radius; + const auto sphereMax = sphere.center + sphere.radius; + proceduralGeometries[i] = { + vector3d(sphereMin.x, sphereMin.y, sphereMin.z), + vector3d(sphereMax.x, sphereMax.y, sphereMax.z) + }; + } + + { + IGPUBuffer::SCreationParams params; + params.usage = IGPUBuffer::EUF_STORAGE_BUFFER_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; + params.size = proceduralGeoms.size() * sizeof(SProceduralGeomInfo); + m_utils->createFilledDeviceLocalBufferOnDedMem(SIntendedSubmitInfo{ .queue = queue }, std::move(params), proceduralGeoms.data()).move_into(m_proceduralGeomInfoBuffer); + } + + // get ICPUBuffers into ICPUBLAS + // TODO use one BLAS and multiple triangles/aabbs in one + const auto blasCount = std::size(cpuObjects) + 1; + const auto proceduralBlasIdx = std::size(cpuObjects); + + std::array, std::size(cpuObjects)+1u> cpuBlas; + for (uint32_t i = 0; i < blasCount; i++) + { + auto& blas = cpuBlas[i]; + blas = make_smart_refctd_ptr(); + + if (i == proceduralBlasIdx) + { + auto aabbs = make_refctd_dynamic_array>>(1u); + auto primitiveCounts = make_refctd_dynamic_array>(1u); + + auto& aabb = aabbs->front(); + auto& primCount = primitiveCounts->front(); + + primCount = NumberOfProceduralGeometries; + aabb.data = { .offset = 0, .buffer = cpuProcBuffer }; + aabb.stride = sizeof(IGPUBottomLevelAccelerationStructure::AABB_t); + aabb.geometryFlags = IGPUBottomLevelAccelerationStructure::GEOMETRY_FLAGS::OPAQUE_BIT; // only allow opaque for now + + blas->setGeometries(std::move(aabbs), std::move(primitiveCounts)); + } + else + { + auto triangles = make_refctd_dynamic_array>>(1u); + auto primitiveCounts = make_refctd_dynamic_array>(1u); + + auto& tri = triangles->front(); + auto& primCount = primitiveCounts->front(); + const auto& geom = cpuObjects[i]; + const auto& cpuBuf = cpuTriBuffers[i]; + + const bool useIndex = geom.data.indexType != EIT_UNKNOWN; + const uint32_t vertexStride = geom.data.inputParams.bindings[0].stride; + const uint32_t numVertices = cpuBuf.vertex.buffer->getSize() / vertexStride; + + if (useIndex) + primCount = geom.data.indexCount / 3; + else + primCount = numVertices / 3; + + tri.vertexData[0] = cpuBuf.vertex; + tri.indexData = useIndex ? cpuBuf.index : cpuBuf.vertex; + tri.maxVertex = numVertices - 1; + tri.vertexStride = vertexStride; + tri.vertexFormat = EF_R32G32B32_SFLOAT; + tri.indexType = geom.data.indexType; + tri.geometryFlags = geom.material.isTransparent() ? + IGPUBottomLevelAccelerationStructure::GEOMETRY_FLAGS::NO_DUPLICATE_ANY_HIT_INVOCATION_BIT : + IGPUBottomLevelAccelerationStructure::GEOMETRY_FLAGS::OPAQUE_BIT; + + blas->setGeometries(std::move(triangles), std::move(primitiveCounts)); + } + + auto blasFlags = bitflag(IGPUBottomLevelAccelerationStructure::BUILD_FLAGS::PREFER_FAST_TRACE_BIT) | IGPUBottomLevelAccelerationStructure::BUILD_FLAGS::ALLOW_COMPACTION_BIT; + if (i == proceduralBlasIdx) + blasFlags |= IGPUBottomLevelAccelerationStructure::BUILD_FLAGS::GEOMETRY_TYPE_IS_AABB_BIT; + + blas->setBuildFlags(blasFlags); + blas->setContentHash(blas->computeContentHash()); + } + + auto geomInfoBuffer = ICPUBuffer::create({ std::size(cpuObjects) * sizeof(STriangleGeomInfo) }); + STriangleGeomInfo* geomInfos = reinterpret_cast(geomInfoBuffer->getPointer()); + + // get ICPUBLAS into ICPUTLAS + auto geomInstances = make_refctd_dynamic_array>(blasCount); + { + uint32_t i = 0; + for (auto instance = geomInstances->begin(); instance != geomInstances->end(); instance++, i++) + { + const auto isProceduralInstance = i == proceduralBlasIdx; + ICPUTopLevelAccelerationStructure::StaticInstance inst; + inst.base.blas = cpuBlas[i]; + inst.base.flags = static_cast(IGPUTopLevelAccelerationStructure::INSTANCE_FLAGS::TRIANGLE_FACING_CULL_DISABLE_BIT); + inst.base.instanceCustomIndex = i; + inst.base.instanceShaderBindingTableRecordOffset = isProceduralInstance ? 2 : 0;; + inst.base.mask = 0xFF; + inst.transform = isProceduralInstance ? matrix3x4SIMD() : cpuObjects[i].transform; + + instance->instance = inst; + } + } + + auto cpuTlas = make_smart_refctd_ptr(); + cpuTlas->setInstances(std::move(geomInstances)); + cpuTlas->setBuildFlags(IGPUTopLevelAccelerationStructure::BUILD_FLAGS::PREFER_FAST_TRACE_BIT); + + // convert with asset converter + smart_refctd_ptr converter = CAssetConverter::create({ .device = m_device.get(), .optimizer = {} }); + struct MyInputs : CAssetConverter::SInputs + { + // For the GPU Buffers to be directly writeable and so that we don't need a Transfer Queue submit at all + inline uint32_t constrainMemoryTypeBits(const size_t groupCopyID, const IAsset* canonicalAsset, const blake3_hash_t& contentHash, const IDeviceMemoryBacked* memoryBacked) const override + { + assert(memoryBacked); + return memoryBacked->getObjectType() != IDeviceMemoryBacked::EOT_BUFFER ? (~0u) : rebarMemoryTypes; + } + + uint32_t rebarMemoryTypes; + } inputs = {}; + inputs.logger = m_logger.get(); + inputs.rebarMemoryTypes = m_physicalDevice->getDirectVRAMAccessMemoryTypeBits(); + // the allocator needs to be overriden to hand out memory ranges which have already been mapped so that the ReBAR fast-path can kick in + // (multiple buffers can be bound to same memory, but memory can only be mapped once at one place, so Asset Converter can't do it) + struct MyAllocator final : public IDeviceMemoryAllocator + { + ILogicalDevice* getDeviceForAllocations() const override { return device; } + + SAllocation allocate(const SAllocateInfo& info) override + { + auto retval = device->allocate(info); + // map what is mappable by default so ReBAR checks succeed + if (retval.isValid() && retval.memory->isMappable()) + retval.memory->map({ .offset = 0,.length = info.size }); + return retval; + } + + ILogicalDevice* device; + } myalloc; + myalloc.device = m_device.get(); + inputs.allocator = &myalloc; + + std::array tmpTlas; + std::array tmpBuffers; + { + tmpTlas[0] = cpuTlas.get(); + for (uint32_t i = 0; i < cpuObjects.size(); i++) + { + tmpBuffers[2 * i + 0] = cpuTriBuffers[i].vertex.buffer.get(); + tmpBuffers[2 * i + 1] = cpuTriBuffers[i].index.buffer.get(); + } + tmpBuffers[2 * proceduralBlasIdx] = cpuProcBuffer.get(); + + std::get>(inputs.assets) = tmpTlas; + std::get>(inputs.assets) = tmpBuffers; + } + + auto reservation = converter->reserve(inputs); + { + auto prepass = [&](const auto & references) -> bool + { + auto objects = reservation.getGPUObjects(); + uint32_t counter = {}; + for (auto& object : objects) + { + auto gpu = object.value; + auto* reference = references[counter]; + + if (reference) + { + if (!gpu) + { + m_logger->log("Failed to convert a CPU object to GPU!", ILogger::ELL_ERROR); + return false; + } + } + counter++; + } + return true; + }; + + prepass.template operator() < ICPUTopLevelAccelerationStructure > (tmpTlas); + prepass.template operator() < ICPUBuffer > (tmpBuffers); + } + + constexpr auto CompBufferCount = 2; + std::array, CompBufferCount> compBufs = {}; + std::array compBufInfos = {}; + { + auto pool = m_device->createCommandPool(queue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT | IGPUCommandPool::CREATE_FLAGS::TRANSIENT_BIT); + pool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY, compBufs); + compBufs.front()->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + for (auto i = 0; i < CompBufferCount; i++) + compBufInfos[i].cmdbuf = compBufs[i].get(); + } + auto compSema = m_device->createSemaphore(0u); + SIntendedSubmitInfo compute = {}; + compute.queue = queue; + compute.scratchCommandBuffers = compBufInfos; + compute.scratchSemaphore = { + .semaphore = compSema.get(), + .value = 0u, + .stageMask = PIPELINE_STAGE_FLAGS::ACCELERATION_STRUCTURE_BUILD_BIT | PIPELINE_STAGE_FLAGS::ACCELERATION_STRUCTURE_COPY_BIT + }; + // convert + { + smart_refctd_ptr scratchAlloc; + { + constexpr auto MaxAlignment = 256; + constexpr auto MinAllocationSize = 1024; + const auto scratchSize = core::alignUp(reservation.getMaxASBuildScratchSize(false), MaxAlignment); + + + IGPUBuffer::SCreationParams creationParams = {}; + creationParams.size = scratchSize; + creationParams.usage = IGPUBuffer::EUF_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT | IGPUBuffer::EUF_STORAGE_BUFFER_BIT; + auto scratchBuffer = m_device->createBuffer(std::move(creationParams)); + + auto reqs = scratchBuffer->getMemoryReqs(); + reqs.memoryTypeBits &= m_physicalDevice->getDirectVRAMAccessMemoryTypeBits(); + + auto allocation = m_device->allocate(reqs, scratchBuffer.get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); + allocation.memory->map({ .offset = 0,.length = reqs.size }); + + scratchAlloc = make_smart_refctd_ptr( + SBufferRange{0ull, scratchSize, std::move(scratchBuffer)}, + core::allocator(), MaxAlignment, MinAllocationSize + ); + } + + struct MyParams final : CAssetConverter::SConvertParams + { + inline uint32_t getFinalOwnerQueueFamily(const IGPUBuffer* buffer, const core::blake3_hash_t& createdFrom) override + { + return finalUser; + } + inline uint32_t getFinalOwnerQueueFamily(const IGPUAccelerationStructure* image, const core::blake3_hash_t& createdFrom) override + { + return finalUser; + } + + uint8_t finalUser; + } params = {}; + params.utilities = m_utils.get(); + params.compute = &compute; + params.scratchForDeviceASBuild = scratchAlloc.get(); + params.finalUser = queue->getFamilyIndex(); + + auto future = reservation.convert(params); + if (future.copy() != IQueue::RESULT::SUCCESS) + { + m_logger->log("Failed to await submission feature!", ILogger::ELL_ERROR); + return false; + } + // 2 submits, BLAS build, TLAS build, DO NOT ADD COMPACTIONS IN THIS EXAMPLE! + if (compute.getFutureScratchSemaphore().value>3) + m_logger->log("Overflow submitted on Compute Queue despite using ReBAR (no transfer submits or usage of staging buffer) and providing a AS Build Scratch Buffer of correctly queried max size!",system::ILogger::ELL_ERROR); + + // assign gpu objects to output + auto&& tlases = reservation.getGPUObjects(); + m_gpuTlas = tlases[0].value; + auto&& buffers = reservation.getGPUObjects(); + for (uint32_t i = 0; i < cpuObjects.size(); i++) + { + auto& cpuObject = cpuObjects[i]; + + m_gpuTriangleGeometries.push_back(ReferenceObjectGpu{ + .meta = cpuObject.meta, + .bindings = { + .vertex = {.offset = 0, .buffer = buffers[2 * i + 0].value }, + .index = {.offset = 0, .buffer = buffers[2 * i + 1].value }, + }, + .vertexStride = cpuObject.data.inputParams.bindings[0].stride, + .indexType = cpuObject.data.indexType, + .indexCount = cpuObject.data.indexCount, + .material = hlsl::_static_cast(cpuObject.material), + .transform = cpuObject.transform, + }); + } + m_proceduralAabbBuffer = buffers[2 * proceduralBlasIdx].value; + + for (uint32_t i = 0; i < m_gpuTriangleGeometries.size(); i++) + { + const auto& gpuObject = m_gpuTriangleGeometries[i]; + const uint64_t vertexBufferAddress = gpuObject.bindings.vertex.buffer->getDeviceAddress(); + geomInfos[i] = { + .material = gpuObject.material, + .vertexBufferAddress = vertexBufferAddress, + .indexBufferAddress = gpuObject.useIndex() ? gpuObject.bindings.index.buffer->getDeviceAddress() : vertexBufferAddress, + .vertexStride = gpuObject.vertexStride, + .objType = gpuObject.meta.type, + .indexType = gpuObject.indexType, + .smoothNormals = s_smoothNormals[gpuObject.meta.type], + }; + } + } + + { + IGPUBuffer::SCreationParams params; + params.usage = IGPUBuffer::EUF_STORAGE_BUFFER_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; + params.size = geomInfoBuffer->getSize(); + m_utils->createFilledDeviceLocalBufferOnDedMem(SIntendedSubmitInfo{ .queue = queue }, std::move(params), geomInfos).move_into(m_triangleGeomInfoBuffer); + } + + return true; + } +#endif + smart_refctd_ptr m_converter; + + smart_refctd_ptr m_window; + smart_refctd_ptr> m_surface; + smart_refctd_ptr m_semaphore; + uint64_t m_realFrameIx = 0; +uint32_t m_frameAccumulationCounter = 0; + std::array, MaxFramesInFlight> m_cmdBufs; + ISimpleManagedSurface::SAcquireResult m_currentImageAcquire = {}; + + core::smart_refctd_ptr m_inputSystem; + InputSystem::ChannelReader m_mouse; + InputSystem::ChannelReader m_keyboard; + + struct CameraSetting + { + float fov = 60.f; + float zNear = 0.1f; + float zFar = 10000.f; + float moveSpeed = 1.f; + float rotateSpeed = 1.f; + float viewWidth = 10.f; + float camYAngle = 165.f / 180.f * 3.14159f; + float camXAngle = 32.f / 180.f * 3.14159f; + + } m_cameraSetting; + Camera m_camera = Camera(core::vectorSIMDf(0, 0, 0), core::vectorSIMDf(0, 0, 0), core::matrix4SIMD()); + + video::CDumbPresentationOracle m_oracle; + +#if 0 + struct C_UI + { + nbl::core::smart_refctd_ptr manager; + + struct + { + core::smart_refctd_ptr gui, scene; + } samplers; + + core::smart_refctd_ptr descriptorSet; + } m_ui; + core::smart_refctd_ptr m_guiDescriptorSetPool; + + core::vector m_gpuTriangleGeometries; + core::vector m_gpuIntersectionSpheres; + uint32_t m_intersectionHitGroupIdx; + + smart_refctd_ptr m_gpuTlas; + smart_refctd_ptr m_instanceBuffer; + + smart_refctd_ptr m_triangleGeomInfoBuffer; + smart_refctd_ptr m_proceduralGeomInfoBuffer; + smart_refctd_ptr m_proceduralAabbBuffer; + smart_refctd_ptr m_indirectBuffer; + + smart_refctd_ptr m_hdrImage; + smart_refctd_ptr m_hdrImageView; + + smart_refctd_ptr m_rayTracingDsPool; + smart_refctd_ptr m_rayTracingDs; + smart_refctd_ptr m_rayTracingPipeline; + uint64_t m_rayTracingStackSize; + ShaderBindingTable m_shaderBindingTable; + + smart_refctd_ptr m_presentDs; + smart_refctd_ptr m_presentDsPool; + smart_refctd_ptr m_presentPipeline; + +#endif +}; +NBL_MAIN_FUNC(MeshLoadersApp) diff --git a/27_PLYSTLDemo/pipeline.groovy b/29_MeshLoaders/pipeline.groovy similarity index 100% rename from 27_PLYSTLDemo/pipeline.groovy rename to 29_MeshLoaders/pipeline.groovy diff --git a/29_SpecializationConstants/CMakeLists.txt b/29_SpecializationConstants/CMakeLists.txt deleted file mode 100644 index a476b6203..000000000 --- a/29_SpecializationConstants/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ - -include(common RESULT_VARIABLE RES) -if(NOT RES) - message(FATAL_ERROR "common.cmake not found. Should be in {repo_root}/cmake directory") -endif() - -nbl_create_executable_project("" "" "" "" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") \ No newline at end of file diff --git a/29_SpecializationConstants/main.cpp b/29_SpecializationConstants/main.cpp deleted file mode 100644 index 11b73a330..000000000 --- a/29_SpecializationConstants/main.cpp +++ /dev/null @@ -1,566 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -#define _NBL_STATIC_LIB_ -#include - -#include "../common/CommonAPI.h" -using namespace nbl; -using namespace core; -using namespace ui; - -struct UBOCompute -{ - //xyz - gravity point, w - dt - core::vectorSIMDf gravPointAndDt; -}; - -class SpecializationConstantsSampleApp : public ApplicationBase -{ - constexpr static uint32_t WIN_W = 1280u; - constexpr static uint32_t WIN_H = 720u; - constexpr static uint32_t SC_IMG_COUNT = 3u; - constexpr static uint32_t FRAMES_IN_FLIGHT = 5u; - static constexpr uint64_t MAX_TIMEOUT = 99999999999999ull; - static_assert(FRAMES_IN_FLIGHT > SC_IMG_COUNT); - - core::smart_refctd_ptr window; - core::smart_refctd_ptr system; - core::smart_refctd_ptr windowCb; - core::smart_refctd_ptr api; - core::smart_refctd_ptr surface; - core::smart_refctd_ptr utils; - core::smart_refctd_ptr device; - video::IPhysicalDevice* gpu; - std::array queues; - core::smart_refctd_ptr swapchain; - core::smart_refctd_ptr renderpass; - nbl::core::smart_refctd_dynamic_array> fbo; - std::array, CommonAPI::InitOutput::MaxFramesInFlight>, CommonAPI::InitOutput::MaxQueuesCount> commandPools; - core::smart_refctd_ptr filesystem; - core::smart_refctd_ptr assetManager; - video::IGPUObjectFromAssetConverter::SParams cpu2gpuParams; - core::smart_refctd_ptr logger; - core::smart_refctd_ptr inputSystem; - video::IGPUObjectFromAssetConverter cpu2gpu; - - constexpr static uint32_t COMPUTE_SET = 0u; - constexpr static uint32_t PARTICLE_BUF_BINDING = 0u; - constexpr static uint32_t COMPUTE_DATA_UBO_BINDING = 1u; - constexpr static uint32_t WORKGROUP_SIZE = 256u; - constexpr static uint32_t PARTICLE_COUNT = 1u << 21; - constexpr static uint32_t PARTICLE_COUNT_PER_AXIS = 1u << 7; - constexpr static uint32_t POS_BUF_IX = 0u; - constexpr static uint32_t VEL_BUF_IX = 1u; - constexpr static uint32_t BUF_COUNT = 2u; - constexpr static uint32_t GRAPHICS_SET = 0u; - constexpr static uint32_t GRAPHICS_DATA_UBO_BINDING = 0u; - - std::chrono::high_resolution_clock::time_point m_lastTime; - int32_t m_resourceIx = -1; - core::smart_refctd_ptr m_cmdbuf[FRAMES_IN_FLIGHT]; - core::smart_refctd_ptr m_frameComplete[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr m_imageAcquire[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr m_renderFinished[FRAMES_IN_FLIGHT] = { nullptr }; - core::vectorSIMDf m_cameraPosition; - core::vectorSIMDf m_camFront; - UBOCompute m_uboComputeData; - asset::SBufferRange m_computeUBORange; - asset::SBufferRange m_graphicsUBORange; - core::smart_refctd_ptr m_gpuComputePipeline; - core::smart_refctd_ptr m_graphicsPipeline; - core::smart_refctd_ptr m_gpuds0Compute; - core::smart_refctd_ptr m_gpuds0Graphics; - asset::SBasicViewParameters m_viewParams; - core::matrix4SIMD m_viewProj; - core::smart_refctd_ptr m_gpuParticleBuf; - core::smart_refctd_ptr m_rpIndependentPipeline; - nbl::video::ISwapchain::SCreationParams m_swapchainCreationParams; - -public: - - void setWindow(core::smart_refctd_ptr&& wnd) override - { - window = std::move(wnd); - } - void setSystem(core::smart_refctd_ptr&& s) override - { - system = std::move(s); - } - nbl::ui::IWindow* getWindow() override - { - return window.get(); - } - video::IAPIConnection* getAPIConnection() override - { - return api.get(); - } - video::ILogicalDevice* getLogicalDevice() override - { - return device.get(); - } - video::IGPURenderpass* getRenderpass() override - { - return renderpass.get(); - } - void setSurface(core::smart_refctd_ptr&& s) override - { - surface = std::move(s); - } - void setFBOs(std::vector>& f) override - { - for (int i = 0; i < f.size(); i++) - { - fbo->begin()[i] = core::smart_refctd_ptr(f[i]); - } - } - void setSwapchain(core::smart_refctd_ptr&& s) override - { - swapchain = std::move(s); - } - uint32_t getSwapchainImageCount() override - { - return swapchain->getImageCount(); - } - virtual nbl::asset::E_FORMAT getDepthFormat() override - { - return nbl::asset::EF_UNKNOWN; - } - - APP_CONSTRUCTOR(SpecializationConstantsSampleApp); - - void onAppInitialized_impl() override - { - const auto swapchainImageUsage = static_cast(asset::IImage::EUF_COLOR_ATTACHMENT_BIT | asset::IImage::EUF_STORAGE_BIT); - const asset::E_FORMAT depthFormat = asset::EF_UNKNOWN; - CommonAPI::InitParams initParams; - initParams.window = core::smart_refctd_ptr(window); - initParams.apiType = video::EAT_VULKAN; - initParams.appName = { _NBL_APP_NAME_ }; - initParams.framesInFlight = FRAMES_IN_FLIGHT; - initParams.windowWidth = WIN_W; - initParams.windowHeight = WIN_H; - initParams.swapchainImageCount = SC_IMG_COUNT; - initParams.swapchainImageUsage = swapchainImageUsage; - initParams.depthFormat = depthFormat; - initParams.physicalDeviceFilter.minimumLimits.workgroupSizeFromSpecConstant = true; - auto initOutp = CommonAPI::InitWithDefaultExt(std::move(initParams)); - - window = std::move(initParams.window); - system = std::move(initOutp.system); - windowCb = std::move(initParams.windowCb); - api = std::move(initOutp.apiConnection); - surface = std::move(initOutp.surface); - device = std::move(initOutp.logicalDevice); - gpu = std::move(initOutp.physicalDevice); - queues = std::move(initOutp.queues); - renderpass = std::move(initOutp.renderToSwapchainRenderpass); - commandPools = std::move(initOutp.commandPools); - assetManager = std::move(initOutp.assetManager); - filesystem = std::move(initOutp.system); - cpu2gpuParams = std::move(initOutp.cpu2gpuParams); - utils = std::move(initOutp.utilities); - m_swapchainCreationParams = std::move(initOutp.swapchainCreationParams); - - CommonAPI::createSwapchain(std::move(device), m_swapchainCreationParams, WIN_W, WIN_H, swapchain); - assert(swapchain); - fbo = CommonAPI::createFBOWithSwapchainImages( - swapchain->getImageCount(), WIN_W, WIN_H, - device, swapchain, renderpass, - depthFormat - ); - - video::IGPUObjectFromAssetConverter CPU2GPU; - m_cameraPosition = core::vectorSIMDf(0, 0, -10); - matrix4SIMD proj = matrix4SIMD::buildProjectionMatrixPerspectiveFovRH(core::radians(90.0f), video::ISurface::getTransformedAspectRatio(swapchain->getPreTransform(), WIN_W, WIN_H), 0.01, 100); - matrix3x4SIMD view = matrix3x4SIMD::buildCameraLookAtMatrixRH(m_cameraPosition, core::vectorSIMDf(0, 0, 0), core::vectorSIMDf(0, 1, 0)); - m_viewProj = matrix4SIMD::concatenateBFollowedByAPrecisely( - video::ISurface::getSurfaceTransformationMatrix(swapchain->getPreTransform()), - matrix4SIMD::concatenateBFollowedByA(proj, matrix4SIMD(view)) - ); - m_camFront = view[2]; - - // auto glslExts = device->getSupportedGLSLExtensions(); - asset::CSPIRVIntrospector introspector; - - const char* pathToCompShader = "../particles.comp"; - auto compilerSet = assetManager->getCompilerSet(); - core::smart_refctd_ptr computeUnspec = nullptr; - core::smart_refctd_ptr computeUnspecSPIRV = nullptr; - { - auto csBundle = assetManager->getAsset(pathToCompShader, {}); - auto csContents = csBundle.getContents(); - if (csContents.empty()) - assert(false); - - asset::ICPUSpecializedShader* csSpec = static_cast(csContents.begin()->get()); - computeUnspec = core::smart_refctd_ptr(csSpec->getUnspecialized()); - - auto compiler = compilerSet->getShaderCompiler(computeUnspec->getContentType()); - - asset::IShaderCompiler::SPreprocessorOptions preprocessOptions = {}; - preprocessOptions.sourceIdentifier = pathToCompShader; - preprocessOptions.includeFinder = compiler->getDefaultIncludeFinder(); - computeUnspec = compilerSet->preprocessShader(computeUnspec.get(), preprocessOptions); - } - - core::smart_refctd_ptr introspection = nullptr; - { - //! This example first preprocesses and then compiles the shader, although it could've been done by calling compileToSPIRV with setting compilerOptions.preprocessorOptions - asset::IShaderCompiler::SCompilerOptions compilerOptions = {}; - // compilerOptions.entryPoint = "main"; - compilerOptions.stage = computeUnspec->getStage(); - compilerOptions.debugInfoFlags = asset::IShaderCompiler::E_DEBUG_INFO_FLAGS::EDIF_SOURCE_BIT; // should be DIF_SOURCE_BIT for introspection - compilerOptions.preprocessorOptions.sourceIdentifier = computeUnspec->getFilepathHint(); // already preprocessed but for logging it's best to fill sourceIdentifier - computeUnspecSPIRV = compilerSet->compileToSPIRV(computeUnspec.get(), compilerOptions); - - asset::CSPIRVIntrospector::SIntrospectionParams params = { "main", computeUnspecSPIRV }; - introspection = introspector.introspect(params); - } - - asset::ISpecializedShader::SInfo specInfo; - { - struct SpecConstants - { - int32_t wg_size; - int32_t particle_count; - int32_t pos_buf_ix; - int32_t vel_buf_ix; - int32_t buf_count; - }; - SpecConstants swapchain{ WORKGROUP_SIZE, PARTICLE_COUNT, POS_BUF_IX, VEL_BUF_IX, BUF_COUNT }; - - auto it_particleBufDescIntro = std::find_if(introspection->descriptorSetBindings[COMPUTE_SET].begin(), introspection->descriptorSetBindings[COMPUTE_SET].end(), - [=](auto b) { return b.binding == PARTICLE_BUF_BINDING; } - ); - assert(it_particleBufDescIntro->descCountIsSpecConstant); - const uint32_t buf_count_specID = it_particleBufDescIntro->count_specID; - auto& particleDataArrayIntro = it_particleBufDescIntro->get().members.array[0]; - assert(particleDataArrayIntro.countIsSpecConstant); - const uint32_t particle_count_specID = particleDataArrayIntro.count_specID; - - auto backbuf = asset::ICPUBuffer::create({ sizeof(swapchain) }); - memcpy(backbuf->getPointer(), &swapchain, sizeof(swapchain)); - auto entries = core::make_refctd_dynamic_array>(5u); - (*entries)[0] = { 0u,offsetof(SpecConstants,wg_size),sizeof(int32_t) };//currently local_size_{x|y|z}_id is not queryable via introspection API - (*entries)[1] = { particle_count_specID,offsetof(SpecConstants,particle_count),sizeof(int32_t) }; - (*entries)[2] = { 2u,offsetof(SpecConstants,pos_buf_ix),sizeof(int32_t) }; - (*entries)[3] = { 3u,offsetof(SpecConstants,vel_buf_ix),sizeof(int32_t) }; - (*entries)[4] = { buf_count_specID,offsetof(SpecConstants,buf_count),sizeof(int32_t) }; - - specInfo = asset::ISpecializedShader::SInfo(std::move(entries), std::move(backbuf), "main"); - } - - auto compute = core::make_smart_refctd_ptr(std::move(computeUnspecSPIRV), std::move(specInfo)); - - auto computePipeline = introspector.createApproximateComputePipelineFromIntrospection(compute.get()); - auto computeLayout = core::make_smart_refctd_ptr(nullptr, nullptr, core::smart_refctd_ptr(computePipeline->getLayout()->getDescriptorSetLayout(0))); - computePipeline->setLayout(core::smart_refctd_ptr(computeLayout)); - - // These conversions don't require command buffers - m_gpuComputePipeline = CPU2GPU.getGPUObjectsFromAssets(&computePipeline.get(), &computePipeline.get() + 1, cpu2gpuParams)->front(); - auto* ds0layoutCompute = computeLayout->getDescriptorSetLayout(0); - core::smart_refctd_ptr gpuDs0layoutCompute = CPU2GPU.getGPUObjectsFromAssets(&ds0layoutCompute, &ds0layoutCompute + 1, cpu2gpuParams)->front(); - - core::vector particlePosAndVel; - particlePosAndVel.reserve(PARTICLE_COUNT * 2); - for (int32_t i = 0; i < PARTICLE_COUNT_PER_AXIS; ++i) - for (int32_t j = 0; j < PARTICLE_COUNT_PER_AXIS; ++j) - for (int32_t k = 0; k < PARTICLE_COUNT_PER_AXIS; ++k) - particlePosAndVel.push_back(core::vector3df_SIMD(i, j, k) * 0.5f); - - for (int32_t i = 0; i < PARTICLE_COUNT; ++i) - particlePosAndVel.push_back(core::vector3df_SIMD(0.0f)); - - constexpr size_t BUF_SZ = 4ull * sizeof(float) * PARTICLE_COUNT; - video::IGPUBuffer::SCreationParams bufferCreationParams = {}; - bufferCreationParams.usage = static_cast(asset::IBuffer::EUF_TRANSFER_DST_BIT | asset::IBuffer::EUF_STORAGE_BUFFER_BIT | asset::IBuffer::EUF_VERTEX_BUFFER_BIT); - bufferCreationParams.size = 2ull * BUF_SZ; - m_gpuParticleBuf = device->createBuffer(std::move(bufferCreationParams)); - m_gpuParticleBuf->setObjectDebugName("m_gpuParticleBuf"); - auto particleBufMemReqs = m_gpuParticleBuf->getMemoryReqs(); - particleBufMemReqs.memoryTypeBits &= device->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - device->allocate(particleBufMemReqs, m_gpuParticleBuf.get()); - asset::SBufferRange range; - range.buffer = m_gpuParticleBuf; - range.offset = 0ull; - range.size = BUF_SZ * 2ull; - utils->updateBufferRangeViaStagingBufferAutoSubmit(range, particlePosAndVel.data(), queues[CommonAPI::InitOutput::EQT_GRAPHICS]); - particlePosAndVel.clear(); - - video::IGPUBuffer::SCreationParams uboComputeCreationParams = {}; - uboComputeCreationParams.usage = static_cast(asset::IBuffer::EUF_UNIFORM_BUFFER_BIT | asset::IBuffer::EUF_TRANSFER_DST_BIT | asset::IBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF); - uboComputeCreationParams.size = core::roundUp(sizeof(UBOCompute), 64ull); - auto gpuUboCompute = device->createBuffer(std::move(uboComputeCreationParams)); - auto gpuUboComputeMemReqs = gpuUboCompute->getMemoryReqs(); - gpuUboComputeMemReqs.memoryTypeBits &= device->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - device->allocate(gpuUboComputeMemReqs, gpuUboCompute.get()); - - asset::SBufferBinding vtxBindings[video::IGPUMeshBuffer::MAX_ATTR_BUF_BINDING_COUNT]; - vtxBindings[0].buffer = m_gpuParticleBuf; - vtxBindings[0].offset = 0u; - //auto meshbuffer = core::make_smart_refctd_ptr(nullptr, nullptr, vtxBindings, asset::SBufferBinding{}); - //meshbuffer->setIndexCount(PARTICLE_COUNT); - //meshbuffer->setIndexType(asset::EIT_UNKNOWN); - - - auto createSpecShader = [&](const char* filepath, asset::IShader::E_SHADER_STAGE stage) - { - auto shaderBundle = assetManager->getAsset(filepath, {}); - auto shaderContents = shaderBundle.getContents(); - if (shaderContents.empty()) - assert(false); - - auto specializedShader = static_cast(shaderContents.begin()->get()); - auto unspecShader = specializedShader->getUnspecialized(); - - auto compiler = compilerSet->getShaderCompiler(computeUnspec->getContentType()); - asset::IShaderCompiler::SCompilerOptions compilerOptions = {}; - // compilerOptions.entryPoint = specializedShader->getSpecializationInfo().entryPoint; - compilerOptions.stage = unspecShader->getStage(); - compilerOptions.debugInfoFlags = asset::IShaderCompiler::E_DEBUG_INFO_FLAGS::EDIF_SOURCE_BIT; - compilerOptions.preprocessorOptions.sourceIdentifier = unspecShader->getFilepathHint(); // already preprocessed but for logging it's best to fill sourceIdentifier - compilerOptions.preprocessorOptions.includeFinder = compiler->getDefaultIncludeFinder(); - auto unspecSPIRV = compilerSet->compileToSPIRV(unspecShader, compilerOptions); - - return core::make_smart_refctd_ptr(std::move(unspecSPIRV), asset::ISpecializedShader::SInfo(specializedShader->getSpecializationInfo())); - }; - auto vs = createSpecShader("../particles.vert", asset::IShader::ESS_VERTEX); - auto fs = createSpecShader("../particles.frag", asset::IShader::ESS_FRAGMENT); - - asset::ICPUSpecializedShader* shaders[2] = { vs.get(),fs.get() }; - auto pipeline = introspector.createApproximateRenderpassIndependentPipelineFromIntrospection({ shaders, shaders + 2 }); - { - auto& vtxParams = pipeline->getVertexInputParams(); - vtxParams.attributes[0].binding = 0u; - vtxParams.attributes[0].format = asset::EF_R32G32B32_SFLOAT; - vtxParams.attributes[0].relativeOffset = 0u; - vtxParams.bindings[0].inputRate = asset::EVIR_PER_VERTEX; - vtxParams.bindings[0].stride = 4u * sizeof(float); - - pipeline->getPrimitiveAssemblyParams().primitiveType = asset::EPT_POINT_LIST; - - auto& blendParams = pipeline->getBlendParams(); - blendParams.logicOpEnable = false; - blendParams.logicOp = nbl::asset::ELO_NO_OP; - } - auto gfxLayout = core::make_smart_refctd_ptr(nullptr, nullptr, core::smart_refctd_ptr(pipeline->getLayout()->getDescriptorSetLayout(0))); - pipeline->setLayout(core::smart_refctd_ptr(gfxLayout)); - - m_rpIndependentPipeline = CPU2GPU.getGPUObjectsFromAssets(&pipeline.get(), &pipeline.get() + 1, cpu2gpuParams)->front(); - auto* ds0layoutGraphics = gfxLayout->getDescriptorSetLayout(0); - core::smart_refctd_ptr gpuDs0layoutGraphics = CPU2GPU.getGPUObjectsFromAssets(&ds0layoutGraphics, &ds0layoutGraphics + 1, cpu2gpuParams)->front(); - - video::IGPUDescriptorSetLayout* gpuDSLayouts_raw[2] = { gpuDs0layoutCompute.get(), gpuDs0layoutGraphics.get() }; - const uint32_t setCount[2] = { 1u, 1u }; - auto dscPool = device->createDescriptorPoolForDSLayouts(video::IDescriptorPool::ECF_NONE, gpuDSLayouts_raw, gpuDSLayouts_raw + 2ull, setCount); - - m_gpuds0Compute = dscPool->createDescriptorSet(std::move(gpuDs0layoutCompute)); - { - video::IGPUDescriptorSet::SDescriptorInfo i[3]; - video::IGPUDescriptorSet::SWriteDescriptorSet w[2]; - w[0].arrayElement = 0u; - w[0].binding = PARTICLE_BUF_BINDING; - w[0].count = BUF_COUNT; - w[0].descriptorType = asset::IDescriptor::E_TYPE::ET_STORAGE_BUFFER; - w[0].dstSet = m_gpuds0Compute.get(); - w[0].info = i; - w[1].arrayElement = 0u; - w[1].binding = COMPUTE_DATA_UBO_BINDING; - w[1].count = 1u; - w[1].descriptorType = asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER; - w[1].dstSet = m_gpuds0Compute.get(); - w[1].info = i + 2u; - i[0].desc = m_gpuParticleBuf; - i[0].info.buffer.offset = 0ull; - i[0].info.buffer.size = BUF_SZ; - i[1].desc = m_gpuParticleBuf; - i[1].info.buffer.offset = BUF_SZ; - i[1].info.buffer.size = BUF_SZ; - i[2].desc = gpuUboCompute; - i[2].info.buffer.offset = 0ull; - i[2].info.buffer.size = gpuUboCompute->getSize(); - - device->updateDescriptorSets(2u, w, 0u, nullptr); - } - - - m_gpuds0Graphics = dscPool->createDescriptorSet(std::move(gpuDs0layoutGraphics)); - - video::IGPUGraphicsPipeline::SCreationParams gp_params; - gp_params.rasterizationSamples = asset::IImage::ESCF_1_BIT; - gp_params.renderpass = core::smart_refctd_ptr(renderpass); - gp_params.renderpassIndependent = core::smart_refctd_ptr(m_rpIndependentPipeline); - gp_params.subpassIx = 0u; - - m_graphicsPipeline = device->createGraphicsPipeline(nullptr, std::move(gp_params)); - - video::IGPUBuffer::SCreationParams gfxUboCreationParams = {}; - gfxUboCreationParams.usage = static_cast(asset::IBuffer::EUF_UNIFORM_BUFFER_BIT | asset::IBuffer::EUF_TRANSFER_DST_BIT | asset::IBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF); - gfxUboCreationParams.size = sizeof(m_viewParams); - auto gpuUboGraphics = device->createBuffer(std::move(gfxUboCreationParams)); - auto gpuUboGraphicsMemReqs = gpuUboGraphics->getMemoryReqs(); - gpuUboGraphicsMemReqs.memoryTypeBits &= device->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - - device->allocate(gpuUboGraphicsMemReqs, gpuUboGraphics.get()); - { - video::IGPUDescriptorSet::SWriteDescriptorSet w; - video::IGPUDescriptorSet::SDescriptorInfo i; - w.arrayElement = 0u; - w.binding = GRAPHICS_DATA_UBO_BINDING; - w.count = 1u; - w.descriptorType = asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER; - w.dstSet = m_gpuds0Graphics.get(); - w.info = &i; - i.desc = gpuUboGraphics; - i.info.buffer.offset = 0u; - i.info.buffer.size = gpuUboGraphics->getSize(); // gpuUboGraphics->getSize(); - - device->updateDescriptorSets(1u, &w, 0u, nullptr); - } - - m_lastTime = std::chrono::high_resolution_clock::now(); - constexpr uint32_t FRAME_COUNT = 500000u; - constexpr uint64_t MAX_TIMEOUT = 99999999999999ull; - m_computeUBORange = { 0, gpuUboCompute->getSize(), gpuUboCompute }; - m_graphicsUBORange = { 0, gpuUboGraphics->getSize(), gpuUboGraphics }; - - const auto& graphicsCommandPools = commandPools[CommonAPI::InitOutput::EQT_GRAPHICS]; - for (uint32_t i = 0u; i < FRAMES_IN_FLIGHT; i++) - { - device->createCommandBuffers(graphicsCommandPools[i].get(), video::IGPUCommandBuffer::EL_PRIMARY, 1, m_cmdbuf+i); - m_imageAcquire[i] = device->createSemaphore(); - m_renderFinished[i] = device->createSemaphore(); - } - } - - void onAppTerminated_impl() override - { - device->waitIdle(); - } - - void workLoopBody() override - { - m_resourceIx++; - if (m_resourceIx >= FRAMES_IN_FLIGHT) - m_resourceIx = 0; - - auto& cb = m_cmdbuf[m_resourceIx]; - auto& fence = m_frameComplete[m_resourceIx]; - if (fence) - { - auto retval = device->waitForFences(1u, &fence.get(), false, MAX_TIMEOUT); - assert(retval == video::IGPUFence::ES_TIMEOUT || retval == video::IGPUFence::ES_SUCCESS); - device->resetFences(1u, &fence.get()); - } - else - { - fence = device->createFence(static_cast(0)); - } - - // safe to proceed - cb->begin(video::IGPUCommandBuffer::EU_ONE_TIME_SUBMIT_BIT); // TODO: Reset Frame's CommandPool - - { - auto time = std::chrono::high_resolution_clock::now(); - core::vector3df_SIMD gravPoint = m_cameraPosition + m_camFront * 250.f; - m_uboComputeData.gravPointAndDt = gravPoint; - m_uboComputeData.gravPointAndDt.w = std::chrono::duration_cast(time - m_lastTime).count() * 1e-4; - - m_lastTime = time; - cb->updateBuffer(m_computeUBORange.buffer.get(), m_computeUBORange.offset, m_computeUBORange.size, &m_uboComputeData); - } - cb->bindComputePipeline(m_gpuComputePipeline.get()); - cb->bindDescriptorSets(asset::EPBP_COMPUTE, - m_gpuComputePipeline->getLayout(), - COMPUTE_SET, - 1u, - &m_gpuds0Compute.get(), - 0u); - cb->dispatch(PARTICLE_COUNT / WORKGROUP_SIZE, 1u, 1u); - - asset::SMemoryBarrier memBarrier; - memBarrier.srcAccessMask = asset::EAF_SHADER_WRITE_BIT; - memBarrier.dstAccessMask = asset::EAF_VERTEX_ATTRIBUTE_READ_BIT; - cb->pipelineBarrier( - asset::EPSF_COMPUTE_SHADER_BIT, - asset::EPSF_VERTEX_INPUT_BIT, - static_cast(0u), - 1, &memBarrier, - 0, nullptr, - 0, nullptr); - - { - memcpy(m_viewParams.MVP, &m_viewProj, sizeof(m_viewProj)); - cb->updateBuffer(m_graphicsUBORange.buffer.get(), m_graphicsUBORange.offset, m_graphicsUBORange.size, &m_viewParams); - } - { - asset::SViewport vp; - vp.minDepth = 1.f; - vp.maxDepth = 0.f; - vp.x = 0u; - vp.y = 0u; - vp.width = WIN_W; - vp.height = WIN_H; - cb->setViewport(0u, 1u, &vp); - - VkRect2D scissor; - scissor.offset = { 0, 0 }; - scissor.extent = { WIN_W, WIN_H }; - cb->setScissor(0u, 1u, &scissor); - } - // renderpass - uint32_t imgnum = 0u; - swapchain->acquireNextImage(MAX_TIMEOUT, m_imageAcquire[m_resourceIx].get(), nullptr, &imgnum); - { - video::IGPUCommandBuffer::SRenderpassBeginInfo info; - asset::SClearValue clear; - clear.color.float32[0] = 0.f; - clear.color.float32[1] = 0.f; - clear.color.float32[2] = 0.f; - clear.color.float32[3] = 1.f; - info.renderpass = renderpass; - info.framebuffer = fbo->begin()[imgnum]; - info.clearValueCount = 1u; - info.clearValues = &clear; - info.renderArea.offset = { 0, 0 }; - info.renderArea.extent = { WIN_W, WIN_H }; - cb->beginRenderPass(&info, asset::ESC_INLINE); - } - // individual draw - { - cb->bindGraphicsPipeline(m_graphicsPipeline.get()); - size_t vbOffset = 0; - cb->bindVertexBuffers(0, 1, &m_gpuParticleBuf.get(), &vbOffset); - cb->bindDescriptorSets(asset::EPBP_GRAPHICS, m_rpIndependentPipeline->getLayout(), GRAPHICS_SET, 1u, &m_gpuds0Graphics.get(), 0u); - cb->draw(PARTICLE_COUNT, 1, 0, 0); - } - cb->endRenderPass(); - cb->end(); - - CommonAPI::Submit( - device.get(), - cb.get(), - queues[CommonAPI::InitOutput::EQT_GRAPHICS], - m_imageAcquire[m_resourceIx].get(), - m_renderFinished[m_resourceIx].get(), - fence.get()); - - CommonAPI::Present( - device.get(), - swapchain.get(), - queues[CommonAPI::InitOutput::EQT_GRAPHICS], - m_renderFinished[m_resourceIx].get(), - imgnum); - } - - bool keepRunning() override - { - return windowCb->isWindowOpen(); - } -}; - -NBL_COMMON_API_MAIN(SpecializationConstantsSampleApp) - -extern "C" { _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; } \ No newline at end of file diff --git a/29_SpecializationConstants/particles.comp b/29_SpecializationConstants/particles.comp deleted file mode 100644 index 5889af74c..000000000 --- a/29_SpecializationConstants/particles.comp +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -#version 430 core - -layout (constant_id = 1) const int PARTICLE_COUNT = 256; -layout (constant_id = 2) const int POS_BUF_IX = 0; -layout (constant_id = 3) const int VEL_BUF_IX = 1; -layout (constant_id = 4) const int BUF_COUNT = 2; - -layout (local_size_x_id = 0) in; - -layout (set = 0, binding = 0, std430) restrict buffer PARTICLE_DATA -{ - vec3 p[PARTICLE_COUNT]; -} data[BUF_COUNT]; -layout (set = 0, binding = 1, std140) uniform UBO -{ - vec3 gravP; - float dt; -} ubo; - -void main() -{ - uint GID = gl_GlobalInvocationID.x; - - vec3 p = data[POS_BUF_IX].p[GID]; - vec3 v = data[VEL_BUF_IX].p[GID]; - - v *= 1.0 - 0.99*ubo.dt; - float d = distance(ubo.gravP,p); - float a = 10000.0 / max(1.0, 0.01*pow(d,1.5)); - v += (ubo.gravP-p)/d * a * ubo.dt; - p += v*ubo.dt; - - data[POS_BUF_IX].p[GID] = p; - data[VEL_BUF_IX].p[GID] = v; -} \ No newline at end of file diff --git a/29_SpecializationConstants/particles.frag b/29_SpecializationConstants/particles.frag deleted file mode 100644 index c03ba9afc..000000000 --- a/29_SpecializationConstants/particles.frag +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -#version 430 core - -layout (location = 0) out vec4 Color; - -void main() -{ - Color = vec4(1.0); -} \ No newline at end of file diff --git a/29_SpecializationConstants/particles.vert b/29_SpecializationConstants/particles.vert deleted file mode 100644 index f87486cac..000000000 --- a/29_SpecializationConstants/particles.vert +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -#version 430 core - -layout (location = 0) in vec3 vPos; - -#include -#include - -layout (set = 0, binding = 0, row_major, std140) uniform UBO -{ - nbl_glsl_SBasicViewParameters params; -} CamData; - -void main() -{ - gl_PointSize = 1; - gl_Position = nbl_glsl_pseudoMul4x4with3x1(CamData.params.MVP, vPos); -} \ No newline at end of file diff --git a/29_SpecializationConstants/pipeline.groovy b/29_SpecializationConstants/pipeline.groovy deleted file mode 100644 index d61a3c808..000000000 --- a/29_SpecializationConstants/pipeline.groovy +++ /dev/null @@ -1,50 +0,0 @@ -import org.DevshGraphicsProgramming.Agent -import org.DevshGraphicsProgramming.BuilderInfo -import org.DevshGraphicsProgramming.IBuilder - -class CSpecializationConstantsBuilder extends IBuilder -{ - public CSpecializationConstantsBuilder(Agent _agent, _info) - { - super(_agent, _info) - } - - @Override - public boolean prepare(Map axisMapping) - { - return true - } - - @Override - public boolean build(Map axisMapping) - { - IBuilder.CONFIGURATION config = axisMapping.get("CONFIGURATION") - IBuilder.BUILD_TYPE buildType = axisMapping.get("BUILD_TYPE") - - def nameOfBuildDirectory = getNameOfBuildDirectory(buildType) - def nameOfConfig = getNameOfConfig(config) - - agent.execute("cmake --build ${info.rootProjectPath}/${nameOfBuildDirectory}/${info.targetProjectPathRelativeToRoot} --target ${info.targetBaseName} --config ${nameOfConfig} -j12 -v") - - return true - } - - @Override - public boolean test(Map axisMapping) - { - return true - } - - @Override - public boolean install(Map axisMapping) - { - return true - } -} - -def create(Agent _agent, _info) -{ - return new CSpecializationConstantsBuilder(_agent, _info) -} - -return this \ No newline at end of file diff --git a/30_ComputeShaderPathTracer/app_resources/common.glsl b/30_ComputeShaderPathTracer/app_resources/common.glsl index 2463f82cf..65ed0609e 100644 --- a/30_ComputeShaderPathTracer/app_resources/common.glsl +++ b/30_ComputeShaderPathTracer/app_resources/common.glsl @@ -352,9 +352,9 @@ struct Payload_t vec3 accumulation; float otherTechniqueHeuristic; vec3 throughput; - #ifdef KILL_DIFFUSE_SPECULAR_PATHS +#ifdef KILL_DIFFUSE_SPECULAR_PATHS bool hasDiffuse; - #endif +#endif }; struct Ray_t @@ -491,6 +491,7 @@ layout (constant_id = 1) const int MAX_SAMPLES_LOG2 = 10; #include +// TODO: use PCG hash + XOROSHIRO and don't read any textures mat2x3 rand3d(in uint protoDimension, in uint _sample, inout nbl_glsl_xoroshiro64star_state_t scramble_state) { mat2x3 retval; @@ -552,6 +553,7 @@ nbl_glsl_LightSample nbl_glsl_light_generate_and_remainder_and_pdf(out vec3 rema } uint getBSDFLightIDAndDetermineNormal(out vec3 normal, in uint objectID, in vec3 intersection); +// returns whether to stop tracing bool closestHitProgram(in uint depth, in uint _sample, inout Ray_t ray, inout nbl_glsl_xoroshiro64star_state_t scramble_state) { const MutableRay_t _mutable = ray._mutable; @@ -594,7 +596,7 @@ bool closestHitProgram(in uint depth, in uint _sample, inout Ray_t ray, inout nb if (BSDFNode_isNotDiffuse(bsdf)) { if (ray._payload.hasDiffuse) - return true; + return false; } else ray._payload.hasDiffuse = true; @@ -602,7 +604,7 @@ bool closestHitProgram(in uint depth, in uint _sample, inout Ray_t ray, inout nb const bool isBSDF = BSDFNode_isBSDF(bsdf); //rand - mat2x3 epsilon = rand3d(depth,_sample,scramble_state); + mat2x3 epsilon = rand3d(depth*2,_sample,scramble_state); // thresholds const float bsdfPdfThreshold = 0.0001; @@ -611,47 +613,55 @@ bool closestHitProgram(in uint depth, in uint _sample, inout Ray_t ray, inout nb const float monochromeEta = dot(throughputCIE_Y,BSDFNode_getEta(bsdf)[0])/(throughputCIE_Y.r+throughputCIE_Y.g+throughputCIE_Y.b); // do NEE - const float neeProbability = 1.0;// BSDFNode_getNEEProb(bsdf); +#ifndef NEE_ONLY + // to turn off NEE, set this to 0 + const float neeProbability = BSDFNode_getNEEProb(bsdf); float rcpChoiceProb; - if (!nbl_glsl_partitionRandVariable(neeProbability,epsilon[0].z,rcpChoiceProb) && depth<2u) + if (!nbl_glsl_partitionRandVariable(neeProbability,epsilon[0].z,rcpChoiceProb)) { +#endif vec3 neeContrib; float lightPdf, t; nbl_glsl_LightSample nee_sample = nbl_glsl_light_generate_and_remainder_and_pdf( neeContrib, lightPdf, t, intersection, interaction, isBSDF, epsilon[0], depth ); - // We don't allow non watertight transmitters in this renderer + // We don't allow non watertight transmitters in this renderer & scene, one cannot reach a light from the backface (optimization) bool validPath = nee_sample.NdotL>nbl_glsl_FLT_MIN; // but if we allowed non-watertight transmitters (single water surface), it would make sense just to apply this line by itself nbl_glsl_AnisotropicMicrofacetCache _cache; validPath = validPath && nbl_glsl_calcAnisotropicMicrofacetCache(_cache, interaction, nee_sample, monochromeEta); + // infinite PDF would mean a point light or a thin line, but our lights have finite radiance per steradian (area lights) if (lightPdflumaContributionThreshold && traceRay(t,intersection+nee_sample.L*t*getStartTolerance(depth),nee_sample.L)==-1) - ray._payload.accumulation += neeContrib; - }} + if (bsdfPdflumaContributionThreshold && traceRay(t,intersection+nee_sample.L*t*getStartTolerance(depth),nee_sample.L)==-1) + ray._payload.accumulation += neeContrib; + } + } +#ifndef NEE_ONLY } -#if NEE_ONLY - return false; -#endif + // sample BSDF float bsdfPdf; vec3 bsdfSampleL; { @@ -680,6 +690,7 @@ bool closestHitProgram(in uint depth, in uint _sample, inout Ray_t ray, inout nb #endif return true; } +#endif } return false; } @@ -748,15 +759,15 @@ void main() ray._payload.accumulation = vec3(0.0); ray._payload.otherTechniqueHeuristic = 0.0; // needed for direct eye-light paths ray._payload.throughput = vec3(1.0); - #ifdef KILL_DIFFUSE_SPECULAR_PATHS +#ifdef KILL_DIFFUSE_SPECULAR_PATHS ray._payload.hasDiffuse = false; - #endif +#endif } // bounces { bool hit = true; bool rayAlive = true; - for (int d=1; d<=PTPushConstant.depth && hit && rayAlive; d+=2) + for (int d=1; d<=PTPushConstant.depth && hit && rayAlive; d++) { ray._mutable.intersectionT = nbl_glsl_FLT_MAX; ray._mutable.objectID = traceRay(ray._mutable.intersectionT,ray._immutable.origin,ray._immutable.direction); diff --git a/30_ComputeShaderPathTracer/include/nbl/this_example/common.hpp b/30_ComputeShaderPathTracer/include/nbl/this_example/common.hpp index ff3dd8095..3745ca512 100644 --- a/30_ComputeShaderPathTracer/include/nbl/this_example/common.hpp +++ b/30_ComputeShaderPathTracer/include/nbl/this_example/common.hpp @@ -1,17 +1,11 @@ -#ifndef __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ -#define __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ +#ifndef _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ +#define _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ -#include - -// common api -#include "CCamera.hpp" -#include "SimpleWindowedApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" -#include "CEventCallback.hpp" +#include "nbl/examples/examples.hpp" // example's own headers -#include "nbl/ui/ICursorControl.h" +#include "nbl/ui/ICursorControl.h" // TODO: why not in nabla.h ? #include "nbl/ext/ImGui/ImGui.h" #include "imgui/imgui_internal.h" -#endif // __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ \ No newline at end of file +#endif // _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ \ No newline at end of file diff --git a/30_ComputeShaderPathTracer/main.cpp b/30_ComputeShaderPathTracer/main.cpp index 26d673002..54bc64495 100644 --- a/30_ComputeShaderPathTracer/main.cpp +++ b/30_ComputeShaderPathTracer/main.cpp @@ -2,31 +2,37 @@ // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h -#include "nbl/this_example/common.hpp" -#include "nbl/asset/interchange/IImageAssetHandlerBase.h" + +#include "nbl/examples/examples.hpp" + #include "nbl/ext/FullScreenTriangle/FullScreenTriangle.h" #include "nbl/builtin/hlsl/surface_transform.h" -using namespace nbl; -using namespace core; -using namespace hlsl; -using namespace system; -using namespace asset; -using namespace ui; -using namespace video; +#include "nbl/this_example/common.hpp" + +using namespace nbl; +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::examples; + +// TODO: share push constants struct PTPushConstant { matrix4SIMD invMVP; int sampleCount; int depth; }; -// TODO: Add a QueryPool for timestamping once its ready +// TODO: Add a QueryPool for timestamping once its ready (actually add IMGUI mspf plotter) // TODO: Do buffer creation using assConv -class ComputeShaderPathtracer final : public examples::SimpleWindowedApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +class ComputeShaderPathtracer final : public SimpleWindowedApplication, public BuiltinResourcesApplication { - using device_base_t = examples::SimpleWindowedApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using device_base_t = SimpleWindowedApplication; + using asset_base_t = BuiltinResourcesApplication; using clock_t = std::chrono::steady_clock; enum E_LIGHT_GEOMETRY : uint8_t @@ -313,12 +319,11 @@ class ComputeShaderPathtracer final : public examples::SimpleWindowedApplication std::exit(-1); } - auto source = IAsset::castDown(assets[0]); + auto source = IAsset::castDown(assets[0]); // The down-cast should not fail! assert(source); - // this time we skip the use of the asset converter since the ICPUShader->IGPUShader path is quick and simple - auto shader = m_device->createShader(source.get()); + auto shader = m_device->compileShader({ .source = source.get(), .stage = ESS_COMPUTE }); if (!shader) { m_logger->log("Shader creationed failed: %s!", ILogger::ELL_ERROR, pathToShader); @@ -353,8 +358,8 @@ class ComputeShaderPathtracer final : public examples::SimpleWindowedApplication params.shader.shader = ptShader.get(); params.shader.entryPoint = "main"; params.shader.entries = nullptr; - params.shader.requireFullSubgroups = true; - params.shader.requiredSubgroupSize = static_cast(5); + params.cached.requireFullSubgroups = true; + params.shader.requiredSubgroupSize = static_cast(5); if (!m_device->createComputePipelines(nullptr, { ¶ms, 1 }, m_PTPipelines.data() + index)) { return logFail("Failed to create compute pipeline!\n"); } @@ -373,9 +378,9 @@ class ComputeShaderPathtracer final : public examples::SimpleWindowedApplication if (!fragmentShader) return logFail("Failed to Load and Compile Fragment Shader: lumaMeterShader!"); - const IGPUShader::SSpecInfo fragSpec = { + const IGPUPipelineBase::SShaderSpecInfo fragSpec = { + .shader = fragmentShader.get(), .entryPoint = "main", - .shader = fragmentShader.get() }; auto presentLayout = m_device->createPipelineLayout( @@ -533,6 +538,9 @@ class ComputeShaderPathtracer final : public examples::SimpleWindowedApplication region.imageExtent = scrambleMapCPU->getCreationParameters().extent; scrambleMapCPU->setBufferAndRegions(std::move(texelBuffer), regions); + + // programmatically user-created IPreHashed need to have their hash computed (loaders do it while loading) + scrambleMapCPU->setContentHash(scrambleMapCPU->computeContentHash()); } std::array cpuImgs = { envMapCPU.get(), scrambleMapCPU.get()}; @@ -859,7 +867,7 @@ class ComputeShaderPathtracer final : public examples::SimpleWindowedApplication ImGui::SliderFloat("zFar", &zFar, 110.f, 10000.f); ImGui::ListBox("Shader", &PTPipline, shaderNames, E_LIGHT_GEOMETRY::ELG_COUNT); ImGui::SliderInt("SPP", &spp, 1, MaxBufferSamples); - ImGui::SliderInt("Depth", &depth, 1, MaxBufferDimensions / 3); + ImGui::SliderInt("Depth", &depth, 1, MaxBufferDimensions / 6); ImGui::Text("X: %f Y: %f", io.MousePos.x, io.MousePos.y); diff --git a/31_HLSLPathTracer/CMakeLists.txt b/31_HLSLPathTracer/CMakeLists.txt new file mode 100644 index 000000000..07b0fd396 --- /dev/null +++ b/31_HLSLPathTracer/CMakeLists.txt @@ -0,0 +1,37 @@ +include(common RESULT_VARIABLE RES) +if(NOT RES) + message(FATAL_ERROR "common.cmake not found. Should be in {repo_root}/cmake directory") +endif() + +if(NBL_BUILD_IMGUI) + set(NBL_INCLUDE_SERACH_DIRECTORIES + "${CMAKE_CURRENT_SOURCE_DIR}/include" + ) + + list(APPEND NBL_LIBRARIES + imtestengine + "${NBL_EXT_IMGUI_UI_LIB}" + ) + + nbl_create_executable_project("" "" "${NBL_INCLUDE_SERACH_DIRECTORIES}" "${NBL_LIBRARIES}" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") + + if(NBL_EMBED_BUILTIN_RESOURCES) + set(_BR_TARGET_ ${EXECUTABLE_NAME}_builtinResourceData) + set(RESOURCE_DIR "app_resources") + + get_filename_component(_SEARCH_DIRECTORIES_ "${CMAKE_CURRENT_SOURCE_DIR}" ABSOLUTE) + get_filename_component(_OUTPUT_DIRECTORY_SOURCE_ "${CMAKE_CURRENT_BINARY_DIR}/src" ABSOLUTE) + get_filename_component(_OUTPUT_DIRECTORY_HEADER_ "${CMAKE_CURRENT_BINARY_DIR}/include" ABSOLUTE) + + file(GLOB_RECURSE BUILTIN_RESOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/${RESOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/${RESOURCE_DIR}/*") + foreach(RES_FILE ${BUILTIN_RESOURCE_FILES}) + LIST_BUILTIN_RESOURCE(RESOURCES_TO_EMBED "${RES_FILE}") + endforeach() + + ADD_CUSTOM_BUILTIN_RESOURCES(${_BR_TARGET_} RESOURCES_TO_EMBED "${_SEARCH_DIRECTORIES_}" "${RESOURCE_DIR}" "nbl::this_example::builtin" "${_OUTPUT_DIRECTORY_HEADER_}" "${_OUTPUT_DIRECTORY_SOURCE_}") + + LINK_BUILTIN_RESOURCES_TO_TARGET(${EXECUTABLE_NAME} ${_BR_TARGET_}) + endif() +endif() + + diff --git a/42_FragmentShaderPathTracer/common.glsl b/31_HLSLPathTracer/app_resources/glsl/common.glsl similarity index 93% rename from 42_FragmentShaderPathTracer/common.glsl rename to 31_HLSLPathTracer/app_resources/glsl/common.glsl index 20f7a7359..6b6e96710 100644 --- a/42_FragmentShaderPathTracer/common.glsl +++ b/31_HLSLPathTracer/app_resources/glsl/common.glsl @@ -2,27 +2,27 @@ // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h -// basic settings -#define MAX_DEPTH 3 -#define SAMPLES 128 - // firefly and variance reduction techniques //#define KILL_DIFFUSE_SPECULAR_PATHS //#define VISUALIZE_HIGH_VARIANCE -layout(set = 2, binding = 0) uniform sampler2D envMap; +// debug +//#define NEE_ONLY + +layout(set = 2, binding = 0) uniform sampler2D envMap; layout(set = 2, binding = 1) uniform usamplerBuffer sampleSequence; layout(set = 2, binding = 2) uniform usampler2D scramblebuf; layout(set=0, binding=0, rgba16f) uniform image2D outImage; #ifndef _NBL_GLSL_WORKGROUP_SIZE_ -#define _NBL_GLSL_WORKGROUP_SIZE_ 16 -layout(local_size_x=_NBL_GLSL_WORKGROUP_SIZE_, local_size_y=_NBL_GLSL_WORKGROUP_SIZE_, local_size_z=1) in; +#define _NBL_GLSL_WORKGROUP_SIZE_ 512 +layout(local_size_x=_NBL_GLSL_WORKGROUP_SIZE_, local_size_y=1, local_size_z=1) in; #endif ivec2 getCoordinates() { - return ivec2(gl_GlobalInvocationID.xy); + ivec2 imageSize = imageSize(outImage); + return ivec2(gl_GlobalInvocationID.x % imageSize.x, gl_GlobalInvocationID.x / imageSize.x); } vec2 getTexCoords() { @@ -35,15 +35,18 @@ vec2 getTexCoords() { #include #include #include -#include +#ifdef PERSISTENT_WORKGROUPS +#include +#endif #include -layout(set = 1, binding = 0, row_major, std140) uniform UBO +layout(push_constant, row_major) uniform constants { - nbl_glsl_SBasicViewParameters params; -} cameraData; - + mat4 invMVP; + int sampleCount; + int depth; +} PTPushConstant; #define INVALID_ID_16BIT 0xffffu struct Sphere @@ -51,7 +54,7 @@ struct Sphere vec3 position; float radius2; uint bsdfLightIDs; -}; +}; Sphere Sphere_Sphere(in vec3 position, in float radius, in uint bsdfID, in uint lightID) { @@ -188,7 +191,7 @@ void Rectangle_getNormalBasis(in Rectangle rect, out mat3 basis, out vec2 extent basis[0] = rect.edge0/extents[0]; basis[1] = rect.edge1/extents[1]; basis[2] = normalize(cross(basis[0],basis[1])); -} +} // return intersection distance if found, nbl_glsl_FLT_NAN otherwise float Rectangle_intersect(in Rectangle rect, in vec3 origin, in vec3 direction) @@ -222,7 +225,7 @@ vec3 Rectangle_getNormalTimesArea(in Rectangle rect) #define OP_BITS_OFFSET 0 #define OP_BITS_SIZE 2 struct BSDFNode -{ +{ uvec4 data[2]; }; @@ -386,13 +389,13 @@ vec2 SampleSphericalMap(vec3 v) { vec2 uv = vec2(atan(v.z, v.x), asin(v.y)); uv *= nbl_glsl_RECIPROCAL_PI*0.5; - uv += 0.5; + uv += 0.5; return uv; } void missProgram(in ImmutableRay_t _immutable, inout Payload_t _payload) { - vec3 finalContribution = _payload.throughput; + vec3 finalContribution = _payload.throughput; // #define USE_ENVMAP #ifdef USE_ENVMAP vec2 uv = SampleSphericalMap(_immutable.direction); @@ -415,7 +418,7 @@ nbl_glsl_LightSample nbl_glsl_bsdf_cos_generate(in nbl_glsl_AnisotropicViewSurfa { const float a = BSDFNode_getRoughness(bsdf); const mat2x3 ior = BSDFNode_getEta(bsdf); - + // fresnel stuff for dielectrics float orientedEta, rcpOrientedEta; const bool viewerInsideMedium = nbl_glsl_getOrientedEtas(orientedEta,rcpOrientedEta,interaction.isotropic.NdotV,monochromeEta); @@ -519,7 +522,7 @@ int traceRay(inout float intersectionT, in vec3 origin, in vec3 direction) intersectionT = closerIntersection ? t : intersectionT; objectID = closerIntersection ? i:objectID; - + // allowing early out results in a performance regression, WTF!? //if (anyHit && closerIntersection) //break; @@ -543,7 +546,7 @@ nbl_glsl_LightSample nbl_glsl_light_generate_and_remainder_and_pdf(out vec3 rema { // normally we'd pick from set of lights, using `xi.z` const Light light = lights[0]; - + vec3 L = nbl_glsl_light_generate_and_pdf(pdf,newRayMaxT,origin,interaction,isBSDF,xi,Light_getObjectID(light)); newRayMaxT *= getEndTolerance(depth); @@ -640,7 +643,7 @@ bool closestHitProgram(in uint depth, in uint _sample, inout Ray_t ray, inout nb float bsdfPdf; neeContrib *= nbl_glsl_bsdf_cos_remainder_and_pdf(bsdfPdf,nee_sample,interaction,bsdf,monochromeEta,_cache)*throughput; const float otherGenOverChoice = bsdfPdf*rcpChoiceProb; -#if 0 +#ifndef NEE_ONLY const float otherGenOverLightAndChoice = otherGenOverChoice/lightPdf; neeContrib *= otherGenOverChoice/(1.f+otherGenOverLightAndChoice*otherGenOverLightAndChoice); // MIS weight #else @@ -650,7 +653,7 @@ bool closestHitProgram(in uint depth, in uint _sample, inout Ray_t ray, inout nb ray._payload.accumulation += neeContrib; }} } -#if 1 +#if NEE_ONLY return false; #endif // sample BSDF @@ -663,7 +666,7 @@ bool closestHitProgram(in uint depth, in uint _sample, inout Ray_t ray, inout nb // bsdfSampleL = bsdf_sample.L; } - + // additional threshold const float lumaThroughputThreshold = lumaContributionThreshold; if (bsdfPdf>bsdfPdfThreshold && getLuma(throughput)>lumaThroughputThreshold) @@ -671,7 +674,7 @@ bool closestHitProgram(in uint depth, in uint _sample, inout Ray_t ray, inout nb ray._payload.throughput = throughput; ray._payload.otherTechniqueHeuristic = neeProbability/bsdfPdf; // numerically stable, don't touch ray._payload.otherTechniqueHeuristic *= ray._payload.otherTechniqueHeuristic; - + // trace new ray ray._immutable.origin = intersection+bsdfSampleL*(1.0/*kSceneSize*/)*getStartTolerance(depth); ray._immutable.direction = bsdfSampleL; @@ -688,27 +691,45 @@ bool closestHitProgram(in uint depth, in uint _sample, inout Ray_t ray, inout nb void main() { const ivec2 imageExtents = imageSize(outImage); + +#ifdef PERSISTENT_WORKGROUPS + uint virtualThreadIndex; + for (uint virtualThreadBase = gl_WorkGroupID.x * _NBL_GLSL_WORKGROUP_SIZE_; virtualThreadBase < 1920*1080; virtualThreadBase += gl_NumWorkGroups.x * _NBL_GLSL_WORKGROUP_SIZE_) // not sure why 1280*720 doesn't cover draw surface + { + virtualThreadIndex = virtualThreadBase + gl_LocalInvocationIndex.x; + const ivec2 coords = ivec2(nbl_glsl_morton_decode2d32b(virtualThreadIndex)); +#else const ivec2 coords = getCoordinates(); +#endif + vec2 texCoord = vec2(coords) / vec2(imageExtents); texCoord.y = 1.0 - texCoord.y; if (false == (all(lessThanEqual(ivec2(0),coords)) && all(greaterThan(imageExtents,coords)))) { +#ifdef PERSISTENT_WORKGROUPS + continue; +#else return; +#endif } - if (((MAX_DEPTH-1)>>MAX_DEPTH_LOG2)>0 || ((SAMPLES-1)>>MAX_SAMPLES_LOG2)>0) + if (((PTPushConstant.depth-1)>>MAX_DEPTH_LOG2)>0 || ((PTPushConstant.sampleCount-1)>>MAX_SAMPLES_LOG2)>0) { vec4 pixelCol = vec4(1.0,0.0,0.0,1.0); imageStore(outImage, coords, pixelCol); +#ifdef PERSISTENT_WORKGROUPS + continue; +#else return; +#endif } - nbl_glsl_xoroshiro64star_state_t scramble_start_state = texelFetch(scramblebuf,coords,0).rg; + nbl_glsl_xoroshiro64star_state_t scramble_start_state = texelFetch(scramblebuf,coords,0).rg; const vec2 pixOffsetParam = vec2(1.0)/vec2(textureSize(scramblebuf,0)); - const mat4 invMVP = inverse(cameraData.params.MVP); - + const mat4 invMVP = PTPushConstant.invMVP; + vec4 NDC = vec4(texCoord*vec2(2.0,-2.0)+vec2(-1.0,1.0),0.0,1.0); vec3 camPos; { @@ -719,8 +740,8 @@ void main() vec3 color = vec3(0.0); float meanLumaSquared = 0.0; - // TODO: if we collapse the nested for loop, then all GPUs will get `MAX_DEPTH` factor speedup, not just NV with separate PC - for (int i=0; i +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace nbl +{ +namespace hlsl +{ +namespace ext +{ + +template // TODO make type T Spectrum +struct Payload +{ + using this_t = Payload; + using scalar_type = T; + using vector3_type = vector; + + vector3_type accumulation; + scalar_type otherTechniqueHeuristic; + vector3_type throughput; + // #ifdef KILL_DIFFUSE_SPECULAR_PATHS + // bool hasDiffuse; + // #endif +}; + +enum ProceduralShapeType : uint16_t +{ + PST_NONE = 0, + PST_SPHERE, + PST_TRIANGLE, + PST_RECTANGLE +}; + +struct ObjectID +{ + static ObjectID create(uint32_t id, uint32_t mode, ProceduralShapeType shapeType) + { + ObjectID retval; + retval.id = id; + retval.mode = mode; + retval.shapeType = shapeType; + return retval; + } + + uint32_t id; + uint32_t mode; + ProceduralShapeType shapeType; +}; + +template +struct Ray +{ + using this_t = Ray; + using scalar_type = T; + using vector3_type = vector; + + // immutable + vector3_type origin; + vector3_type direction; + + // polygon method == PPM_APPROX_PROJECTED_SOLID_ANGLE + vector3_type normalAtOrigin; + bool wasBSDFAtOrigin; + + // mutable + scalar_type intersectionT; + ObjectID objectID; + + Payload payload; +}; + +template +struct Light +{ + using spectral_type = Spectrum; + + NBL_CONSTEXPR_STATIC_INLINE uint32_t INVALID_ID = 0xffffu; + + static Light create(NBL_CONST_REF_ARG(spectral_type) radiance, uint32_t objId, uint32_t mode, ProceduralShapeType shapeType) + { + Light retval; + retval.radiance = radiance; + retval.objectID = ObjectID::create(objId, mode, shapeType); + return retval; + } + + static Light create(NBL_CONST_REF_ARG(spectral_type) radiance, NBL_CONST_REF_ARG(ObjectID) objectID) + { + Light retval; + retval.radiance = radiance; + retval.objectID = objectID; + return retval; + } + + spectral_type radiance; + ObjectID objectID; +}; + +template +struct BxDFNode +{ + using spectral_type = Spectrum; + using params_type = bxdf::SBxDFCreationParams; + + NBL_CONSTEXPR_STATIC_INLINE uint32_t INVALID_ID = 0xffffu; + + // for diffuse bxdfs + static BxDFNode create(uint32_t materialType, bool isAniso, NBL_CONST_REF_ARG(float32_t2) A, NBL_CONST_REF_ARG(spectral_type) albedo) + { + BxDFNode retval; + retval.albedo = albedo; + retval.materialType = materialType; + retval.params.is_aniso = isAniso; + retval.params.A = hlsl::max(A, (float32_t2)1e-4); + retval.params.ior0 = (spectral_type)1.0; + retval.params.ior1 = (spectral_type)1.0; + return retval; + } + + // for conductor + dielectric + static BxDFNode create(uint32_t materialType, bool isAniso, NBL_CONST_REF_ARG(float32_t2) A, NBL_CONST_REF_ARG(spectral_type) ior0, NBL_CONST_REF_ARG(spectral_type) ior1) + { + BxDFNode retval; + retval.albedo = (spectral_type)1.0; + retval.materialType = materialType; + retval.params.is_aniso = isAniso; + retval.params.A = hlsl::max(A, (float32_t2)1e-4); + retval.params.ior0 = ior0; + retval.params.ior1 = ior1; + return retval; + } + + spectral_type albedo; + uint32_t materialType; + params_type params; +}; + +template +struct Tolerance +{ + NBL_CONSTEXPR_STATIC_INLINE float INTERSECTION_ERROR_BOUND_LOG2 = -8.0; + + static T __common(uint32_t depth) + { + float depthRcp = 1.0 / float(depth); + return INTERSECTION_ERROR_BOUND_LOG2; + } + + static T getStart(uint32_t depth) + { + return nbl::hlsl::exp2(__common(depth)); + } + + static T getEnd(uint32_t depth) + { + return 1.0 - nbl::hlsl::exp2(__common(depth) + 1.0); + } +}; + +enum PTPolygonMethod : uint16_t +{ + PPM_AREA, + PPM_SOLID_ANGLE, + PPM_APPROX_PROJECTED_SOLID_ANGLE +}; + +enum IntersectMode : uint32_t +{ + IM_RAY_QUERY, + IM_RAY_TRACING, + IM_PROCEDURAL +}; + +template +struct Shape; + +template<> +struct Shape +{ + static Shape create(NBL_CONST_REF_ARG(float32_t3) position, float32_t radius2, uint32_t bsdfLightIDs) + { + Shape retval; + retval.position = position; + retval.radius2 = radius2; + retval.bsdfLightIDs = bsdfLightIDs; + return retval; + } + + static Shape create(NBL_CONST_REF_ARG(float32_t3) position, float32_t radius, uint32_t bsdfID, uint32_t lightID) + { + uint32_t bsdfLightIDs = glsl::bitfieldInsert(bsdfID, lightID, 16, 16); + return create(position, radius * radius, bsdfLightIDs); + } + + // return intersection distance if found, nan otherwise + float intersect(NBL_CONST_REF_ARG(float32_t3) origin, NBL_CONST_REF_ARG(float32_t3) direction) + { + float32_t3 relOrigin = origin - position; + float relOriginLen2 = hlsl::dot(relOrigin, relOrigin); + + float dirDotRelOrigin = hlsl::dot(direction, relOrigin); + float det = radius2 - relOriginLen2 + dirDotRelOrigin * dirDotRelOrigin; + + // do some speculative math here + float detsqrt = hlsl::sqrt(det); + return -dirDotRelOrigin + (relOriginLen2 > radius2 ? (-detsqrt) : detsqrt); + } + + float32_t3 getNormal(NBL_CONST_REF_ARG(float32_t3) hitPosition) + { + const float radiusRcp = hlsl::rsqrt(radius2); + return (hitPosition - position) * radiusRcp; + } + + float getSolidAngle(NBL_CONST_REF_ARG(float32_t3) origin) + { + float32_t3 dist = position - origin; + float cosThetaMax = hlsl::sqrt(1.0 - radius2 / hlsl::dot(dist, dist)); + return 2.0 * numbers::pi * (1.0 - cosThetaMax); + } + + NBL_CONSTEXPR_STATIC_INLINE uint32_t ObjSize = 5; + + float32_t3 position; + float32_t radius2; + uint32_t bsdfLightIDs; +}; + +template<> +struct Shape +{ + static Shape create(NBL_CONST_REF_ARG(float32_t3) vertex0, NBL_CONST_REF_ARG(float32_t3) vertex1, NBL_CONST_REF_ARG(float32_t3) vertex2, uint32_t bsdfLightIDs) + { + Shape retval; + retval.vertex0 = vertex0; + retval.vertex1 = vertex1; + retval.vertex2 = vertex2; + retval.bsdfLightIDs = bsdfLightIDs; + return retval; + } + + static Shape create(NBL_CONST_REF_ARG(float32_t3) vertex0, NBL_CONST_REF_ARG(float32_t3) vertex1, NBL_CONST_REF_ARG(float32_t3) vertex2, uint32_t bsdfID, uint32_t lightID) + { + uint32_t bsdfLightIDs = glsl::bitfieldInsert(bsdfID, lightID, 16, 16); + return create(vertex0, vertex1, vertex2, bsdfLightIDs); + } + + float intersect(NBL_CONST_REF_ARG(float32_t3) origin, NBL_CONST_REF_ARG(float32_t3) direction) + { + const float32_t3 edges[2] = { vertex1 - vertex0, vertex2 - vertex0 }; + + const float32_t3 h = hlsl::cross(direction, edges[1]); + const float a = hlsl::dot(edges[0], h); + + const float32_t3 relOrigin = origin - vertex0; + + const float u = hlsl::dot(relOrigin, h) / a; + + const float32_t3 q = hlsl::cross(relOrigin, edges[0]); + const float v = hlsl::dot(direction, q) / a; + + const float t = hlsl::dot(edges[1], q) / a; + + const bool intersection = t > 0.f && u >= 0.f && v >= 0.f && (u + v) <= 1.f; + return intersection ? t : bit_cast(numeric_limits::infinity); + } + + float32_t3 getNormalTimesArea() + { + const float32_t3 edges[2] = { vertex1 - vertex0, vertex2 - vertex0 }; + return hlsl::cross(edges[0], edges[1]) * 0.5f; + } + + NBL_CONSTEXPR_STATIC_INLINE uint32_t ObjSize = 10; + + float32_t3 vertex0; + float32_t3 vertex1; + float32_t3 vertex2; + uint32_t bsdfLightIDs; +}; + +template<> +struct Shape +{ + static Shape create(NBL_CONST_REF_ARG(float32_t3) offset, NBL_CONST_REF_ARG(float32_t3) edge0, NBL_CONST_REF_ARG(float32_t3) edge1, uint32_t bsdfLightIDs) + { + Shape retval; + retval.offset = offset; + retval.edge0 = edge0; + retval.edge1 = edge1; + retval.bsdfLightIDs = bsdfLightIDs; + return retval; + } + + static Shape create(NBL_CONST_REF_ARG(float32_t3) offset, NBL_CONST_REF_ARG(float32_t3) edge0, NBL_CONST_REF_ARG(float32_t3) edge1, uint32_t bsdfID, uint32_t lightID) + { + uint32_t bsdfLightIDs = glsl::bitfieldInsert(bsdfID, lightID, 16, 16); + return create(offset, edge0, edge1, bsdfLightIDs); + } + + float intersect(NBL_CONST_REF_ARG(float32_t3) origin, NBL_CONST_REF_ARG(float32_t3) direction) + { + const float32_t3 h = hlsl::cross(direction, edge1); + const float a = hlsl::dot(edge0, h); + + const float32_t3 relOrigin = origin - offset; + + const float u = hlsl::dot(relOrigin,h)/a; + + const float32_t3 q = hlsl::cross(relOrigin, edge0); + const float v = hlsl::dot(direction, q) / a; + + const float t = hlsl::dot(edge1, q) / a; + + const bool intersection = t > 0.f && u >= 0.f && v >= 0.f && u <= 1.f && v <= 1.f; + return intersection ? t : bit_cast(numeric_limits::infinity); + } + + float32_t3 getNormalTimesArea() + { + return hlsl::cross(edge0, edge1); + } + + void getNormalBasis(NBL_REF_ARG(float32_t3x3) basis, NBL_REF_ARG(float32_t2) extents) + { + extents = float32_t2(nbl::hlsl::length(edge0), nbl::hlsl::length(edge1)); + basis[0] = edge0 / extents[0]; + basis[1] = edge1 / extents[1]; + basis[2] = normalize(cross(basis[0],basis[1])); + } + + NBL_CONSTEXPR_STATIC_INLINE uint32_t ObjSize = 10; + + float32_t3 offset; + float32_t3 edge0; + float32_t3 edge1; + uint32_t bsdfLightIDs; +}; + +} +} +} + +#endif diff --git a/31_HLSLPathTracer/app_resources/hlsl/intersector.hlsl b/31_HLSLPathTracer/app_resources/hlsl/intersector.hlsl new file mode 100644 index 000000000..e59fdc2c3 --- /dev/null +++ b/31_HLSLPathTracer/app_resources/hlsl/intersector.hlsl @@ -0,0 +1,88 @@ +#ifndef _NBL_HLSL_EXT_INTERSECTOR_INCLUDED_ +#define _NBL_HLSL_EXT_INTERSECTOR_INCLUDED_ + +#include "common.hlsl" +#include "scene.hlsl" +#include + +namespace nbl +{ +namespace hlsl +{ +namespace ext +{ +namespace Intersector +{ + +template +struct Comprehensive +{ + using scalar_type = typename Ray::scalar_type; + using vector3_type = vector; + using ray_type = Ray; + + using light_type = Light; + using bxdfnode_type = BxdfNode; + using scene_type = Scene; + + static ObjectID traceRay(NBL_REF_ARG(ray_type) ray, NBL_CONST_REF_ARG(scene_type) scene) + { + ObjectID objectID; + objectID.id = -1; + + // prodedural shapes + for (int i = 0; i < scene.sphereCount; i++) + { + float t = scene.spheres[i].intersect(ray.origin, ray.direction); + + bool closerIntersection = t > 0.0 && t < ray.intersectionT; + + if (closerIntersection) + { + ray.intersectionT = t; + objectID.id = i; + objectID.mode = IM_PROCEDURAL; + objectID.shapeType = PST_SPHERE; + } + } + for (int i = 0; i < scene.triangleCount; i++) + { + float t = scene.triangles[i].intersect(ray.origin, ray.direction); + + bool closerIntersection = t > 0.0 && t < ray.intersectionT; + + if (closerIntersection) + { + ray.intersectionT = t; + objectID.id = i; + objectID.mode = IM_PROCEDURAL; + objectID.shapeType = PST_TRIANGLE; + } + } + for (int i = 0; i < scene.rectangleCount; i++) + { + float t = scene.rectangles[i].intersect(ray.origin, ray.direction); + + bool closerIntersection = t > 0.0 && t < ray.intersectionT; + + if (closerIntersection) + { + ray.intersectionT = t; + objectID.id = i; + objectID.mode = IM_PROCEDURAL; + objectID.shapeType = PST_TRIANGLE; + } + } + + // TODO: trace AS + + return objectID; + } +}; + +} +} +} +} + +#endif diff --git a/31_HLSLPathTracer/app_resources/hlsl/material_system.hlsl b/31_HLSLPathTracer/app_resources/hlsl/material_system.hlsl new file mode 100644 index 000000000..4e2fdc5a0 --- /dev/null +++ b/31_HLSLPathTracer/app_resources/hlsl/material_system.hlsl @@ -0,0 +1,205 @@ +#ifndef _NBL_HLSL_EXT_MATERIAL_SYSTEM_INCLUDED_ +#define _NBL_HLSL_EXT_MATERIAL_SYSTEM_INCLUDED_ + +#include +#include +#include + +namespace nbl +{ +namespace hlsl +{ +namespace ext +{ +namespace MaterialSystem +{ + +enum MaterialType : uint32_t // enum class? +{ + DIFFUSE, + CONDUCTOR, + DIELECTRIC +}; + +template +struct MaterialParams +{ + using this_t = MaterialParams; + using sample_type = typename DiffuseBxDF::sample_type; + using anisotropic_interaction_type = typename DiffuseBxDF::anisotropic_interaction_type; + using isotropic_interaction_type = typename anisotropic_interaction_type::isotropic_interaction_type; + using anisocache_type = typename ConductorBxDF::anisocache_type; + using isocache_type = typename anisocache_type::isocache_type; + + using diffuse_params_type = typename DiffuseBxDF::params_isotropic_t; + using conductor_params_type = typename ConductorBxDF::params_isotropic_t; + using dielectric_params_type = typename DielectricBxDF::params_isotropic_t; + + // we're only doing isotropic for this example + static this_t create(sample_type _sample, isotropic_interaction_type _interaction, isocache_type _cache, bxdf::BxDFClampMode _clamp) + { + this_t retval; + retval._Sample = _sample; + retval.interaction = _interaction; + retval.cache = _cache; + retval.clampMode = _clamp; + return retval; + } + + diffuse_params_type getDiffuseParams() + { + return diffuse_params_type::create(_Sample, interaction, clampMode); + } + + conductor_params_type getConductorParams() + { + return conductor_params_type::create(_Sample, interaction, cache, clampMode); + } + + dielectric_params_type getDielectricParams() + { + return dielectric_params_type::create(_Sample, interaction, cache, clampMode); + } + + sample_type _Sample; + isotropic_interaction_type interaction; + isocache_type cache; + bxdf::BxDFClampMode clampMode; +}; + +template // NOTE: these bxdfs should match the ones in Scene BxDFNode +struct System +{ + using this_t = System; + using scalar_type = typename DiffuseBxDF::scalar_type; // types should be same across all 3 bxdfs + using vector2_type = vector; + using vector3_type = vector; + using measure_type = typename DiffuseBxDF::spectral_type; + using sample_type = typename DiffuseBxDF::sample_type; + using ray_dir_info_type = typename sample_type::ray_dir_info_type; + using quotient_pdf_type = typename DiffuseBxDF::quotient_pdf_type; + using anisotropic_interaction_type = typename DiffuseBxDF::anisotropic_interaction_type; + using isotropic_interaction_type = typename anisotropic_interaction_type::isotropic_interaction_type; + using anisocache_type = typename ConductorBxDF::anisocache_type; + using isocache_type = typename anisocache_type::isocache_type; + using params_t = MaterialParams; + using create_params_t = bxdf::SBxDFCreationParams; + + using diffuse_op_type = DiffuseBxDF; + using conductor_op_type = ConductorBxDF; + using dielectric_op_type = DielectricBxDF; + + static this_t create(NBL_CONST_REF_ARG(create_params_t) diffuseParams, NBL_CONST_REF_ARG(create_params_t) conductorParams, NBL_CONST_REF_ARG(create_params_t) dielectricParams) + { + this_t retval; + retval.diffuseBxDF = diffuse_op_type::create(diffuseParams); + retval.conductorBxDF = conductor_op_type::create(conductorParams); + retval.dielectricBxDF = dielectric_op_type::create(dielectricParams); + return retval; + } + + measure_type eval(uint32_t material, NBL_CONST_REF_ARG(create_params_t) cparams, NBL_CONST_REF_ARG(params_t) params) + { + switch(material) + { + case MaterialType::DIFFUSE: + { + diffuseBxDF.init(cparams); + return (measure_type)diffuseBxDF.eval(params.getDiffuseParams()); + } + break; + case MaterialType::CONDUCTOR: + { + conductorBxDF.init(cparams); + return conductorBxDF.eval(params.getConductorParams()); + } + break; + case MaterialType::DIELECTRIC: + { + dielectricBxDF.init(cparams); + return dielectricBxDF.eval(params.getDielectricParams()); + } + break; + default: + return (measure_type)0.0; + } + } + + sample_type generate(uint32_t material, NBL_CONST_REF_ARG(create_params_t) cparams, NBL_CONST_REF_ARG(anisotropic_interaction_type) interaction, NBL_CONST_REF_ARG(vector3_type) u, NBL_REF_ARG(anisocache_type) _cache) + { + switch(material) + { + case MaterialType::DIFFUSE: + { + diffuseBxDF.init(cparams); + return diffuseBxDF.generate(interaction, u.xy); + } + break; + case MaterialType::CONDUCTOR: + { + conductorBxDF.init(cparams); + return conductorBxDF.generate(interaction, u.xy, _cache); + } + break; + case MaterialType::DIELECTRIC: + { + dielectricBxDF.init(cparams); + return dielectricBxDF.generate(interaction, u, _cache); + } + break; + default: + { + ray_dir_info_type L; + L.direction = (vector3_type)0; + return sample_type::create(L, 0, (vector3_type)0); + } + } + + ray_dir_info_type L; + L.direction = (vector3_type)0; + return sample_type::create(L, 0, (vector3_type)0); + } + + quotient_pdf_type quotient_and_pdf(uint32_t material, NBL_CONST_REF_ARG(create_params_t) cparams, NBL_CONST_REF_ARG(params_t) params) + { + const float minimumProjVectorLen = 0.00000001; + if (params.interaction.getNdotV() > minimumProjVectorLen && params._Sample.getNdotL() > minimumProjVectorLen) + { + switch(material) + { + case MaterialType::DIFFUSE: + { + diffuseBxDF.init(cparams); + return diffuseBxDF.quotient_and_pdf(params.getDiffuseParams()); + } + break; + case MaterialType::CONDUCTOR: + { + conductorBxDF.init(cparams); + return conductorBxDF.quotient_and_pdf(params.getConductorParams()); + } + break; + case MaterialType::DIELECTRIC: + { + dielectricBxDF.init(cparams); + return dielectricBxDF.quotient_and_pdf(params.getDielectricParams()); + } + break; + default: + return quotient_pdf_type::create((measure_type)0.0, 0.0); + } + } + return quotient_pdf_type::create((measure_type)0.0, 0.0); + } + + DiffuseBxDF diffuseBxDF; + ConductorBxDF conductorBxDF; + DielectricBxDF dielectricBxDF; +}; + +} +} +} +} + +#endif diff --git a/31_HLSLPathTracer/app_resources/hlsl/next_event_estimator.hlsl b/31_HLSLPathTracer/app_resources/hlsl/next_event_estimator.hlsl new file mode 100644 index 000000000..ac74b1abf --- /dev/null +++ b/31_HLSLPathTracer/app_resources/hlsl/next_event_estimator.hlsl @@ -0,0 +1,446 @@ +#ifndef _NBL_HLSL_EXT_NEXT_EVENT_ESTIMATOR_INCLUDED_ +#define _NBL_HLSL_EXT_NEXT_EVENT_ESTIMATOR_INCLUDED_ + +#include "common.hlsl" + +namespace nbl +{ +namespace hlsl +{ +namespace ext +{ +namespace NextEventEstimator +{ + +template +struct ShapeSampling; + +template +struct ShapeSampling +{ + static ShapeSampling create(NBL_CONST_REF_ARG(Shape) sphere) + { + ShapeSampling retval; + retval.sphere = sphere; + return retval; + } + + template + float deferredPdf(NBL_CONST_REF_ARG(Ray) ray) + { + return 1.0 / sphere.getSolidAngle(ray.origin); + } + + template + float32_t3 generate_and_pdf(NBL_REF_ARG(float32_t) pdf, NBL_REF_ARG(float32_t) newRayMaxT, NBL_CONST_REF_ARG(float32_t3) origin, NBL_CONST_REF_ARG(Aniso) interaction, bool isBSDF, NBL_CONST_REF_ARG(float32_t3) xi) + { + float32_t3 Z = sphere.position - origin; + const float distanceSQ = hlsl::dot(Z,Z); + const float cosThetaMax2 = 1.0 - sphere.radius2 / distanceSQ; + if (cosThetaMax2 > 0.0) + { + const float rcpDistance = 1.0 / hlsl::sqrt(distanceSQ); + Z *= rcpDistance; + + const float cosThetaMax = hlsl::sqrt(cosThetaMax2); + const float cosTheta = hlsl::mix(1.0, cosThetaMax, xi.x); + + float32_t3 L = Z * cosTheta; + + const float cosTheta2 = cosTheta * cosTheta; + const float sinTheta = hlsl::sqrt(1.0 - cosTheta2); + float sinPhi, cosPhi; + math::sincos(2.0 * numbers::pi * xi.y - numbers::pi, sinPhi, cosPhi); + float32_t3 X, Y; + math::frisvad(Z, X, Y); + + L += (X * cosPhi + Y * sinPhi) * sinTheta; + + newRayMaxT = (cosTheta - hlsl::sqrt(cosTheta2 - cosThetaMax2)) / rcpDistance; + pdf = 1.0 / (2.0 * numbers::pi * (1.0 - cosThetaMax)); + return L; + } + pdf = 0.0; + return float32_t3(0.0,0.0,0.0); + } + + Shape sphere; +}; + +template<> +struct ShapeSampling +{ + static ShapeSampling create(NBL_CONST_REF_ARG(Shape) tri) + { + ShapeSampling retval; + retval.tri = tri; + return retval; + } + + template + float deferredPdf(NBL_CONST_REF_ARG(Ray) ray) + { + const float dist = ray.intersectionT; + const float32_t3 L = ray.direction; + return dist * dist / hlsl::abs(hlsl::dot(tri.getNormalTimesArea(), L)); + } + + template + float32_t3 generate_and_pdf(NBL_REF_ARG(float32_t) pdf, NBL_REF_ARG(float32_t) newRayMaxT, NBL_CONST_REF_ARG(float32_t3) origin, NBL_CONST_REF_ARG(Aniso) interaction, bool isBSDF, NBL_CONST_REF_ARG(float32_t3) xi) + { + const float32_t3 edge0 = tri.vertex1 - tri.vertex0; + const float32_t3 edge1 = tri.vertex2 - tri.vertex0; + const float sqrtU = hlsl::sqrt(xi.x); + float32_t3 pnt = tri.vertex0 + edge0 * (1.0 - sqrtU) + edge1 * sqrtU * xi.y; + float32_t3 L = pnt - origin; + + const float distanceSq = hlsl::dot(L,L); + const float rcpDistance = 1.0 / hlsl::sqrt(distanceSq); + L *= rcpDistance; + + pdf = distanceSq / hlsl::abs(hlsl::dot(hlsl::cross(edge0, edge1) * 0.5f, L)); + newRayMaxT = 1.0 / rcpDistance; + return L; + } + + Shape tri; +}; + +template<> +struct ShapeSampling +{ + static ShapeSampling create(NBL_CONST_REF_ARG(Shape) tri) + { + ShapeSampling retval; + retval.tri = tri; + return retval; + } + + template + float deferredPdf(NBL_CONST_REF_ARG(Ray) ray) + { + shapes::SphericalTriangle st = shapes::SphericalTriangle::create(tri.vertex0, tri.vertex1, tri.vertex2, ray.origin); + const float rcpProb = st.solidAngleOfTriangle(); + // if `rcpProb` is NAN then the triangle's solid angle was close to 0.0 + return rcpProb > numeric_limits::min ? (1.0 / rcpProb) : numeric_limits::max; + } + + template + float32_t3 generate_and_pdf(NBL_REF_ARG(float32_t) pdf, NBL_REF_ARG(float32_t) newRayMaxT, NBL_CONST_REF_ARG(float32_t3) origin, NBL_CONST_REF_ARG(Aniso) interaction, bool isBSDF, NBL_CONST_REF_ARG(float32_t3) xi) + { + float rcpPdf; + shapes::SphericalTriangle st = shapes::SphericalTriangle::create(tri.vertex0, tri.vertex1, tri.vertex2, origin); + sampling::SphericalTriangle sst = sampling::SphericalTriangle::create(st); + + const float32_t3 L = sst.generate(rcpPdf, xi.xy); + + pdf = rcpPdf > numeric_limits::min ? (1.0 / rcpPdf) : numeric_limits::max; + + const float32_t3 N = tri.getNormalTimesArea(); + newRayMaxT = hlsl::dot(N, tri.vertex0 - origin) / hlsl::dot(N, L); + return L; + } + + Shape tri; +}; + +template<> +struct ShapeSampling +{ + static ShapeSampling create(NBL_CONST_REF_ARG(Shape) tri) + { + ShapeSampling retval; + retval.tri = tri; + return retval; + } + + template + float deferredPdf(NBL_CONST_REF_ARG(Ray) ray) + { + const float32_t3 L = ray.direction; + shapes::SphericalTriangle st = shapes::SphericalTriangle::create(tri.vertex0, tri.vertex1, tri.vertex2, ray.origin); + sampling::ProjectedSphericalTriangle pst = sampling::ProjectedSphericalTriangle::create(st); + const float pdf = pst.pdf(ray.normalAtOrigin, ray.wasBSDFAtOrigin, L); + // if `pdf` is NAN then the triangle's projected solid angle was close to 0.0, if its close to INF then the triangle was very small + return pdf < numeric_limits::max ? pdf : numeric_limits::max; + } + + template + float32_t3 generate_and_pdf(NBL_REF_ARG(float32_t) pdf, NBL_REF_ARG(float32_t) newRayMaxT, NBL_CONST_REF_ARG(float32_t3) origin, NBL_CONST_REF_ARG(Aniso) interaction, bool isBSDF, NBL_CONST_REF_ARG(float32_t3) xi) + { + float rcpPdf; + shapes::SphericalTriangle st = shapes::SphericalTriangle::create(tri.vertex0, tri.vertex1, tri.vertex2, origin); + sampling::ProjectedSphericalTriangle sst = sampling::ProjectedSphericalTriangle::create(st); + + const float32_t3 L = sst.generate(rcpPdf, interaction.isotropic.N, isBSDF, xi.xy); + + pdf = rcpPdf > numeric_limits::min ? (1.0 / rcpPdf) : numeric_limits::max; + + const float32_t3 N = tri.getNormalTimesArea(); + newRayMaxT = hlsl::dot(N, tri.vertex0 - origin) / hlsl::dot(N, L); + return L; + } + + Shape tri; +}; + +template<> +struct ShapeSampling +{ + static ShapeSampling create(NBL_CONST_REF_ARG(Shape) rect) + { + ShapeSampling retval; + retval.rect = rect; + return retval; + } + + template + float deferredPdf(NBL_CONST_REF_ARG(Ray) ray) + { + const float dist = ray.intersectionT; + const float32_t3 L = ray.direction; + return dist * dist / hlsl::abs(hlsl::dot(rect.getNormalTimesArea(), L)); + } + + template + float32_t3 generate_and_pdf(NBL_REF_ARG(float32_t) pdf, NBL_REF_ARG(float32_t) newRayMaxT, NBL_CONST_REF_ARG(float32_t3) origin, NBL_CONST_REF_ARG(Aniso) interaction, bool isBSDF, NBL_CONST_REF_ARG(float32_t3) xi) + { + const float32_t3 N = rect.getNormalTimesArea(); + const float32_t3 origin2origin = rect.offset - origin; + + float32_t3 L = origin2origin + rect.edge0 * xi.x + rect.edge1 * xi.y; + const float distSq = hlsl::dot(L, L); + const float rcpDist = 1.0 / hlsl::sqrt(distSq); + L *= rcpDist; + pdf = distSq / hlsl::abs(hlsl::dot(N, L)); + newRayMaxT = 1.0 / rcpDist; + return L; + } + + Shape rect; +}; + +template<> +struct ShapeSampling +{ + static ShapeSampling create(NBL_CONST_REF_ARG(Shape) rect) + { + ShapeSampling retval; + retval.rect = rect; + return retval; + } + + template + float deferredPdf(NBL_CONST_REF_ARG(Ray) ray) + { + float pdf; + float32_t3x3 rectNormalBasis; + float32_t2 rectExtents; + rect.getNormalBasis(rectNormalBasis, rectExtents); + shapes::SphericalRectangle sphR0 = shapes::SphericalRectangle::create(ray.origin, rect.offset, rectNormalBasis); + float solidAngle = sphR0.solidAngleOfRectangle(rectExtents); + if (solidAngle > numeric_limits::min) + pdf = 1.f / solidAngle; + else + pdf = bit_cast(numeric_limits::infinity); + return pdf; + } + + template + float32_t3 generate_and_pdf(NBL_REF_ARG(float32_t) pdf, NBL_REF_ARG(float32_t) newRayMaxT, NBL_CONST_REF_ARG(float32_t3) origin, NBL_CONST_REF_ARG(Aniso) interaction, bool isBSDF, NBL_CONST_REF_ARG(float32_t3) xi) + { + const float32_t3 N = rect.getNormalTimesArea(); + const float32_t3 origin2origin = rect.offset - origin; + + float32_t3x3 rectNormalBasis; + float32_t2 rectExtents; + rect.getNormalBasis(rectNormalBasis, rectExtents); + shapes::SphericalRectangle sphR0 = shapes::SphericalRectangle::create(origin, rect.offset, rectNormalBasis); + float32_t3 L = (float32_t3)0.0; + float solidAngle = sphR0.solidAngleOfRectangle(rectExtents); + + sampling::SphericalRectangle ssph = sampling::SphericalRectangle::create(sphR0); + float32_t2 sphUv = ssph.generate(rectExtents, xi.xy, solidAngle); + if (solidAngle > numeric_limits::min) + { + float32_t3 sph_sample = sphUv[0] * rect.edge0 + sphUv[1] * rect.edge1 + rect.offset; + L = sph_sample - origin; + L = hlsl::mix(nbl::hlsl::normalize(L), (float32_t3)0.0, hlsl::abs(L) > (float32_t3)numeric_limits::min); // TODO? sometimes L is vec3(0), find cause + pdf = 1.f / solidAngle; + } + else + pdf = bit_cast(numeric_limits::infinity); + + newRayMaxT = hlsl::dot(N, origin2origin) / hlsl::dot(N, L); + return L; + } + + Shape rect; +}; + +// PPM_APPROX_PROJECTED_SOLID_ANGLE not available for PST_TRIANGLE + + +template +struct Estimator; + +template +struct Estimator +{ + using scalar_type = typename Ray::scalar_type; + using vector3_type = vector; + using ray_type = Ray; + using scene_type = Scene; + using light_type = typename Scene::light_type; + using spectral_type = typename light_type::spectral_type; + using interaction_type = Aniso; + using quotient_pdf_type = sampling::quotient_and_pdf; + using sample_type = LightSample; + using ray_dir_info_type = typename sample_type::ray_dir_info_type; + + // affected by https://github.com/microsoft/DirectXShaderCompiler/issues/7007 + // NBL_CONSTEXPR_STATIC_INLINE PTPolygonMethod PolygonMethod = PPM; + enum : uint16_t { PolygonMethod = PPM }; + + static spectral_type deferredEvalAndPdf(NBL_REF_ARG(scalar_type) pdf, NBL_CONST_REF_ARG(scene_type) scene, uint32_t lightID, NBL_CONST_REF_ARG(ray_type) ray) + { + pdf = 1.0 / scene.lightCount; + const light_type light = scene.lights[lightID]; + const Shape sphere = scene.spheres[light.objectID.id]; + const ShapeSampling sampling = ShapeSampling::create(sphere); + pdf *= sampling.template deferredPdf(ray); + + return light.radiance; + } + + static sample_type generate_and_quotient_and_pdf(NBL_REF_ARG(quotient_pdf_type) quotient_pdf, NBL_REF_ARG(scalar_type) newRayMaxT, NBL_CONST_REF_ARG(scene_type) scene, uint32_t lightID, NBL_CONST_REF_ARG(vector3_type) origin, NBL_CONST_REF_ARG(interaction_type) interaction, bool isBSDF, NBL_CONST_REF_ARG(vector3_type) xi, uint32_t depth) + { + const light_type light = scene.lights[lightID]; + const Shape sphere = scene.spheres[light.objectID.id]; + const ShapeSampling sampling = ShapeSampling::create(sphere); + + scalar_type pdf; + const vector3_type sampleL = sampling.template generate_and_pdf(pdf, newRayMaxT, origin, interaction, isBSDF, xi); + const vector3_type V = interaction.isotropic.V.getDirection(); + const scalar_type VdotL = nbl::hlsl::dot(V, sampleL); + ray_dir_info_type rayL; + rayL.direction = sampleL; + sample_type L = sample_type::create(rayL,VdotL,interaction.T,interaction.B,interaction.isotropic.N); + + newRayMaxT *= Tolerance::getEnd(depth); + pdf *= 1.0 / scalar_type(scene.lightCount); + spectral_type quo = light.radiance / pdf; + quotient_pdf = quotient_pdf_type::create(quo, pdf); + + return L; + } +}; + +template +struct Estimator +{ + using scalar_type = typename Ray::scalar_type; + using vector3_type = vector; + using ray_type = Ray; + using scene_type = Scene; + using light_type = typename Scene::light_type; + using spectral_type = typename light_type::spectral_type; + using interaction_type = Aniso; + using quotient_pdf_type = sampling::quotient_and_pdf; + using sample_type = LightSample; + using ray_dir_info_type = typename sample_type::ray_dir_info_type; + + // NBL_CONSTEXPR_STATIC_INLINE PTPolygonMethod PolygonMethod = PPM; + enum : uint16_t { PolygonMethod = PPM }; + + static spectral_type deferredEvalAndPdf(NBL_REF_ARG(scalar_type) pdf, NBL_CONST_REF_ARG(scene_type) scene, uint32_t lightID, NBL_CONST_REF_ARG(ray_type) ray) + { + pdf = 1.0 / scene.lightCount; + const light_type light = scene.lights[lightID]; + const Shape tri = scene.triangles[light.objectID.id]; + const ShapeSampling sampling = ShapeSampling::create(tri); + pdf *= sampling.template deferredPdf(ray); + + return light.radiance; + } + + static sample_type generate_and_quotient_and_pdf(NBL_REF_ARG(quotient_pdf_type) quotient_pdf, NBL_REF_ARG(scalar_type) newRayMaxT, NBL_CONST_REF_ARG(scene_type) scene, uint32_t lightID, NBL_CONST_REF_ARG(vector3_type) origin, NBL_CONST_REF_ARG(interaction_type) interaction, bool isBSDF, NBL_CONST_REF_ARG(vector3_type) xi, uint32_t depth) + { + const light_type light = scene.lights[lightID]; + const Shape tri = scene.triangles[light.objectID.id]; + const ShapeSampling sampling = ShapeSampling::create(tri); + + scalar_type pdf; + const vector3_type sampleL = sampling.template generate_and_pdf(pdf, newRayMaxT, origin, interaction, isBSDF, xi); + const vector3_type V = interaction.isotropic.V.getDirection(); + const scalar_type VdotL = nbl::hlsl::dot(V, sampleL); + ray_dir_info_type rayL; + rayL.direction = sampleL; + sample_type L = sample_type::create(rayL,VdotL,interaction.T,interaction.B,interaction.isotropic.N); + + newRayMaxT *= Tolerance::getEnd(depth); + pdf *= 1.0 / scalar_type(scene.lightCount); + spectral_type quo = light.radiance / pdf; + quotient_pdf = quotient_pdf_type::create(quo, pdf); + + return L; + } +}; + +template +struct Estimator +{ + using scalar_type = typename Ray::scalar_type; + using vector3_type = vector; + using ray_type = Ray; + using scene_type = Scene; + using light_type = typename Scene::light_type; + using spectral_type = typename light_type::spectral_type; + using interaction_type = Aniso; + using quotient_pdf_type = sampling::quotient_and_pdf; + using sample_type = LightSample; + using ray_dir_info_type = typename sample_type::ray_dir_info_type; + + // NBL_CONSTEXPR_STATIC_INLINE PTPolygonMethod PolygonMethod = PPM; + enum : uint16_t { PolygonMethod = PPM }; + + static spectral_type deferredEvalAndPdf(NBL_REF_ARG(scalar_type) pdf, NBL_CONST_REF_ARG(scene_type) scene, uint32_t lightID, NBL_CONST_REF_ARG(ray_type) ray) + { + pdf = 1.0 / scene.lightCount; + const light_type light = scene.lights[lightID]; + const Shape rect = scene.rectangles[light.objectID.id]; + const ShapeSampling sampling = ShapeSampling::create(rect); + pdf *= sampling.template deferredPdf(ray); + + return light.radiance; + } + + static sample_type generate_and_quotient_and_pdf(NBL_REF_ARG(quotient_pdf_type) quotient_pdf, NBL_REF_ARG(scalar_type) newRayMaxT, NBL_CONST_REF_ARG(scene_type) scene, uint32_t lightID, NBL_CONST_REF_ARG(vector3_type) origin, NBL_CONST_REF_ARG(interaction_type) interaction, bool isBSDF, NBL_CONST_REF_ARG(vector3_type) xi, uint32_t depth) + { + const light_type light = scene.lights[lightID]; + const Shape rect = scene.rectangles[light.objectID.id]; + const ShapeSampling sampling = ShapeSampling::create(rect); + + scalar_type pdf; + const vector3_type sampleL = sampling.template generate_and_pdf(pdf, newRayMaxT, origin, interaction, isBSDF, xi); + const vector3_type V = interaction.isotropic.V.getDirection(); + const scalar_type VdotL = nbl::hlsl::dot(V, sampleL); + ray_dir_info_type rayL; + rayL.direction = sampleL; + sample_type L = sample_type::create(rayL,VdotL,interaction.T,interaction.B,interaction.isotropic.N); + + newRayMaxT *= Tolerance::getEnd(depth); + pdf *= 1.0 / scalar_type(scene.lightCount); + spectral_type quo = light.radiance / pdf; + quotient_pdf = quotient_pdf_type::create(quo, pdf); + + return L; + } +}; + +} +} +} +} + +#endif diff --git a/31_HLSLPathTracer/app_resources/hlsl/pathtracer.hlsl b/31_HLSLPathTracer/app_resources/hlsl/pathtracer.hlsl new file mode 100644 index 000000000..add1eb8a9 --- /dev/null +++ b/31_HLSLPathTracer/app_resources/hlsl/pathtracer.hlsl @@ -0,0 +1,320 @@ +#ifndef _NBL_HLSL_EXT_PATHTRACER_INCLUDED_ +#define _NBL_HLSL_EXT_PATHTRACER_INCLUDED_ + +#include +#include +#include +#include + +#include "rand_gen.hlsl" +#include "ray_gen.hlsl" +#include "intersector.hlsl" +#include "material_system.hlsl" +#include "next_event_estimator.hlsl" +#include "scene.hlsl" + +namespace nbl +{ +namespace hlsl +{ +namespace ext +{ +namespace PathTracer +{ + +template +struct PathTracerCreationParams +{ + // rng gen + uint32_t2 rngState; + + // ray gen + vector pixOffsetParam; + vector camPos; + vector NDC; + matrix invMVP; + + // mat + BxDFCreation diffuseParams; + BxDFCreation conductorParams; + BxDFCreation dielectricParams; +}; + +template +struct Unidirectional +{ + using this_t = Unidirectional; + using randgen_type = RandGen; + using raygen_type = RayGen; + using intersector_type = Intersector; + using material_system_type = MaterialSystem; + using nee_type = NextEventEstimator; + + using scalar_type = typename MaterialSystem::scalar_type; + using vector3_type = vector; + using measure_type = typename MaterialSystem::measure_type; + using sample_type = typename NextEventEstimator::sample_type; + using ray_dir_info_type = typename sample_type::ray_dir_info_type; + using ray_type = typename RayGen::ray_type; + using light_type = Light; + using bxdfnode_type = BxDFNode; + using anisotropic_interaction_type = typename MaterialSystem::anisotropic_interaction_type; + using isotropic_interaction_type = typename anisotropic_interaction_type::isotropic_interaction_type; + using anisocache_type = typename MaterialSystem::anisocache_type; + using isocache_type = typename anisocache_type::isocache_type; + using quotient_pdf_type = typename NextEventEstimator::quotient_pdf_type; + using params_type = typename MaterialSystem::params_t; + using create_params_type = typename MaterialSystem::create_params_t; + using scene_type = Scene; + + using diffuse_op_type = typename MaterialSystem::diffuse_op_type; + using conductor_op_type = typename MaterialSystem::conductor_op_type; + using dielectric_op_type = typename MaterialSystem::dielectric_op_type; + + static this_t create(NBL_CONST_REF_ARG(PathTracerCreationParams) params) + { + this_t retval; + retval.randGen = randgen_type::create(params.rngState); + retval.rayGen = raygen_type::create(params.pixOffsetParam, params.camPos, params.NDC, params.invMVP); + retval.materialSystem = material_system_type::create(params.diffuseParams, params.conductorParams, params.dielectricParams); + return retval; + } + + vector3_type rand3d(uint32_t protoDimension, uint32_t _sample, uint32_t i) + { + uint32_t address = glsl::bitfieldInsert(protoDimension, _sample, MAX_DEPTH_LOG2, MAX_SAMPLES_LOG2); + uint32_t3 seqVal = sampleSequence[address + i].xyz; + seqVal ^= randGen(); + return vector3_type(seqVal) * bit_cast(0x2f800004u); + } + + scalar_type getLuma(NBL_CONST_REF_ARG(vector3_type) col) + { + return hlsl::dot(hlsl::transpose(colorspace::scRGBtoXYZ)[1], col); + } + + // TODO: probably will only work with procedural shapes, do the other ones + bool closestHitProgram(uint32_t depth, uint32_t _sample, NBL_REF_ARG(ray_type) ray, NBL_CONST_REF_ARG(scene_type) scene) + { + const ObjectID objectID = ray.objectID; + const vector3_type intersection = ray.origin + ray.direction * ray.intersectionT; + + uint32_t bsdfLightIDs; + anisotropic_interaction_type interaction; + isotropic_interaction_type iso_interaction; + uint32_t mode = objectID.mode; + switch (mode) + { + // TODO + case IM_RAY_QUERY: + case IM_RAY_TRACING: + break; + case IM_PROCEDURAL: + { + bsdfLightIDs = scene.getBsdfLightIDs(objectID); + vector3_type N = scene.getNormal(objectID, intersection); + N = nbl::hlsl::normalize(N); + ray_dir_info_type V; + V.direction = -ray.direction; + isotropic_interaction_type iso_interaction = isotropic_interaction_type::create(V, N); + interaction = anisotropic_interaction_type::create(iso_interaction); + } + break; + default: + break; + } + + vector3_type throughput = ray.payload.throughput; + + // emissive + const uint32_t lightID = glsl::bitfieldExtract(bsdfLightIDs, 16, 16); + if (lightID != light_type::INVALID_ID) + { + float _pdf; + ray.payload.accumulation += nee.deferredEvalAndPdf(_pdf, scene, lightID, ray) * throughput / (1.0 + _pdf * _pdf * ray.payload.otherTechniqueHeuristic); + } + + const uint32_t bsdfID = glsl::bitfieldExtract(bsdfLightIDs, 0, 16); + if (bsdfID == bxdfnode_type::INVALID_ID) + return false; + + bxdfnode_type bxdf = scene.bxdfs[bsdfID]; + + // TODO: ifdef kill diffuse specular paths + + const bool isBSDF = (bxdf.materialType == ext::MaterialSystem::MaterialType::DIFFUSE) ? bxdf::traits::type == bxdf::BT_BSDF : + (bxdf.materialType == ext::MaterialSystem::MaterialType::CONDUCTOR) ? bxdf::traits::type == bxdf::BT_BSDF : + bxdf::traits::type == bxdf::BT_BSDF; + + vector3_type eps0 = rand3d(depth, _sample, 0u); + vector3_type eps1 = rand3d(depth, _sample, 1u); + + // thresholds + const scalar_type bxdfPdfThreshold = 0.0001; + const scalar_type lumaContributionThreshold = getLuma(colorspace::eotf::sRGB((vector3_type)1.0 / 255.0)); // OETF smallest perceptible value + const vector3_type throughputCIE_Y = hlsl::transpose(colorspace::sRGBtoXYZ)[1] * throughput; // TODO: this only works if spectral_type is dim 3 + const measure_type eta = bxdf.params.ior0 / bxdf.params.ior1; // assume it's real, not imaginary? + const scalar_type monochromeEta = hlsl::dot(throughputCIE_Y, eta) / (throughputCIE_Y.r + throughputCIE_Y.g + throughputCIE_Y.b); // TODO: imaginary eta? + + // sample lights + const scalar_type neeProbability = 1.0; // BSDFNode_getNEEProb(bsdf); + scalar_type rcpChoiceProb; + if (!math::partitionRandVariable(neeProbability, eps0.z, rcpChoiceProb) && depth < 2u) + { + uint32_t randLightID = uint32_t(float32_t(randGen().x) / numeric_limits::max) * scene.lightCount; + quotient_pdf_type neeContrib_pdf; + scalar_type t; + sample_type nee_sample = nee.generate_and_quotient_and_pdf( + neeContrib_pdf, t, + scene, randLightID, intersection, interaction, + isBSDF, eps0, depth + ); + + // We don't allow non watertight transmitters in this renderer + bool validPath = nee_sample.getNdotL() > numeric_limits::min; + // but if we allowed non-watertight transmitters (single water surface), it would make sense just to apply this line by itself + bxdf::fresnel::OrientedEtas orientedEta = bxdf::fresnel::OrientedEtas::create(interaction.getNdotV(), monochromeEta); + anisocache_type _cache = anisocache_type::template create(interaction, nee_sample, orientedEta); + validPath = validPath && _cache.getNdotH() >= 0.0; + bxdf.params.eta = monochromeEta; + + if (neeContrib_pdf.pdf < numeric_limits::max) + { + if (nbl::hlsl::any(isnan(nee_sample.getL().getDirection()))) + ray.payload.accumulation += vector3_type(1000.f, 0.f, 0.f); + else if (nbl::hlsl::all((vector3_type)69.f == nee_sample.getL().getDirection())) + ray.payload.accumulation += vector3_type(0.f, 1000.f, 0.f); + else if (validPath) + { + bxdf::BxDFClampMode _clamp; + _clamp = (bxdf.materialType == ext::MaterialSystem::MaterialType::DIELECTRIC) ? bxdf::BxDFClampMode::BCM_ABS : bxdf::BxDFClampMode::BCM_MAX; + // example only uses isotropic bxdfs + params_type params = params_type::create(nee_sample, interaction.isotropic, _cache.iso_cache, _clamp); + + quotient_pdf_type bsdf_quotient_pdf = materialSystem.quotient_and_pdf(bxdf.materialType, bxdf.params, params); + neeContrib_pdf.quotient *= bxdf.albedo * throughput * bsdf_quotient_pdf.quotient; + const scalar_type otherGenOverChoice = bsdf_quotient_pdf.pdf * rcpChoiceProb; + const scalar_type otherGenOverLightAndChoice = otherGenOverChoice / bsdf_quotient_pdf.pdf; + neeContrib_pdf.quotient *= otherGenOverChoice / (1.f + otherGenOverLightAndChoice * otherGenOverLightAndChoice); // balance heuristic + + // TODO: ifdef NEE only + // neeContrib_pdf.quotient *= otherGenOverChoice; + + ray_type nee_ray; + nee_ray.origin = intersection + nee_sample.getL().getDirection() * t * Tolerance::getStart(depth); + nee_ray.direction = nee_sample.getL().getDirection(); + nee_ray.intersectionT = t; + if (bsdf_quotient_pdf.pdf < numeric_limits::max && getLuma(neeContrib_pdf.quotient) > lumaContributionThreshold && intersector_type::traceRay(nee_ray, scene).id == -1) + ray.payload.accumulation += neeContrib_pdf.quotient; + } + } + } + + // return false; // NEE only + + // sample BSDF + scalar_type bxdfPdf; + vector3_type bxdfSample; + { + anisocache_type _cache; + sample_type bsdf_sample = materialSystem.generate(bxdf.materialType, bxdf.params, interaction, eps1, _cache); + + bxdf::BxDFClampMode _clamp; + _clamp = (bxdf.materialType == ext::MaterialSystem::MaterialType::DIELECTRIC) ? bxdf::BxDFClampMode::BCM_ABS : bxdf::BxDFClampMode::BCM_MAX; + // example only uses isotropic bxdfs + params_type params = params_type::create(bsdf_sample, interaction.isotropic, _cache.iso_cache, _clamp); + + // the value of the bsdf divided by the probability of the sample being generated + quotient_pdf_type bsdf_quotient_pdf = materialSystem.quotient_and_pdf(bxdf.materialType, bxdf.params, params); + throughput *= bxdf.albedo * bsdf_quotient_pdf.quotient; + bxdfPdf = bsdf_quotient_pdf.pdf; + bxdfSample = bsdf_sample.getL().getDirection(); + } + + // additional threshold + const float lumaThroughputThreshold = lumaContributionThreshold; + if (bxdfPdf > bxdfPdfThreshold && getLuma(throughput) > lumaThroughputThreshold) + { + ray.payload.throughput = throughput; + scalar_type otherTechniqueHeuristic = neeProbability / bxdfPdf; // numerically stable, don't touch + ray.payload.otherTechniqueHeuristic = otherTechniqueHeuristic * otherTechniqueHeuristic; + + // trace new ray + ray.origin = intersection + bxdfSample * (1.0/*kSceneSize*/) * Tolerance::getStart(depth); + ray.direction = bxdfSample; + if ((PTPolygonMethod)nee_type::PolygonMethod == PPM_APPROX_PROJECTED_SOLID_ANGLE) + { + ray.normalAtOrigin = interaction.getN(); + ray.wasBSDFAtOrigin = isBSDF; + } + return true; + } + + return false; + } + + void missProgram(NBL_REF_ARG(ray_type) ray) + { + vector3_type finalContribution = ray.payload.throughput; + // #ifdef USE_ENVMAP + // vec2 uv = SampleSphericalMap(_immutable.direction); + // finalContribution *= textureLod(envMap, uv, 0.0).rgb; + // #else + const vector3_type kConstantEnvLightRadiance = vector3_type(0.15, 0.21, 0.3); // TODO: match spectral_type + finalContribution *= kConstantEnvLightRadiance; + ray.payload.accumulation += finalContribution; + // #endif + } + + // Li + measure_type getMeasure(uint32_t numSamples, uint32_t depth, NBL_CONST_REF_ARG(scene_type) scene) + { + measure_type Li = (measure_type)0.0; + scalar_type meanLumaSq = 0.0; + for (uint32_t i = 0; i < numSamples; i++) + { + vector3_type uvw = rand3d(0u, i, randGen.rng()); // TODO: take from scramblebuf? + ray_type ray = rayGen.generate(uvw); + + // bounces + bool hit = true; + bool rayAlive = true; + for (int d = 1; (d <= depth) && hit && rayAlive; d += 2) + { + ray.intersectionT = numeric_limits::max; + ray.objectID = intersector_type::traceRay(ray, scene); + + hit = ray.objectID.id != -1; + if (hit) + rayAlive = closestHitProgram(1, i, ray, scene); + } + if (!hit) + missProgram(ray); + + measure_type accumulation = ray.payload.accumulation; + scalar_type rcpSampleSize = 1.0 / (i + 1); + Li += (accumulation - Li) * rcpSampleSize; + + // TODO: visualize high variance + + // TODO: russian roulette early exit? + } + + return Li; + } + + NBL_CONSTEXPR_STATIC_INLINE uint32_t MAX_DEPTH_LOG2 = 4u; + NBL_CONSTEXPR_STATIC_INLINE uint32_t MAX_SAMPLES_LOG2 = 10u; + + randgen_type randGen; + raygen_type rayGen; + material_system_type materialSystem; + nee_type nee; +}; + +} +} +} +} + +#endif diff --git a/31_HLSLPathTracer/app_resources/hlsl/present.frag.hlsl b/31_HLSLPathTracer/app_resources/hlsl/present.frag.hlsl new file mode 100644 index 000000000..22695657c --- /dev/null +++ b/31_HLSLPathTracer/app_resources/hlsl/present.frag.hlsl @@ -0,0 +1,19 @@ +// Copyright (C) 2024-2024 - DevSH Graphics Programming Sp. z O.O. +// This file is part of the "Nabla Engine". +// For conditions of distribution and use, see copyright notice in nabla.h + +#pragma wave shader_stage(fragment) + +// vertex shader is provided by the fullScreenTriangle extension +#include +using namespace nbl::hlsl; +using namespace ext::FullScreenTriangle; + +// binding 0 set 0 +[[vk::combinedImageSampler]] [[vk::binding(0, 0)]] Texture2D texture; +[[vk::combinedImageSampler]] [[vk::binding(0, 0)]] SamplerState samplerState; + +[[vk::location(0)]] float32_t4 main(SVertexAttributes vxAttr) : SV_Target0 +{ + return float32_t4(texture.Sample(samplerState, vxAttr.uv).rgb, 1.0f); +} \ No newline at end of file diff --git a/31_HLSLPathTracer/app_resources/hlsl/rand_gen.hlsl b/31_HLSLPathTracer/app_resources/hlsl/rand_gen.hlsl new file mode 100644 index 000000000..4f5302fea --- /dev/null +++ b/31_HLSLPathTracer/app_resources/hlsl/rand_gen.hlsl @@ -0,0 +1,38 @@ +#ifndef _NBL_HLSL_EXT_RANDGEN_INCLUDED_ +#define _NBL_HLSL_EXT_RANDGEN_INCLUDED_ + +namespace nbl +{ +namespace hlsl +{ +namespace ext +{ +namespace RandGen +{ + +template +struct Uniform3D +{ + using rng_type = RNG; + + static Uniform3D create(uint32_t2 seed) + { + Uniform3D retval; + retval.rng = rng_type::construct(seed); + return retval; + } + + uint32_t3 operator()() + { + return uint32_t3(rng(), rng(), rng()); + } + + rng_type rng; +}; + +} +} +} +} + +#endif diff --git a/31_HLSLPathTracer/app_resources/hlsl/ray_gen.hlsl b/31_HLSLPathTracer/app_resources/hlsl/ray_gen.hlsl new file mode 100644 index 000000000..0759b1cd3 --- /dev/null +++ b/31_HLSLPathTracer/app_resources/hlsl/ray_gen.hlsl @@ -0,0 +1,82 @@ +#ifndef _NBL_HLSL_EXT_RAYGEN_INCLUDED_ +#define _NBL_HLSL_EXT_RAYGEN_INCLUDED_ + +#include + +#include "common.hlsl" + +namespace nbl +{ +namespace hlsl +{ +namespace ext +{ +namespace RayGen +{ + +template +struct Basic +{ + using this_t = Basic; + using ray_type = Ray; + using scalar_type = typename Ray::scalar_type; + using vector3_type = typename Ray::vector3_type; + + using vector2_type = vector; + using vector4_type = vector; + using matrix4x4_type = matrix; + + static this_t create(NBL_CONST_REF_ARG(vector2_type) pixOffsetParam, NBL_CONST_REF_ARG(vector3_type) camPos, NBL_CONST_REF_ARG(vector4_type) NDC, NBL_CONST_REF_ARG(matrix4x4_type) invMVP) + { + this_t retval; + retval.pixOffsetParam = pixOffsetParam; + retval.camPos = camPos; + retval.NDC = NDC; + retval.invMVP = invMVP; + return retval; + } + + ray_type generate(NBL_CONST_REF_ARG(vector3_type) randVec) + { + ray_type ray; + ray.origin = camPos; + + vector4_type tmp = NDC; + // apply stochastic reconstruction filter + const float gaussianFilterCutoff = 2.5; + const float truncation = nbl::hlsl::exp(-0.5 * gaussianFilterCutoff * gaussianFilterCutoff); + vector2_type remappedRand = randVec.xy; + remappedRand.x *= 1.0 - truncation; + remappedRand.x += truncation; + tmp.xy += pixOffsetParam * nbl::hlsl::boxMullerTransform(remappedRand, 1.5); + // for depth of field we could do another stochastic point-pick + tmp = nbl::hlsl::mul(invMVP, tmp); + ray.direction = nbl::hlsl::normalize(tmp.xyz / tmp.w - camPos); + + // #if POLYGON_METHOD==2 + // ray._immutable.normalAtOrigin = vec3(0.0,0.0,0.0); + // ray._immutable.wasBSDFAtOrigin = false; + // #endif + + ray.payload.accumulation = (vector3_type)0.0; + ray.payload.otherTechniqueHeuristic = 0.0; // needed for direct eye-light paths + ray.payload.throughput = (vector3_type)1.0; + // #ifdef KILL_DIFFUSE_SPECULAR_PATHS + // ray._payload.hasDiffuse = false; + // #endif + + return ray; + } + + vector2_type pixOffsetParam; + vector3_type camPos; + vector4_type NDC; + matrix4x4_type invMVP; +}; + +} +} +} +} + +#endif diff --git a/31_HLSLPathTracer/app_resources/hlsl/render.comp.hlsl b/31_HLSLPathTracer/app_resources/hlsl/render.comp.hlsl new file mode 100644 index 000000000..a40eb3dd0 --- /dev/null +++ b/31_HLSLPathTracer/app_resources/hlsl/render.comp.hlsl @@ -0,0 +1,226 @@ +#include "nbl/builtin/hlsl/cpp_compat.hlsl" +#include "nbl/builtin/hlsl/glsl_compat/core.hlsl" +#include "nbl/builtin/hlsl/random/pcg.hlsl" +#include "nbl/builtin/hlsl/random/xoroshiro.hlsl" +#ifdef PERSISTENT_WORKGROUPS +#include "nbl/builtin/hlsl/math/morton.hlsl" +#endif + +#include "nbl/builtin/hlsl/bxdf/reflection.hlsl" +#include "nbl/builtin/hlsl/bxdf/transmission.hlsl" + +// add these defines (one at a time) using -D argument to dxc +// #define SPHERE_LIGHT +// #define TRIANGLE_LIGHT +// #define RECTANGLE_LIGHT + +#ifdef SPHERE_LIGHT +#define SPHERE_COUNT 9 +#define TRIANGLE_COUNT 0 +#define RECTANGLE_COUNT 0 +#endif + +#ifdef TRIANGLE_LIGHT +#define TRIANGLE_COUNT 1 +#define SPHERE_COUNT 8 +#define RECTANGLE_COUNT 0 +#endif + +#ifdef RECTANGLE_LIGHT +#define RECTANGLE_COUNT 1 +#define SPHERE_COUNT 8 +#define TRIANGLE_COUNT 0 +#endif + +#define LIGHT_COUNT 1 +#define BXDF_COUNT 7 + +#include "render_common.hlsl" +#include "pathtracer.hlsl" + +using namespace nbl; +using namespace hlsl; + +NBL_CONSTEXPR uint32_t WorkgroupSize = 512; +NBL_CONSTEXPR uint32_t MAX_DEPTH_LOG2 = 4; +NBL_CONSTEXPR uint32_t MAX_SAMPLES_LOG2 = 10; + +#ifdef SPHERE_LIGHT +NBL_CONSTEXPR ext::ProceduralShapeType LIGHT_TYPE = ext::PST_SPHERE; +#endif +#ifdef TRIANGLE_LIGHT +NBL_CONSTEXPR ext::ProceduralShapeType LIGHT_TYPE = ext::PST_TRIANGLE; +#endif +#ifdef RECTANGLE_LIGHT +NBL_CONSTEXPR ext::ProceduralShapeType LIGHT_TYPE = ext::PST_RECTANGLE; +#endif + +NBL_CONSTEXPR ext::PTPolygonMethod POLYGON_METHOD = ext::PPM_SOLID_ANGLE; + +int32_t2 getCoordinates() +{ + uint32_t width, height; + outImage.GetDimensions(width, height); + return int32_t2(glsl::gl_GlobalInvocationID().x % width, glsl::gl_GlobalInvocationID().x / width); +} + +float32_t2 getTexCoords() +{ + uint32_t width, height; + outImage.GetDimensions(width, height); + int32_t2 iCoords = getCoordinates(); + return float32_t2(float(iCoords.x) / width, 1.0 - float(iCoords.y) / height); +} + +using ray_dir_info_t = bxdf::ray_dir_info::SBasic; +using iso_interaction = bxdf::surface_interactions::SIsotropic; +using aniso_interaction = bxdf::surface_interactions::SAnisotropic; +using sample_t = bxdf::SLightSample; +using iso_cache = bxdf::SIsotropicMicrofacetCache; +using aniso_cache = bxdf::SAnisotropicMicrofacetCache; +using quotient_pdf_t = sampling::quotient_and_pdf; +using spectral_t = vector; +using create_params_t = bxdf::SBxDFCreationParams; + +using diffuse_bxdf_type = bxdf::reflection::SOrenNayarBxDF; +using conductor_bxdf_type = bxdf::reflection::SGGXBxDF; +using dielectric_bxdf_type = bxdf::transmission::SGGXDielectricBxDF; + +using ray_type = ext::Ray; +using light_type = ext::Light; +using bxdfnode_type = ext::BxDFNode; +using scene_type = ext::Scene; +using randgen_type = ext::RandGen::Uniform3D; +using raygen_type = ext::RayGen::Basic; +using intersector_type = ext::Intersector::Comprehensive; +using material_system_type = ext::MaterialSystem::System; +using nee_type = ext::NextEventEstimator::Estimator; +using pathtracer_type = ext::PathTracer::Unidirectional; + +static const ext::Shape spheres[SPHERE_COUNT] = { + ext::Shape::create(float3(0.0, -100.5, -1.0), 100.0, 0u, light_type::INVALID_ID), + ext::Shape::create(float3(2.0, 0.0, -1.0), 0.5, 1u, light_type::INVALID_ID), + ext::Shape::create(float3(0.0, 0.0, -1.0), 0.5, 2u, light_type::INVALID_ID), + ext::Shape::create(float3(-2.0, 0.0, -1.0), 0.5, 3u, light_type::INVALID_ID), + ext::Shape::create(float3(2.0, 0.0, 1.0), 0.5, 4u, light_type::INVALID_ID), + ext::Shape::create(float3(0.0, 0.0, 1.0), 0.5, 4u, light_type::INVALID_ID), + ext::Shape::create(float3(-2.0, 0.0, 1.0), 0.5, 5u, light_type::INVALID_ID), + ext::Shape::create(float3(0.5, 1.0, 0.5), 0.5, 6u, light_type::INVALID_ID) +#ifdef SPHERE_LIGHT + ,ext::Shape::create(float3(-1.5, 1.5, 0.0), 0.3, bxdfnode_type::INVALID_ID, 0u) +#endif +}; + +#ifdef TRIANGLE_LIGHT +static const ext::Shape triangles[TRIANGLE_COUNT] = { + ext::Shape::create(float3(-1.8,0.35,0.3) * 10.0, float3(-1.2,0.35,0.0) * 10.0, float3(-1.5,0.8,-0.3) * 10.0, bxdfnode_type::INVALID_ID, 0u) +}; +#else +static const ext::Shape triangles[1]; +#endif + +#ifdef RECTANGLE_LIGHT +static const ext::Shape rectangles[RECTANGLE_COUNT] = { + ext::Shape::create(float3(-3.8,0.35,1.3), normalize(float3(2,0,-1))*7.0, normalize(float3(2,-5,4))*0.1, bxdfnode_type::INVALID_ID, 0u) +}; +#else +static const ext::Shape rectangles[1]; +#endif + +static const light_type lights[LIGHT_COUNT] = { + light_type::create(spectral_t(30.0,25.0,15.0), +#ifdef SPHERE_LIGHT + 8u, +#else + 0u, +#endif + ext::IntersectMode::IM_PROCEDURAL, LIGHT_TYPE) +}; + +static const bxdfnode_type bxdfs[BXDF_COUNT] = { + bxdfnode_type::create(ext::MaterialSystem::MaterialType::DIFFUSE, false, float2(0,0), spectral_t(0.8,0.8,0.8)), + bxdfnode_type::create(ext::MaterialSystem::MaterialType::DIFFUSE, false, float2(0,0), spectral_t(0.8,0.4,0.4)), + bxdfnode_type::create(ext::MaterialSystem::MaterialType::DIFFUSE, false, float2(0,0), spectral_t(0.4,0.8,0.4)), + bxdfnode_type::create(ext::MaterialSystem::MaterialType::CONDUCTOR, false, float2(0,0), spectral_t(1.02,1.02,1.3), spectral_t(1.0,1.0,2.0)), + bxdfnode_type::create(ext::MaterialSystem::MaterialType::CONDUCTOR, false, float2(0,0), spectral_t(1.02,1.3,1.02), spectral_t(1.0,2.0,1.0)), + bxdfnode_type::create(ext::MaterialSystem::MaterialType::CONDUCTOR, false, float2(0.15,0.15), spectral_t(1.02,1.3,1.02), spectral_t(1.0,2.0,1.0)), + bxdfnode_type::create(ext::MaterialSystem::MaterialType::DIELECTRIC, false, float2(0.0625,0.0625), spectral_t(1,1,1), spectral_t(0.71,0.69,0.67)) +}; + +static const ext::Scene scene = ext::Scene::create( + spheres, triangles, rectangles, + SPHERE_COUNT, TRIANGLE_COUNT, RECTANGLE_COUNT, + lights, LIGHT_COUNT, bxdfs, BXDF_COUNT +); + +[numthreads(WorkgroupSize, 1, 1)] +void main(uint32_t3 threadID : SV_DispatchThreadID) +{ + uint32_t width, height; + outImage.GetDimensions(width, height); +#ifdef PERSISTENT_WORKGROUPS + uint32_t virtualThreadIndex; + [loop] + for (uint32_t virtualThreadBase = glsl::gl_WorkGroupID().x * WorkgroupSize; virtualThreadBase < 1920*1080; virtualThreadBase += glsl::gl_NumWorkGroups().x * WorkgroupSize) // not sure why 1280*720 doesn't cover draw surface + { + virtualThreadIndex = virtualThreadBase + glsl::gl_LocalInvocationIndex().x; + const int32_t2 coords = (int32_t2)math::Morton::decode2d(virtualThreadIndex); +#else + const int32_t2 coords = getCoordinates(); +#endif + float32_t2 texCoord = float32_t2(coords) / float32_t2(width, height); + texCoord.y = 1.0 - texCoord.y; + + if (false == (all((int32_t2)0 < coords)) && all(int32_t2(width, height) < coords)) { +#ifdef PERSISTENT_WORKGROUPS + continue; +#else + return; +#endif + } + + if (((pc.depth - 1) >> MAX_DEPTH_LOG2) > 0 || ((pc.sampleCount - 1) >> MAX_SAMPLES_LOG2) > 0) + { + float32_t4 pixelCol = float32_t4(1.0,0.0,0.0,1.0); + outImage[coords] = pixelCol; +#ifdef PERSISTENT_WORKGROUPS + continue; +#else + return; +#endif + } + + int flatIdx = glsl::gl_GlobalInvocationID().y * glsl::gl_NumWorkGroups().x * WorkgroupSize + glsl::gl_GlobalInvocationID().x; + + // set up path tracer + ext::PathTracer::PathTracerCreationParams ptCreateParams; + ptCreateParams.rngState = scramblebuf[coords].rg; + + uint2 scrambleDim; + scramblebuf.GetDimensions(scrambleDim.x, scrambleDim.y); + ptCreateParams.pixOffsetParam = (float2)1.0 / float2(scrambleDim); + + float4 NDC = float4(texCoord * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); + { + float4 tmp = mul(pc.invMVP, NDC); + ptCreateParams.camPos = tmp.xyz / tmp.w; + NDC.z = 1.0; + } + + ptCreateParams.NDC = NDC; + ptCreateParams.invMVP = pc.invMVP; + + ptCreateParams.diffuseParams = bxdfs[0].params; + ptCreateParams.conductorParams = bxdfs[3].params; + ptCreateParams.dielectricParams = bxdfs[6].params; + + pathtracer_type pathtracer = pathtracer_type::create(ptCreateParams); + + float32_t3 color = pathtracer.getMeasure(pc.sampleCount, pc.depth, scene); + float32_t4 pixCol = float32_t4(color, 1.0); + outImage[coords] = pixCol; + +#ifdef PERSISTENT_WORKGROUPS + } +#endif +} diff --git a/31_HLSLPathTracer/app_resources/hlsl/render_common.hlsl b/31_HLSLPathTracer/app_resources/hlsl/render_common.hlsl new file mode 100644 index 000000000..5e5cf89da --- /dev/null +++ b/31_HLSLPathTracer/app_resources/hlsl/render_common.hlsl @@ -0,0 +1,23 @@ +#ifndef _NBL_HLSL_PATHTRACER_RENDER_COMMON_INCLUDED_ +#define _NBL_HLSL_PATHTRACER_RENDER_COMMON_INCLUDED_ + +struct SPushConstants +{ + float32_t4x4 invMVP; + int sampleCount; + int depth; +}; + +[[vk::push_constant]] SPushConstants pc; + +[[vk::combinedImageSampler]][[vk::binding(0, 2)]] Texture2D envMap; // unused +[[vk::combinedImageSampler]][[vk::binding(0, 2)]] SamplerState envSampler; + +[[vk::binding(1, 2)]] Buffer sampleSequence; + +[[vk::combinedImageSampler]][[vk::binding(2, 2)]] Texture2D scramblebuf; // unused +[[vk::combinedImageSampler]][[vk::binding(2, 2)]] SamplerState scrambleSampler; + +[[vk::image_format("rgba16f")]][[vk::binding(0, 0)]] RWTexture2D outImage; + +#endif diff --git a/31_HLSLPathTracer/app_resources/hlsl/scene.hlsl b/31_HLSLPathTracer/app_resources/hlsl/scene.hlsl new file mode 100644 index 000000000..40fb01057 --- /dev/null +++ b/31_HLSLPathTracer/app_resources/hlsl/scene.hlsl @@ -0,0 +1,111 @@ +#ifndef _NBL_HLSL_EXT_PATHTRACING_SCENE_INCLUDED_ +#define _NBL_HLSL_EXT_PATHTRACING_SCENE_INCLUDED_ + +#include "common.hlsl" + +namespace nbl +{ +namespace hlsl +{ +namespace ext +{ + +template +struct Scene +{ + using light_type = Light; + using bxdfnode_type = BxdfNode; + using this_t = Scene; + + // NBL_CONSTEXPR_STATIC_INLINE uint32_t maxSphereCount = 25; + // NBL_CONSTEXPR_STATIC_INLINE uint32_t maxTriangleCount = 12; + // NBL_CONSTEXPR_STATIC_INLINE uint32_t maxRectangleCount = 12; + +#if SPHERE_COUNT < 1 +#define SCENE_SPHERE_COUNT 1 +#else +#define SCENE_SPHERE_COUNT SPHERE_COUNT +#endif + +#if TRIANGLE_COUNT < 1 +#define SCENE_TRIANGLE_COUNT 1 +#else +#define SCENE_TRIANGLE_COUNT TRIANGLE_COUNT +#endif + +#if RECTANGLE_COUNT < 1 +#define SCENE_RECTANGLE_COUNT 1 +#else +#define SCENE_RECTANGLE_COUNT RECTANGLE_COUNT +#endif + + Shape spheres[SCENE_SPHERE_COUNT]; + Shape triangles[SCENE_TRIANGLE_COUNT]; + Shape rectangles[SCENE_RECTANGLE_COUNT]; + + uint32_t sphereCount; + uint32_t triangleCount; + uint32_t rectangleCount; + + // NBL_CONSTEXPR_STATIC_INLINE uint32_t maxLightCount = 4; + + light_type lights[LIGHT_COUNT]; + uint32_t lightCount; + + // NBL_CONSTEXPR_STATIC_INLINE uint32_t maxBxdfCount = 16; + + bxdfnode_type bxdfs[BXDF_COUNT]; + uint32_t bxdfCount; + + // AS ases; + + static this_t create( + NBL_CONST_REF_ARG(Shape) spheres[SCENE_SPHERE_COUNT], + NBL_CONST_REF_ARG(Shape) triangles[SCENE_TRIANGLE_COUNT], + NBL_CONST_REF_ARG(Shape) rectangles[SCENE_RECTANGLE_COUNT], + uint32_t sphereCount, uint32_t triangleCount, uint32_t rectangleCount, + NBL_CONST_REF_ARG(light_type) lights[LIGHT_COUNT], uint32_t lightCount, + NBL_CONST_REF_ARG(bxdfnode_type) bxdfs[BXDF_COUNT], uint32_t bxdfCount) + { + this_t retval; + retval.spheres = spheres; + retval.triangles = triangles; + retval.rectangles = rectangles; + retval.sphereCount = sphereCount; + retval.triangleCount = triangleCount; + retval.rectangleCount = rectangleCount; + + retval.lights = lights; + retval.lightCount = lightCount; + + retval.bxdfs = bxdfs; + retval.bxdfCount = bxdfCount; + return retval; + } + +#undef SCENE_SPHERE_COUNT +#undef SCENE_TRIANGLE_COUNT +#undef SCENE_RECTANGLE_COUNT + + // TODO: get these to work with AS types as well + uint32_t getBsdfLightIDs(NBL_CONST_REF_ARG(ObjectID) objectID) + { + return (objectID.shapeType == PST_SPHERE) ? spheres[objectID.id].bsdfLightIDs : + (objectID.shapeType == PST_TRIANGLE) ? triangles[objectID.id].bsdfLightIDs : + (objectID.shapeType == PST_RECTANGLE) ? rectangles[objectID.id].bsdfLightIDs : -1; + } + + float32_t3 getNormal(NBL_CONST_REF_ARG(ObjectID) objectID, NBL_CONST_REF_ARG(float32_t3) intersection) + { + return (objectID.shapeType == PST_SPHERE) ? spheres[objectID.id].getNormal(intersection) : + (objectID.shapeType == PST_TRIANGLE) ? triangles[objectID.id].getNormalTimesArea() : + (objectID.shapeType == PST_RECTANGLE) ? rectangles[objectID.id].getNormalTimesArea() : + (float32_t3)0.0; + } +}; + +} +} +} + +#endif diff --git a/60_ClusteredRendering/config.json.template b/31_HLSLPathTracer/config.json.template similarity index 99% rename from 60_ClusteredRendering/config.json.template rename to 31_HLSLPathTracer/config.json.template index f961745c1..24adf54fb 100644 --- a/60_ClusteredRendering/config.json.template +++ b/31_HLSLPathTracer/config.json.template @@ -25,4 +25,4 @@ "outputs": [] } ] -} \ No newline at end of file +} diff --git a/31_HLSLPathTracer/include/nbl/this_example/common.hpp b/31_HLSLPathTracer/include/nbl/this_example/common.hpp new file mode 100644 index 000000000..db051bb3e --- /dev/null +++ b/31_HLSLPathTracer/include/nbl/this_example/common.hpp @@ -0,0 +1,17 @@ +#ifndef __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ +#define __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ + +#include + +// common api +#include "nbl/examples/common/SimpleWindowedApplication.hpp" +#include "nbl/examples/examples.hpp" +#include "nbl/examples/cameras/CCamera.hpp" +#include "nbl/examples/common/CEventCallback.hpp" + +// example's own headers +#include "nbl/ui/ICursorControl.h" +#include "nbl/ext/ImGui/ImGui.h" +#include "imgui/imgui_internal.h" + +#endif // __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ \ No newline at end of file diff --git a/31_HLSLPathTracer/main.cpp b/31_HLSLPathTracer/main.cpp new file mode 100644 index 000000000..2e139af8d --- /dev/null +++ b/31_HLSLPathTracer/main.cpp @@ -0,0 +1,1425 @@ +// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. +// This file is part of the "Nabla Engine". +// For conditions of distribution and use, see copyright notice in nabla.h + +#include "nbl/this_example/common.hpp" +#include "nbl/asset/interchange/IImageAssetHandlerBase.h" +#include "nbl/ext/FullScreenTriangle/FullScreenTriangle.h" +#include "nbl/builtin/hlsl/surface_transform.h" + +using namespace nbl; +using namespace core; +using namespace hlsl; +using namespace system; +using namespace asset; +using namespace ui; +using namespace video; +using namespace nbl::examples; + +struct PTPushConstant { + matrix4SIMD invMVP; + int sampleCount; + int depth; +}; + +// TODO: Add a QueryPool for timestamping once its ready +// TODO: Do buffer creation using assConv +class HLSLComputePathtracer final : public SimpleWindowedApplication, public BuiltinResourcesApplication +{ + using device_base_t = SimpleWindowedApplication; + using asset_base_t = BuiltinResourcesApplication; + using clock_t = std::chrono::steady_clock; + + enum E_LIGHT_GEOMETRY : uint8_t + { + ELG_SPHERE, + ELG_TRIANGLE, + ELG_RECTANGLE, + ELG_COUNT + }; + + enum E_RENDER_MODE : uint8_t + { + ERM_GLSL, + ERM_HLSL, + // ERM_CHECKERED, + ERM_COUNT + }; + + constexpr static inline uint32_t2 WindowDimensions = { 1280, 720 }; + constexpr static inline uint32_t MaxFramesInFlight = 5; + constexpr static inline clock_t::duration DisplayImageDuration = std::chrono::milliseconds(900); + constexpr static inline uint32_t DefaultWorkGroupSize = 512u; + constexpr static inline uint32_t MaxDescriptorCount = 256u; + constexpr static inline uint32_t MaxDepthLog2 = 4u; // 5 + constexpr static inline uint32_t MaxSamplesLog2 = 10u; // 18 + constexpr static inline uint32_t MaxBufferDimensions = 3u << MaxDepthLog2; + constexpr static inline uint32_t MaxBufferSamples = 1u << MaxSamplesLog2; + constexpr static inline uint8_t MaxUITextureCount = 1u; + static inline std::string DefaultImagePathsFile = "envmap/envmap_0.exr"; + static inline std::string OwenSamplerFilePath = "owen_sampler_buffer.bin"; + static inline std::array PTGLSLShaderPaths = { "app_resources/glsl/litBySphere.comp", "app_resources/glsl/litByTriangle.comp", "app_resources/glsl/litByRectangle.comp" }; + static inline std::string PTHLSLShaderPath = "app_resources/hlsl/render.comp.hlsl"; + static inline std::array PTHLSLShaderVariants = { "SPHERE_LIGHT", "TRIANGLE_LIGHT", "RECTANGLE_LIGHT" }; + static inline std::string PresentShaderPath = "app_resources/hlsl/present.frag.hlsl"; + + const char* shaderNames[E_LIGHT_GEOMETRY::ELG_COUNT] = { + "ELG_SPHERE", + "ELG_TRIANGLE", + "ELG_RECTANGLE" + }; + + const char* shaderTypes[E_RENDER_MODE::ERM_COUNT] = { + "ERM_GLSL", + "ERM_HLSL" + }; + + public: + inline HLSLComputePathtracer(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) + : IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) {} + + inline bool isComputeOnly() const override { return false; } + + inline core::vector getSurfaces() const override + { + if (!m_surface) + { + { + auto windowCallback = core::make_smart_refctd_ptr(smart_refctd_ptr(m_inputSystem), smart_refctd_ptr(m_logger)); + IWindow::SCreationParams params = {}; + params.callback = core::make_smart_refctd_ptr(); + params.width = WindowDimensions.x; + params.height = WindowDimensions.y; + params.x = 32; + params.y = 32; + params.flags = ui::IWindow::ECF_HIDDEN | IWindow::ECF_BORDERLESS | IWindow::ECF_RESIZABLE; + params.windowCaption = "ComputeShaderPathtracer"; + params.callback = windowCallback; + const_cast&>(m_window) = m_winMgr->createWindow(std::move(params)); + } + + auto surface = CSurfaceVulkanWin32::create(smart_refctd_ptr(m_api), smart_refctd_ptr_static_cast(m_window)); + const_cast&>(m_surface) = nbl::video::CSimpleResizeSurface::create(std::move(surface)); + } + + if (m_surface) + return { {m_surface->getSurface()/*,EQF_NONE*/} }; + + return {}; + } + + inline bool onAppInitialized(smart_refctd_ptr&& system) override + { + // Init systems + { + m_inputSystem = make_smart_refctd_ptr(logger_opt_smart_ptr(smart_refctd_ptr(m_logger))); + + // Remember to call the base class initialization! + if (!device_base_t::onAppInitialized(smart_refctd_ptr(system))) + return false; + if (!asset_base_t::onAppInitialized(std::move(system))) + return false; + + m_semaphore = m_device->createSemaphore(m_realFrameIx); + + if (!m_semaphore) + return logFail("Failed to create semaphore!"); + } + + // Create renderpass and init surface + nbl::video::IGPURenderpass* renderpass; + { + ISwapchain::SCreationParams swapchainParams = { .surface = smart_refctd_ptr(m_surface->getSurface()) }; + if (!swapchainParams.deduceFormat(m_physicalDevice)) + return logFail("Could not choose a Surface Format for the Swapchain!"); + + const static IGPURenderpass::SCreationParams::SSubpassDependency dependencies[] = + { + { + .srcSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .dstSubpass = 0, + .memoryBarrier = + { + .srcStageMask = asset::PIPELINE_STAGE_FLAGS::COPY_BIT, + .srcAccessMask = asset::ACCESS_FLAGS::TRANSFER_WRITE_BIT, + .dstStageMask = asset::PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + .dstAccessMask = asset::ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + } + }, + { + .srcSubpass = 0, + .dstSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .memoryBarrier = + { + .srcStageMask = asset::PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = asset::ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + } + }, + IGPURenderpass::SCreationParams::DependenciesEnd + }; + + auto scResources = std::make_unique(m_device.get(), swapchainParams.surfaceFormat.format, dependencies); + renderpass = scResources->getRenderpass(); + + if (!renderpass) + return logFail("Failed to create Renderpass!"); + + auto gQueue = getGraphicsQueue(); + if (!m_surface || !m_surface->init(gQueue, std::move(scResources), swapchainParams.sharedParams)) + return logFail("Could not create Window & Surface or initialize the Surface!"); + } + + // image upload utils + { + m_scratchSemaphore = m_device->createSemaphore(0); + if (!m_scratchSemaphore) + return logFail("Could not create Scratch Semaphore"); + m_scratchSemaphore->setObjectDebugName("Scratch Semaphore"); + // we don't want to overcomplicate the example with multi-queue + m_intendedSubmit.queue = getGraphicsQueue(); + // wait for nothing before upload + m_intendedSubmit.waitSemaphores = {}; + m_intendedSubmit.waitSemaphores = {}; + // fill later + m_intendedSubmit.scratchCommandBuffers = {}; + m_intendedSubmit.scratchSemaphore = { + .semaphore = m_scratchSemaphore.get(), + .value = 0, + .stageMask = PIPELINE_STAGE_FLAGS::ALL_TRANSFER_BITS + }; + } + + // Create command pool and buffers + { + auto gQueue = getGraphicsQueue(); + m_cmdPool = m_device->createCommandPool(gQueue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); + if (!m_cmdPool) + return logFail("Couldn't create Command Pool!"); + + if (!m_cmdPool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY, { m_cmdBufs.data(), MaxFramesInFlight })) + return logFail("Couldn't create Command Buffer!"); + } + + ISampler::SParams samplerParams = { + .AnisotropicFilter = 0 + }; + auto defaultSampler = m_device->createSampler(samplerParams); + + // Create descriptors and pipeline for the pathtracer + { + auto convertDSLayoutCPU2GPU = [&](smart_refctd_ptr cpuLayout) { + auto converter = CAssetConverter::create({ .device = m_device.get() }); + CAssetConverter::SInputs inputs = {}; + inputs.readCache = converter.get(); + inputs.logger = m_logger.get(); + CAssetConverter::SConvertParams params = {}; + params.utilities = m_utils.get(); + + std::get>(inputs.assets) = { &cpuLayout.get(),1 }; + // don't need to assert that we don't need to provide patches since layouts are not patchable + //assert(true); + auto reservation = converter->reserve(inputs); + // the `.value` is just a funny way to make the `smart_refctd_ptr` copyable + auto gpuLayout = reservation.getGPUObjects().front().value; + if (!gpuLayout) { + m_logger->log("Failed to convert %s into an IGPUDescriptorSetLayout handle", ILogger::ELL_ERROR); + std::exit(-1); + } + + return gpuLayout; + }; + auto convertDSCPU2GPU = [&](smart_refctd_ptr cpuDS) { + auto converter = CAssetConverter::create({ .device = m_device.get() }); + CAssetConverter::SInputs inputs = {}; + inputs.readCache = converter.get(); + inputs.logger = m_logger.get(); + CAssetConverter::SConvertParams params = {}; + params.utilities = m_utils.get(); + + std::get>(inputs.assets) = { &cpuDS.get(), 1 }; + // don't need to assert that we don't need to provide patches since layouts are not patchable + //assert(true); + auto reservation = converter->reserve(inputs); + // the `.value` is just a funny way to make the `smart_refctd_ptr` copyable + auto gpuDS = reservation.getGPUObjects().front().value; + if (!gpuDS) { + m_logger->log("Failed to convert %s into an IGPUDescriptorSet handle", ILogger::ELL_ERROR); + std::exit(-1); + } + + return gpuDS; + }; + + std::array descriptorSet0Bindings = {}; + std::array descriptorSet3Bindings = {}; + std::array presentDescriptorSetBindings; + + descriptorSet0Bindings[0] = { + .binding = 0u, + .type = nbl::asset::IDescriptor::E_TYPE::ET_STORAGE_IMAGE, + .createFlags = ICPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, + .count = 1u, + .immutableSamplers = nullptr + }; + descriptorSet3Bindings[0] = { + .binding = 0u, + .type = nbl::asset::IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER, + .createFlags = ICPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, + .count = 1u, + .immutableSamplers = nullptr + }; + descriptorSet3Bindings[1] = { + .binding = 1u, + .type = nbl::asset::IDescriptor::E_TYPE::ET_UNIFORM_TEXEL_BUFFER, + .createFlags = ICPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, + .count = 1u, + .immutableSamplers = nullptr + }; + descriptorSet3Bindings[2] = { + .binding = 2u, + .type = nbl::asset::IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER, + .createFlags = ICPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, + .count = 1u, + .immutableSamplers = nullptr + }; + presentDescriptorSetBindings[0] = { + .binding = 0u, + .type = nbl::asset::IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER, + .createFlags = ICPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_FRAGMENT, + .count = 1u, + .immutableSamplers = &defaultSampler + }; + + auto cpuDescriptorSetLayout0 = make_smart_refctd_ptr(descriptorSet0Bindings); + auto cpuDescriptorSetLayout2 = make_smart_refctd_ptr(descriptorSet3Bindings); + + auto gpuDescriptorSetLayout0 = convertDSLayoutCPU2GPU(cpuDescriptorSetLayout0); + auto gpuDescriptorSetLayout2 = convertDSLayoutCPU2GPU(cpuDescriptorSetLayout2); + auto gpuPresentDescriptorSetLayout = m_device->createDescriptorSetLayout(presentDescriptorSetBindings); + + auto cpuDescriptorSet0 = make_smart_refctd_ptr(std::move(cpuDescriptorSetLayout0)); + auto cpuDescriptorSet2 = make_smart_refctd_ptr(std::move(cpuDescriptorSetLayout2)); + + m_descriptorSet0 = convertDSCPU2GPU(cpuDescriptorSet0); + m_descriptorSet2 = convertDSCPU2GPU(cpuDescriptorSet2); + + smart_refctd_ptr presentDSPool; + { + const video::IGPUDescriptorSetLayout* const layouts[] = { gpuPresentDescriptorSetLayout.get() }; + const uint32_t setCounts[] = { 1u }; + presentDSPool = m_device->createDescriptorPoolForDSLayouts(IDescriptorPool::E_CREATE_FLAGS::ECF_NONE, layouts, setCounts); + } + m_presentDescriptorSet = presentDSPool->createDescriptorSet(gpuPresentDescriptorSetLayout); + + // Create Shaders + auto loadAndCompileGLSLShader = [&](const std::string& pathToShader, bool persistentWorkGroups = false) -> smart_refctd_ptr + { + IAssetLoader::SAssetLoadParams lp = {}; + lp.workingDirectory = localInputCWD; + auto assetBundle = m_assetMgr->getAsset(pathToShader, lp); + const auto assets = assetBundle.getContents(); + if (assets.empty()) + { + m_logger->log("Could not load shader: ", ILogger::ELL_ERROR, pathToShader); + std::exit(-1); + } + + auto source = smart_refctd_ptr_static_cast(assets[0]); + // The down-cast should not fail! + assert(source); + + auto compiler = make_smart_refctd_ptr(smart_refctd_ptr(m_system)); + CGLSLCompiler::SOptions options = {}; + options.stage = IShader::E_SHADER_STAGE::ESS_COMPUTE; // should be compute + options.targetSpirvVersion = m_device->getPhysicalDevice()->getLimits().spirvVersion; + options.spirvOptimizer = nullptr; +#ifndef _NBL_DEBUG + ISPIRVOptimizer::E_OPTIMIZER_PASS optPasses = ISPIRVOptimizer::EOP_STRIP_DEBUG_INFO; + auto opt = make_smart_refctd_ptr(std::span(&optPasses, 1)); + options.spirvOptimizer = opt.get(); +#endif + options.debugInfoFlags |= IShaderCompiler::E_DEBUG_INFO_FLAGS::EDIF_LINE_BIT; + options.preprocessorOptions.sourceIdentifier = source->getFilepathHint(); + options.preprocessorOptions.logger = m_logger.get(); + options.preprocessorOptions.includeFinder = compiler->getDefaultIncludeFinder(); + + const IShaderCompiler::SMacroDefinition persistentDefine = { "PERSISTENT_WORKGROUPS", "1" }; + if (persistentWorkGroups) + options.preprocessorOptions.extraDefines = { &persistentDefine, &persistentDefine + 1 }; + + source = compiler->compileToSPIRV((const char*)source->getContent()->getPointer(), options); + + // this time we skip the use of the asset converter since the ICPUShader->IGPUShader path is quick and simple + auto shader = m_device->compileShader({ source.get(), nullptr, nullptr, nullptr }); + if (!shader) + { + m_logger->log("GLSL shader creationed failed: %s!", ILogger::ELL_ERROR, pathToShader); + std::exit(-1); + } + + return shader; + }; + + auto loadAndCompileHLSLShader = [&](const std::string& pathToShader, const std::string& defineMacro = "", bool persistentWorkGroups = false) -> smart_refctd_ptr + { + IAssetLoader::SAssetLoadParams lp = {}; + lp.workingDirectory = localInputCWD; + auto assetBundle = m_assetMgr->getAsset(pathToShader, lp); + const auto assets = assetBundle.getContents(); + if (assets.empty()) + { + m_logger->log("Could not load shader: ", ILogger::ELL_ERROR, pathToShader); + std::exit(-1); + } + + auto source = smart_refctd_ptr_static_cast(assets[0]); + // The down-cast should not fail! + assert(source); + + auto compiler = make_smart_refctd_ptr(smart_refctd_ptr(m_system)); + CHLSLCompiler::SOptions options = {}; + options.stage = IShader::E_SHADER_STAGE::ESS_COMPUTE; + options.targetSpirvVersion = m_device->getPhysicalDevice()->getLimits().spirvVersion; + options.spirvOptimizer = nullptr; +#ifndef _NBL_DEBUG + ISPIRVOptimizer::E_OPTIMIZER_PASS optPasses = ISPIRVOptimizer::EOP_STRIP_DEBUG_INFO; + auto opt = make_smart_refctd_ptr(std::span(&optPasses, 1)); + options.spirvOptimizer = opt.get(); +#endif + options.debugInfoFlags |= IShaderCompiler::E_DEBUG_INFO_FLAGS::EDIF_LINE_BIT; + options.preprocessorOptions.sourceIdentifier = source->getFilepathHint(); + options.preprocessorOptions.logger = m_logger.get(); + options.preprocessorOptions.includeFinder = compiler->getDefaultIncludeFinder(); + + const IShaderCompiler::SMacroDefinition defines[2] = { {defineMacro, ""}, { "PERSISTENT_WORKGROUPS", "1" } }; + if (!defineMacro.empty() && persistentWorkGroups) + options.preprocessorOptions.extraDefines = { defines, defines + 2 }; + else if (!defineMacro.empty() && !persistentWorkGroups) + options.preprocessorOptions.extraDefines = { defines, defines + 1 }; + + source = compiler->compileToSPIRV((const char*)source->getContent()->getPointer(), options); + + auto shader = m_device->compileShader({ source.get(), nullptr, nullptr, nullptr }); + if (!shader) + { + m_logger->log("HLSL shader creationed failed: %s!", ILogger::ELL_ERROR, pathToShader); + std::exit(-1); + } + + return shader; + }; + + // Create compute pipelines + { + for (int index = 0; index < E_LIGHT_GEOMETRY::ELG_COUNT; index++) { + const nbl::asset::SPushConstantRange pcRange = { + .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, + .offset = 0, + .size = sizeof(PTPushConstant) + }; + auto ptPipelineLayout = m_device->createPipelineLayout( + { &pcRange, 1 }, + core::smart_refctd_ptr(gpuDescriptorSetLayout0), + nullptr, + core::smart_refctd_ptr(gpuDescriptorSetLayout2), + nullptr + ); + if (!ptPipelineLayout) { + return logFail("Failed to create Pathtracing pipeline layout"); + } + + { + auto ptShader = loadAndCompileGLSLShader(PTGLSLShaderPaths[index]); + + IGPUComputePipeline::SCreationParams params = {}; + params.layout = ptPipelineLayout.get(); + params.shader.shader = ptShader.get(); + params.shader.entryPoint = "main"; + params.shader.entries = nullptr; + params.cached.requireFullSubgroups = true; + params.shader.requiredSubgroupSize = static_cast(5); + if (!m_device->createComputePipelines(nullptr, { ¶ms, 1 }, m_PTGLSLPipelines.data() + index)) + return logFail("Failed to create GLSL compute pipeline!\n"); + } + { + auto ptShader = loadAndCompileHLSLShader(PTHLSLShaderPath, PTHLSLShaderVariants[index]); + + IGPUComputePipeline::SCreationParams params = {}; + params.layout = ptPipelineLayout.get(); + params.shader.shader = ptShader.get(); + params.shader.entryPoint = "main"; + params.shader.entries = nullptr; + params.cached.requireFullSubgroups = true; + params.shader.requiredSubgroupSize = static_cast(5); + if (!m_device->createComputePipelines(nullptr, { ¶ms, 1 }, m_PTHLSLPipelines.data() + index)) + return logFail("Failed to create HLSL compute pipeline!\n"); + } + + // persistent wg pipelines + { + auto ptShader = loadAndCompileGLSLShader(PTGLSLShaderPaths[index], true); + + IGPUComputePipeline::SCreationParams params = {}; + params.layout = ptPipelineLayout.get(); + params.shader.shader = ptShader.get(); + params.shader.entryPoint = "main"; + params.shader.entries = nullptr; + params.cached.requireFullSubgroups = true; + params.shader.requiredSubgroupSize = static_cast(5); + if (!m_device->createComputePipelines(nullptr, { ¶ms, 1 }, m_PTGLSLPersistentWGPipelines.data() + index)) + return logFail("Failed to create GLSL PersistentWG compute pipeline!\n"); + } + { + auto ptShader = loadAndCompileHLSLShader(PTHLSLShaderPath, PTHLSLShaderVariants[index], true); + + IGPUComputePipeline::SCreationParams params = {}; + params.layout = ptPipelineLayout.get(); + params.shader.shader = ptShader.get(); + params.shader.entryPoint = "main"; + params.shader.entries = nullptr; + params.cached.requireFullSubgroups = true; + params.shader.requiredSubgroupSize = static_cast(5); + if (!m_device->createComputePipelines(nullptr, { ¶ms, 1 }, m_PTHLSLPersistentWGPipelines.data() + index)) + return logFail("Failed to create HLSL PersistentWG compute pipeline!\n"); + } + } + } + + // Create graphics pipeline + { + auto scRes = static_cast(m_surface->getSwapchainResources()); + ext::FullScreenTriangle::ProtoPipeline fsTriProtoPPln(m_assetMgr.get(), m_device.get(), m_logger.get()); + if (!fsTriProtoPPln) + return logFail("Failed to create Full Screen Triangle protopipeline or load its vertex shader!"); + + // Load Fragment Shader + auto fragmentShader = loadAndCompileHLSLShader(PresentShaderPath); + if (!fragmentShader) + return logFail("Failed to Load and Compile Fragment Shader: lumaMeterShader!"); + + const IGPUPipelineBase::SShaderSpecInfo fragSpec = { + .shader = fragmentShader.get(), + .entryPoint = "main" + }; + + auto presentLayout = m_device->createPipelineLayout( + {}, + core::smart_refctd_ptr(gpuPresentDescriptorSetLayout), + nullptr, + nullptr, + nullptr + ); + m_presentPipeline = fsTriProtoPPln.createPipeline(fragSpec, presentLayout.get(), scRes->getRenderpass()); + if (!m_presentPipeline) + return logFail("Could not create Graphics Pipeline!"); + + } + } + + // load CPUImages and convert to GPUImages + smart_refctd_ptr envMap, scrambleMap; + { + auto convertImgCPU2GPU = [&](std::span cpuImgs) { + auto queue = getGraphicsQueue(); + auto cmdbuf = m_cmdBufs[0].get(); + cmdbuf->reset(IGPUCommandBuffer::RESET_FLAGS::NONE); + std::array commandBufferInfo = { cmdbuf }; + core::smart_refctd_ptr imgFillSemaphore = m_device->createSemaphore(0); + imgFillSemaphore->setObjectDebugName("Image Fill Semaphore"); + + auto converter = CAssetConverter::create({ .device = m_device.get() }); + // We don't want to generate mip-maps for these images, to ensure that we must override the default callbacks. + struct SInputs final : CAssetConverter::SInputs + { + // we also need to override this to have concurrent sharing + inline std::span getSharedOwnershipQueueFamilies(const size_t groupCopyID, const asset::ICPUImage* buffer, const CAssetConverter::patch_t& patch) const override + { + if (familyIndices.size() > 1) + return familyIndices; + return {}; + } + + inline uint8_t getMipLevelCount(const size_t groupCopyID, const ICPUImage* image, const CAssetConverter::patch_t& patch) const override + { + return image->getCreationParameters().mipLevels; + } + inline uint16_t needToRecomputeMips(const size_t groupCopyID, const ICPUImage* image, const CAssetConverter::patch_t& patch) const override + { + return 0b0u; + } + + std::vector familyIndices; + } inputs = {}; + inputs.readCache = converter.get(); + inputs.logger = m_logger.get(); + { + const core::set uniqueFamilyIndices = { queue->getFamilyIndex(), queue->getFamilyIndex() }; + inputs.familyIndices = { uniqueFamilyIndices.begin(),uniqueFamilyIndices.end() }; + } + // scratch command buffers for asset converter transfer commands + SIntendedSubmitInfo transfer = { + .queue = queue, + .waitSemaphores = {}, + .prevCommandBuffers = {}, + .scratchCommandBuffers = commandBufferInfo, + .scratchSemaphore = { + .semaphore = imgFillSemaphore.get(), + .value = 0, + // because of layout transitions + .stageMask = PIPELINE_STAGE_FLAGS::ALL_COMMANDS_BITS + } + }; + // as per the `SIntendedSubmitInfo` one commandbuffer must be begun + cmdbuf->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + // Normally we'd have to inherit and override the `getFinalOwnerQueueFamily` callback to ensure that the + // compute queue becomes the owner of the buffers and images post-transfer, but in this example we use concurrent sharing + CAssetConverter::SConvertParams params = {}; + params.transfer = &transfer; + params.utilities = m_utils.get(); + + std::get>(inputs.assets) = cpuImgs; + // assert that we don't need to provide patches + assert(cpuImgs[0]->getImageUsageFlags().hasFlags(ICPUImage::E_USAGE_FLAGS::EUF_SAMPLED_BIT)); + auto reservation = converter->reserve(inputs); + // the `.value` is just a funny way to make the `smart_refctd_ptr` copyable + auto gpuImgs = reservation.getGPUObjects(); + for (auto& gpuImg : gpuImgs) { + if (!gpuImg) { + m_logger->log("Failed to convert %s into an IGPUImage handle", ILogger::ELL_ERROR, DefaultImagePathsFile); + std::exit(-1); + } + } + + // and launch the conversions + m_api->startCapture(); + auto result = reservation.convert(params); + m_api->endCapture(); + if (!result.blocking() && result.copy() != IQueue::RESULT::SUCCESS) { + m_logger->log("Failed to record or submit conversions", ILogger::ELL_ERROR); + std::exit(-1); + } + + envMap = gpuImgs[0].value; + scrambleMap = gpuImgs[1].value; + }; + + smart_refctd_ptr envMapCPU, scrambleMapCPU; + { + IAssetLoader::SAssetLoadParams lp; + lp.workingDirectory = this->sharedInputCWD; + SAssetBundle bundle = m_assetMgr->getAsset(DefaultImagePathsFile, lp); + if (bundle.getContents().empty()) { + m_logger->log("Couldn't load an asset.", ILogger::ELL_ERROR); + std::exit(-1); + } + + envMapCPU = IAsset::castDown(bundle.getContents()[0]); + if (!envMapCPU) { + m_logger->log("Couldn't load an asset.", ILogger::ELL_ERROR); + std::exit(-1); + } + }; + { + asset::ICPUImage::SCreationParams info; + info.format = asset::E_FORMAT::EF_R32G32_UINT; + info.type = asset::ICPUImage::ET_2D; + auto extent = envMapCPU->getCreationParameters().extent; + info.extent.width = extent.width; + info.extent.height = extent.height; + info.extent.depth = 1u; + info.mipLevels = 1u; + info.arrayLayers = 1u; + info.samples = asset::ICPUImage::E_SAMPLE_COUNT_FLAGS::ESCF_1_BIT; + info.flags = static_cast(0u); + info.usage = asset::IImage::EUF_TRANSFER_SRC_BIT | asset::IImage::EUF_SAMPLED_BIT; + + scrambleMapCPU = ICPUImage::create(std::move(info)); + const uint32_t texelFormatByteSize = getTexelOrBlockBytesize(scrambleMapCPU->getCreationParameters().format); + const uint32_t texelBufferSize = scrambleMapCPU->getImageDataSizeInBytes(); + auto texelBuffer = ICPUBuffer::create({ texelBufferSize }); + + core::RandomSampler rng(0xbadc0ffeu); + auto out = reinterpret_cast(texelBuffer->getPointer()); + for (auto index = 0u; index < texelBufferSize / 4; index++) { + out[index] = rng.nextSample(); + } + + auto regions = core::make_refctd_dynamic_array>(1u); + ICPUImage::SBufferCopy& region = regions->front(); + region.imageSubresource.aspectMask = IImage::E_ASPECT_FLAGS::EAF_COLOR_BIT; + region.imageSubresource.mipLevel = 0u; + region.imageSubresource.baseArrayLayer = 0u; + region.imageSubresource.layerCount = 1u; + region.bufferOffset = 0u; + region.bufferRowLength = IImageAssetHandlerBase::calcPitchInBlocks(extent.width, texelFormatByteSize); + region.bufferImageHeight = 0u; + region.imageOffset = { 0u, 0u, 0u }; + region.imageExtent = scrambleMapCPU->getCreationParameters().extent; + + scrambleMapCPU->setBufferAndRegions(std::move(texelBuffer), regions); + } + + std::array cpuImgs = { envMapCPU.get(), scrambleMapCPU.get()}; + convertImgCPU2GPU(cpuImgs); + } + + // create views for textures + { + auto createHDRIImage = [this](const asset::E_FORMAT colorFormat, const uint32_t width, const uint32_t height) -> smart_refctd_ptr { + IGPUImage::SCreationParams imgInfo; + imgInfo.format = colorFormat; + imgInfo.type = IGPUImage::ET_2D; + imgInfo.extent.width = width; + imgInfo.extent.height = height; + imgInfo.extent.depth = 1u; + imgInfo.mipLevels = 1u; + imgInfo.arrayLayers = 1u; + imgInfo.samples = IGPUImage::ESCF_1_BIT; + imgInfo.flags = static_cast(0u); + imgInfo.usage = asset::IImage::EUF_STORAGE_BIT | asset::IImage::EUF_TRANSFER_DST_BIT | asset::IImage::EUF_SAMPLED_BIT; + + auto image = m_device->createImage(std::move(imgInfo)); + auto imageMemReqs = image->getMemoryReqs(); + imageMemReqs.memoryTypeBits &= m_device->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); + m_device->allocate(imageMemReqs, image.get()); + + return image; + }; + auto createHDRIImageView = [this](smart_refctd_ptr img) -> smart_refctd_ptr + { + auto format = img->getCreationParameters().format; + IGPUImageView::SCreationParams imgViewInfo; + imgViewInfo.image = std::move(img); + imgViewInfo.format = format; + imgViewInfo.viewType = IGPUImageView::ET_2D; + imgViewInfo.flags = static_cast(0u); + imgViewInfo.subresourceRange.aspectMask = IImage::E_ASPECT_FLAGS::EAF_COLOR_BIT; + imgViewInfo.subresourceRange.baseArrayLayer = 0u; + imgViewInfo.subresourceRange.baseMipLevel = 0u; + imgViewInfo.subresourceRange.layerCount = 1u; + imgViewInfo.subresourceRange.levelCount = 1u; + + return m_device->createImageView(std::move(imgViewInfo)); + }; + + auto params = envMap->getCreationParameters(); + auto extent = params.extent; + envMap->setObjectDebugName("Env Map"); + m_envMapView = createHDRIImageView(envMap); + m_envMapView->setObjectDebugName("Env Map View"); + scrambleMap->setObjectDebugName("Scramble Map"); + m_scrambleView = createHDRIImageView(scrambleMap); + m_scrambleView->setObjectDebugName("Scramble Map View"); + auto outImg = createHDRIImage(asset::E_FORMAT::EF_R16G16B16A16_SFLOAT, WindowDimensions.x, WindowDimensions.y); + outImg->setObjectDebugName("Output Image"); + m_outImgView = createHDRIImageView(outImg); + m_outImgView->setObjectDebugName("Output Image View"); + } + + // create sequence buffer view + { + // TODO: do this better use asset manager to get the ICPUBuffer from `.bin` + auto createBufferFromCacheFile = [this]( + system::path filename, + size_t bufferSize, + void *data, + smart_refctd_ptr& buffer + ) -> std::pair, bool> + { + ISystem::future_t> owenSamplerFileFuture; + ISystem::future_t owenSamplerFileReadFuture; + size_t owenSamplerFileBytesRead; + + m_system->createFile(owenSamplerFileFuture, localOutputCWD / filename, IFile::ECF_READ); + smart_refctd_ptr owenSamplerFile; + + if (owenSamplerFileFuture.wait()) + { + owenSamplerFileFuture.acquire().move_into(owenSamplerFile); + if (!owenSamplerFile) + return { nullptr, false }; + + owenSamplerFile->read(owenSamplerFileReadFuture, data, 0, bufferSize); + if (owenSamplerFileReadFuture.wait()) + { + owenSamplerFileReadFuture.acquire().move_into(owenSamplerFileBytesRead); + + if (owenSamplerFileBytesRead < bufferSize) + { + buffer = asset::ICPUBuffer::create({ sizeof(uint32_t) * bufferSize }); + return { owenSamplerFile, false }; + } + + buffer = asset::ICPUBuffer::create({ { sizeof(uint32_t) * bufferSize }, data }); + } + } + + return { owenSamplerFile, true }; + }; + auto writeBufferIntoCacheFile = [this](smart_refctd_ptr file, size_t bufferSize, void* data) + { + ISystem::future_t owenSamplerFileWriteFuture; + size_t owenSamplerFileBytesWritten; + + file->write(owenSamplerFileWriteFuture, data, 0, bufferSize); + if (owenSamplerFileWriteFuture.wait()) + owenSamplerFileWriteFuture.acquire().move_into(owenSamplerFileBytesWritten); + }; + + constexpr size_t bufferSize = MaxBufferDimensions * MaxBufferSamples; + std::array data = {}; + smart_refctd_ptr sampleSeq; + + auto cacheBufferResult = createBufferFromCacheFile(sharedOutputCWD/OwenSamplerFilePath, bufferSize, data.data(), sampleSeq); + if (!cacheBufferResult.second) + { + core::OwenSampler sampler(MaxBufferDimensions, 0xdeadbeefu); + + ICPUBuffer::SCreationParams params = {}; + params.size = MaxBufferDimensions*MaxBufferSamples*sizeof(uint32_t); + sampleSeq = ICPUBuffer::create(std::move(params)); + + auto out = reinterpret_cast(sampleSeq->getPointer()); + for (auto dim = 0u; dim < MaxBufferDimensions; dim++) + for (uint32_t i = 0; i < MaxBufferSamples; i++) + { + out[i * MaxBufferDimensions + dim] = sampler.sample(dim, i); + } + if (cacheBufferResult.first) + writeBufferIntoCacheFile(cacheBufferResult.first, bufferSize, out); + } + + IGPUBuffer::SCreationParams params = {}; + params.usage = asset::IBuffer::EUF_TRANSFER_DST_BIT | asset::IBuffer::EUF_UNIFORM_TEXEL_BUFFER_BIT; + params.size = sampleSeq->getSize(); + + // we don't want to overcomplicate the example with multi-queue + auto queue = getGraphicsQueue(); + auto cmdbuf = m_cmdBufs[0].get(); + cmdbuf->reset(IGPUCommandBuffer::RESET_FLAGS::NONE); + IQueue::SSubmitInfo::SCommandBufferInfo cmdbufInfo = { cmdbuf }; + m_intendedSubmit.scratchCommandBuffers = { &cmdbufInfo, 1 }; + + cmdbuf->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + m_api->startCapture(); + auto bufferFuture = m_utils->createFilledDeviceLocalBufferOnDedMem( + m_intendedSubmit, + std::move(params), + sampleSeq->getPointer() + ); + m_api->endCapture(); + bufferFuture.wait(); + auto buffer = bufferFuture.get(); + + m_sequenceBufferView = m_device->createBufferView({ 0u, buffer->get()->getSize(), *buffer }, asset::E_FORMAT::EF_R32G32B32_UINT); + m_sequenceBufferView->setObjectDebugName("Sequence Buffer"); + } + + // Update Descriptors + { + ISampler::SParams samplerParams0 = { + ISampler::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE, + ISampler::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE, + ISampler::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE, + ISampler::ETBC_FLOAT_OPAQUE_BLACK, + ISampler::ETF_LINEAR, + ISampler::ETF_LINEAR, + ISampler::ESMM_LINEAR, + 0u, + false, + ECO_ALWAYS + }; + auto sampler0 = m_device->createSampler(samplerParams0); + ISampler::SParams samplerParams1 = { + ISampler::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE, + ISampler::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE, + ISampler::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE, + ISampler::ETBC_INT_OPAQUE_BLACK, + ISampler::ETF_NEAREST, + ISampler::ETF_NEAREST, + ISampler::ESMM_NEAREST, + 0u, + false, + ECO_ALWAYS + }; + auto sampler1 = m_device->createSampler(samplerParams1); + + std::array writeDSInfos = {}; + writeDSInfos[0].desc = m_outImgView; + writeDSInfos[0].info.image.imageLayout = IImage::LAYOUT::GENERAL; + writeDSInfos[1].desc = m_envMapView; + // ISampler::SParams samplerParams = { ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETBC_FLOAT_OPAQUE_BLACK, ISampler::ETF_LINEAR, ISampler::ETF_LINEAR, ISampler::ESMM_LINEAR, 0u, false, ECO_ALWAYS }; + writeDSInfos[1].info.combinedImageSampler.sampler = sampler0; + writeDSInfos[1].info.combinedImageSampler.imageLayout = asset::IImage::LAYOUT::READ_ONLY_OPTIMAL; + writeDSInfos[2].desc = m_sequenceBufferView; + writeDSInfos[3].desc = m_scrambleView; + // ISampler::SParams samplerParams = { ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETBC_INT_OPAQUE_BLACK, ISampler::ETF_NEAREST, ISampler::ETF_NEAREST, ISampler::ESMM_NEAREST, 0u, false, ECO_ALWAYS }; + writeDSInfos[3].info.combinedImageSampler.sampler = sampler1; + writeDSInfos[3].info.combinedImageSampler.imageLayout = asset::IImage::LAYOUT::READ_ONLY_OPTIMAL; + writeDSInfos[4].desc = m_outImgView; + writeDSInfos[4].info.image.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; + + std::array writeDescriptorSets = {}; + writeDescriptorSets[0] = { + .dstSet = m_descriptorSet0.get(), + .binding = 0, + .arrayElement = 0u, + .count = 1u, + .info = &writeDSInfos[0] + }; + writeDescriptorSets[1] = { + .dstSet = m_descriptorSet2.get(), + .binding = 0, + .arrayElement = 0u, + .count = 1u, + .info = &writeDSInfos[1] + }; + writeDescriptorSets[2] = { + .dstSet = m_descriptorSet2.get(), + .binding = 1, + .arrayElement = 0u, + .count = 1u, + .info = &writeDSInfos[2] + }; + writeDescriptorSets[3] = { + .dstSet = m_descriptorSet2.get(), + .binding = 2, + .arrayElement = 0u, + .count = 1u, + .info = &writeDSInfos[3] + }; + writeDescriptorSets[4] = { + .dstSet = m_presentDescriptorSet.get(), + .binding = 0, + .arrayElement = 0u, + .count = 1u, + .info = &writeDSInfos[4] + }; + + m_device->updateDescriptorSets(writeDescriptorSets, {}); + } + + // Create ui descriptors + { + using binding_flags_t = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS; + { + IGPUSampler::SParams params; + params.AnisotropicFilter = 1u; + params.TextureWrapU = ISampler::E_TEXTURE_CLAMP::ETC_REPEAT; + params.TextureWrapV = ISampler::E_TEXTURE_CLAMP::ETC_REPEAT; + params.TextureWrapW = ISampler::E_TEXTURE_CLAMP::ETC_REPEAT; + + m_ui.samplers.gui = m_device->createSampler(params); + m_ui.samplers.gui->setObjectDebugName("Nabla IMGUI UI Sampler"); + } + + std::array, 69u> immutableSamplers; + for (auto& it : immutableSamplers) + it = smart_refctd_ptr(m_ui.samplers.scene); + + immutableSamplers[nbl::ext::imgui::UI::FontAtlasTexId] = smart_refctd_ptr(m_ui.samplers.gui); + + nbl::ext::imgui::UI::SCreationParameters params; + + params.resources.texturesInfo = { .setIx = 0u, .bindingIx = 0u }; + params.resources.samplersInfo = { .setIx = 0u, .bindingIx = 1u }; + params.assetManager = m_assetMgr; + params.pipelineCache = nullptr; + params.pipelineLayout = nbl::ext::imgui::UI::createDefaultPipelineLayout(m_utils->getLogicalDevice(), params.resources.texturesInfo, params.resources.samplersInfo, MaxUITextureCount); + params.renderpass = smart_refctd_ptr(renderpass); + params.streamingBuffer = nullptr; + params.subpassIx = 0u; + params.transfer = getTransferUpQueue(); + params.utilities = m_utils; + { + m_ui.manager = ext::imgui::UI::create(std::move(params)); + + // note that we use default layout provided by our extension, but you are free to create your own by filling nbl::ext::imgui::UI::S_CREATION_PARAMETERS::resources + const auto* descriptorSetLayout = m_ui.manager->getPipeline()->getLayout()->getDescriptorSetLayout(0u); + const auto& params = m_ui.manager->getCreationParameters(); + + IDescriptorPool::SCreateInfo descriptorPoolInfo = {}; + descriptorPoolInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_SAMPLER)] = (uint32_t)nbl::ext::imgui::UI::DefaultSamplerIx::COUNT; + descriptorPoolInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_SAMPLED_IMAGE)] = MaxUITextureCount; + descriptorPoolInfo.maxSets = 1u; + descriptorPoolInfo.flags = IDescriptorPool::E_CREATE_FLAGS::ECF_UPDATE_AFTER_BIND_BIT; + + m_guiDescriptorSetPool = m_device->createDescriptorPool(std::move(descriptorPoolInfo)); + assert(m_guiDescriptorSetPool); + + m_guiDescriptorSetPool->createDescriptorSets(1u, &descriptorSetLayout, &m_ui.descriptorSet); + assert(m_ui.descriptorSet); + } + } + m_ui.manager->registerListener( + [this]() -> void { + ImGuiIO& io = ImGui::GetIO(); + + m_camera.setProjectionMatrix([&]() + { + static matrix4SIMD projection; + + projection = matrix4SIMD::buildProjectionMatrixPerspectiveFovRH(core::radians(fov), io.DisplaySize.x / io.DisplaySize.y, zNear, zFar); + + return projection; + }()); + + ImGui::SetNextWindowPos(ImVec2(1024, 100), ImGuiCond_Appearing); + ImGui::SetNextWindowSize(ImVec2(256, 256), ImGuiCond_Appearing); + + // create a window and insert the inspector + ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_Appearing); + ImGui::SetNextWindowSize(ImVec2(320, 340), ImGuiCond_Appearing); + ImGui::Begin("Controls"); + + ImGui::SameLine(); + + ImGui::Text("Camera"); + + ImGui::SliderFloat("Move speed", &moveSpeed, 0.1f, 10.f); + ImGui::SliderFloat("Rotate speed", &rotateSpeed, 0.1f, 10.f); + ImGui::SliderFloat("Fov", &fov, 20.f, 150.f); + ImGui::SliderFloat("zNear", &zNear, 0.1f, 100.f); + ImGui::SliderFloat("zFar", &zFar, 110.f, 10000.f); + ImGui::Combo("Shader", &PTPipeline, shaderNames, E_LIGHT_GEOMETRY::ELG_COUNT); + ImGui::Combo("Render Mode", &renderMode, shaderTypes, E_RENDER_MODE::ERM_COUNT); + ImGui::SliderInt("SPP", &spp, 1, MaxBufferSamples); + ImGui::SliderInt("Depth", &depth, 1, MaxBufferDimensions / 3); + ImGui::Checkbox("Persistent WorkGroups", &usePersistentWorkGroups); + + ImGui::Text("X: %f Y: %f", io.MousePos.x, io.MousePos.y); + + ImGui::End(); + } + ); + + // Set Camera + { + core::vectorSIMDf cameraPosition(0, 5, -10); + matrix4SIMD proj = matrix4SIMD::buildProjectionMatrixPerspectiveFovRH( + core::radians(60.0f), + WindowDimensions.x / WindowDimensions.y, + 0.01f, + 500.0f + ); + m_camera = Camera(cameraPosition, core::vectorSIMDf(0, 0, 0), proj); + } + + m_winMgr->setWindowSize(m_window.get(), WindowDimensions.x, WindowDimensions.y); + m_surface->recreateSwapchain(); + m_winMgr->show(m_window.get()); + m_oracle.reportBeginFrameRecord(); + m_camera.mapKeysToWASD(); + + return true; + } + + bool updateGUIDescriptorSet() + { + // texture atlas, note we don't create info & write pair for the font sampler because UI extension's is immutable and baked into DS layout + static std::array descriptorInfo; + static IGPUDescriptorSet::SWriteDescriptorSet writes[MaxUITextureCount]; + + descriptorInfo[nbl::ext::imgui::UI::FontAtlasTexId].info.image.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; + descriptorInfo[nbl::ext::imgui::UI::FontAtlasTexId].desc = smart_refctd_ptr(m_ui.manager->getFontAtlasView()); + + for (uint32_t i = 0; i < descriptorInfo.size(); ++i) + { + writes[i].dstSet = m_ui.descriptorSet.get(); + writes[i].binding = 0u; + writes[i].arrayElement = i; + writes[i].count = 1u; + } + writes[nbl::ext::imgui::UI::FontAtlasTexId].info = descriptorInfo.data() + nbl::ext::imgui::UI::FontAtlasTexId; + + return m_device->updateDescriptorSets(writes, {}); + } + + inline void workLoopBody() override + { + // framesInFlight: ensuring safe execution of command buffers and acquires, `framesInFlight` only affect semaphore waits, don't use this to index your resources because it can change with swapchain recreation. + const uint32_t framesInFlight = core::min(MaxFramesInFlight, m_surface->getMaxAcquiresInFlight()); + // We block for semaphores for 2 reasons here: + // A) Resource: Can't use resource like a command buffer BEFORE previous use is finished! [MaxFramesInFlight] + // B) Acquire: Can't have more acquires in flight than a certain threshold returned by swapchain or your surface helper class. [MaxAcquiresInFlight] + if (m_realFrameIx >= framesInFlight) + { + const ISemaphore::SWaitInfo cbDonePending[] = + { + { + .semaphore = m_semaphore.get(), + .value = m_realFrameIx + 1 - framesInFlight + } + }; + if (m_device->blockForSemaphores(cbDonePending) != ISemaphore::WAIT_RESULT::SUCCESS) + return; + } + const auto resourceIx = m_realFrameIx % MaxFramesInFlight; + + m_api->startCapture(); + + // CPU events + update(); + + auto queue = getGraphicsQueue(); + auto cmdbuf = m_cmdBufs[resourceIx].get(); + + if (!keepRunning()) + return; + + // render whole scene to offline frame buffer & submit + { + cmdbuf->reset(IGPUCommandBuffer::RESET_FLAGS::NONE); + // disregard surface/swapchain transformation for now + const auto viewProjectionMatrix = m_camera.getConcatenatedMatrix(); + PTPushConstant pc; + viewProjectionMatrix.getInverseTransform(pc.invMVP); + pc.sampleCount = spp; + pc.depth = depth; + + // safe to proceed + // upload buffer data + cmdbuf->beginDebugMarker("ComputeShaderPathtracer IMGUI Frame"); + cmdbuf->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + + // TRANSITION m_outImgView to GENERAL (because of descriptorSets0 -> ComputeShader Writes into the image) + { + const IGPUCommandBuffer::SImageMemoryBarrier imgBarriers[] = { + { + .barrier = { + .dep = { + .srcStageMask = PIPELINE_STAGE_FLAGS::ALL_TRANSFER_BITS, + .srcAccessMask = ACCESS_FLAGS::TRANSFER_WRITE_BIT, + .dstStageMask = PIPELINE_STAGE_FLAGS::COMPUTE_SHADER_BIT, + .dstAccessMask = ACCESS_FLAGS::SHADER_WRITE_BITS + } + }, + .image = m_outImgView->getCreationParameters().image.get(), + .subresourceRange = { + .aspectMask = IImage::EAF_COLOR_BIT, + .baseMipLevel = 0u, + .levelCount = 1u, + .baseArrayLayer = 0u, + .layerCount = 1u + }, + .oldLayout = IImage::LAYOUT::UNDEFINED, + .newLayout = IImage::LAYOUT::GENERAL + } + }; + cmdbuf->pipelineBarrier(E_DEPENDENCY_FLAGS::EDF_NONE, { .imgBarriers = imgBarriers }); + } + + // cube envmap handle + { + IGPUComputePipeline* pipeline; + if (usePersistentWorkGroups) + pipeline = renderMode == E_RENDER_MODE::ERM_HLSL ? m_PTHLSLPersistentWGPipelines[PTPipeline].get() : m_PTGLSLPersistentWGPipelines[PTPipeline].get(); + else + pipeline = renderMode == E_RENDER_MODE::ERM_HLSL ? m_PTHLSLPipelines[PTPipeline].get() : m_PTGLSLPipelines[PTPipeline].get(); + cmdbuf->bindComputePipeline(pipeline); + cmdbuf->bindDescriptorSets(EPBP_COMPUTE, pipeline->getLayout(), 0u, 1u, &m_descriptorSet0.get()); + cmdbuf->bindDescriptorSets(EPBP_COMPUTE, pipeline->getLayout(), 2u, 1u, &m_descriptorSet2.get()); + cmdbuf->pushConstants(pipeline->getLayout(), IShader::E_SHADER_STAGE::ESS_COMPUTE, 0, sizeof(PTPushConstant), &pc); + if (usePersistentWorkGroups) + { + uint32_t dispatchSize = m_physicalDevice->getLimits().computeOptimalPersistentWorkgroupDispatchSize(WindowDimensions.x * WindowDimensions.y, DefaultWorkGroupSize); + cmdbuf->dispatch(dispatchSize, 1u, 1u); + } + else + cmdbuf->dispatch(1 + (WindowDimensions.x * WindowDimensions.y - 1) / DefaultWorkGroupSize, 1u, 1u); + } + + // TRANSITION m_outImgView to READ (because of descriptorSets0 -> ComputeShader Writes into the image) + { + const IGPUCommandBuffer::SImageMemoryBarrier imgBarriers[] = { + { + .barrier = { + .dep = { + .srcStageMask = PIPELINE_STAGE_FLAGS::COMPUTE_SHADER_BIT, + .srcAccessMask = ACCESS_FLAGS::SHADER_WRITE_BITS, + .dstStageMask = PIPELINE_STAGE_FLAGS::FRAGMENT_SHADER_BIT, + .dstAccessMask = ACCESS_FLAGS::SHADER_READ_BITS + } + }, + .image = m_outImgView->getCreationParameters().image.get(), + .subresourceRange = { + .aspectMask = IImage::EAF_COLOR_BIT, + .baseMipLevel = 0u, + .levelCount = 1u, + .baseArrayLayer = 0u, + .layerCount = 1u + }, + .oldLayout = IImage::LAYOUT::GENERAL, + .newLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL + } + }; + cmdbuf->pipelineBarrier(E_DEPENDENCY_FLAGS::EDF_NONE, { .imgBarriers = imgBarriers }); + } + + // TODO: tone mapping and stuff + } + + asset::SViewport viewport; + { + viewport.minDepth = 1.f; + viewport.maxDepth = 0.f; + viewport.x = 0u; + viewport.y = 0u; + viewport.width = WindowDimensions.x; + viewport.height = WindowDimensions.y; + } + cmdbuf->setViewport(0u, 1u, &viewport); + + + VkRect2D defaultScisors[] = { {.offset = {(int32_t)viewport.x, (int32_t)viewport.y}, .extent = {(uint32_t)viewport.width, (uint32_t)viewport.height}} }; + cmdbuf->setScissor(defaultScisors); + + const VkRect2D currentRenderArea = + { + .offset = {0,0}, + .extent = {m_window->getWidth(),m_window->getHeight()} + }; + auto scRes = static_cast(m_surface->getSwapchainResources()); + + // Upload m_outImg to swapchain + UI + { + const IGPUCommandBuffer::SRenderpassBeginInfo info = + { + .framebuffer = scRes->getFramebuffer(m_currentImageAcquire.imageIndex), + .colorClearValues = &clearColor, + .depthStencilClearValues = nullptr, + .renderArea = currentRenderArea + }; + nbl::video::ISemaphore::SWaitInfo waitInfo = { .semaphore = m_semaphore.get(), .value = m_realFrameIx + 1u }; + + cmdbuf->beginRenderPass(info, IGPUCommandBuffer::SUBPASS_CONTENTS::INLINE); + + cmdbuf->bindGraphicsPipeline(m_presentPipeline.get()); + cmdbuf->bindDescriptorSets(EPBP_GRAPHICS, m_presentPipeline->getLayout(), 0, 1u, &m_presentDescriptorSet.get()); + ext::FullScreenTriangle::recordDrawCall(cmdbuf); + + const auto uiParams = m_ui.manager->getCreationParameters(); + auto* uiPipeline = m_ui.manager->getPipeline(); + cmdbuf->bindGraphicsPipeline(uiPipeline); + cmdbuf->bindDescriptorSets(EPBP_GRAPHICS, uiPipeline->getLayout(), uiParams.resources.texturesInfo.setIx, 1u, &m_ui.descriptorSet.get()); + m_ui.manager->render(cmdbuf, waitInfo); + + cmdbuf->endRenderPass(); + } + + cmdbuf->end(); + { + const IQueue::SSubmitInfo::SSemaphoreInfo rendered[] = + { + { + .semaphore = m_semaphore.get(), + .value = ++m_realFrameIx, + .stageMask = PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT + } + }; + { + { + const IQueue::SSubmitInfo::SCommandBufferInfo commandBuffers[] = + { + {.cmdbuf = cmdbuf } + }; + + const IQueue::SSubmitInfo::SSemaphoreInfo acquired[] = + { + { + .semaphore = m_currentImageAcquire.semaphore, + .value = m_currentImageAcquire.acquireCount, + .stageMask = PIPELINE_STAGE_FLAGS::NONE + } + }; + const IQueue::SSubmitInfo infos[] = + { + { + .waitSemaphores = acquired, + .commandBuffers = commandBuffers, + .signalSemaphores = rendered + } + }; + + updateGUIDescriptorSet(); + + if (queue->submit(infos) != IQueue::RESULT::SUCCESS) + m_realFrameIx--; + } + } + + m_window->setCaption("[Nabla Engine] HLSL Compute Path Tracer"); + m_surface->present(m_currentImageAcquire.imageIndex, rendered); + } + m_api->endCapture(); + } + + inline bool keepRunning() override + { + if (m_surface->irrecoverable()) + return false; + + return true; + } + + inline bool onAppTerminated() override + { + return device_base_t::onAppTerminated(); + } + + inline void update() + { + m_camera.setMoveSpeed(moveSpeed); + m_camera.setRotateSpeed(rotateSpeed); + + static std::chrono::microseconds previousEventTimestamp{}; + + m_inputSystem->getDefaultMouse(&mouse); + m_inputSystem->getDefaultKeyboard(&keyboard); + + auto updatePresentationTimestamp = [&]() + { + m_currentImageAcquire = m_surface->acquireNextImage(); + + m_oracle.reportEndFrameRecord(); + const auto timestamp = m_oracle.getNextPresentationTimeStamp(); + m_oracle.reportBeginFrameRecord(); + + return timestamp; + }; + + const auto nextPresentationTimestamp = updatePresentationTimestamp(); + + struct + { + std::vector mouse{}; + std::vector keyboard{}; + } capturedEvents; + + m_camera.beginInputProcessing(nextPresentationTimestamp); + { + const auto& io = ImGui::GetIO(); + mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void + { + if (!io.WantCaptureMouse) + m_camera.mouseProcess(events); // don't capture the events, only let camera handle them with its impl + + for (const auto& e : events) // here capture + { + if (e.timeStamp < previousEventTimestamp) + continue; + + previousEventTimestamp = e.timeStamp; + capturedEvents.mouse.emplace_back(e); + + if (e.type == nbl::ui::SMouseEvent::EET_SCROLL) + gcIndex = std::clamp(int16_t(gcIndex) + int16_t(core::sign(e.scrollEvent.verticalScroll)), int64_t(0), int64_t(ELG_COUNT - (uint8_t)1u)); + } + }, m_logger.get()); + + keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void + { + if (!io.WantCaptureKeyboard) + m_camera.keyboardProcess(events); // don't capture the events, only let camera handle them with its impl + + for (const auto& e : events) // here capture + { + if (e.timeStamp < previousEventTimestamp) + continue; + + previousEventTimestamp = e.timeStamp; + capturedEvents.keyboard.emplace_back(e); + } + }, m_logger.get()); + } + m_camera.endInputProcessing(nextPresentationTimestamp); + + const core::SRange mouseEvents(capturedEvents.mouse.data(), capturedEvents.mouse.data() + capturedEvents.mouse.size()); + const core::SRange keyboardEvents(capturedEvents.keyboard.data(), capturedEvents.keyboard.data() + capturedEvents.keyboard.size()); + const auto cursorPosition = m_window->getCursorControl()->getPosition(); + const auto mousePosition = float32_t2(cursorPosition.x, cursorPosition.y) - float32_t2(m_window->getX(), m_window->getY()); + + const ext::imgui::UI::SUpdateParameters params = + { + .mousePosition = mousePosition, + .displaySize = { m_window->getWidth(), m_window->getHeight() }, + .mouseEvents = mouseEvents, + .keyboardEvents = keyboardEvents + }; + + m_ui.manager->update(params); + } + + private: + smart_refctd_ptr m_window; + smart_refctd_ptr> m_surface; + + // gpu resources + smart_refctd_ptr m_cmdPool; + std::array, E_LIGHT_GEOMETRY::ELG_COUNT> m_PTGLSLPipelines; + std::array, E_LIGHT_GEOMETRY::ELG_COUNT> m_PTHLSLPipelines; + std::array, E_LIGHT_GEOMETRY::ELG_COUNT> m_PTGLSLPersistentWGPipelines; + std::array, E_LIGHT_GEOMETRY::ELG_COUNT> m_PTHLSLPersistentWGPipelines; + smart_refctd_ptr m_presentPipeline; + uint64_t m_realFrameIx = 0; + std::array, MaxFramesInFlight> m_cmdBufs; + ISimpleManagedSurface::SAcquireResult m_currentImageAcquire = {}; + smart_refctd_ptr m_descriptorSet0, m_descriptorSet2, m_presentDescriptorSet; + + core::smart_refctd_ptr m_guiDescriptorSetPool; + + // system resources + core::smart_refctd_ptr m_inputSystem; + InputSystem::ChannelReader mouse; + InputSystem::ChannelReader keyboard; + + // pathtracer resources + smart_refctd_ptr m_envMapView, m_scrambleView; + smart_refctd_ptr m_sequenceBufferView; + smart_refctd_ptr m_outImgView; + + // sync + smart_refctd_ptr m_semaphore; + + // image upload resources + smart_refctd_ptr m_scratchSemaphore; + SIntendedSubmitInfo m_intendedSubmit; + + struct C_UI + { + nbl::core::smart_refctd_ptr manager; + + struct + { + core::smart_refctd_ptr gui, scene; + } samplers; + + core::smart_refctd_ptr descriptorSet; + } m_ui; + + Camera m_camera; + + video::CDumbPresentationOracle m_oracle; + + uint16_t gcIndex = {}; // note: this is dirty however since I assume only single object in scene I can leave it now, when this example is upgraded to support multiple objects this needs to be changed + + float fov = 60.f, zNear = 0.1f, zFar = 10000.f, moveSpeed = 1.f, rotateSpeed = 1.f; + float viewWidth = 10.f; + float camYAngle = 165.f / 180.f * 3.14159f; + float camXAngle = 32.f / 180.f * 3.14159f; + int PTPipeline = E_LIGHT_GEOMETRY::ELG_SPHERE; + int renderMode = E_RENDER_MODE::ERM_HLSL; + int spp = 32; + int depth = 3; + bool usePersistentWorkGroups = false; + + bool m_firstFrame = true; + IGPUCommandBuffer::SClearColorValue clearColor = { .float32 = {0.f,0.f,0.f,1.f} }; +}; + +NBL_MAIN_FUNC(HLSLComputePathtracer) diff --git a/06_MeshLoaders/pipeline.groovy b/31_HLSLPathTracer/pipeline.groovy similarity index 85% rename from 06_MeshLoaders/pipeline.groovy rename to 31_HLSLPathTracer/pipeline.groovy index 0923d296f..955e77cec 100644 --- a/06_MeshLoaders/pipeline.groovy +++ b/31_HLSLPathTracer/pipeline.groovy @@ -2,9 +2,9 @@ import org.DevshGraphicsProgramming.Agent import org.DevshGraphicsProgramming.BuilderInfo import org.DevshGraphicsProgramming.IBuilder -class CMeshLoadersBuilder extends IBuilder +class CHLSLPathTracerBuilder extends IBuilder { - public CMeshLoadersBuilder(Agent _agent, _info) + public CHLSLPathTracerBuilder(Agent _agent, _info) { super(_agent, _info) } @@ -44,7 +44,7 @@ class CMeshLoadersBuilder extends IBuilder def create(Agent _agent, _info) { - return new CMeshLoadersBuilder(_agent, _info) + return new CHLSLPathTracerBuilder(_agent, _info) } -return this \ No newline at end of file +return this diff --git a/42_FragmentShaderPathTracer/CMakeLists.txt b/42_FragmentShaderPathTracer/CMakeLists.txt deleted file mode 100644 index a476b6203..000000000 --- a/42_FragmentShaderPathTracer/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ - -include(common RESULT_VARIABLE RES) -if(NOT RES) - message(FATAL_ERROR "common.cmake not found. Should be in {repo_root}/cmake directory") -endif() - -nbl_create_executable_project("" "" "" "" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") \ No newline at end of file diff --git a/42_FragmentShaderPathTracer/main.cpp b/42_FragmentShaderPathTracer/main.cpp deleted file mode 100644 index f8505b8d1..000000000 --- a/42_FragmentShaderPathTracer/main.cpp +++ /dev/null @@ -1,693 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -#define _NBL_STATIC_LIB_ -#include - -#include "../common/CommonAPI.h" -#include "CCamera.hpp" -#include "nbl/ext/ScreenShot/ScreenShot.h" -#include "nbl/video/utilities/CDumbPresentationOracle.h" - -using namespace nbl; -using namespace core; -using namespace ui; - - -using namespace nbl; -using namespace core; -using namespace asset; -using namespace video; - -smart_refctd_ptr createHDRImageView(nbl::core::smart_refctd_ptr device, asset::E_FORMAT colorFormat, uint32_t width, uint32_t height) -{ - smart_refctd_ptr gpuImageViewColorBuffer; - { - IGPUImage::SCreationParams imgInfo; - imgInfo.format = colorFormat; - imgInfo.type = IGPUImage::ET_2D; - imgInfo.extent.width = width; - imgInfo.extent.height = height; - imgInfo.extent.depth = 1u; - imgInfo.mipLevels = 1u; - imgInfo.arrayLayers = 1u; - imgInfo.samples = asset::ICPUImage::ESCF_1_BIT; - imgInfo.flags = static_cast(0u); - imgInfo.usage = core::bitflag(asset::IImage::EUF_STORAGE_BIT) | asset::IImage::EUF_TRANSFER_SRC_BIT; - - auto image = device->createImage(std::move(imgInfo)); - auto imageMemReqs = image->getMemoryReqs(); - imageMemReqs.memoryTypeBits &= device->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - device->allocate(imageMemReqs, image.get()); - - IGPUImageView::SCreationParams imgViewInfo; - imgViewInfo.image = std::move(image); - imgViewInfo.format = colorFormat; - imgViewInfo.viewType = IGPUImageView::ET_2D; - imgViewInfo.flags = static_cast(0u); - imgViewInfo.subresourceRange.aspectMask = IImage::E_ASPECT_FLAGS::EAF_COLOR_BIT; - imgViewInfo.subresourceRange.baseArrayLayer = 0u; - imgViewInfo.subresourceRange.baseMipLevel = 0u; - imgViewInfo.subresourceRange.layerCount = 1u; - imgViewInfo.subresourceRange.levelCount = 1u; - - gpuImageViewColorBuffer = device->createImageView(std::move(imgViewInfo)); - } - - return gpuImageViewColorBuffer; -} - -struct ShaderParameters -{ - const uint32_t MaxDepthLog2 = 4; //5 - const uint32_t MaxSamplesLog2 = 10; //18 -} kShaderParameters; - -enum E_LIGHT_GEOMETRY -{ - ELG_SPHERE, - ELG_TRIANGLE, - ELG_RECTANGLE -}; - -struct DispatchInfo_t -{ - uint32_t workGroupCount[3]; -}; - -_NBL_STATIC_INLINE_CONSTEXPR uint32_t DEFAULT_WORK_GROUP_SIZE = 16u; - -DispatchInfo_t getDispatchInfo(uint32_t imgWidth, uint32_t imgHeight) { - DispatchInfo_t ret = {}; - ret.workGroupCount[0] = (uint32_t)core::ceil((float)imgWidth / (float)DEFAULT_WORK_GROUP_SIZE); - ret.workGroupCount[1] = (uint32_t)core::ceil((float)imgHeight / (float)DEFAULT_WORK_GROUP_SIZE); - ret.workGroupCount[2] = 1; - return ret; -} - -int main() -{ - system::IApplicationFramework::GlobalsInit(); - - constexpr uint32_t WIN_W = 1280; - constexpr uint32_t WIN_H = 720; - constexpr uint32_t FBO_COUNT = 2u; - constexpr uint32_t FRAMES_IN_FLIGHT = 5u; - constexpr bool LOG_TIMESTAMP = false; - static_assert(FRAMES_IN_FLIGHT>FBO_COUNT); - - const auto swapchainImageUsage = static_cast(asset::IImage::EUF_COLOR_ATTACHMENT_BIT | asset::IImage::EUF_TRANSFER_DST_BIT); - CommonAPI::InitParams initParams; - initParams.apiType = video::EAT_VULKAN; - initParams.appName = { "Compute Shader PathTracer" }; - initParams.framesInFlight = FRAMES_IN_FLIGHT; - initParams.windowWidth = WIN_W; - initParams.windowHeight = WIN_H; - initParams.swapchainImageCount = FBO_COUNT; - initParams.swapchainImageUsage = swapchainImageUsage; - initParams.depthFormat = asset::EF_D32_SFLOAT; - auto initOutput = CommonAPI::InitWithDefaultExt(std::move(initParams)); - - auto system = std::move(initOutput.system); - auto window = std::move(initParams.window); - auto windowCb = std::move(initParams.windowCb); - auto gl = std::move(initOutput.apiConnection); - auto surface = std::move(initOutput.surface); - auto gpuPhysicalDevice = std::move(initOutput.physicalDevice); - auto device = std::move(initOutput.logicalDevice); - auto queues = std::move(initOutput.queues); - auto graphicsQueue = queues[CommonAPI::InitOutput::EQT_GRAPHICS]; - auto transferUpQueue = queues[CommonAPI::InitOutput::EQT_TRANSFER_UP]; - auto computeQueue = queues[CommonAPI::InitOutput::EQT_COMPUTE]; - auto renderpass = std::move(initOutput.renderToSwapchainRenderpass); - auto assetManager = std::move(initOutput.assetManager); - auto cpu2gpuParams = std::move(initOutput.cpu2gpuParams); - auto logger = std::move(initOutput.logger); - auto inputSystem = std::move(initOutput.inputSystem); - auto utilities = std::move(initOutput.utilities); - auto graphicsCommandPools = std::move(initOutput.commandPools[CommonAPI::InitOutput::EQT_GRAPHICS]); - auto computeCommandPools = std::move(initOutput.commandPools[CommonAPI::InitOutput::EQT_COMPUTE]); - auto swapchainCreationParams = std::move(initOutput.swapchainCreationParams); - - core::smart_refctd_ptr swapchain = nullptr; - CommonAPI::createSwapchain(std::move(device), swapchainCreationParams, WIN_W, WIN_H, swapchain); - assert(swapchain); - auto fbo = CommonAPI::createFBOWithSwapchainImages( - swapchain->getImageCount(), WIN_W, WIN_H, - device, swapchain, renderpass, - asset::EF_D32_SFLOAT - ); - - auto graphicsCmdPoolQueueFamIdx = graphicsQueue->getFamilyIndex(); - - nbl::video::IGPUObjectFromAssetConverter CPU2GPU; - - core::smart_refctd_ptr cmdbuf[FRAMES_IN_FLIGHT]; - for (uint32_t i = 0u; i < FRAMES_IN_FLIGHT; i++) - device->createCommandBuffers(graphicsCommandPools[i].get(), video::IGPUCommandBuffer::EL_PRIMARY, 1, cmdbuf+i); - - constexpr uint32_t maxDescriptorCount = 256u; - constexpr uint32_t PoolSizesCount = 5u; - - nbl::video::IDescriptorPool::SCreateInfo createInfo; - createInfo.maxDescriptorCount[static_cast(nbl::asset::IDescriptor::E_TYPE::ET_STORAGE_BUFFER)] = maxDescriptorCount * 1; - createInfo.maxDescriptorCount[static_cast(nbl::asset::IDescriptor::E_TYPE::ET_STORAGE_IMAGE)] = maxDescriptorCount * 8; - createInfo.maxDescriptorCount[static_cast(nbl::asset::IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER)] = maxDescriptorCount * 2; - createInfo.maxDescriptorCount[static_cast(nbl::asset::IDescriptor::E_TYPE::ET_UNIFORM_TEXEL_BUFFER)] = maxDescriptorCount * 1; - createInfo.maxDescriptorCount[static_cast(nbl::asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER)] = maxDescriptorCount * 1; - createInfo.maxSets = maxDescriptorCount; - - auto descriptorPool = device->createDescriptorPool(std::move(createInfo)); - - const auto timestampQueryPool = device->createQueryPool({ - .queryType = video::IQueryPool::EQT_TIMESTAMP, - .queryCount = 2u - }); - - // Camera - core::vectorSIMDf cameraPosition(0, 5, -10); - matrix4SIMD proj = matrix4SIMD::buildProjectionMatrixPerspectiveFovRH(core::radians(60.0f), video::ISurface::getTransformedAspectRatio(swapchain->getPreTransform(), WIN_W, WIN_H), 0.01f, 500.0f); - Camera cam = Camera(cameraPosition, core::vectorSIMDf(0, 0, 0), proj); - - IGPUDescriptorSetLayout::SBinding descriptorSet0Bindings[] = { - { 0u, nbl::asset::IDescriptor::E_TYPE::ET_STORAGE_IMAGE, IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, IShader::ESS_COMPUTE, 1u, nullptr }, - }; - IGPUDescriptorSetLayout::SBinding uboBinding - { 0u, nbl::asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER, IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, IShader::ESS_COMPUTE, 1u, nullptr }; - IGPUDescriptorSetLayout::SBinding descriptorSet3Bindings[] = { - { 0u, nbl::asset::IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER, IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, IShader::ESS_COMPUTE, 1u, nullptr }, - { 1u, nbl::asset::IDescriptor::E_TYPE::ET_UNIFORM_TEXEL_BUFFER, IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, IShader::ESS_COMPUTE, 1u, nullptr }, - { 2u, nbl::asset::IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER, IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, IShader::ESS_COMPUTE, 1u, nullptr }, - }; - - auto gpuDescriptorSetLayout0 = device->createDescriptorSetLayout(descriptorSet0Bindings, descriptorSet0Bindings + 1u); - auto gpuDescriptorSetLayout1 = device->createDescriptorSetLayout(&uboBinding, &uboBinding + 1u); - auto gpuDescriptorSetLayout2 = device->createDescriptorSetLayout(descriptorSet3Bindings, descriptorSet3Bindings+3u); - - auto createGpuResources = [&](std::string pathToShader) -> core::smart_refctd_ptr - { - asset::IAssetLoader::SAssetLoadParams params{}; - params.logger = logger.get(); - //params.relativeDir = tmp.c_str(); - auto spec = assetManager->getAsset(pathToShader,params).getContents(); - - if (spec.empty()) - assert(false); - - auto cpuComputeSpecializedShader = core::smart_refctd_ptr_static_cast(*spec.begin()); - - ISpecializedShader::SInfo info = cpuComputeSpecializedShader->getSpecializationInfo(); - info.m_backingBuffer = ICPUBuffer::create({ sizeof(ShaderParameters) }); - memcpy(info.m_backingBuffer->getPointer(),&kShaderParameters,sizeof(ShaderParameters)); - info.m_entries = core::make_refctd_dynamic_array>(2u); - for (uint32_t i=0; i<2; i++) - info.m_entries->operator[](i) = {i,(uint32_t)(i*sizeof(uint32_t)),sizeof(uint32_t)}; - - - cpuComputeSpecializedShader->setSpecializationInfo(std::move(info)); - - auto gpuComputeSpecializedShader = CPU2GPU.getGPUObjectsFromAssets(&cpuComputeSpecializedShader, &cpuComputeSpecializedShader + 1, cpu2gpuParams)->front(); - - auto gpuPipelineLayout = device->createPipelineLayout(nullptr, nullptr, core::smart_refctd_ptr(gpuDescriptorSetLayout0), core::smart_refctd_ptr(gpuDescriptorSetLayout1), core::smart_refctd_ptr(gpuDescriptorSetLayout2), nullptr); - - auto gpuPipeline = device->createComputePipeline(nullptr, std::move(gpuPipelineLayout), std::move(gpuComputeSpecializedShader)); - - return gpuPipeline; - }; - - E_LIGHT_GEOMETRY lightGeom = ELG_SPHERE; - constexpr const char* shaderPaths[] = {"../litBySphere.comp","../litByTriangle.comp","../litByRectangle.comp"}; - auto gpuComputePipeline = createGpuResources(shaderPaths[lightGeom]); - - DispatchInfo_t dispatchInfo = getDispatchInfo(WIN_W, WIN_H); - - auto createImageView = [&](std::string pathToOpenEXRHDRIImage) - { -#ifndef _NBL_COMPILE_WITH_OPENEXR_LOADER_ - assert(false); -#endif - - auto pathToTexture = pathToOpenEXRHDRIImage; - IAssetLoader::SAssetLoadParams lp(0ull, nullptr, IAssetLoader::ECF_DONT_CACHE_REFERENCES); - auto cpuTexture = assetManager->getAsset(pathToTexture, lp); - auto cpuTextureContents = cpuTexture.getContents(); - assert(!cpuTextureContents.empty()); - auto cpuImage = core::smart_refctd_ptr_static_cast(*cpuTextureContents.begin()); - cpuImage->setImageUsageFlags(IImage::E_USAGE_FLAGS::EUF_SAMPLED_BIT); - - ICPUImageView::SCreationParams viewParams; - viewParams.flags = static_cast(0u); - viewParams.image = cpuImage; - viewParams.format = viewParams.image->getCreationParameters().format; - viewParams.viewType = IImageView::ET_2D; - viewParams.subresourceRange.aspectMask = IImage::E_ASPECT_FLAGS::EAF_COLOR_BIT; - viewParams.subresourceRange.baseArrayLayer = 0u; - viewParams.subresourceRange.layerCount = 1u; - viewParams.subresourceRange.baseMipLevel = 0u; - viewParams.subresourceRange.levelCount = 1u; - - auto cpuImageView = ICPUImageView::create(std::move(viewParams)); - - cpu2gpuParams.beginCommandBuffers(); - auto gpuImageView = CPU2GPU.getGPUObjectsFromAssets(&cpuImageView, &cpuImageView + 1u, cpu2gpuParams)->front(); - cpu2gpuParams.waitForCreationToComplete(false); - - return gpuImageView; - }; - - auto gpuEnvmapImageView = createImageView("../../media/envmap/envmap_0.exr"); - - smart_refctd_ptr gpuSequenceBufferView; - { - const uint32_t MaxDimensions = 3u<(sampleSequence->getPointer()); - for (auto dim=0u; dimcreateFilledDeviceLocalBufferOnDedMem(graphicsQueue, sampleSequence->getSize(), sampleSequence->getPointer()); - core::smart_refctd_ptr gpuSequenceBuffer; - { - IGPUBuffer::SCreationParams params = {}; - const size_t size = sampleSequence->getSize(); - params.usage = core::bitflag(asset::IBuffer::EUF_TRANSFER_DST_BIT) | asset::IBuffer::EUF_UNIFORM_TEXEL_BUFFER_BIT; - params.size = size; - gpuSequenceBuffer = device->createBuffer(std::move(params)); - auto gpuSequenceBufferMemReqs = gpuSequenceBuffer->getMemoryReqs(); - gpuSequenceBufferMemReqs.memoryTypeBits &= device->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - device->allocate(gpuSequenceBufferMemReqs, gpuSequenceBuffer.get()); - utilities->updateBufferRangeViaStagingBufferAutoSubmit(asset::SBufferRange{0u,size,gpuSequenceBuffer},sampleSequence->getPointer(), graphicsQueue); - } - gpuSequenceBufferView = device->createBufferView(gpuSequenceBuffer.get(), asset::EF_R32G32B32_UINT); - } - - smart_refctd_ptr gpuScrambleImageView; - { - IGPUImage::SCreationParams imgParams; - imgParams.flags = static_cast(0u); - imgParams.type = IImage::ET_2D; - imgParams.format = EF_R32G32_UINT; - imgParams.extent = {WIN_W, WIN_H,1u}; - imgParams.mipLevels = 1u; - imgParams.arrayLayers = 1u; - imgParams.samples = IImage::ESCF_1_BIT; - imgParams.usage = core::bitflag(IImage::EUF_SAMPLED_BIT) | IImage::EUF_TRANSFER_DST_BIT; - imgParams.initialLayout = asset::IImage::EL_UNDEFINED; - - IGPUImage::SBufferCopy region = {}; - region.bufferOffset = 0u; - region.bufferRowLength = 0u; - region.bufferImageHeight = 0u; - region.imageExtent = imgParams.extent; - region.imageOffset = {0u,0u,0u}; - region.imageSubresource.layerCount = 1u; - region.imageSubresource.aspectMask = IImage::E_ASPECT_FLAGS::EAF_COLOR_BIT; - - constexpr auto ScrambleStateChannels = 2u; - const auto renderPixelCount = imgParams.extent.width*imgParams.extent.height; - core::vector random(renderPixelCount*ScrambleStateChannels); - { - core::RandomSampler rng(0xbadc0ffeu); - for (auto& pixel : random) - pixel = rng.nextSample(); - } - - // TODO: Temp Fix because createFilledDeviceLocalBufferOnDedMem doesn't take in params - // auto buffer = utilities->createFilledDeviceLocalBufferOnDedMem(graphicsQueue, random.size()*sizeof(uint32_t), random.data()); - core::smart_refctd_ptr buffer; - { - IGPUBuffer::SCreationParams params = {}; - const size_t size = random.size() * sizeof(uint32_t); - params.usage = core::bitflag(asset::IBuffer::EUF_TRANSFER_DST_BIT) | asset::IBuffer::EUF_TRANSFER_SRC_BIT; - params.size = size; - buffer = device->createBuffer(std::move(params)); - auto bufferMemReqs = buffer->getMemoryReqs(); - bufferMemReqs.memoryTypeBits &= device->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - device->allocate(bufferMemReqs, buffer.get()); - utilities->updateBufferRangeViaStagingBufferAutoSubmit(asset::SBufferRange{0u,size,buffer},random.data(),graphicsQueue); - } - - IGPUImageView::SCreationParams viewParams; - viewParams.flags = static_cast(0u); - // TODO: Replace this IGPUBuffer -> IGPUImage to using image upload utility - viewParams.image = utilities->createFilledDeviceLocalImageOnDedMem(std::move(imgParams), buffer.get(), 1u, ®ion, graphicsQueue); - viewParams.viewType = IGPUImageView::ET_2D; - viewParams.format = EF_R32G32_UINT; - viewParams.subresourceRange.aspectMask = IImage::E_ASPECT_FLAGS::EAF_COLOR_BIT; - viewParams.subresourceRange.levelCount = 1u; - viewParams.subresourceRange.layerCount = 1u; - gpuScrambleImageView = device->createImageView(std::move(viewParams)); - } - - // Create Out Image TODO - constexpr uint32_t MAX_FBO_COUNT = 4u; - smart_refctd_ptr outHDRImageViews[MAX_FBO_COUNT] = {}; - assert(MAX_FBO_COUNT >= swapchain->getImageCount()); - for(uint32_t i = 0; i < swapchain->getImageCount(); ++i) { - outHDRImageViews[i] = createHDRImageView(device, asset::EF_R16G16B16A16_SFLOAT, WIN_W, WIN_H); - } - - core::smart_refctd_ptr descriptorSets0[FBO_COUNT] = {}; - for(uint32_t i = 0; i < FBO_COUNT; ++i) - { - auto & descSet = descriptorSets0[i]; - descSet = descriptorPool->createDescriptorSet(core::smart_refctd_ptr(gpuDescriptorSetLayout0)); - video::IGPUDescriptorSet::SWriteDescriptorSet writeDescriptorSet; - writeDescriptorSet.dstSet = descSet.get(); - writeDescriptorSet.binding = 0; - writeDescriptorSet.count = 1u; - writeDescriptorSet.arrayElement = 0u; - writeDescriptorSet.descriptorType = asset::IDescriptor::E_TYPE::ET_STORAGE_IMAGE; - video::IGPUDescriptorSet::SDescriptorInfo info; - { - info.desc = outHDRImageViews[i]; - info.info.image.sampler = nullptr; - info.info.image.imageLayout = asset::IImage::EL_GENERAL; - } - writeDescriptorSet.info = &info; - device->updateDescriptorSets(1u, &writeDescriptorSet, 0u, nullptr); - } - - struct SBasicViewParametersAligned - { - SBasicViewParameters uboData; - }; - - IGPUBuffer::SCreationParams gpuuboParams = {}; - gpuuboParams.usage = core::bitflag(IGPUBuffer::EUF_UNIFORM_BUFFER_BIT) | IGPUBuffer::EUF_TRANSFER_DST_BIT; - gpuuboParams.size = sizeof(SBasicViewParametersAligned); - auto gpuubo = device->createBuffer(std::move(gpuuboParams)); - auto gpuuboMemReqs = gpuubo->getMemoryReqs(); - gpuuboMemReqs.memoryTypeBits &= device->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - device->allocate(gpuuboMemReqs, gpuubo.get()); - - auto uboDescriptorSet1 = descriptorPool->createDescriptorSet(core::smart_refctd_ptr(gpuDescriptorSetLayout1)); - { - video::IGPUDescriptorSet::SWriteDescriptorSet uboWriteDescriptorSet; - uboWriteDescriptorSet.dstSet = uboDescriptorSet1.get(); - uboWriteDescriptorSet.binding = 0; - uboWriteDescriptorSet.count = 1u; - uboWriteDescriptorSet.arrayElement = 0u; - uboWriteDescriptorSet.descriptorType = asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER; - video::IGPUDescriptorSet::SDescriptorInfo info; - { - info.desc = gpuubo; - info.info.buffer.offset = 0ull; - info.info.buffer.size = sizeof(SBasicViewParametersAligned); - } - uboWriteDescriptorSet.info = &info; - device->updateDescriptorSets(1u, &uboWriteDescriptorSet, 0u, nullptr); - } - - ISampler::SParams samplerParams0 = { ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETBC_FLOAT_OPAQUE_BLACK, ISampler::ETF_LINEAR, ISampler::ETF_LINEAR, ISampler::ESMM_LINEAR, 0u, false, ECO_ALWAYS }; - auto sampler0 = device->createSampler(samplerParams0); - ISampler::SParams samplerParams1 = { ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETBC_INT_OPAQUE_BLACK, ISampler::ETF_NEAREST, ISampler::ETF_NEAREST, ISampler::ESMM_NEAREST, 0u, false, ECO_ALWAYS }; - auto sampler1 = device->createSampler(samplerParams1); - - auto descriptorSet2 = descriptorPool->createDescriptorSet(core::smart_refctd_ptr(gpuDescriptorSetLayout2)); - { - constexpr auto kDescriptorCount = 3; - IGPUDescriptorSet::SWriteDescriptorSet samplerWriteDescriptorSet[kDescriptorCount]; - IGPUDescriptorSet::SDescriptorInfo samplerDescriptorInfo[kDescriptorCount]; - for (auto i=0; iupdateDescriptorSets(kDescriptorCount, samplerWriteDescriptorSet, 0u, nullptr); - } - - constexpr uint32_t FRAME_COUNT = 500000u; - - core::smart_refctd_ptr frameComplete[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr imageAcquire[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr renderFinished[FRAMES_IN_FLIGHT] = { nullptr }; - for (uint32_t i=0u; icreateSemaphore(); - renderFinished[i] = device->createSemaphore(); - } - - CDumbPresentationOracle oracle; - oracle.reportBeginFrameRecord(); - constexpr uint64_t MAX_TIMEOUT = 99999999999999ull; - - // polling for events! - CommonAPI::InputSystem::ChannelReader mouse; - CommonAPI::InputSystem::ChannelReader keyboard; - - uint32_t resourceIx = 0; - while(windowCb->isWindowOpen()) - { - resourceIx++; - if(resourceIx >= FRAMES_IN_FLIGHT) { - resourceIx = 0; - } - - oracle.reportEndFrameRecord(); - double dt = oracle.getDeltaTimeInMicroSeconds() / 1000.0; - auto nextPresentationTimeStamp = oracle.getNextPresentationTimeStamp(); - oracle.reportBeginFrameRecord(); - - // Input - inputSystem->getDefaultMouse(&mouse); - inputSystem->getDefaultKeyboard(&keyboard); - - cam.beginInputProcessing(nextPresentationTimeStamp); - mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void { cam.mouseProcess(events); }, logger.get()); - keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void { cam.keyboardProcess(events); }, logger.get()); - cam.endInputProcessing(nextPresentationTimeStamp); - - auto& cb = cmdbuf[resourceIx]; - auto& fence = frameComplete[resourceIx]; - if (fence) - while (device->waitForFences(1u,&fence.get(),false,MAX_TIMEOUT)==video::IGPUFence::ES_TIMEOUT) - { - } - else - fence = device->createFence(static_cast(0)); - - const auto viewMatrix = cam.getViewMatrix(); - const auto viewProjectionMatrix = matrix4SIMD::concatenateBFollowedByAPrecisely( - video::ISurface::getSurfaceTransformationMatrix(swapchain->getPreTransform()), - cam.getConcatenatedMatrix() - ); - - // safe to proceed - cb->begin(IGPUCommandBuffer::EU_NONE); - cb->resetQueryPool(timestampQueryPool.get(), 0u, 2u); - - // renderpass - uint32_t imgnum = 0u; - swapchain->acquireNextImage(MAX_TIMEOUT,imageAcquire[resourceIx].get(),nullptr,&imgnum); - { - auto mv = viewMatrix; - auto mvp = viewProjectionMatrix; - core::matrix3x4SIMD normalMat; - mv.getSub3x3InverseTranspose(normalMat); - - SBasicViewParametersAligned viewParams; - memcpy(viewParams.uboData.MV, mv.pointer(), sizeof(mv)); - memcpy(viewParams.uboData.MVP, mvp.pointer(), sizeof(mvp)); - memcpy(viewParams.uboData.NormalMat, normalMat.pointer(), sizeof(normalMat)); - - asset::SBufferRange range; - range.buffer = gpuubo; - range.offset = 0ull; - range.size = sizeof(viewParams); - utilities->updateBufferRangeViaStagingBufferAutoSubmit(range, &viewParams, graphicsQueue); - } - - // TRANSITION outHDRImageViews[imgnum] to EIL_GENERAL (because of descriptorSets0 -> ComputeShader Writes into the image) - { - IGPUCommandBuffer::SImageMemoryBarrier imageBarriers[3u] = {}; - imageBarriers[0].barrier.srcAccessMask = asset::EAF_NONE; - imageBarriers[0].barrier.dstAccessMask = static_cast(asset::EAF_SHADER_WRITE_BIT); - imageBarriers[0].oldLayout = asset::IImage::EL_UNDEFINED; - imageBarriers[0].newLayout = asset::IImage::EL_GENERAL; - imageBarriers[0].srcQueueFamilyIndex = graphicsCmdPoolQueueFamIdx; - imageBarriers[0].dstQueueFamilyIndex = graphicsCmdPoolQueueFamIdx; - imageBarriers[0].image = outHDRImageViews[imgnum]->getCreationParameters().image; - imageBarriers[0].subresourceRange.aspectMask = asset::IImage::EAF_COLOR_BIT; - imageBarriers[0].subresourceRange.baseMipLevel = 0u; - imageBarriers[0].subresourceRange.levelCount = 1; - imageBarriers[0].subresourceRange.baseArrayLayer = 0u; - imageBarriers[0].subresourceRange.layerCount = 1; - - imageBarriers[1].barrier.srcAccessMask = asset::EAF_NONE; - imageBarriers[1].barrier.dstAccessMask = static_cast(asset::EAF_SHADER_READ_BIT); - imageBarriers[1].oldLayout = asset::IImage::EL_UNDEFINED; - imageBarriers[1].newLayout = asset::IImage::EL_SHADER_READ_ONLY_OPTIMAL; - imageBarriers[1].srcQueueFamilyIndex = graphicsCmdPoolQueueFamIdx; - imageBarriers[1].dstQueueFamilyIndex = graphicsCmdPoolQueueFamIdx; - imageBarriers[1].image = gpuScrambleImageView->getCreationParameters().image; - imageBarriers[1].subresourceRange.aspectMask = asset::IImage::EAF_COLOR_BIT; - imageBarriers[1].subresourceRange.baseMipLevel = 0u; - imageBarriers[1].subresourceRange.levelCount = 1; - imageBarriers[1].subresourceRange.baseArrayLayer = 0u; - imageBarriers[1].subresourceRange.layerCount = 1; - - imageBarriers[2].barrier.srcAccessMask = asset::EAF_NONE; - imageBarriers[2].barrier.dstAccessMask = static_cast(asset::EAF_SHADER_READ_BIT); - imageBarriers[2].oldLayout = asset::IImage::EL_UNDEFINED; - imageBarriers[2].newLayout = asset::IImage::EL_SHADER_READ_ONLY_OPTIMAL; - imageBarriers[2].srcQueueFamilyIndex = graphicsCmdPoolQueueFamIdx; - imageBarriers[2].dstQueueFamilyIndex = graphicsCmdPoolQueueFamIdx; - imageBarriers[2].image = gpuEnvmapImageView->getCreationParameters().image; - imageBarriers[2].subresourceRange.aspectMask = asset::IImage::EAF_COLOR_BIT; - imageBarriers[2].subresourceRange.baseMipLevel = 0u; - imageBarriers[2].subresourceRange.levelCount = gpuEnvmapImageView->getCreationParameters().subresourceRange.levelCount; - imageBarriers[2].subresourceRange.baseArrayLayer = 0u; - imageBarriers[2].subresourceRange.layerCount = gpuEnvmapImageView->getCreationParameters().subresourceRange.layerCount; - - cb->pipelineBarrier(asset::EPSF_TOP_OF_PIPE_BIT, asset::EPSF_COMPUTE_SHADER_BIT, asset::EDF_NONE, 0u, nullptr, 0u, nullptr, 3u, imageBarriers); - } - - // cube envmap handle - { - cb->writeTimestamp(asset::E_PIPELINE_STAGE_FLAGS::EPSF_TOP_OF_PIPE_BIT, timestampQueryPool.get(), 0u); - cb->bindComputePipeline(gpuComputePipeline.get()); - cb->bindDescriptorSets(EPBP_COMPUTE, gpuComputePipeline->getLayout(), 0u, 1u, &descriptorSets0[imgnum].get()); - cb->bindDescriptorSets(EPBP_COMPUTE, gpuComputePipeline->getLayout(), 1u, 1u, &uboDescriptorSet1.get()); - cb->bindDescriptorSets(EPBP_COMPUTE, gpuComputePipeline->getLayout(), 2u, 1u, &descriptorSet2.get()); - cb->dispatch(dispatchInfo.workGroupCount[0], dispatchInfo.workGroupCount[1], dispatchInfo.workGroupCount[2]); - cb->writeTimestamp(asset::E_PIPELINE_STAGE_FLAGS::EPSF_BOTTOM_OF_PIPE_BIT, timestampQueryPool.get(), 1u); - } - // TODO: tone mapping and stuff - - // Copy HDR Image to SwapChain - auto srcImgViewCreationParams = outHDRImageViews[imgnum]->getCreationParameters(); - auto dstImgViewCreationParams = fbo->begin()[imgnum]->getCreationParameters().attachments[0]->getCreationParameters(); - - // Getting Ready for Blit - // TRANSITION outHDRImageViews[imgnum] to EIL_TRANSFER_SRC_OPTIMAL - // TRANSITION `fbo[imgnum]->getCreationParameters().attachments[0]` to EIL_TRANSFER_DST_OPTIMAL - { - IGPUCommandBuffer::SImageMemoryBarrier imageBarriers[2u] = {}; - imageBarriers[0].barrier.srcAccessMask = asset::EAF_NONE; - imageBarriers[0].barrier.dstAccessMask = asset::EAF_TRANSFER_WRITE_BIT; - imageBarriers[0].oldLayout = asset::IImage::EL_UNDEFINED; - imageBarriers[0].newLayout = asset::IImage::EL_TRANSFER_SRC_OPTIMAL; - imageBarriers[0].srcQueueFamilyIndex = graphicsCmdPoolQueueFamIdx; - imageBarriers[0].dstQueueFamilyIndex = graphicsCmdPoolQueueFamIdx; - imageBarriers[0].image = srcImgViewCreationParams.image; - imageBarriers[0].subresourceRange.aspectMask = asset::IImage::EAF_COLOR_BIT; - imageBarriers[0].subresourceRange.baseMipLevel = 0u; - imageBarriers[0].subresourceRange.levelCount = 1; - imageBarriers[0].subresourceRange.baseArrayLayer = 0u; - imageBarriers[0].subresourceRange.layerCount = 1; - - imageBarriers[1].barrier.srcAccessMask = asset::EAF_NONE; - imageBarriers[1].barrier.dstAccessMask = asset::EAF_TRANSFER_WRITE_BIT; - imageBarriers[1].oldLayout = asset::IImage::EL_UNDEFINED; - imageBarriers[1].newLayout = asset::IImage::EL_TRANSFER_DST_OPTIMAL; - imageBarriers[1].srcQueueFamilyIndex = graphicsCmdPoolQueueFamIdx; - imageBarriers[1].dstQueueFamilyIndex = graphicsCmdPoolQueueFamIdx; - imageBarriers[1].image = dstImgViewCreationParams.image; - imageBarriers[1].subresourceRange.aspectMask = asset::IImage::EAF_COLOR_BIT; - imageBarriers[1].subresourceRange.baseMipLevel = 0u; - imageBarriers[1].subresourceRange.levelCount = 1; - imageBarriers[1].subresourceRange.baseArrayLayer = 0u; - imageBarriers[1].subresourceRange.layerCount = 1; - cb->pipelineBarrier(asset::EPSF_TRANSFER_BIT, asset::EPSF_TRANSFER_BIT, asset::EDF_NONE, 0u, nullptr, 0u, nullptr, 2u, imageBarriers); - } - - // Blit Image - { - SImageBlit blit = {}; - blit.srcOffsets[0] = {0, 0, 0}; - blit.srcOffsets[1] = {WIN_W, WIN_H, 1}; - - blit.srcSubresource.aspectMask = srcImgViewCreationParams.subresourceRange.aspectMask; - blit.srcSubresource.mipLevel = srcImgViewCreationParams.subresourceRange.baseMipLevel; - blit.srcSubresource.baseArrayLayer = srcImgViewCreationParams.subresourceRange.baseArrayLayer; - blit.srcSubresource.layerCount = srcImgViewCreationParams.subresourceRange.layerCount; - blit.dstOffsets[0] = {0, 0, 0}; - blit.dstOffsets[1] = {WIN_W, WIN_H, 1}; - blit.dstSubresource.aspectMask = dstImgViewCreationParams.subresourceRange.aspectMask; - blit.dstSubresource.mipLevel = dstImgViewCreationParams.subresourceRange.baseMipLevel; - blit.dstSubresource.baseArrayLayer = dstImgViewCreationParams.subresourceRange.baseArrayLayer; - blit.dstSubresource.layerCount = dstImgViewCreationParams.subresourceRange.layerCount; - - auto srcImg = srcImgViewCreationParams.image; - auto dstImg = dstImgViewCreationParams.image; - - cb->blitImage(srcImg.get(), asset::IImage::EL_TRANSFER_SRC_OPTIMAL, dstImg.get(), asset::IImage::EL_TRANSFER_DST_OPTIMAL, 1u, &blit , ISampler::ETF_NEAREST); - } - - // TRANSITION `fbo[imgnum]->getCreationParameters().attachments[0]` to EIL_PRESENT - { - IGPUCommandBuffer::SImageMemoryBarrier imageBarriers[1u] = {}; - imageBarriers[0].barrier.srcAccessMask = asset::EAF_TRANSFER_WRITE_BIT; - imageBarriers[0].barrier.dstAccessMask = asset::EAF_NONE; - imageBarriers[0].oldLayout = asset::IImage::EL_TRANSFER_DST_OPTIMAL; - imageBarriers[0].newLayout = asset::IImage::EL_PRESENT_SRC; - imageBarriers[0].srcQueueFamilyIndex = graphicsCmdPoolQueueFamIdx; - imageBarriers[0].dstQueueFamilyIndex = graphicsCmdPoolQueueFamIdx; - imageBarriers[0].image = dstImgViewCreationParams.image; - imageBarriers[0].subresourceRange.aspectMask = asset::IImage::EAF_COLOR_BIT; - imageBarriers[0].subresourceRange.baseMipLevel = 0u; - imageBarriers[0].subresourceRange.levelCount = 1; - imageBarriers[0].subresourceRange.baseArrayLayer = 0u; - imageBarriers[0].subresourceRange.layerCount = 1; - cb->pipelineBarrier(asset::EPSF_TRANSFER_BIT, asset::EPSF_TOP_OF_PIPE_BIT, asset::EDF_NONE, 0u, nullptr, 0u, nullptr, 1u, imageBarriers); - } - - cb->end(); - device->resetFences(1, &fence.get()); - CommonAPI::Submit(device.get(), cb.get(), graphicsQueue, imageAcquire[resourceIx].get(), renderFinished[resourceIx].get(), fence.get()); - CommonAPI::Present(device.get(), swapchain.get(), graphicsQueue, renderFinished[resourceIx].get(), imgnum); - - if (LOG_TIMESTAMP) - { - std::array timestamps{}; - auto queryResultFlags = core::bitflag(video::IQueryPool::EQRF_WAIT_BIT) | video::IQueryPool::EQRF_WITH_AVAILABILITY_BIT | video::IQueryPool::EQRF_64_BIT; - device->getQueryPoolResults(timestampQueryPool.get(), 0u, 2u, sizeof(timestamps), timestamps.data(), sizeof(uint64_t) * 2ull, queryResultFlags); - const float timePassed = (timestamps[2] - timestamps[0]) * device->getPhysicalDevice()->getLimits().timestampPeriodInNanoSeconds; - logger->log("Time Passed (Seconds) = %f", system::ILogger::ELL_INFO, (timePassed * 1e-9)); - logger->log("Timestamps availablity: %d, %d", system::ILogger::ELL_INFO, timestamps[1], timestamps[3]); - } - } - - const auto& fboCreationParams = fbo->begin()[0]->getCreationParameters(); - auto gpuSourceImageView = fboCreationParams.attachments[0]; - - device->waitIdle(); - - // bool status = ext::ScreenShot::createScreenShot(device.get(), queues[decltype(initOutput)::EQT_TRANSFER_UP], renderFinished[0].get(), gpuSourceImageView.get(), assetManager.get(), "ScreenShot.png"); - // assert(status); - - return 0; -} diff --git a/42_FragmentShaderPathTracer/pipeline.groovy b/42_FragmentShaderPathTracer/pipeline.groovy deleted file mode 100644 index 9e3a71cf3..000000000 --- a/42_FragmentShaderPathTracer/pipeline.groovy +++ /dev/null @@ -1,50 +0,0 @@ -import org.DevshGraphicsProgramming.Agent -import org.DevshGraphicsProgramming.BuilderInfo -import org.DevshGraphicsProgramming.IBuilder - -class CFragmentShaderPathTracerBuilder extends IBuilder -{ - public CFragmentShaderPathTracerBuilder(Agent _agent, _info) - { - super(_agent, _info) - } - - @Override - public boolean prepare(Map axisMapping) - { - return true - } - - @Override - public boolean build(Map axisMapping) - { - IBuilder.CONFIGURATION config = axisMapping.get("CONFIGURATION") - IBuilder.BUILD_TYPE buildType = axisMapping.get("BUILD_TYPE") - - def nameOfBuildDirectory = getNameOfBuildDirectory(buildType) - def nameOfConfig = getNameOfConfig(config) - - agent.execute("cmake --build ${info.rootProjectPath}/${nameOfBuildDirectory}/${info.targetProjectPathRelativeToRoot} --target ${info.targetBaseName} --config ${nameOfConfig} -j12 -v") - - return true - } - - @Override - public boolean test(Map axisMapping) - { - return true - } - - @Override - public boolean install(Map axisMapping) - { - return true - } -} - -def create(Agent _agent, _info) -{ - return new CFragmentShaderPathTracerBuilder(_agent, _info) -} - -return this \ No newline at end of file diff --git a/53_ComputeShaders/CMakeLists.txt b/53_ComputeShaders/CMakeLists.txt deleted file mode 100644 index 2f9218f93..000000000 --- a/53_ComputeShaders/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -include(common RESULT_VARIABLE RES) -if(NOT RES) - message(FATAL_ERROR "common.cmake not found. Should be in {repo_root}/cmake directory") -endif() - -nbl_create_executable_project("" "" "" "" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") \ No newline at end of file diff --git a/53_ComputeShaders/computeShader.comp b/53_ComputeShaders/computeShader.comp deleted file mode 100644 index 033a6aabb..000000000 --- a/53_ComputeShaders/computeShader.comp +++ /dev/null @@ -1,95 +0,0 @@ -#version 450 core -#extension GL_EXT_shader_16bit_storage : require - -#include "shaderCommon.glsl" - -layout(set = 0, binding = 0, std430) buffer Position -{ - vec4 positions[]; -}; - -layout(set = 0, binding = 1, std430) buffer Velocity -{ - vec4 velocities[]; -}; - -layout(set = 0, binding = 2, std430) buffer Color -{ - vec4 colors[]; -}; - -layout(set = 0, binding = 3, std430) buffer ColorRisingFlag -{ - bvec4 colorsRisingFlag[]; -}; - -layout(local_size_x = 128, local_size_y = 1, local_size_z = 1) in; - -void manageColorAxieState(float colorAxie, inout bool colorIntensityRisingAxieFlag) -{ - if(colorAxie <= 0) - colorIntensityRisingAxieFlag = true; - else if(colorAxie >= 1) - colorIntensityRisingAxieFlag = false; -} - -void manageColorState(vec3 color) -{ - uint globalInvocationID = gl_GlobalInvocationID.x; // the .y and .z are both 1 in this case - bvec4 isColorIntensityRising = colorsRisingFlag[globalInvocationID]; - - manageColorAxieState(color.x, isColorIntensityRising.x); - manageColorAxieState(color.y, isColorIntensityRising.y); - manageColorAxieState(color.z, isColorIntensityRising.z); - - colorsRisingFlag[globalInvocationID] = isColorIntensityRising; -} - -float getNewAxieColor(float colorAxie, bool colorIntensityRisingAxieFlag) -{ - const float colorDelta = 0.04; - - if(colorIntensityRisingAxieFlag) - colorAxie += colorDelta; - else - colorAxie -= colorDelta; - - return colorAxie; -} - -vec3 getNewColor(vec3 color) -{ - uint globalInvocationID = gl_GlobalInvocationID.x; // the .y and .z are both 1 in this case - bvec4 isColorIntensityRising = colorsRisingFlag[globalInvocationID]; - - return vec3(getNewAxieColor(color.x, isColorIntensityRising.x), getNewAxieColor(color.y, isColorIntensityRising.y), getNewAxieColor(color.z, isColorIntensityRising.z)); -} - -void main() -{ - const float deltaTime = 0.004; - - uint globalInvocationID = gl_GlobalInvocationID.x; // the .y and .z are both 1 in this case - - vec3 position = positions[globalInvocationID].xyz; - vec3 velocity = velocities[globalInvocationID].xyz; - vec3 color = colors[globalInvocationID].xyz; - - if(!pushConstants.isXPressed) - { - /* - if(pushConstants.isZPressed) - { - // TODO gravity to force a particle's velocity towards the user - } - */ - position += velocity * deltaTime; - } - - vec3 newComputedColor = getNewColor(color); - manageColorState(newComputedColor); - - positions[globalInvocationID].xyz = position; - velocities[globalInvocationID].xyz = velocity; - colors[globalInvocationID].xyz = newComputedColor; -} \ No newline at end of file diff --git a/53_ComputeShaders/config.json.template b/53_ComputeShaders/config.json.template deleted file mode 100644 index f961745c1..000000000 --- a/53_ComputeShaders/config.json.template +++ /dev/null @@ -1,28 +0,0 @@ -{ - "enableParallelBuild": true, - "threadsPerBuildProcess" : 2, - "isExecuted": false, - "scriptPath": "", - "cmake": { - "configurations": [ "Release", "Debug", "RelWithDebInfo" ], - "buildModes": [], - "requiredOptions": [] - }, - "profiles": [ - { - "backend": "vulkan", - "platform": "windows", - "buildModes": [], - "runConfiguration": "Release", - "gpuArchitectures": [] - } - ], - "dependencies": [], - "data": [ - { - "dependencies": [], - "command": [""], - "outputs": [] - } - ] -} \ No newline at end of file diff --git a/53_ComputeShaders/fragmentShader.frag b/53_ComputeShaders/fragmentShader.frag deleted file mode 100644 index 9fe445b2b..000000000 --- a/53_ComputeShaders/fragmentShader.frag +++ /dev/null @@ -1,12 +0,0 @@ -#version 430 core - -layout(location = 0) in vec4 inFFullyProjectedVelocity; -layout(location = 1) in vec4 inFColor; - -layout(location = 0) out vec4 outColor; - -void main() -{ - outColor = inFColor; -} - \ No newline at end of file diff --git a/53_ComputeShaders/geometryShader.geom b/53_ComputeShaders/geometryShader.geom deleted file mode 100644 index 4a8bf36f0..000000000 --- a/53_ComputeShaders/geometryShader.geom +++ /dev/null @@ -1,27 +0,0 @@ -#version 450 core - -#include "shaderCommon.glsl" - -layout(location = 0) in vec4 gFullyProjectedVelocity[]; -layout(location = 1) in vec4 gColor[]; - -layout(location = 0) out vec4 outFVelocity; -layout(location = 1) out vec4 outFColor; - -layout (points) in; -layout (line_strip, max_vertices = 2) out; - -void main() -{ - if(pushConstants.isCPressed) - { - outFColor = vec4(0.0, 1.0, 0.0, 0.0); - gl_Position = gl_in[0].gl_Position; - EmitVertex(); - gl_Position = gl_in[0].gl_Position + gFullyProjectedVelocity[0]; - EmitVertex(); - - EndPrimitive(); - } -} - \ No newline at end of file diff --git a/53_ComputeShaders/main.cpp b/53_ComputeShaders/main.cpp deleted file mode 100644 index b8fb14017..000000000 --- a/53_ComputeShaders/main.cpp +++ /dev/null @@ -1,694 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -#define _NBL_STATIC_LIB_ -#include -#include -#include - -#include "CCamera.hpp" -#include "../common/CommonAPI.h" -#include "nbl/ext/ScreenShot/ScreenShot.h" - -using namespace nbl; -using namespace asset; -using namespace core; - -/* - Uncomment for more detailed logging -*/ - -// #define NBL_MORE_LOGS - -class CEventReceiver -{ -public: - CEventReceiver() : particlesVectorChangeFlag(false), forceChangeVelocityFlag(false), visualizeVelocityVectorsFlag(false) {} - - void process(const ui::IKeyboardEventChannel::range_t& events) - { - particlesVectorChangeFlag = false; - forceChangeVelocityFlag = false; - visualizeVelocityVectorsFlag = false; - - for (auto eventIterator = events.begin(); eventIterator != events.end(); eventIterator++) - { - auto event = *eventIterator; - - if (event.keyCode == nbl::ui::EKC_X) - particlesVectorChangeFlag = true; - - if (event.keyCode == nbl::ui::EKC_Z) - forceChangeVelocityFlag = true; - - if (event.keyCode == nbl::ui::EKC_C) - visualizeVelocityVectorsFlag = true; - - if (event.keyCode == nbl::ui::EKC_V) - visualizeVelocityVectorsFlag = false; - } - } - - inline bool isXPressed() const { return particlesVectorChangeFlag; } - inline bool isZPressed() const { return forceChangeVelocityFlag; } - inline bool isCPressed() const { return visualizeVelocityVectorsFlag; } - -private: - bool particlesVectorChangeFlag; - bool forceChangeVelocityFlag; - bool visualizeVelocityVectorsFlag; -}; - -_NBL_STATIC_INLINE_CONSTEXPR size_t NUMBER_OF_PARTICLES = 1024 * 1024; // total number of particles to move -_NBL_STATIC_INLINE_CONSTEXPR size_t WORK_GROUP_SIZE = 128; // work-items per work-group - -enum E_ENTRIES -{ - EE_POSITIONS, - EE_VELOCITIES, - EE_COLORS, - EE_COLORS_RISING_FLAG, - EE_COUNT -}; - -#include "nbl/nblpack.h" -struct alignas(16) SShaderStorageBufferObject -{ - core::vector4df_SIMD positions[NUMBER_OF_PARTICLES]; - core::vector4df_SIMD velocities[NUMBER_OF_PARTICLES]; - core::vector4df_SIMD colors[NUMBER_OF_PARTICLES]; - bool isColorIntensityRising[NUMBER_OF_PARTICLES][4]; -} PACK_STRUCT; -#include "nbl/nblunpack.h" - -static_assert(sizeof(SShaderStorageBufferObject) == sizeof(SShaderStorageBufferObject::positions) + sizeof(SShaderStorageBufferObject::velocities) + sizeof(SShaderStorageBufferObject::colors) + sizeof(SShaderStorageBufferObject::isColorIntensityRising), "There will be inproper alignment!"); - -#include "nbl/nblpack.h" -struct alignas(32) SPushConstants -{ - uint32_t isXPressed = false; - uint32_t isZPressed = false; - uint32_t isCPressed = false; - core::vector3df currentUserAbsolutePosition; -} PACK_STRUCT; -#include "nbl/nblunpack.h" - -void triggerRandomSetup(SShaderStorageBufferObject* ssbo) -{ - _NBL_STATIC_INLINE_CONSTEXPR float POSITION_EACH_AXIE_MIN = -10.f; - _NBL_STATIC_INLINE_CONSTEXPR float POSITION_EACH_AXIE_MAX = 10.f; - - _NBL_STATIC_INLINE_CONSTEXPR float VELOCITY_EACH_AXIE_MIN = 0.f; - _NBL_STATIC_INLINE_CONSTEXPR float VELOCITY_EACH_AXIE_MAX = 0.001f; - - _NBL_STATIC_INLINE_CONSTEXPR float COLOR_EACH_AXIE_MIN = 0.f; - _NBL_STATIC_INLINE_CONSTEXPR float COLOR_EACH_AXIE_MAX = 1.f; - - auto get_random = [&](const float& min, const float& max) - { - static std::default_random_engine engine; - static std::uniform_real_distribution<> distribution(min, max); - return distribution(engine); - }; - - for (size_t i = 0; i < NUMBER_OF_PARTICLES; ++i) - { - ssbo->positions[i] = core::vector4df_SIMD(get_random(POSITION_EACH_AXIE_MIN, POSITION_EACH_AXIE_MAX), get_random(POSITION_EACH_AXIE_MIN, POSITION_EACH_AXIE_MAX), get_random(POSITION_EACH_AXIE_MIN, POSITION_EACH_AXIE_MAX), get_random(POSITION_EACH_AXIE_MIN, POSITION_EACH_AXIE_MAX)); - ssbo->velocities[i] = core::vector4df_SIMD(get_random(VELOCITY_EACH_AXIE_MIN, VELOCITY_EACH_AXIE_MAX), get_random(VELOCITY_EACH_AXIE_MIN, VELOCITY_EACH_AXIE_MAX), get_random(VELOCITY_EACH_AXIE_MIN, VELOCITY_EACH_AXIE_MAX), get_random(VELOCITY_EACH_AXIE_MIN, VELOCITY_EACH_AXIE_MAX)); - ssbo->colors[i] = core::vector4df_SIMD(get_random(COLOR_EACH_AXIE_MIN, COLOR_EACH_AXIE_MAX), get_random(COLOR_EACH_AXIE_MIN, COLOR_EACH_AXIE_MAX), get_random(COLOR_EACH_AXIE_MIN, COLOR_EACH_AXIE_MAX), get_random(COLOR_EACH_AXIE_MIN, COLOR_EACH_AXIE_MAX)); - - for (uint8_t b = 0; b < 4; ++b) - ssbo->isColorIntensityRising[i][b] = true; - } -} - -class MeshLoadersApp : public ApplicationBase -{ - static constexpr uint32_t WIN_W = 1280; - static constexpr uint32_t WIN_H = 720; - static constexpr uint32_t FBO_COUNT = 2u; - static constexpr uint32_t FRAMES_IN_FLIGHT = 1u; - static constexpr size_t NBL_FRAMES_TO_AVERAGE = 100ull; - -public: - nbl::core::smart_refctd_ptr windowManager; - nbl::core::smart_refctd_ptr window; - nbl::core::smart_refctd_ptr windowCallback; - nbl::core::smart_refctd_ptr gl; - nbl::core::smart_refctd_ptr surface; - nbl::core::smart_refctd_ptr utilities; - nbl::core::smart_refctd_ptr logicalDevice; - nbl::video::IPhysicalDevice* gpuPhysicalDevice; - std::array queues = { nullptr, nullptr, nullptr, nullptr }; - nbl::core::smart_refctd_ptr swapchain; - nbl::core::smart_refctd_ptr renderpass; - nbl::core::smart_refctd_dynamic_array> fbo; - std::array, CommonAPI::InitOutput::MaxFramesInFlight>, CommonAPI::InitOutput::MaxQueuesCount> commandPools; - nbl::core::smart_refctd_ptr system; - nbl::core::smart_refctd_ptr assetManager; - nbl::video::IGPUObjectFromAssetConverter::SParams cpu2gpuParams; - nbl::core::smart_refctd_ptr logger; - nbl::core::smart_refctd_ptr inputSystem; - - nbl::core::smart_refctd_ptr gpuTransferFence; - nbl::core::smart_refctd_ptr gpuComputeFence; - nbl::video::IGPUObjectFromAssetConverter cpu2gpu; - - core::smart_refctd_ptr commandBuffers[1]; - - CEventReceiver eventReceiver; - CommonAPI::InputSystem::ChannelReader mouse; - CommonAPI::InputSystem::ChannelReader keyboard; - - Camera camera = Camera(core::vectorSIMDf(0, 0, 0), core::vectorSIMDf(0, 0, 0), core::matrix4SIMD()); - std::chrono::system_clock::time_point lastTime; - size_t frame_count = 0ull; - double time_sum = 0; - double dtList[NBL_FRAMES_TO_AVERAGE] = {}; - - SPushConstants pushConstants; - nbl::core::smart_refctd_ptr gpuComputePipeline; - nbl::core::smart_refctd_ptr gpuCDescriptorSet; - nbl::core::smart_refctd_ptr gpuUBO; - nbl::core::smart_refctd_ptr gpuGraphicsPipeline; - nbl::core::smart_refctd_ptr gpuGraphicsPipeline2; - nbl::core::smart_refctd_ptr gpuMeshBuffer; - nbl::core::smart_refctd_ptr gpuMeshBuffer2; - core::smart_refctd_ptr gpuGDescriptorSet1; - nbl::core::smart_refctd_ptr render_finished_sem; - nbl::video::ISwapchain::SCreationParams m_swapchainCreationParams; - - void setWindow(core::smart_refctd_ptr&& wnd) override - { - window = std::move(wnd); - } - void setSystem(core::smart_refctd_ptr&& s) override - { - system = std::move(s); - } - nbl::ui::IWindow* getWindow() override - { - return window.get(); - } - video::IAPIConnection* getAPIConnection() override - { - return gl.get(); - } - video::ILogicalDevice* getLogicalDevice() override - { - return logicalDevice.get(); - } - video::IGPURenderpass* getRenderpass() override - { - return renderpass.get(); - } - void setSurface(core::smart_refctd_ptr&& s) override - { - surface = std::move(s); - } - void setFBOs(std::vector>& f) override - { - for (int i = 0; i < f.size(); i++) - { - fbo->begin()[i] = core::smart_refctd_ptr(f[i]); - } - } - void setSwapchain(core::smart_refctd_ptr&& s) override - { - swapchain = std::move(s); - } - uint32_t getSwapchainImageCount() override - { - return swapchain->getImageCount(); - } - virtual nbl::asset::E_FORMAT getDepthFormat() override - { - return nbl::asset::EF_D32_SFLOAT; - } - -APP_CONSTRUCTOR(MeshLoadersApp) - - void onAppInitialized_impl() override - { - const auto swapchainImageUsage = static_cast(asset::IImage::EUF_COLOR_ATTACHMENT_BIT); - CommonAPI::InitParams initParams; - initParams.window = core::smart_refctd_ptr(window); - initParams.apiType = video::EAT_VULKAN; - initParams.appName = { _NBL_APP_NAME_ }; - initParams.framesInFlight = FRAMES_IN_FLIGHT; - initParams.windowWidth = WIN_W; - initParams.windowHeight = WIN_H; - initParams.swapchainImageCount = FBO_COUNT; - initParams.swapchainImageUsage = swapchainImageUsage; - initParams.depthFormat = nbl::asset::EF_D32_SFLOAT; - auto initOutput = CommonAPI::InitWithDefaultExt(std::move(initParams)); - - window = std::move(initParams.window); - gl = std::move(initOutput.apiConnection); - surface = std::move(initOutput.surface); - gpuPhysicalDevice = std::move(initOutput.physicalDevice); - logicalDevice = std::move(initOutput.logicalDevice); - queues = std::move(initOutput.queues); - renderpass = std::move(initOutput.renderToSwapchainRenderpass); - commandPools = std::move(initOutput.commandPools); - assetManager = std::move(initOutput.assetManager); - logger = std::move(initOutput.logger); - inputSystem = std::move(initOutput.inputSystem); - windowCallback = std::move(initParams.windowCb); - cpu2gpuParams = std::move(initOutput.cpu2gpuParams); - m_swapchainCreationParams = std::move(initOutput.swapchainCreationParams); - auto defaultGraphicsCommandPool = commandPools[CommonAPI::InitOutput::EQT_GRAPHICS][0]; - - CommonAPI::createSwapchain(std::move(logicalDevice), m_swapchainCreationParams, WIN_W, WIN_H, swapchain); - assert(swapchain); - fbo = CommonAPI::createFBOWithSwapchainImages( - swapchain->getImageCount(), WIN_W, WIN_H, - logicalDevice, swapchain, renderpass, - nbl::asset::EF_D32_SFLOAT - ); - - logicalDevice->createCommandBuffers(defaultGraphicsCommandPool.get(), nbl::video::IGPUCommandBuffer::EL_PRIMARY, 1, commandBuffers); - auto commandBuffer = commandBuffers[0]; - - auto createDescriptorPool = [&](const uint32_t itemCount, E_DESCRIPTOR_TYPE descriptorType) - { - constexpr uint32_t maxItemCount = 256u; - { - nbl::video::IDescriptorPool::SDescriptorPoolSize poolSize; - poolSize.count = itemCount; - poolSize.type = descriptorType; - return logicalDevice->createDescriptorPool(static_cast(0), maxItemCount, 1u, &poolSize); - } - }; - - /* - Compute pipeline - */ - - auto computeShaderBundle = assetManager->getAsset("../computeShader.comp", {}); - { - bool status = !computeShaderBundle.getContents().empty(); - assert(status); - } - - auto cpuComputeShader = core::smart_refctd_ptr_static_cast(computeShaderBundle.getContents().begin()[0]); - smart_refctd_ptr gpuComputeShader; - { - auto gpu_array = cpu2gpu.getGPUObjectsFromAssets(&cpuComputeShader, &cpuComputeShader + 1, cpu2gpuParams); - if (!gpu_array || gpu_array->size() < 1u || !(*gpu_array)[0]) - assert(false); - - gpuComputeShader = (*gpu_array)[0]; - } - - auto cpuSSBOBuffer = ICPUBuffer::create({ sizeof(SShaderStorageBufferObject) }); - cpuSSBOBuffer->addUsageFlags(asset::IBuffer::EUF_STORAGE_BUFFER_BIT); - triggerRandomSetup(reinterpret_cast(cpuSSBOBuffer->getPointer())); - core::smart_refctd_ptr gpuSSBOBuffer; - { - cpu2gpuParams.beginCommandBuffers(); - - auto gpu_array = cpu2gpu.getGPUObjectsFromAssets(&cpuSSBOBuffer, &cpuSSBOBuffer + 1, cpu2gpuParams); - if (!gpu_array || gpu_array->size() < 1u || !(*gpu_array)[0]) - assert(false); - - cpu2gpuParams.waitForCreationToComplete(false); - - auto gpuSSBOOffsetBufferPair = (*gpu_array)[0]; - gpuSSBOBuffer = core::smart_refctd_ptr(gpuSSBOOffsetBufferPair->getBuffer()); - } - - video::IGPUDescriptorSetLayout::SBinding gpuBindingsLayout[EE_COUNT] = - { - {EE_POSITIONS, EDT_STORAGE_BUFFER, 1u, video::IGPUShader::ESS_COMPUTE, nullptr}, - {EE_VELOCITIES, EDT_STORAGE_BUFFER, 1u, video::IGPUShader::ESS_COMPUTE, nullptr}, - {EE_COLORS, EDT_STORAGE_BUFFER, 1u, video::IGPUShader::ESS_COMPUTE, nullptr}, - {EE_COLORS_RISING_FLAG, EDT_STORAGE_BUFFER, 1u, video::IGPUShader::ESS_COMPUTE, nullptr} - }; - - auto gpuCDescriptorPool = createDescriptorPool(EE_COUNT, EDT_STORAGE_BUFFER); - auto gpuCDescriptorSetLayout = logicalDevice->createDescriptorSetLayout(gpuBindingsLayout, gpuBindingsLayout + EE_COUNT); - gpuCDescriptorSet = logicalDevice->createDescriptorSet(gpuCDescriptorPool.get(), core::smart_refctd_ptr(gpuCDescriptorSetLayout)); - { - video::IGPUDescriptorSet::SDescriptorInfo gpuDescriptorSetInfos[EE_COUNT]; - - gpuDescriptorSetInfos[EE_POSITIONS].desc = gpuSSBOBuffer; - gpuDescriptorSetInfos[EE_POSITIONS].buffer.size = sizeof(SShaderStorageBufferObject::positions); - gpuDescriptorSetInfos[EE_POSITIONS].buffer.offset = 0; - - gpuDescriptorSetInfos[EE_VELOCITIES].desc = gpuSSBOBuffer; - gpuDescriptorSetInfos[EE_VELOCITIES].buffer.size = sizeof(SShaderStorageBufferObject::velocities); - gpuDescriptorSetInfos[EE_VELOCITIES].buffer.offset = sizeof(SShaderStorageBufferObject::positions); - - gpuDescriptorSetInfos[EE_COLORS].desc = gpuSSBOBuffer; - gpuDescriptorSetInfos[EE_COLORS].buffer.size = sizeof(SShaderStorageBufferObject::colors); - gpuDescriptorSetInfos[EE_COLORS].buffer.offset = gpuDescriptorSetInfos[EE_VELOCITIES].buffer.offset + sizeof(SShaderStorageBufferObject::velocities); - - gpuDescriptorSetInfos[EE_COLORS_RISING_FLAG].desc = gpuSSBOBuffer; - gpuDescriptorSetInfos[EE_COLORS_RISING_FLAG].buffer.size = sizeof(SShaderStorageBufferObject::isColorIntensityRising); - gpuDescriptorSetInfos[EE_COLORS_RISING_FLAG].buffer.offset = gpuDescriptorSetInfos[EE_COLORS].buffer.offset + sizeof(SShaderStorageBufferObject::colors); - - video::IGPUDescriptorSet::SWriteDescriptorSet gpuWrites[EE_COUNT]; - { - for (uint32_t binding = 0u; binding < EE_COUNT; binding++) - gpuWrites[binding] = { gpuCDescriptorSet.get(), binding, 0u, 1u, EDT_STORAGE_BUFFER, gpuDescriptorSetInfos + binding }; - logicalDevice->updateDescriptorSets(EE_COUNT, gpuWrites, 0u, nullptr); - } - } - - asset::SPushConstantRange pushConstantRange; - { - pushConstantRange.stageFlags = (asset::IShader::E_SHADER_STAGE)(asset::IShader::ESS_COMPUTE | asset::IShader::ESS_GEOMETRY); - pushConstantRange.offset = 0; - pushConstantRange.size = sizeof(SPushConstants); - } - - auto gpuCPipelineLayout = logicalDevice->createPipelineLayout(&pushConstantRange, &pushConstantRange + 1, std::move(gpuCDescriptorSetLayout), nullptr, nullptr, nullptr); - gpuComputePipeline = logicalDevice->createComputePipeline(nullptr, std::move(gpuCPipelineLayout), std::move(gpuComputeShader)); - - /* - Graphics Pipeline - */ - - asset::SVertexInputParams inputVertexParams; - inputVertexParams.enabledAttribFlags = core::createBitmask({ EE_POSITIONS, EE_VELOCITIES, EE_COLORS, EE_COLORS_RISING_FLAG }); - inputVertexParams.enabledBindingFlags = core::createBitmask({ EE_POSITIONS, EE_VELOCITIES, EE_COLORS, EE_COLORS_RISING_FLAG }); - - for (uint8_t i = 0; i < EE_COUNT; ++i) - { - inputVertexParams.bindings[i].stride = (i == EE_COLORS_RISING_FLAG ? getTexelOrBlockBytesize(EF_R8G8B8A8_UINT) : getTexelOrBlockBytesize(EF_R32G32B32A32_SFLOAT)); - inputVertexParams.bindings[i].inputRate = asset::EVIR_PER_VERTEX; - - inputVertexParams.attributes[i].binding = i; - inputVertexParams.attributes[i].format = (i == EE_COLORS_RISING_FLAG ? EF_R8G8B8A8_UINT : asset::EF_R32G32B32A32_SFLOAT); - inputVertexParams.attributes[i].relativeOffset = 0; - } - - asset::SBlendParams blendParams; - asset::SPrimitiveAssemblyParams primitiveAssemblyParams; - primitiveAssemblyParams.primitiveType = EPT_POINT_LIST; - asset::SRasterizationParams rasterizationParams; - - video::IGPUDescriptorSetLayout::SBinding gpuUboBinding = {}; - gpuUboBinding.count = 1u; - gpuUboBinding.binding = 0; - gpuUboBinding.stageFlags = static_cast(asset::ICPUShader::ESS_VERTEX | asset::ICPUShader::ESS_FRAGMENT); - gpuUboBinding.type = asset::EDT_UNIFORM_BUFFER; - - auto gpuGDescriptorPool = createDescriptorPool(1, EDT_UNIFORM_BUFFER); - auto gpuGDs1Layout = logicalDevice->createDescriptorSetLayout(&gpuUboBinding, &gpuUboBinding + 1); - - video::IGPUBuffer::SCreationParams gpuUBOCreationParams; - //gpuUBOCreationParams.size = sizeof(SBasicViewParameters); - gpuUBOCreationParams.usage = asset::IBuffer::E_USAGE_FLAGS(asset::IBuffer::EUF_UNIFORM_BUFFER_BIT | asset::IBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF); - gpuUBOCreationParams.queueFamilyIndexCount = 0u; - gpuUBOCreationParams.queueFamilyIndices = nullptr; - gpuUBOCreationParams.size = sizeof(SBasicViewParameters); - - gpuUBO = logicalDevice->createBuffer(std::move(gpuUBOCreationParams)); - auto gpuUBOmemreqs = gpuUBO->getMemoryReqs(); - gpuUBOmemreqs.memoryTypeBits &= gpuPhysicalDevice->getDeviceLocalMemoryTypeBits(); - logicalDevice->allocate(gpuUBOmemreqs, gpuUBO.get()); - - gpuGDescriptorSet1 = logicalDevice->createDescriptorSet(gpuGDescriptorPool.get(), gpuGDs1Layout); - { - video::IGPUDescriptorSet::SWriteDescriptorSet write; - write.dstSet = gpuGDescriptorSet1.get(); - write.binding = 0; - write.count = 1u; - write.arrayElement = 0u; - write.descriptorType = asset::EDT_UNIFORM_BUFFER; - video::IGPUDescriptorSet::SDescriptorInfo info; - { - info.desc = gpuUBO; - info.buffer.offset = 0ull; - info.buffer.size = sizeof(SBasicViewParameters); - } - write.info = &info; - logicalDevice->updateDescriptorSets(1u, &write, 0u, nullptr); - } - - auto vertexShaderBundle = assetManager->getAsset("../vertexShader.vert", {}); - { - bool status = !vertexShaderBundle.getContents().empty(); - assert(status); - } - - auto cpuVertexShader = core::smart_refctd_ptr_static_cast(vertexShaderBundle.getContents().begin()[0]); - smart_refctd_ptr gpuVertexShader; - { - auto gpu_array = cpu2gpu.getGPUObjectsFromAssets(&cpuVertexShader, &cpuVertexShader + 1, cpu2gpuParams); - if (!gpu_array || gpu_array->size() < 1u || !(*gpu_array)[0]) - assert(false); - - gpuVertexShader = (*gpu_array)[0]; - } - - auto fragmentShaderBundle = assetManager->getAsset("../fragmentShader.frag", {}); - { - bool status = !fragmentShaderBundle.getContents().empty(); - assert(status); - } - - auto cpuFragmentShader = core::smart_refctd_ptr_static_cast(fragmentShaderBundle.getContents().begin()[0]); - smart_refctd_ptr gpuFragmentShader; - { - auto gpu_array = cpu2gpu.getGPUObjectsFromAssets(&cpuFragmentShader, &cpuFragmentShader + 1, cpu2gpuParams); - if (!gpu_array || gpu_array->size() < 1u || !(*gpu_array)[0]) - assert(false); - - gpuFragmentShader = (*gpu_array)[0]; - } - - auto geometryShaderBundle = assetManager->getAsset("../geometryShader.geom", {}); - { - bool status = !geometryShaderBundle.getContents().empty(); - assert(status); - } - - auto cpuGeometryShader = core::smart_refctd_ptr_static_cast(geometryShaderBundle.getContents().begin()[0]); - smart_refctd_ptr gpuGeometryShader; - { - auto gpu_array = cpu2gpu.getGPUObjectsFromAssets(&cpuGeometryShader, &cpuGeometryShader + 1, cpu2gpuParams); - if (!gpu_array || gpu_array->size() < 1u || !(*gpu_array)[0]) - assert(false); - - gpuGeometryShader = (*gpu_array)[0]; - } - - core::smart_refctd_ptr gpuGShaders[] = { gpuVertexShader, gpuFragmentShader, gpuGeometryShader }; - auto gpuGShadersPointer = reinterpret_cast(gpuGShaders); - - auto gpuGPipelineLayout = logicalDevice->createPipelineLayout(&pushConstantRange, &pushConstantRange + 1, nullptr, std::move(gpuGDs1Layout), nullptr, nullptr); - auto gpuRenderpassIndependentPipeline = logicalDevice->createRenderpassIndependentPipeline(nullptr, core::smart_refctd_ptr(gpuGPipelineLayout), gpuGShadersPointer, gpuGShadersPointer + 2 /* discard geometry shader*/, inputVertexParams, blendParams, primitiveAssemblyParams, rasterizationParams); - auto gpuRenderpassIndependentPipeline2 = logicalDevice->createRenderpassIndependentPipeline(nullptr, core::smart_refctd_ptr(gpuGPipelineLayout), gpuGShadersPointer, gpuGShadersPointer + 3, inputVertexParams, blendParams, primitiveAssemblyParams, rasterizationParams); - - asset::SBufferBinding gpuGbindings[video::IGPUMeshBuffer::MAX_ATTR_BUF_BINDING_COUNT]; - - gpuGbindings[EE_POSITIONS].buffer = gpuSSBOBuffer; - gpuGbindings[EE_POSITIONS].offset = 0; - - gpuGbindings[EE_VELOCITIES].buffer = gpuSSBOBuffer; - gpuGbindings[EE_VELOCITIES].offset = sizeof(SShaderStorageBufferObject::positions); - - gpuGbindings[EE_COLORS].buffer = gpuSSBOBuffer; - gpuGbindings[EE_COLORS].offset = gpuGbindings[EE_VELOCITIES].offset + sizeof(SShaderStorageBufferObject::velocities); - - gpuGbindings[EE_COLORS_RISING_FLAG].buffer = gpuSSBOBuffer; - gpuGbindings[EE_COLORS_RISING_FLAG].offset = gpuGbindings[EE_COLORS].offset + sizeof(SShaderStorageBufferObject::colors); - - gpuMeshBuffer = core::make_smart_refctd_ptr(std::move(gpuRenderpassIndependentPipeline), nullptr, gpuGbindings, asset::SBufferBinding()); - { - gpuMeshBuffer->setIndexType(asset::EIT_UNKNOWN); - gpuMeshBuffer->setIndexCount(NUMBER_OF_PARTICLES); - } - - { - nbl::video::IGPUGraphicsPipeline::SCreationParams graphicsPipelineParams; - graphicsPipelineParams.renderpassIndependent = core::smart_refctd_ptr(const_cast(gpuMeshBuffer->getPipeline())); - graphicsPipelineParams.renderpass = core::smart_refctd_ptr(renderpass); - gpuGraphicsPipeline = logicalDevice->createGraphicsPipeline(nullptr, std::move(graphicsPipelineParams)); - } - - gpuMeshBuffer2 = core::make_smart_refctd_ptr(std::move(gpuRenderpassIndependentPipeline2), nullptr, gpuGbindings, asset::SBufferBinding()); - { - gpuMeshBuffer2->setIndexType(asset::EIT_UNKNOWN); - gpuMeshBuffer2->setIndexCount(NUMBER_OF_PARTICLES); - } - - { - nbl::video::IGPUGraphicsPipeline::SCreationParams graphicsPipelineParams; - graphicsPipelineParams.renderpassIndependent = core::smart_refctd_ptr(const_cast(gpuMeshBuffer2->getPipeline())); - graphicsPipelineParams.renderpass = core::smart_refctd_ptr(renderpass); - gpuGraphicsPipeline2 = logicalDevice->createGraphicsPipeline(nullptr, std::move(graphicsPipelineParams)); - } - - const std::string captionData = "[Nabla Engine] Compute Shaders"; - window->setCaption(captionData); - - core::vectorSIMDf cameraPosition(0, 0, 0); - matrix4SIMD projectionMatrix = matrix4SIMD::buildProjectionMatrixPerspectiveFovLH(core::radians(60.0f), video::ISurface::getTransformedAspectRatio(swapchain->getPreTransform(), WIN_W, WIN_H), 0.001, 1000); - camera = Camera(cameraPosition, core::vectorSIMDf(0, 0, -1), projectionMatrix, 10.f, 1.f); - lastTime = std::chrono::system_clock::now(); - for (size_t i = 0ull; i < NBL_FRAMES_TO_AVERAGE; ++i) - dtList[i] = 0.0; - } - - void onAppTerminated_impl() override - { - const auto& fboCreationParams = fbo->begin()[0]->getCreationParameters(); - auto gpuSourceImageView = fboCreationParams.attachments[0]; - - bool status = ext::ScreenShot::createScreenShot(logicalDevice.get(), - queues[CommonAPI::InitOutput::EQT_TRANSFER_UP], - render_finished_sem.get(), - gpuSourceImageView.get(), - assetManager.get(), - "ScreenShot.png", - asset::IImage::EL_PRESENT_SRC, - asset::EAF_NONE); - - assert(status); - } - - void workLoopBody() override - { - auto renderStart = std::chrono::system_clock::now(); - const auto renderDt = std::chrono::duration_cast(renderStart - lastTime).count(); - lastTime = renderStart; - { // Calculate Simple Moving Average for FrameTime - time_sum -= dtList[frame_count]; - time_sum += renderDt; - dtList[frame_count] = renderDt; - frame_count++; - if (frame_count >= NBL_FRAMES_TO_AVERAGE) - frame_count = 0; - } - const double averageFrameTime = time_sum / (double)NBL_FRAMES_TO_AVERAGE; - -#ifdef NBL_MORE_LOGS - logger->log("renderDt = %f ------ averageFrameTime = %f", system::ILogger::ELL_INFO, renderDt, averageFrameTime); -#endif // NBL_MORE_LOGS - - auto averageFrameTimeDuration = std::chrono::duration(averageFrameTime); - auto nextPresentationTime = renderStart + averageFrameTimeDuration; - auto nextPresentationTimeStamp = std::chrono::duration_cast(nextPresentationTime.time_since_epoch()); - - inputSystem->getDefaultMouse(&mouse); - inputSystem->getDefaultKeyboard(&keyboard); - - camera.beginInputProcessing(nextPresentationTimeStamp); - mouse.consumeEvents([&](const ui::IMouseEventChannel::range_t& events) -> void { camera.mouseProcess(events); }, logger.get()); - keyboard.consumeEvents([&](const ui::IKeyboardEventChannel::range_t& events) -> void { camera.keyboardProcess(events); eventReceiver.process(events); }, logger.get()); - camera.endInputProcessing(nextPresentationTimeStamp); - - const auto& viewMatrix = camera.getViewMatrix(); - const auto& viewProjectionMatrix = matrix4SIMD::concatenateBFollowedByAPrecisely( - video::ISurface::getSurfaceTransformationMatrix(swapchain->getPreTransform()), - camera.getConcatenatedMatrix() - ); - - auto& commandBuffer = commandBuffers[0]; - commandBuffer->reset(nbl::video::IGPUCommandBuffer::ERF_RELEASE_RESOURCES_BIT); - commandBuffer->begin(video::IGPUCommandBuffer::EU_ONE_TIME_SUBMIT_BIT); // TODO: Reset Frame's CommandPool - - asset::SViewport viewport; - viewport.minDepth = 1.f; - viewport.maxDepth = 0.f; - viewport.x = 0u; - viewport.y = 0u; - viewport.width = WIN_W; - viewport.height = WIN_H; - commandBuffer->setViewport(0u, 1u, &viewport); - - nbl::video::IGPUCommandBuffer::SRenderpassBeginInfo beginInfo; - VkRect2D area; - area.offset = { 0,0 }; - area.extent = { WIN_W, WIN_H }; - nbl::asset::SClearValue clear[2]; - clear[0].color.float32[0] = 0.f; - clear[0].color.float32[1] = 0.f; - clear[0].color.float32[2] = 0.f; - clear[0].color.float32[3] = 0.f; - clear[1].depthStencil.depth = 0.f; - - beginInfo.clearValueCount = 2u; - beginInfo.framebuffer = fbo->begin()[0]; - beginInfo.renderpass = renderpass; - beginInfo.renderArea = area; - beginInfo.clearValues = clear; - - commandBuffer->beginRenderPass(&beginInfo, nbl::asset::ESC_INLINE); - - pushConstants.isXPressed = eventReceiver.isXPressed(); - pushConstants.isZPressed = eventReceiver.isZPressed(); - pushConstants.isCPressed = eventReceiver.isCPressed(); - pushConstants.currentUserAbsolutePosition = camera.getPosition().getAsVector3df(); - - /* - Calculation of particle postitions takes place here - */ - - commandBuffer->bindComputePipeline(gpuComputePipeline.get()); - commandBuffer->pushConstants(gpuComputePipeline->getLayout(), asset::IShader::ESS_COMPUTE, 0, sizeof(SPushConstants), &pushConstants); - commandBuffer->bindDescriptorSets(EPBP_COMPUTE, gpuComputePipeline->getLayout(), 0, 1, &gpuCDescriptorSet.get(), 0u); - - static_assert(NUMBER_OF_PARTICLES % WORK_GROUP_SIZE == 0, "Inccorect amount!"); - _NBL_STATIC_INLINE_CONSTEXPR size_t groupCountX = NUMBER_OF_PARTICLES / WORK_GROUP_SIZE; - - commandBuffer->dispatch(groupCountX, 1, 1); - - /* - After calculation of positions each particle gets displayed - */ - - core::matrix3x4SIMD modelMatrix; - modelMatrix.setTranslation(nbl::core::vectorSIMDf(0, 0, 0, 0)); - - core::matrix4SIMD mvp = core::concatenateBFollowedByA(viewProjectionMatrix, modelMatrix); - - SBasicViewParameters uboData; - memcpy(uboData.MV, viewMatrix.pointer(), sizeof(uboData.MV)); - memcpy(uboData.MVP, mvp.pointer(), sizeof(uboData.MVP)); - memcpy(uboData.NormalMat, viewMatrix.pointer(), sizeof(uboData.NormalMat)); - commandBuffer->updateBuffer(gpuUBO.get(), 0ull, sizeof(uboData), &uboData); - - /* - Draw particles - */ - - commandBuffer->bindGraphicsPipeline(gpuGraphicsPipeline.get()); - commandBuffer->bindDescriptorSets(asset::EPBP_GRAPHICS, gpuMeshBuffer->getPipeline()->getLayout(), 1u, 1u, &gpuGDescriptorSet1.get(), 0u); - commandBuffer->drawMeshBuffer(gpuMeshBuffer.get()); - - /* - Draw extras with geometry usage under key c and v conditions - */ - - commandBuffer->bindGraphicsPipeline(gpuGraphicsPipeline2.get()); - commandBuffer->pushConstants(gpuMeshBuffer2->getPipeline()->getLayout(), asset::IShader::ESS_GEOMETRY, 0, sizeof(SPushConstants), &pushConstants); - commandBuffer->bindDescriptorSets(asset::EPBP_GRAPHICS, gpuMeshBuffer2->getPipeline()->getLayout(), 1u, 1u, &gpuGDescriptorSet1.get(), 0u); - commandBuffer->drawMeshBuffer(gpuMeshBuffer2.get()); - - commandBuffer->endRenderPass(); - commandBuffer->end(); - - auto img_acq_sem = logicalDevice->createSemaphore(); - render_finished_sem = logicalDevice->createSemaphore(); - - uint32_t imgnum = 0u; - constexpr uint64_t MAX_TIMEOUT = 99999999999999ull; // ns - swapchain->acquireNextImage(MAX_TIMEOUT, img_acq_sem.get(), nullptr, &imgnum); - - CommonAPI::Submit(logicalDevice.get(), commandBuffer.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS], img_acq_sem.get(), render_finished_sem.get()); - CommonAPI::Present(logicalDevice.get(), swapchain.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS], render_finished_sem.get(), imgnum); - } - - bool keepRunning() override - { - return windowCallback->isWindowOpen(); - } -}; - -NBL_COMMON_API_MAIN(MeshLoadersApp, MeshLoadersApp::Nabla) diff --git a/53_ComputeShaders/pipeline.groovy b/53_ComputeShaders/pipeline.groovy deleted file mode 100644 index e8eb74b5b..000000000 --- a/53_ComputeShaders/pipeline.groovy +++ /dev/null @@ -1,50 +0,0 @@ -import org.DevshGraphicsProgramming.Agent -import org.DevshGraphicsProgramming.BuilderInfo -import org.DevshGraphicsProgramming.IBuilder - -class CComputeShadersBuilder extends IBuilder -{ - public CComputeShadersBuilder(Agent _agent, _info) - { - super(_agent, _info) - } - - @Override - public boolean prepare(Map axisMapping) - { - return true - } - - @Override - public boolean build(Map axisMapping) - { - IBuilder.CONFIGURATION config = axisMapping.get("CONFIGURATION") - IBuilder.BUILD_TYPE buildType = axisMapping.get("BUILD_TYPE") - - def nameOfBuildDirectory = getNameOfBuildDirectory(buildType) - def nameOfConfig = getNameOfConfig(config) - - agent.execute("cmake --build ${info.rootProjectPath}/${nameOfBuildDirectory}/${info.targetProjectPathRelativeToRoot} --target ${info.targetBaseName} --config ${nameOfConfig} -j12 -v") - - return true - } - - @Override - public boolean test(Map axisMapping) - { - return true - } - - @Override - public boolean install(Map axisMapping) - { - return true - } -} - -def create(Agent _agent, _info) -{ - return new CComputeShadersBuilder(_agent, _info) -} - -return this \ No newline at end of file diff --git a/53_ComputeShaders/shaderCommon.glsl b/53_ComputeShaders/shaderCommon.glsl deleted file mode 100644 index 972a8789a..000000000 --- a/53_ComputeShaders/shaderCommon.glsl +++ /dev/null @@ -1,6 +0,0 @@ -layout(push_constant, row_major) uniform Block{ - bool isXPressed; - bool isZPressed; - bool isCPressed; - vec3 currentUserAbsolutePostion; -} pushConstants; \ No newline at end of file diff --git a/53_ComputeShaders/vertexShader.vert b/53_ComputeShaders/vertexShader.vert deleted file mode 100644 index 6b14d97c8..000000000 --- a/53_ComputeShaders/vertexShader.vert +++ /dev/null @@ -1,23 +0,0 @@ -#version 430 core - -layout(location = 0) in vec4 vPosition; -layout(location = 1) in vec4 vVelocity; -layout(location = 2) in vec4 vColor; - -#include -#include - -layout (set = 1, binding = 0, row_major, std140) uniform UBO -{ - nbl_glsl_SBasicViewParameters params; -} cameraData; - -layout(location = 0) flat out vec4 outGOrFFullyProjectedVelocity; -layout(location = 1) flat out vec4 outGorFColor; - -void main() -{ - gl_Position = (cameraData.params.MVP) * vPosition; - outGOrFFullyProjectedVelocity = (cameraData.params.MVP) * vVelocity * 0.0001; - outGorFColor = vColor; -} \ No newline at end of file diff --git a/56_RayQuery/CMakeLists.txt b/56_RayQuery/CMakeLists.txt deleted file mode 100644 index a476b6203..000000000 --- a/56_RayQuery/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ - -include(common RESULT_VARIABLE RES) -if(NOT RES) - message(FATAL_ERROR "common.cmake not found. Should be in {repo_root}/cmake directory") -endif() - -nbl_create_executable_project("" "" "" "" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") \ No newline at end of file diff --git a/56_RayQuery/common.glsl b/56_RayQuery/common.glsl deleted file mode 100644 index ad88789f8..000000000 --- a/56_RayQuery/common.glsl +++ /dev/null @@ -1,793 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -// basic settings -#define MAX_DEPTH 15 -#define SAMPLES 32 - -// firefly and variance reduction techniques -//#define KILL_DIFFUSE_SPECULAR_PATHS -//#define VISUALIZE_HIGH_VARIANCE - -#define INVALID_ID_16BIT 0xffffu -struct Sphere -{ - vec3 position; - float radius2; - uint bsdfLightIDs; -}; - -layout(set=0, binding=0, rgba16f) uniform image2D outImage; - -layout(set = 2, binding = 0) uniform sampler2D envMap; -layout(set = 2, binding = 1) uniform usamplerBuffer sampleSequence; -layout(set = 2, binding = 2) uniform usampler2D scramblebuf; -layout(set = 2, binding = 3) uniform accelerationStructureEXT topLevelAS; -layout(set = 2, binding = 4) readonly restrict buffer InputBuffer -{ - Sphere spheres[]; -}; - -#ifndef _NBL_GLSL_WORKGROUP_SIZE_ -#define _NBL_GLSL_WORKGROUP_SIZE_ 16 -layout(local_size_x=_NBL_GLSL_WORKGROUP_SIZE_, local_size_y=_NBL_GLSL_WORKGROUP_SIZE_, local_size_z=1) in; -#endif - -ivec2 getCoordinates() { - return ivec2(gl_GlobalInvocationID.xy); -} - -vec2 getTexCoords() { - ivec2 imageSize = imageSize(outImage); - ivec2 iCoords = getCoordinates(); - return vec2(float(iCoords.x) / imageSize.x, 1.0 - float(iCoords.y) / imageSize.y); -} - - -#include -#include -#include - -#include - -layout(set = 1, binding = 0, row_major, std140) uniform UBO -{ - nbl_glsl_SBasicViewParameters params; -} cameraData; - -Sphere Sphere_Sphere(in vec3 position, in float radius, in uint bsdfID, in uint lightID) -{ - Sphere sphere; - sphere.position = position; - sphere.radius2 = radius*radius; - sphere.bsdfLightIDs = bitfieldInsert(bsdfID,lightID,16,16); - return sphere; -} - -// return intersection distance if found, FLT_NAN otherwise -float Sphere_intersect(in Sphere sphere, in vec3 origin, in vec3 direction) -{ - vec3 relOrigin = origin-sphere.position; - float relOriginLen2 = dot(relOrigin,relOrigin); - const float radius2 = sphere.radius2; - - float dirDotRelOrigin = dot(direction,relOrigin); - float det = radius2-relOriginLen2+dirDotRelOrigin*dirDotRelOrigin; - - // do some speculative math here - float detsqrt = sqrt(det); - return -dirDotRelOrigin+(relOriginLen2>radius2 ? (-detsqrt):detsqrt); -} - -vec3 Sphere_getNormal(in Sphere sphere, in vec3 position) -{ - const float radiusRcp = inversesqrt(sphere.radius2); - return (position-sphere.position)*radiusRcp; -} - -float Sphere_getSolidAngle_impl(in float cosThetaMax) -{ - return 2.0*nbl_glsl_PI*(1.0-cosThetaMax); -} -float Sphere_getSolidAngle(in Sphere sphere, in vec3 origin) -{ - float cosThetaMax = sqrt(1.0-sphere.radius2/nbl_glsl_lengthSq(sphere.position-origin)); - return Sphere_getSolidAngle_impl(cosThetaMax); -} - -struct Triangle -{ - vec3 vertex0; - uint bsdfLightIDs; - vec3 vertex1; - uint padding0; - vec3 vertex2; - uint padding1; -}; - -Triangle Triangle_Triangle(in mat3 vertices, in uint bsdfID, in uint lightID) -{ - Triangle tri; - tri.vertex0 = vertices[0]; - tri.vertex1 = vertices[1]; - tri.vertex2 = vertices[2]; - // - tri.bsdfLightIDs = bitfieldInsert(bsdfID, lightID, 16, 16); - return tri; -} - -// return intersection distance if found, FLT_NAN otherwise -float Triangle_intersect(in Triangle tri, in vec3 origin, in vec3 direction) -{ - const vec3 edges[2] = vec3[2](tri.vertex1-tri.vertex0,tri.vertex2-tri.vertex0); - - const vec3 h = cross(direction,edges[1]); - const float a = dot(edges[0],h); - - const vec3 relOrigin = origin-tri.vertex0; - - const float u = dot(relOrigin,h)/a; - - const vec3 q = cross(relOrigin,edges[0]); - const float v = dot(direction,q)/a; - - const float t = dot(edges[1],q)/a; - - return t>0.f&&u>=0.f&&v>=0.f&&(u+v)<=1.f ? t:nbl_glsl_FLT_NAN; -} - -vec3 Triangle_getNormalTimesArea_impl(in mat2x3 edges) -{ - return cross(edges[0],edges[1])*0.5; -} -vec3 Triangle_getNormalTimesArea(in Triangle tri) -{ - return Triangle_getNormalTimesArea_impl(mat2x3(tri.vertex1-tri.vertex0,tri.vertex2-tri.vertex0)); -} - - - -struct Rectangle -{ - vec3 offset; - uint bsdfLightIDs; - vec3 edge0; - uint padding0; - vec3 edge1; - uint padding1; -}; - -Rectangle Rectangle_Rectangle(in vec3 offset, in vec3 edge0, in vec3 edge1, in uint bsdfID, in uint lightID) -{ - Rectangle rect; - rect.offset = offset; - rect.edge0 = edge0; - rect.edge1 = edge1; - // - rect.bsdfLightIDs = bitfieldInsert(bsdfID, lightID, 16, 16); - return rect; -} - -// return intersection distance if found, FLT_NAN otherwise -float Rectangle_intersect(in Rectangle rect, in vec3 origin, in vec3 direction) -{ - const vec3 h = cross(direction,rect.edge1); - const float a = dot(rect.edge0,h); - - const vec3 relOrigin = origin-rect.offset; - - const float u = dot(relOrigin,h)/a; - - const vec3 q = cross(relOrigin,rect.edge0); - const float v = dot(direction,q)/a; - - const float t = dot(rect.edge1,q)/a; - - const bool intersection = t>0.f&&u>=0.f&&v>=0.f&&u<=1.f&&v<=1.f; - return intersection ? t:nbl_glsl_FLT_NAN; -} - -vec3 Rectangle_getNormalTimesArea(in Rectangle rect) -{ - return cross(rect.edge0,rect.edge1); -} - - - -#define DIFFUSE_OP 0u -#define CONDUCTOR_OP 1u -#define DIELECTRIC_OP 2u -#define OP_BITS_OFFSET 0 -#define OP_BITS_SIZE 2 -struct BSDFNode -{ - uvec4 data[2]; -}; - -uint BSDFNode_getType(in BSDFNode node) -{ - return bitfieldExtract(node.data[0].w,OP_BITS_OFFSET,OP_BITS_SIZE); -} -bool BSDFNode_isBSDF(in BSDFNode node) -{ - return BSDFNode_getType(node)==DIELECTRIC_OP; -} -bool BSDFNode_isNotDiffuse(in BSDFNode node) -{ - return BSDFNode_getType(node)!=DIFFUSE_OP; -} -float BSDFNode_getRoughness(in BSDFNode node) -{ - return uintBitsToFloat(node.data[1].w); -} -vec3 BSDFNode_getRealEta(in BSDFNode node) -{ - return uintBitsToFloat(node.data[0].rgb); -} -vec3 BSDFNode_getImaginaryEta(in BSDFNode node) -{ - return uintBitsToFloat(node.data[1].rgb); -} -mat2x3 BSDFNode_getEta(in BSDFNode node) -{ - return mat2x3(BSDFNode_getRealEta(node),BSDFNode_getImaginaryEta(node)); -} -#include -vec3 BSDFNode_getReflectance(in BSDFNode node, in float VdotH) -{ - const vec3 albedoOrRealIoR = uintBitsToFloat(node.data[0].rgb); - if (BSDFNode_isNotDiffuse(node)) - return nbl_glsl_fresnel_conductor(albedoOrRealIoR, BSDFNode_getImaginaryEta(node), VdotH); - else - return albedoOrRealIoR; -} - -float BSDFNode_getNEEProb(in BSDFNode bsdf) -{ - const float alpha = BSDFNode_isNotDiffuse(bsdf) ? BSDFNode_getRoughness(bsdf):1.0; - return min(8.0*alpha,1.0); -} - -#include -#include -float getLuma(in vec3 col) -{ - return dot(transpose(nbl_glsl_scRGBtoXYZ)[1],col); -} - -#define BSDF_COUNT 7 -BSDFNode bsdfs[BSDF_COUNT] = { - {{uvec4(floatBitsToUint(vec3(0.8,0.8,0.8)),DIFFUSE_OP),floatBitsToUint(vec4(0.0,0.0,0.0,0.0))}}, - {{uvec4(floatBitsToUint(vec3(0.8,0.4,0.4)),DIFFUSE_OP),floatBitsToUint(vec4(0.0,0.0,0.0,0.0))}}, - {{uvec4(floatBitsToUint(vec3(0.4,0.8,0.4)),DIFFUSE_OP),floatBitsToUint(vec4(0.0,0.0,0.0,0.0))}}, - {{uvec4(floatBitsToUint(vec3(1.02,1.02,1.3)),CONDUCTOR_OP),floatBitsToUint(vec4(1.0,1.0,2.0,0.0))}}, - {{uvec4(floatBitsToUint(vec3(1.02,1.3,1.02)),CONDUCTOR_OP),floatBitsToUint(vec4(1.0,2.0,1.0,0.0))}}, - {{uvec4(floatBitsToUint(vec3(1.02,1.3,1.02)),CONDUCTOR_OP),floatBitsToUint(vec4(1.0,2.0,1.0,0.15))}}, - {{uvec4(floatBitsToUint(vec3(1.4,1.45,1.5)),DIELECTRIC_OP),floatBitsToUint(vec4(0.0,0.0,0.0,0.0625))}} -}; - - -struct Light -{ - vec3 radiance; - uint objectID; -}; - -vec3 Light_getRadiance(in Light light) -{ - return light.radiance; -} -uint Light_getObjectID(in Light light) -{ - return light.objectID; -} - - -#define LIGHT_COUNT 1 -float scene_getLightChoicePdf(in Light light) -{ - return 1.0/float(LIGHT_COUNT); -} - - -#define LIGHT_COUNT 1 -Light lights[LIGHT_COUNT] = -{ - { - vec3(30.0,25.0,15.0), -#ifdef POLYGON_METHOD - 0u -#else - 8u -#endif - } -}; - - - -#define ANY_HIT_FLAG (-2147483648) -#define DEPTH_BITS_COUNT 8 -#define DEPTH_BITS_OFFSET (31-DEPTH_BITS_COUNT) -struct ImmutableRay_t -{ - vec3 origin; - vec3 direction; -#if POLYGON_METHOD==2 - vec3 normalAtOrigin; - bool wasBSDFAtOrigin; -#endif -}; -struct MutableRay_t -{ - float intersectionT; - uint objectID; - /* irrelevant here - uint triangleID; - vec2 barycentrics; - */ -}; -struct Payload_t -{ - vec3 accumulation; - float otherTechniqueHeuristic; - vec3 throughput; - #ifdef KILL_DIFFUSE_SPECULAR_PATHS - bool hasDiffuse; - #endif -}; - -struct Ray_t -{ - ImmutableRay_t _immutable; - MutableRay_t _mutable; - Payload_t _payload; -}; - - -#define INTERSECTION_ERROR_BOUND_LOG2 (-8.0) -float getTolerance_common(in uint depth) -{ - float depthRcp = 1.0/float(depth); - return INTERSECTION_ERROR_BOUND_LOG2;// *depthRcp*depthRcp; -} -float getStartTolerance(in uint depth) -{ - return exp2(getTolerance_common(depth)); -} -float getEndTolerance(in uint depth) -{ - return 1.0-exp2(getTolerance_common(depth)+1.0); -} - - -vec2 SampleSphericalMap(vec3 v) -{ - vec2 uv = vec2(atan(v.z, v.x), asin(v.y)); - uv *= nbl_glsl_RECIPROCAL_PI*0.5; - uv += 0.5; - return uv; -} - -void missProgram(in ImmutableRay_t _immutable, inout Payload_t _payload) -{ - vec3 finalContribution = _payload.throughput; - // #define USE_ENVMAP -#ifdef USE_ENVMAP - vec2 uv = SampleSphericalMap(_immutable.direction); - finalContribution *= textureLod(envMap, uv, 0.0).rgb; -#else - const vec3 kConstantEnvLightRadiance = vec3(0.15, 0.21, 0.3); - finalContribution *= kConstantEnvLightRadiance; -#endif - _payload.accumulation += finalContribution; -} - -#include -#include -#include -#include -#include -#include -#include -nbl_glsl_LightSample nbl_glsl_bsdf_cos_generate(in nbl_glsl_AnisotropicViewSurfaceInteraction interaction, in vec3 u, in BSDFNode bsdf, in float monochromeEta, out nbl_glsl_AnisotropicMicrofacetCache _cache) -{ - const float a = BSDFNode_getRoughness(bsdf); - const mat2x3 ior = BSDFNode_getEta(bsdf); - - // fresnel stuff for dielectrics - float orientedEta, rcpOrientedEta; - const bool viewerInsideMedium = nbl_glsl_getOrientedEtas(orientedEta,rcpOrientedEta,interaction.isotropic.NdotV,monochromeEta); - - nbl_glsl_LightSample smpl; - nbl_glsl_AnisotropicMicrofacetCache dummy; - switch (BSDFNode_getType(bsdf)) - { - case DIFFUSE_OP: - smpl = nbl_glsl_oren_nayar_cos_generate(interaction,u.xy,a*a); - break; - case CONDUCTOR_OP: - smpl = nbl_glsl_ggx_cos_generate(interaction,u.xy,a,a,_cache); - break; - default: - smpl = nbl_glsl_ggx_dielectric_cos_generate(interaction,u,a,a,monochromeEta,_cache); - break; - } - return smpl; -} - -vec3 nbl_glsl_bsdf_cos_remainder_and_pdf(out float pdf, in nbl_glsl_LightSample _sample, in nbl_glsl_AnisotropicViewSurfaceInteraction interaction, in BSDFNode bsdf, in float monochromeEta, in nbl_glsl_AnisotropicMicrofacetCache _cache) -{ - // are V and L on opposite sides of the surface? - const bool transmitted = nbl_glsl_isTransmissionPath(interaction.isotropic.NdotV,_sample.NdotL); - - // is the BSDF or BRDF, if it is then we make the dot products `abs` before `max(,0.0)` - const bool transmissive = BSDFNode_isBSDF(bsdf); - const float clampedNdotL = nbl_glsl_conditionalAbsOrMax(transmissive,_sample.NdotL,0.0); - const float clampedNdotV = nbl_glsl_conditionalAbsOrMax(transmissive,interaction.isotropic.NdotV,0.0); - - vec3 remainder; - - const float minimumProjVectorLen = 0.00000001; - if (clampedNdotV>minimumProjVectorLen && clampedNdotL>minimumProjVectorLen) - { - // fresnel stuff for conductors (but reflectance also doubles as albedo) - const mat2x3 ior = BSDFNode_getEta(bsdf); - const vec3 reflectance = BSDFNode_getReflectance(bsdf,_cache.isotropic.VdotH); - - // fresnel stuff for dielectrics - float orientedEta, rcpOrientedEta; - const bool viewerInsideMedium = nbl_glsl_getOrientedEtas(orientedEta,rcpOrientedEta,interaction.isotropic.NdotV,monochromeEta); - - // - const float VdotL = dot(interaction.isotropic.V.dir,_sample.L); - - // - const float a = max(BSDFNode_getRoughness(bsdf),0.0001); // TODO: @Crisspl 0-roughness still doesn't work! Also Beckmann has a weird dark rim instead as fresnel!? - const float a2 = a*a; - - // TODO: refactor into Material Compiler-esque thing - switch (BSDFNode_getType(bsdf)) - { - case DIFFUSE_OP: - remainder = reflectance*nbl_glsl_oren_nayar_cos_remainder_and_pdf_wo_clamps(pdf,a*a,VdotL,clampedNdotL,clampedNdotV); - break; - case CONDUCTOR_OP: - remainder = nbl_glsl_ggx_cos_remainder_and_pdf_wo_clamps(pdf,nbl_glsl_ggx_trowbridge_reitz(a2,_cache.isotropic.NdotH2),clampedNdotL,_sample.NdotL2,clampedNdotV,interaction.isotropic.NdotV_squared,reflectance,a2); - break; - default: - remainder = vec3(nbl_glsl_ggx_dielectric_cos_remainder_and_pdf(pdf, _sample, interaction.isotropic, _cache.isotropic, monochromeEta, a*a)); - break; - } - } - else - remainder = vec3(0.0); - return remainder; -} - -layout (constant_id = 0) const int MAX_DEPTH_LOG2 = 4; -layout (constant_id = 1) const int MAX_SAMPLES_LOG2 = 10; - - -#include - -mat2x3 rand3d(in uint protoDimension, in uint _sample, inout nbl_glsl_xoroshiro64star_state_t scramble_state) -{ - mat2x3 retval; - uint address = bitfieldInsert(protoDimension,_sample,MAX_DEPTH_LOG2,MAX_SAMPLES_LOG2); - for (int i=0; i<2u; i++) - { - uvec3 seqVal = texelFetch(sampleSequence,int(address)+i).xyz; - seqVal ^= uvec3(nbl_glsl_xoroshiro64star(scramble_state),nbl_glsl_xoroshiro64star(scramble_state),nbl_glsl_xoroshiro64star(scramble_state)); - retval[i] = vec3(seqVal)*uintBitsToFloat(0x2f800004u); - } - return retval; -} - - -void traceRay_extraShape(inout int objectID, inout float intersectionT, in vec3 origin, in vec3 direction); -int traceRay(inout float intersectionT, in vec3 origin, in vec3 direction) -{ - int objectID = -1; - -#define USE_RAY_QUERY -#ifdef USE_RAY_QUERY - rayQueryEXT rayQuery; - rayQueryInitializeEXT(rayQuery, topLevelAS, gl_RayFlagsNoneEXT, 0xFF, origin, 0.0, direction, 1000.0); - - // Start traversal: return false if traversal is complete - while(rayQueryProceedEXT(rayQuery)) - { - if(rayQueryGetIntersectionTypeEXT(rayQuery, false) == gl_RayQueryCandidateIntersectionAABBEXT) - { - int id = rayQueryGetIntersectionPrimitiveIndexEXT(rayQuery, false); - float t = Sphere_intersect(spheres[id],origin,direction); - bool reportIntersection = (t != nbl_glsl_FLT_NAN && t > 0 && t < intersectionT); - if(reportIntersection) - { - intersectionT = t; - objectID = id; - rayQueryGenerateIntersectionEXT(rayQuery, t); - } - } - } -#else - for (int i=0; i0.0 && t0.0; - // but if we allowed non-watertight transmitters (single water surface), it would make sense just to apply this line by itself - nbl_glsl_AnisotropicMicrofacetCache _cache; - validPath = validPath && nbl_glsl_calcAnisotropicMicrofacetCache(_cache, interaction, nee_sample, monochromeEta); - if (validPath) - { - float bsdfPdf; - neeContrib *= nbl_glsl_bsdf_cos_remainder_and_pdf(bsdfPdf,nee_sample,interaction,bsdf,monochromeEta,_cache)*throughput; - const float oc = bsdfPdf*rcpChoiceProb; - neeContrib /= 1.0/oc+oc/(lightPdf*lightPdf); // MIS weight - if (bsdfPdflumaContributionThreshold && traceRay(t,intersection+nee_sample.L*t*getStartTolerance(depth),nee_sample.L)==-1) - ray._payload.accumulation += neeContrib; - } - } - - // sample BSDF - float bsdfPdf; vec3 bsdfSampleL; - { - nbl_glsl_AnisotropicMicrofacetCache _cache; - nbl_glsl_LightSample bsdf_sample = nbl_glsl_bsdf_cos_generate(interaction,epsilon[1],bsdf,monochromeEta,_cache); - // the value of the bsdf divided by the probability of the sample being generated - throughput *= nbl_glsl_bsdf_cos_remainder_and_pdf(bsdfPdf,bsdf_sample,interaction,bsdf,monochromeEta,_cache); - // - bsdfSampleL = bsdf_sample.L; - } - - // additional threshold - const float lumaThroughputThreshold = lumaContributionThreshold; - if (bsdfPdf>bsdfPdfThreshold && getLuma(throughput)>lumaThroughputThreshold) - { - ray._payload.throughput = throughput; - ray._payload.otherTechniqueHeuristic = neeProbability/bsdfPdf; // numerically stable, don't touch - ray._payload.otherTechniqueHeuristic *= ray._payload.otherTechniqueHeuristic; - - // trace new ray - ray._immutable.origin = intersection+bsdfSampleL*(1.0/*kSceneSize*/)*getStartTolerance(depth); - ray._immutable.direction = bsdfSampleL; - #if POLYGON_METHOD==2 - ray._immutable.normalAtOrigin = interaction.isotropic.N; - ray._immutable.wasBSDFAtOrigin = isBSDF; - #endif - return true; - } - } - return false; -} - -void main() -{ - const ivec2 coords = getCoordinates(); - const vec2 texCoord = getTexCoords(); - - if (false == (all(lessThanEqual(ivec2(0),coords)) && all(greaterThan(imageSize(outImage),coords)))) { - return; - } - - if (((MAX_DEPTH-1)>>MAX_DEPTH_LOG2)>0 || ((SAMPLES-1)>>MAX_SAMPLES_LOG2)>0) - { - vec4 pixelCol = vec4(1.0,0.0,0.0,1.0); - imageStore(outImage, coords, pixelCol); - return; - } - - nbl_glsl_xoroshiro64star_state_t scramble_start_state = texelFetch(scramblebuf,coords,0).rg; - const vec2 pixOffsetParam = vec2(1.0)/vec2(textureSize(scramblebuf,0)); - - - const mat4 invMVP = inverse(cameraData.params.MVP); - - vec4 NDC = vec4(texCoord*vec2(2.0,-2.0)+vec2(-1.0,1.0),0.0,1.0); - vec3 camPos; - { - vec4 tmp = invMVP*NDC; - camPos = tmp.xyz/tmp.w; - NDC.z = 1.0; - } - - vec3 color = vec3(0.0); - float meanLumaSquared = 0.0; - // TODO: if we collapse the nested for loop, then all GPUs will get `MAX_DEPTH` factor speedup, not just NV with separate PC - for (int i=0; i5.0) - color = vec3(1.0,0.0,0.0); - #endif - - vec4 pixelCol = vec4(color, 1.0); - imageStore(outImage, coords, pixelCol); -} -/** TODO: Improving Rendering - -Now: -- Always MIS (path correlated reuse) -- Test MIS alpha (roughness) scheme - -Many Lights: -- Path Guiding -- Light Importance Lists/Classification -- Spatio-Temporal Reservoir Sampling - -Indirect Light: -- Bidirectional Path Tracing -- Uniform Path Sampling / Vertex Connection and Merging / Path Space Regularization - -Animations: -- A-SVGF / BMFR -**/ \ No newline at end of file diff --git a/56_RayQuery/litByRectangle.comp b/56_RayQuery/litByRectangle.comp deleted file mode 100644 index 829d03398..000000000 --- a/56_RayQuery/litByRectangle.comp +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -#version 460 core -#extension GL_GOOGLE_include_directive : require -#extension GL_EXT_ray_query : enable - -#define SPHERE_COUNT 8 -#define POLYGON_METHOD 0 // 0 area sampling, 1 solid angle sampling, 2 approximate projected solid angle sampling -#include "common.glsl" - - -#define RECTANGLE_COUNT 1 -const vec3 edge0 = normalize(vec3(2,0,-1)); -const vec3 edge1 = normalize(vec3(2,-5,4)); -Rectangle rectangles[RECTANGLE_COUNT] = { - Rectangle_Rectangle(vec3(-3.8,0.35,1.3),edge0*7.0,edge1*0.1,INVALID_ID_16BIT,0u) -}; - - -void traceRay_extraShape(inout int objectID, inout float intersectionT, in vec3 origin, in vec3 direction) -{ - for (int i=0; i0.0 && t -float nbl_glsl_light_deferred_pdf(in Light light, in Ray_t ray) -{ - const Rectangle rect = rectangles[Light_getObjectID(light)]; - - const vec3 L = ray._immutable.direction; -#if POLYGON_METHOD==0 - const float dist = ray._mutable.intersectionT; - return dist*dist/abs(dot(Rectangle_getNormalTimesArea(rect),L)); -#else - const ImmutableRay_t _immutable = ray._immutable; - const mat3 sphericalVertices = nbl_glsl_shapes_getSphericalTriangle(mat3(tri.vertex0,tri.vertex1,tri.vertex2),_immutable.origin); - #if POLYGON_METHOD==1 - const float rcpProb = nbl_glsl_shapes_SolidAngleOfTriangle(sphericalVertices); - // if `rcpProb` is NAN then the triangle's solid angle was close to 0.0 - return rcpProb>FLT_MIN ? (1.0/rcpProb):nbl_glsl_FLT_MAX; - #elif POLYGON_METHOD==2 - const float pdf = nbl_glsl_sampling_probProjectedSphericalTriangleSample(sphericalVertices,_immutable.normalAtOrigin,_immutable.wasBSDFAtOrigin,L); - // if `pdf` is NAN then the triangle's projected solid angle was close to 0.0, if its close to INF then the triangle was very small - return pdfFLT_MIN ? (1.0/rcpPdf):0.0; - - const vec3 N = Triangle_getNormalTimesArea(tri); - newRayMaxT = dot(N,tri.vertex0-origin)/dot(N,L); - return L; -#endif -} - - -uint getBSDFLightIDAndDetermineNormal(out vec3 normal, in uint objectID, in vec3 intersection) -{ - if (objectID0.0) - { - const float rcpDistance = inversesqrt(distanceSQ); - Z *= rcpDistance; - - const float cosThetaMax = sqrt(cosThetaMax2); - const float cosTheta = mix(1.0,cosThetaMax,xi.x); - - vec3 L = Z*cosTheta; - - const float cosTheta2 = cosTheta*cosTheta; - const float sinTheta = sqrt(1.0-cosTheta2); - float sinPhi,cosPhi; - nbl_glsl_sincos(2.0*nbl_glsl_PI*xi.y-nbl_glsl_PI,sinPhi,cosPhi); - mat2x3 XY = nbl_glsl_frisvad(Z); - - L += (XY[0]*cosPhi+XY[1]*sinPhi)*sinTheta; - - newRayMaxT = (cosTheta-sqrt(cosTheta2-cosThetaMax2))/rcpDistance; - pdf = 1.0/Sphere_getSolidAngle_impl(cosThetaMax); - return L; - } - pdf = 0.0; - return vec3(0.0,0.0,0.0); -} - -uint getBSDFLightIDAndDetermineNormal(out vec3 normal, in uint objectID, in vec3 intersection) -{ - Sphere sphere = spheres[objectID]; - normal = Sphere_getNormal(sphere,intersection); - return sphere.bsdfLightIDs; -} \ No newline at end of file diff --git a/56_RayQuery/litByTriangle.comp b/56_RayQuery/litByTriangle.comp deleted file mode 100644 index 1cd1d3ee3..000000000 --- a/56_RayQuery/litByTriangle.comp +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -#version 460 core -#extension GL_GOOGLE_include_directive : require -#extension GL_EXT_ray_query : enable - -#define SPHERE_COUNT 8 -#define POLYGON_METHOD 0 // 0 area sampling, 1 solid angle sampling, 2 approximate projected solid angle sampling -#include "common.glsl" - -#define TRIANGLE_COUNT 1 -Triangle triangles[TRIANGLE_COUNT] = { - Triangle_Triangle(mat3(vec3(-1.8,0.35,0.3),vec3(-1.2,0.35,0.0),vec3(-1.5,0.8,-0.3)),INVALID_ID_16BIT,0u) -}; - -void traceRay_extraShape(inout int objectID, inout float intersectionT, in vec3 origin, in vec3 direction) -{ - for (int i=0; i0.0 && t -float nbl_glsl_light_deferred_pdf(in Light light, in Ray_t ray) -{ - const Triangle tri = triangles[Light_getObjectID(light)]; - - const vec3 L = ray._immutable.direction; -#if POLYGON_METHOD==0 - const float dist = ray._mutable.intersectionT; - return dist*dist/abs(dot(Triangle_getNormalTimesArea(tri),L)); -#else - const ImmutableRay_t _immutable = ray._immutable; - const mat3 sphericalVertices = nbl_glsl_shapes_getSphericalTriangle(mat3(tri.vertex0,tri.vertex1,tri.vertex2),_immutable.origin); - #if POLYGON_METHOD==1 - const float rcpProb = nbl_glsl_shapes_SolidAngleOfTriangle(sphericalVertices); - // if `rcpProb` is NAN then the triangle's solid angle was close to 0.0 - return rcpProb>FLT_MIN ? (1.0/rcpProb):nbl_glsl_FLT_MAX; - #elif POLYGON_METHOD==2 - const float pdf = nbl_glsl_sampling_probProjectedSphericalTriangleSample(sphericalVertices,_immutable.normalAtOrigin,_immutable.wasBSDFAtOrigin,L); - // if `pdf` is NAN then the triangle's projected solid angle was close to 0.0, if its close to INF then the triangle was very small - return pdfFLT_MIN ? (1.0/rcpPdf):0.0; - - const vec3 N = Triangle_getNormalTimesArea(tri); - newRayMaxT = dot(N,tri.vertex0-origin)/dot(N,L); - return L; -#endif -} - - -uint getBSDFLightIDAndDetermineNormal(out vec3 normal, in uint objectID, in vec3 intersection) -{ - if (objectID - -#include "../common/CommonAPI.h" -#include "CCamera.hpp" -#include "nbl/ext/ScreenShot/ScreenShot.h" -#include "nbl/video/utilities/CDumbPresentationOracle.h" - -using namespace nbl; -using namespace core; -using namespace ui; - - -using namespace nbl; -using namespace core; -using namespace asset; -using namespace video; - -smart_refctd_ptr createHDRImageView(nbl::core::smart_refctd_ptr device, asset::E_FORMAT colorFormat, uint32_t width, uint32_t height) -{ - smart_refctd_ptr gpuImageViewColorBuffer; - { - IGPUImage::SCreationParams imgInfo; - imgInfo.format = colorFormat; - imgInfo.type = IGPUImage::ET_2D; - imgInfo.extent.width = width; - imgInfo.extent.height = height; - imgInfo.extent.depth = 1u; - imgInfo.mipLevels = 1u; - imgInfo.arrayLayers = 1u; - imgInfo.samples = asset::ICPUImage::ESCF_1_BIT; - imgInfo.flags = static_cast(0u); - imgInfo.usage = core::bitflag(asset::IImage::EUF_STORAGE_BIT) | asset::IImage::EUF_TRANSFER_SRC_BIT; - - // (Erfan -> Cyprian) - // auto image = device->createGPUImageOnDedMem(std::move(imgInfo),device->getDeviceLocalGPUMemoryReqs()); - auto image = device->createImage(std::move(imgInfo)); - auto imageMemoryReqs = image->getMemoryReqs(); - imageMemoryReqs.memoryTypeBits &= device->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); // getDeviceLocalMemoryTypeBits because of previous code getDeviceLocalGPUMemoryReqs - auto imageMem = device->allocate(imageMemoryReqs, image.get()); - - IGPUImageView::SCreationParams imgViewInfo; - imgViewInfo.image = std::move(image); - imgViewInfo.format = colorFormat; - imgViewInfo.viewType = IGPUImageView::ET_2D; - imgViewInfo.flags = static_cast(0u); - imgViewInfo.subresourceRange.aspectMask = IImage::E_ASPECT_FLAGS::EAF_COLOR_BIT; - imgViewInfo.subresourceRange.baseArrayLayer = 0u; - imgViewInfo.subresourceRange.baseMipLevel = 0u; - imgViewInfo.subresourceRange.layerCount = 1u; - imgViewInfo.subresourceRange.levelCount = 1u; - - gpuImageViewColorBuffer = device->createImageView(std::move(imgViewInfo)); - } - - return gpuImageViewColorBuffer; -} - -struct ShaderParameters -{ - const uint32_t MaxDepthLog2 = 4; //5 - const uint32_t MaxSamplesLog2 = 10; //18 -} kShaderParameters; - -enum E_LIGHT_GEOMETRY -{ - ELG_SPHERE, - ELG_TRIANGLE, - ELG_RECTANGLE -}; - -struct DispatchInfo_t -{ - uint32_t workGroupCount[3]; -}; - -_NBL_STATIC_INLINE_CONSTEXPR uint32_t DEFAULT_WORK_GROUP_SIZE = 16u; - -DispatchInfo_t getDispatchInfo(uint32_t imgWidth, uint32_t imgHeight) { - DispatchInfo_t ret = {}; - ret.workGroupCount[0] = (uint32_t)core::ceil((float)imgWidth / (float)DEFAULT_WORK_GROUP_SIZE); - ret.workGroupCount[1] = (uint32_t)core::ceil((float)imgHeight / (float)DEFAULT_WORK_GROUP_SIZE); - ret.workGroupCount[2] = 1; - return ret; -} - -class RayQuerySampleApp : public ApplicationBase -{ - constexpr static uint32_t WIN_W = 1280u; - constexpr static uint32_t WIN_H = 720u; - constexpr static uint32_t FRAMES_IN_FLIGHT = 5u; - static constexpr uint64_t MAX_TIMEOUT = 99999999999999ull; - - core::smart_refctd_ptr windowManager; - core::smart_refctd_ptr window; - core::smart_refctd_ptr windowCb; - core::smart_refctd_ptr apiConnection; - core::smart_refctd_ptr surface; - core::smart_refctd_ptr utilities; - core::smart_refctd_ptr logicalDevice; - video::IPhysicalDevice* physicalDevice; - std::array queues; - core::smart_refctd_ptr swapchain; - core::smart_refctd_ptr renderpass; - core::smart_refctd_dynamic_array> fbos; - std::array, CommonAPI::InitOutput::MaxFramesInFlight>, CommonAPI::InitOutput::MaxQueuesCount> commandPools; - core::smart_refctd_ptr system; - core::smart_refctd_ptr assetManager; - video::IGPUObjectFromAssetConverter::SParams cpu2gpuParams; - core::smart_refctd_ptr logger; - core::smart_refctd_ptr inputSystem; - video::IGPUObjectFromAssetConverter cpu2gpu; - - int32_t m_resourceIx = -1; - uint32_t m_acquiredNextFBO = {}; - - CDumbPresentationOracle oracle; - - // polling for events! - CommonAPI::InputSystem::ChannelReader mouse; - CommonAPI::InputSystem::ChannelReader keyboard; - - core::smart_refctd_ptr frameUploadDataCompleteFence[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr frameComplete[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr imageAcquire[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr renderFinished[FRAMES_IN_FLIGHT] = { nullptr }; - core::smart_refctd_ptr frameUploadDataCompleteSemaphore[FRAMES_IN_FLIGHT] = { nullptr }; - - core::smart_refctd_ptr cmdbuf[FRAMES_IN_FLIGHT]; // from graphics - - Camera cam; - - core::smart_refctd_ptr gpuubo = nullptr; - core::smart_refctd_ptr gpuEnvmapImageView = nullptr; - core::smart_refctd_ptr gpuScrambleImageView; - - core::smart_refctd_ptr gpuComputePipeline = nullptr; - DispatchInfo_t dispatchInfo = {}; - - core::smart_refctd_ptr outHDRImageViews[CommonAPI::InitOutput::MaxSwapChainImageCount] = {}; - - core::smart_refctd_ptr descriptorSets0[CommonAPI::InitOutput::MaxSwapChainImageCount] = {}; - core::smart_refctd_ptr descriptorSet2 = nullptr; - core::smart_refctd_ptr uboDescriptorSet1 = nullptr; - - core::smart_refctd_ptr aabbsBuffer = nullptr; - core::smart_refctd_ptr gpuBlas = nullptr; - core::smart_refctd_ptr gpuBlas2 = nullptr; // Built via CPUObject To GPUObject operations and utility - core::smart_refctd_ptr gpuTlas = nullptr; - core::smart_refctd_ptr instancesBuffer = nullptr; - - core::smart_refctd_ptr gpuSequenceBufferView = nullptr; - - core::smart_refctd_ptr sampler0 = nullptr; - core::smart_refctd_ptr sampler1 = nullptr; - - core::smart_refctd_ptr gpuSequenceBuffer = nullptr; - - core::smart_refctd_ptr spheresBuffer = nullptr; - - struct SBasicViewParametersAligned - { - SBasicViewParameters uboData; - }; - -public: - void setWindow(core::smart_refctd_ptr&& wnd) override - { - window = std::move(wnd); - } - nbl::ui::IWindow* getWindow() override - { - return window.get(); - } - void setSystem(core::smart_refctd_ptr&& system) override - { - system = std::move(system); - } - - APP_CONSTRUCTOR(RayQuerySampleApp); - - void onAppInitialized_impl() override - { - const auto swapchainImageUsage = static_cast(asset::IImage::EUF_COLOR_ATTACHMENT_BIT | asset::IImage::EUF_TRANSFER_DST_BIT | asset::IImage::EUF_TRANSFER_SRC_BIT); - - CommonAPI::InitParams initParams; - initParams.window = core::smart_refctd_ptr(window); - initParams.apiType = video::EAT_VULKAN; - initParams.appName = { _NBL_APP_NAME_ }; - initParams.framesInFlight = FRAMES_IN_FLIGHT; - initParams.windowWidth = WIN_W; - initParams.windowHeight = WIN_H; - initParams.swapchainImageCount = 2u; - initParams.swapchainImageUsage = swapchainImageUsage; - initParams.depthFormat = asset::EF_D32_SFLOAT; - auto initOutput = CommonAPI::InitWithRaytracingExt(std::move(initParams)); - - system = std::move(initOutput.system); - window = std::move(initParams.window); - windowCb = std::move(initParams.windowCb); - apiConnection = std::move(initOutput.apiConnection); - surface = std::move(initOutput.surface); - physicalDevice = std::move(initOutput.physicalDevice); - logicalDevice = std::move(initOutput.logicalDevice); - utilities = std::move(initOutput.utilities); - queues = std::move(initOutput.queues); - renderpass = std::move(initOutput.renderToSwapchainRenderpass); - commandPools = std::move(initOutput.commandPools); - assetManager = std::move(initOutput.assetManager); - cpu2gpuParams = std::move(initOutput.cpu2gpuParams); - logger = std::move(initOutput.logger); - inputSystem = std::move(initOutput.inputSystem); - - CommonAPI::createSwapchain(std::move(logicalDevice), initOutput.swapchainCreationParams, WIN_W, WIN_H, swapchain); - assert(swapchain); - fbos = CommonAPI::createFBOWithSwapchainImages( - swapchain->getImageCount(), WIN_W, WIN_H, - logicalDevice, swapchain, renderpass, - asset::EF_D32_SFLOAT - ); - auto graphicsQueue = queues[CommonAPI::InitOutput::EQT_GRAPHICS]; - auto computeQueue = queues[CommonAPI::InitOutput::EQT_GRAPHICS]; - auto graphicsCommandPools = commandPools[CommonAPI::InitOutput::EQT_GRAPHICS]; - auto computeCommandPools = commandPools[CommonAPI::InitOutput::EQT_COMPUTE]; - - video::IGPUObjectFromAssetConverter cpu2gpu; - for (uint32_t i = 0u; i < FRAMES_IN_FLIGHT; i++) - logicalDevice->createCommandBuffers(graphicsCommandPools[i].get(), video::IGPUCommandBuffer::EL_PRIMARY, 1, cmdbuf+i); - - core::smart_refctd_ptr descriptorPool = nullptr; - { - video::IDescriptorPool::SCreateInfo createInfo = {}; - createInfo.maxSets = CommonAPI::InitOutput::MaxSwapChainImageCount+2; - createInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_STORAGE_BUFFER)] = 1; - createInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_STORAGE_IMAGE)] = CommonAPI::InitOutput::MaxSwapChainImageCount; - createInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER)] = 2; - createInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_UNIFORM_TEXEL_BUFFER)] = 1; - createInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER)] = 1; - createInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_ACCELERATION_STRUCTURE)] = 1; - - descriptorPool = logicalDevice->createDescriptorPool(std::move(createInfo)); - } - - // Initialize Spheres - constexpr uint32_t SphereCount = 9u; - constexpr uint32_t INVALID_ID_16BIT = 0xffffu; - - struct alignas(16) Sphere - { - Sphere() - : position(0.0f, 0.0f, 0.0f) - , radius2(0.0f) - { - bsdfLightIDs = core::bitfieldInsert(0u,INVALID_ID_16BIT,16,16); - } - - Sphere(core::vector3df _position, float _radius, uint32_t _bsdfID, uint32_t _lightID) - { - position = _position; - radius2 = _radius*_radius; - bsdfLightIDs = core::bitfieldInsert(_bsdfID,_lightID,16,16); - } - - IGPUAccelerationStructure::AABB_Position getAABB() const - { - float radius = core::sqrt(radius2); - return IGPUAccelerationStructure::AABB_Position(position-core::vector3df(radius, radius, radius), position+core::vector3df(radius, radius, radius)); - } - - core::vector3df position; - float radius2; - uint32_t bsdfLightIDs; - }; - - Sphere spheres[SphereCount] = {}; - spheres[0] = Sphere(core::vector3df(0.0,-100.5,-1.0), 100.0, 0u, INVALID_ID_16BIT); - spheres[1] = Sphere(core::vector3df(3.0,0.0,-1.0), 0.5, 1u, INVALID_ID_16BIT); - spheres[2] = Sphere(core::vector3df(0.0,0.0,-1.0), 0.5, 2u, INVALID_ID_16BIT); - spheres[3] = Sphere(core::vector3df(-3.0,0.0,-1.0), 0.5, 3u, INVALID_ID_16BIT); - spheres[4] = Sphere(core::vector3df(3.0,0.0,1.0), 0.5, 4u, INVALID_ID_16BIT); - spheres[5] = Sphere(core::vector3df(0.0,0.0,1.0), 0.5, 4u, INVALID_ID_16BIT); - spheres[6] = Sphere(core::vector3df(-3.0,0.0,1.0), 0.5, 5u, INVALID_ID_16BIT); - spheres[7] = Sphere(core::vector3df(0.5,1.0,0.5), 0.5, 6u, INVALID_ID_16BIT); - spheres[8] = Sphere(core::vector3df(-1.5,1.5,0.0), 0.3, INVALID_ID_16BIT, 0u); - - // Create Spheres Buffer - uint32_t spheresBufferSize = sizeof(Sphere) * SphereCount; - - { - IGPUBuffer::SCreationParams params = {}; - params.size = spheresBufferSize; // (Erfan->Cyprian) See How I moved "createDeviceLocalGPUBufferOnDedMem" second parameter to params.size? IGPUBuffer::SCreationParams::size is very important to be filled unlike before - params.usage = core::bitflag(asset::IBuffer::EUF_STORAGE_BUFFER_BIT) | asset::IBuffer::EUF_TRANSFER_DST_BIT; - spheresBuffer = logicalDevice->createBuffer(std::move(params)); - auto bufferReqs = spheresBuffer->getMemoryReqs(); - bufferReqs.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); // (Erfan->Cyprian) I used `getDeviceLocalMemoryTypeBits` because of previous createDeviceLocalGPUBufferOnDedMem (Focus on DeviceLocal Part) - auto spheresBufferMem = logicalDevice->allocate(bufferReqs, spheresBuffer.get()); - utilities->updateBufferRangeViaStagingBufferAutoSubmit(asset::SBufferRange{0u,spheresBufferSize,spheresBuffer}, spheres, graphicsQueue); - } - -#define TEST_CPU_2_GPU_BLAS -#ifdef TEST_CPU_2_GPU_BLAS - // Acceleration Structure Test - // Create + Build BLAS (CPU2GPU Version) - { - struct AABB { - IGPUAccelerationStructure::AABB_Position aabb; - }; - const uint32_t aabbsCount = SphereCount / 2u; - uint32_t aabbsBufferSize = sizeof(AABB) * aabbsCount; - - AABB aabbs[aabbsCount] = {}; - for(uint32_t i = 0; i < aabbsCount; ++i) - { - aabbs[i].aabb = spheres[i].getAABB(); - } - - // auto raytracingFlags = core::bitflag(asset::IBuffer::EUF_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT) | asset::IBuffer::EUF_STORAGE_BUFFER_BIT; - // | asset::IBuffer::EUF_TRANSFER_DST_BIT | asset::IBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT - core::smart_refctd_ptr aabbsBuffer = ICPUBuffer::create({ aabbsBufferSize }); - memcpy(aabbsBuffer->getPointer(), aabbs, aabbsBufferSize); - - ICPUAccelerationStructure::SCreationParams asCreateParams; - asCreateParams.type = ICPUAccelerationStructure::ET_BOTTOM_LEVEL; - asCreateParams.flags = ICPUAccelerationStructure::ECF_NONE; - core::smart_refctd_ptr cpuBlas = ICPUAccelerationStructure::create(std::move(asCreateParams)); - - using HostGeom = ICPUAccelerationStructure::HostBuildGeometryInfo::Geom; - core::smart_refctd_dynamic_array geometries = core::make_refctd_dynamic_array>(1u); - - HostGeom & simpleGeom = geometries->operator[](0u); - simpleGeom.type = IAccelerationStructure::EGT_AABBS; - simpleGeom.flags = IAccelerationStructure::EGF_OPAQUE_BIT; - simpleGeom.data.aabbs.data.offset = 0u; - simpleGeom.data.aabbs.data.buffer = aabbsBuffer; - simpleGeom.data.aabbs.stride = sizeof(AABB); - - ICPUAccelerationStructure::HostBuildGeometryInfo buildInfo; - buildInfo.type = asCreateParams.type; - buildInfo.buildFlags = ICPUAccelerationStructure::EBF_PREFER_FAST_TRACE_BIT; - buildInfo.buildMode = ICPUAccelerationStructure::EBM_BUILD; - buildInfo.geometries = geometries; - - core::smart_refctd_dynamic_array buildRangeInfos = core::make_refctd_dynamic_array>(1u); - ICPUAccelerationStructure::BuildRangeInfo & firstBuildRangeInfo = buildRangeInfos->operator[](0u); - firstBuildRangeInfo.primitiveCount = aabbsCount; - firstBuildRangeInfo.primitiveOffset = 0u; - firstBuildRangeInfo.firstVertex = 0u; - firstBuildRangeInfo.transformOffset = 0u; - - cpuBlas->setBuildInfoAndRanges(std::move(buildInfo), buildRangeInfos); - - // Build BLAS - { - cpu2gpuParams.beginCommandBuffers(); - gpuBlas2 = cpu2gpu.getGPUObjectsFromAssets(&cpuBlas, &cpuBlas + 1u, cpu2gpuParams)->front(); - cpu2gpuParams.waitForCreationToComplete(); - } - } -#endif - - // Create + Build BLAS - { - // Build BLAS with AABBS - const uint32_t aabbsCount = SphereCount; - - struct AABB { - IGPUAccelerationStructure::AABB_Position aabb; - }; - - AABB aabbs[aabbsCount] = {}; - for(uint32_t i = 0; i < aabbsCount; ++i) - { - aabbs[i].aabb = spheres[i].getAABB(); - } - auto raytracingFlags = core::bitflag(asset::IBuffer::EUF_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT) | asset::IBuffer::EUF_STORAGE_BUFFER_BIT; - uint32_t aabbsBufferSize = sizeof(AABB) * aabbsCount; - - { - IGPUBuffer::SCreationParams params = {}; - params.size = aabbsBufferSize; - params.usage = raytracingFlags | asset::IBuffer::EUF_TRANSFER_DST_BIT | asset::IBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; - aabbsBuffer = logicalDevice->createBuffer(std::move(params)); - auto bufferReqs = aabbsBuffer->getMemoryReqs(); - bufferReqs.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto aabbBufferMem = logicalDevice->allocate(bufferReqs, aabbsBuffer.get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); - // (Erfan->Cyprian) -> I passed `IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT` as a third parameter to the allocate function because the buffer needs the usage `EUF_SHADER_DEVICE_ADDRESS_BIT` - // You don't have to worry about it, it's only used in this example - utilities->updateBufferRangeViaStagingBufferAutoSubmit(asset::SBufferRange{0u,aabbsBufferSize,aabbsBuffer}, aabbs, graphicsQueue); - } - - using DeviceGeom = IGPUAccelerationStructure::DeviceBuildGeometryInfo::Geometry; - - DeviceGeom simpleGeom = {}; - simpleGeom.type = IAccelerationStructure::EGT_AABBS; - simpleGeom.flags = IAccelerationStructure::EGF_OPAQUE_BIT; - simpleGeom.data.aabbs.data.offset = 0u; - simpleGeom.data.aabbs.data.buffer = aabbsBuffer; - simpleGeom.data.aabbs.stride = sizeof(AABB); - - IGPUAccelerationStructure::DeviceBuildGeometryInfo blasBuildInfo = {}; - blasBuildInfo.type = IGPUAccelerationStructure::ET_BOTTOM_LEVEL; - blasBuildInfo.buildFlags = IGPUAccelerationStructure::EBF_PREFER_FAST_TRACE_BIT; - blasBuildInfo.buildMode = IGPUAccelerationStructure::EBM_BUILD; - blasBuildInfo.srcAS = nullptr; - blasBuildInfo.dstAS = nullptr; - blasBuildInfo.geometries = core::SRange(&simpleGeom, &simpleGeom + 1u); - blasBuildInfo.scratchAddr = {}; - - // Get BuildSizes - IGPUAccelerationStructure::BuildSizes buildSizes = {}; - { - std::vector maxPrimCount(1u); - maxPrimCount[0] = aabbsCount; - buildSizes = logicalDevice->getAccelerationStructureBuildSizes(blasBuildInfo, maxPrimCount.data()); - } - - { - core::smart_refctd_ptr asBuffer; - IGPUBuffer::SCreationParams params = {}; - params.size = buildSizes.accelerationStructureSize; - params.usage = core::bitflag(asset::IBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT) | asset::IBuffer::EUF_ACCELERATION_STRUCTURE_STORAGE_BIT; - asBuffer = logicalDevice->createBuffer(std::move(params)); - auto bufferReqs = asBuffer->getMemoryReqs(); - bufferReqs.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto asBufferMem = logicalDevice->allocate(bufferReqs, asBuffer.get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); - - IGPUAccelerationStructure::SCreationParams blasParams = {}; - blasParams.type = IGPUAccelerationStructure::ET_BOTTOM_LEVEL; - blasParams.flags = IGPUAccelerationStructure::ECF_NONE; - blasParams.bufferRange.buffer = asBuffer; - blasParams.bufferRange.offset = 0u; - blasParams.bufferRange.size = buildSizes.accelerationStructureSize; - gpuBlas = logicalDevice->createAccelerationStructure(std::move(blasParams)); - } - - // Allocate ScratchBuffer - core::smart_refctd_ptr scratchBuffer; - { - IGPUBuffer::SCreationParams params = {}; - params.size = buildSizes.buildScratchSize; - params.usage = core::bitflag(asset::IBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT) | asset::IBuffer::EUF_STORAGE_BUFFER_BIT; - scratchBuffer = logicalDevice->createBuffer(std::move(params)); - auto bufferReqs = scratchBuffer->getMemoryReqs(); - bufferReqs.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto scratchBufferMem = logicalDevice->allocate(bufferReqs, scratchBuffer.get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); - } - - // Complete BLAS Build Info - { - blasBuildInfo.dstAS = gpuBlas.get(); - blasBuildInfo.scratchAddr.buffer = scratchBuffer; - blasBuildInfo.scratchAddr.offset = 0u; - } - - IGPUAccelerationStructure::BuildRangeInfo firstBuildRangeInfos[1u]; - firstBuildRangeInfos[0].primitiveCount = aabbsCount; - firstBuildRangeInfos[0].primitiveOffset = 0u; - firstBuildRangeInfos[0].firstVertex = 0u; - firstBuildRangeInfos[0].transformOffset = 0u; - IGPUAccelerationStructure::BuildRangeInfo* pRangeInfos[1u]; - pRangeInfos[0] = firstBuildRangeInfos; - // pRangeInfos[1] = &secondBuildRangeInfos; - - // Build BLAS - { - utilities->buildAccelerationStructures(computeQueue, core::SRange(&blasBuildInfo, &blasBuildInfo + 1u), pRangeInfos); - } - } - - // Create + Build TLAS - { - struct Instance { - IGPUAccelerationStructure::Instance instance; - }; - - const uint32_t instancesCount = 1u; - Instance instances[instancesCount] = {}; - core::matrix3x4SIMD identity; - instances[0].instance.mat = identity; - instances[0].instance.instanceCustomIndex = 0u; - instances[0].instance.mask = 0xFF; - instances[0].instance.instanceShaderBindingTableRecordOffset = 0u; - instances[0].instance.flags = IAccelerationStructure::EIF_TRIANGLE_FACING_CULL_DISABLE_BIT; -#ifdef TEST_CPU_2_GPU_BLAS - instances[0].instance.accelerationStructureReference = gpuBlas2->getReferenceForDeviceOperations(); -#else - instances[0].instance.accelerationStructureReference = gpuBlas->getReferenceForDeviceOperations(); -#endif - auto raytracingFlags = core::bitflag(asset::IBuffer::EUF_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT) | asset::IBuffer::EUF_STORAGE_BUFFER_BIT; - - uint32_t instancesBufferSize = sizeof(Instance); - { - IGPUBuffer::SCreationParams params = {}; - params.size = instancesBufferSize; - params.usage = raytracingFlags | asset::IBuffer::EUF_TRANSFER_DST_BIT | asset::IBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; - instancesBuffer = logicalDevice->createBuffer(std::move(params)); - auto bufferReqs = instancesBuffer->getMemoryReqs(); - bufferReqs.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto instancesBufferMem = logicalDevice->allocate(bufferReqs, instancesBuffer.get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); - utilities->updateBufferRangeViaStagingBufferAutoSubmit(asset::SBufferRange{0u,instancesBufferSize,instancesBuffer}, instances, graphicsQueue); - } - - using DeviceGeom = IGPUAccelerationStructure::DeviceBuildGeometryInfo::Geometry; - - DeviceGeom blasInstancesGeom = {}; - blasInstancesGeom.type = IAccelerationStructure::EGT_INSTANCES; - blasInstancesGeom.flags = IAccelerationStructure::EGF_NONE; - blasInstancesGeom.data.instances.data.offset = 0u; - blasInstancesGeom.data.instances.data.buffer = instancesBuffer; - - IGPUAccelerationStructure::DeviceBuildGeometryInfo tlasBuildInfo = {}; - tlasBuildInfo.type = IGPUAccelerationStructure::ET_TOP_LEVEL; - tlasBuildInfo.buildFlags = IGPUAccelerationStructure::EBF_PREFER_FAST_TRACE_BIT; - tlasBuildInfo.buildMode = IGPUAccelerationStructure::EBM_BUILD; - tlasBuildInfo.srcAS = nullptr; - tlasBuildInfo.dstAS = nullptr; - tlasBuildInfo.geometries = core::SRange(&blasInstancesGeom, &blasInstancesGeom + 1u); - tlasBuildInfo.scratchAddr = {}; - - // Get BuildSizes - IGPUAccelerationStructure::BuildSizes buildSizes = {}; - { - std::vector maxPrimCount(1u); - maxPrimCount[0] = instancesCount; - buildSizes = logicalDevice->getAccelerationStructureBuildSizes(tlasBuildInfo, maxPrimCount.data()); - } - - { - core::smart_refctd_ptr asBuffer; - IGPUBuffer::SCreationParams params = {}; - params.size = buildSizes.accelerationStructureSize; - params.usage = core::bitflag(asset::IBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT) | asset::IBuffer::EUF_ACCELERATION_STRUCTURE_STORAGE_BIT; - asBuffer = logicalDevice->createBuffer(std::move(params)); - auto bufferReqs = asBuffer->getMemoryReqs(); - bufferReqs.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto asBufferMem = logicalDevice->allocate(bufferReqs, asBuffer.get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); - - IGPUAccelerationStructure::SCreationParams tlasParams = {}; - tlasParams.type = IGPUAccelerationStructure::ET_TOP_LEVEL; - tlasParams.flags = IGPUAccelerationStructure::ECF_NONE; - tlasParams.bufferRange.buffer = asBuffer; - tlasParams.bufferRange.offset = 0u; - tlasParams.bufferRange.size = buildSizes.accelerationStructureSize; - gpuTlas = logicalDevice->createAccelerationStructure(std::move(tlasParams)); - } - - // Allocate ScratchBuffer - core::smart_refctd_ptr scratchBuffer; - { - IGPUBuffer::SCreationParams params = {}; - params.size = buildSizes.buildScratchSize; - params.usage = core::bitflag(asset::IBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT) | asset::IBuffer::EUF_STORAGE_BUFFER_BIT; - scratchBuffer = logicalDevice->createBuffer(std::move(params)); - auto bufferReqs = scratchBuffer->getMemoryReqs(); - bufferReqs.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto scratchBufferMem = logicalDevice->allocate(bufferReqs, scratchBuffer.get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); - } - - // Complete BLAS Build Info - { - tlasBuildInfo.dstAS = gpuTlas.get(); - tlasBuildInfo.scratchAddr.buffer = scratchBuffer; - tlasBuildInfo.scratchAddr.offset = 0u; - } - - IGPUAccelerationStructure::BuildRangeInfo firstBuildRangeInfos[1u]; - firstBuildRangeInfos[0].primitiveCount = instancesCount; - firstBuildRangeInfos[0].primitiveOffset = 0u; - firstBuildRangeInfos[0].firstVertex = 0u; - firstBuildRangeInfos[0].transformOffset = 0u; - IGPUAccelerationStructure::BuildRangeInfo* pRangeInfos[1u]; - pRangeInfos[0] = firstBuildRangeInfos; - - // Build TLAS - { - utilities->buildAccelerationStructures(computeQueue, core::SRange(&tlasBuildInfo, &tlasBuildInfo + 1u), pRangeInfos); - } - } - - - // Camera - core::vectorSIMDf cameraPosition(0, 5, -10); - matrix4SIMD proj = matrix4SIMD::buildProjectionMatrixPerspectiveFovRH(core::radians(60.0f), video::ISurface::getTransformedAspectRatio(swapchain->getPreTransform(), WIN_W, WIN_H), 0.01f, 500.0f); - cam = Camera(cameraPosition, core::vectorSIMDf(0, 0, 0), proj); - - IGPUDescriptorSetLayout::SBinding descriptorSet0Bindings[] = - { - { 0u, asset::IDescriptor::E_TYPE::ET_STORAGE_IMAGE, video::IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, IShader::ESS_COMPUTE, 1u, nullptr }, - }; - IGPUDescriptorSetLayout::SBinding uboBinding {0, asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER, video::IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, IShader::ESS_COMPUTE, 1u, nullptr}; - IGPUDescriptorSetLayout::SBinding descriptorSet3Bindings[] = { - { 0u, asset::IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER, video::IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, IShader::ESS_COMPUTE, 1u, nullptr }, - { 1u, asset::IDescriptor::E_TYPE::ET_UNIFORM_TEXEL_BUFFER, video::IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, IShader::ESS_COMPUTE, 1u, nullptr }, - { 2u, asset::IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER, video::IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, IShader::ESS_COMPUTE, 1u, nullptr }, - { 3u, asset::IDescriptor::E_TYPE::ET_ACCELERATION_STRUCTURE, video::IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, IShader::ESS_COMPUTE, 1u, nullptr }, - { 4u, asset::IDescriptor::E_TYPE::ET_STORAGE_BUFFER, video::IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, IShader::ESS_COMPUTE, 1u, nullptr } - }; - - auto gpuDescriptorSetLayout0 = logicalDevice->createDescriptorSetLayout(descriptorSet0Bindings, descriptorSet0Bindings + 1u); - auto gpuDescriptorSetLayout1 = logicalDevice->createDescriptorSetLayout(&uboBinding, &uboBinding + 1u); - auto gpuDescriptorSetLayout2 = logicalDevice->createDescriptorSetLayout(descriptorSet3Bindings, descriptorSet3Bindings+5u); - - auto createGpuResources = [&](std::string pathToShader) -> core::smart_refctd_ptr - { - asset::IAssetLoader::SAssetLoadParams params{}; - params.logger = logger.get(); - //params.relativeDir = tmp.c_str(); - auto spec = assetManager->getAsset(pathToShader,params).getContents(); - - if (spec.empty()) - assert(false); - - auto cpuComputeSpecializedShader = core::smart_refctd_ptr_static_cast(*spec.begin()); - - ISpecializedShader::SInfo info = cpuComputeSpecializedShader->getSpecializationInfo(); - info.m_backingBuffer = ICPUBuffer::create({ sizeof(ShaderParameters) }); - memcpy(info.m_backingBuffer->getPointer(),&kShaderParameters,sizeof(ShaderParameters)); - info.m_entries = core::make_refctd_dynamic_array>(2u); - for (uint32_t i=0; i<2; i++) - info.m_entries->operator[](i) = {i,i*sizeof(uint32_t),sizeof(uint32_t)}; - - - cpuComputeSpecializedShader->setSpecializationInfo(std::move(info)); - - auto gpuComputeSpecializedShader = cpu2gpu.getGPUObjectsFromAssets(&cpuComputeSpecializedShader, &cpuComputeSpecializedShader + 1, cpu2gpuParams)->front(); - - auto gpuPipelineLayout = logicalDevice->createPipelineLayout(nullptr, nullptr, core::smart_refctd_ptr(gpuDescriptorSetLayout0), core::smart_refctd_ptr(gpuDescriptorSetLayout1), core::smart_refctd_ptr(gpuDescriptorSetLayout2), nullptr); - - auto gpuPipeline = logicalDevice->createComputePipeline(nullptr, std::move(gpuPipelineLayout), std::move(gpuComputeSpecializedShader)); - - return gpuPipeline; - }; - - E_LIGHT_GEOMETRY lightGeom = ELG_SPHERE; - constexpr const char* shaderPaths[] = {"../litBySphere.comp","../litByTriangle.comp","../litByRectangle.comp"}; - gpuComputePipeline = createGpuResources(shaderPaths[lightGeom]); - - dispatchInfo = getDispatchInfo(WIN_W, WIN_H); - - auto createImageView = [&](std::string pathToOpenEXRHDRIImage) - { - auto pathToTexture = pathToOpenEXRHDRIImage; - IAssetLoader::SAssetLoadParams lp(0ull, nullptr, IAssetLoader::ECF_DONT_CACHE_REFERENCES); - auto cpuTexture = assetManager->getAsset(pathToTexture, lp); - auto cpuTextureContents = cpuTexture.getContents(); - assert(!cpuTextureContents.empty()); - auto cpuImage = core::smart_refctd_ptr_static_cast(*cpuTextureContents.begin()); - cpuImage->setImageUsageFlags(IImage::E_USAGE_FLAGS::EUF_SAMPLED_BIT); - - ICPUImageView::SCreationParams viewParams; - viewParams.flags = static_cast(0u); - viewParams.image = cpuImage; - viewParams.format = viewParams.image->getCreationParameters().format; - viewParams.viewType = IImageView::ET_2D; - viewParams.subresourceRange.aspectMask = IImage::E_ASPECT_FLAGS::EAF_COLOR_BIT; - viewParams.subresourceRange.baseArrayLayer = 0u; - viewParams.subresourceRange.layerCount = 1u; - viewParams.subresourceRange.baseMipLevel = 0u; - viewParams.subresourceRange.levelCount = 1u; - - auto cpuImageView = ICPUImageView::create(std::move(viewParams)); - - cpu2gpuParams.beginCommandBuffers(); - auto gpuImageView = cpu2gpu.getGPUObjectsFromAssets(&cpuImageView, &cpuImageView + 1u, cpu2gpuParams)->front(); - cpu2gpuParams.waitForCreationToComplete(); - - return gpuImageView; - }; - - gpuEnvmapImageView = createImageView("../../media/envmap/envmap_0.exr"); - - { - const uint32_t MaxDimensions = 3u<(sampleSequence->getPointer()); - for (auto dim=0u; dimgetSize(); - IGPUBuffer::SCreationParams params = {}; - params.size = bufferSize; - params.usage = core::bitflag(asset::IBuffer::EUF_TRANSFER_DST_BIT) | asset::IBuffer::EUF_UNIFORM_TEXEL_BUFFER_BIT; - gpuSequenceBuffer = logicalDevice->createBuffer(std::move(params)); - auto bufferReqs = gpuSequenceBuffer->getMemoryReqs(); - bufferReqs.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto gpuSequenceBufferMem = logicalDevice->allocate(bufferReqs, gpuSequenceBuffer.get()); - utilities->updateBufferRangeViaStagingBufferAutoSubmit(asset::SBufferRange{0u,bufferSize,gpuSequenceBuffer},sampleSequence->getPointer(), graphicsQueue); - } - gpuSequenceBufferView = logicalDevice->createBufferView(gpuSequenceBuffer.get(), asset::EF_R32G32B32_UINT); - } - - { - IGPUImage::SCreationParams imgParams; - imgParams.flags = static_cast(0u); - imgParams.type = IImage::ET_2D; - imgParams.format = EF_R32G32_UINT; - imgParams.extent = {WIN_W, WIN_H,1u}; - imgParams.mipLevels = 1u; - imgParams.arrayLayers = 1u; - imgParams.samples = IImage::ESCF_1_BIT; - imgParams.usage = core::bitflag(IImage::EUF_SAMPLED_BIT) | IImage::EUF_TRANSFER_DST_BIT; - imgParams.initialLayout = asset::IImage::EL_UNDEFINED; - - IGPUImage::SBufferCopy region = {}; - region.bufferOffset = 0u; - region.bufferRowLength = 0u; - region.bufferImageHeight = 0u; - region.imageExtent = imgParams.extent; - region.imageOffset = {0u,0u,0u}; - region.imageSubresource.layerCount = 1u; - region.imageSubresource.aspectMask = IImage::E_ASPECT_FLAGS::EAF_COLOR_BIT; - - constexpr auto ScrambleStateChannels = 2u; - const auto renderPixelCount = imgParams.extent.width*imgParams.extent.height; - core::vector random(renderPixelCount*ScrambleStateChannels); - { - core::RandomSampler rng(0xbadc0ffeu); - for (auto& pixel : random) - pixel = rng.nextSample(); - } - - core::smart_refctd_ptr scrambleImageBuffer; - { - const auto bufferSize = random.size() * sizeof(uint32_t); - IGPUBuffer::SCreationParams params = {}; - params.size = bufferSize; - params.usage = core::bitflag(asset::IBuffer::EUF_TRANSFER_DST_BIT) | asset::IBuffer::EUF_TRANSFER_SRC_BIT; - scrambleImageBuffer = logicalDevice->createBuffer(std::move(params)); - auto bufferReqs = scrambleImageBuffer->getMemoryReqs(); - bufferReqs.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto bufferMem = logicalDevice->allocate(bufferReqs, scrambleImageBuffer.get()); - utilities->updateBufferRangeViaStagingBufferAutoSubmit(asset::SBufferRange{0u,bufferSize,scrambleImageBuffer},random.data(),graphicsQueue); - } - - IGPUImageView::SCreationParams viewParams; - viewParams.flags = static_cast(0u); - // TODO: Replace this IGPUBuffer -> IGPUImage to using image upload utility - viewParams.image = utilities->createFilledDeviceLocalImageOnDedMem(std::move(imgParams), scrambleImageBuffer.get(), 1u, ®ion, graphicsQueue); - viewParams.viewType = IGPUImageView::ET_2D; - viewParams.format = EF_R32G32_UINT; - viewParams.subresourceRange.aspectMask = IImage::E_ASPECT_FLAGS::EAF_COLOR_BIT; - viewParams.subresourceRange.levelCount = 1u; - viewParams.subresourceRange.layerCount = 1u; - gpuScrambleImageView = logicalDevice->createImageView(std::move(viewParams)); - } - - // Create Out Image - for(uint32_t i = 0; i < swapchain->getImageCount(); ++i) { - outHDRImageViews[i] = createHDRImageView(logicalDevice, asset::EF_R16G16B16A16_SFLOAT, WIN_W, WIN_H); - } - - for(uint32_t i = 0; i < swapchain->getImageCount(); ++i) - { - auto & descSet = descriptorSets0[i]; - descSet = descriptorPool->createDescriptorSet(core::smart_refctd_ptr(gpuDescriptorSetLayout0)); - video::IGPUDescriptorSet::SWriteDescriptorSet writeDescriptorSet; - writeDescriptorSet.dstSet = descSet.get(); - writeDescriptorSet.binding = 0; - writeDescriptorSet.count = 1u; - writeDescriptorSet.arrayElement = 0u; - writeDescriptorSet.descriptorType = asset::IDescriptor::E_TYPE::ET_STORAGE_IMAGE; - video::IGPUDescriptorSet::SDescriptorInfo info; - { - info.desc = outHDRImageViews[i]; - info.info.image.sampler = nullptr; - info.info.image.imageLayout = asset::IImage::EL_GENERAL; - } - writeDescriptorSet.info = &info; - logicalDevice->updateDescriptorSets(1u, &writeDescriptorSet, 0u, nullptr); - } - - IGPUBuffer::SCreationParams gpuuboParams = {}; - gpuuboParams.size = sizeof(SBasicViewParametersAligned); - gpuuboParams.usage = core::bitflag(IGPUBuffer::EUF_UNIFORM_BUFFER_BIT) | IGPUBuffer::EUF_TRANSFER_DST_BIT; - gpuubo = logicalDevice->createBuffer(std::move(gpuuboParams)); - auto gpuUboMemReqs = gpuubo->getMemoryReqs(); - gpuUboMemReqs.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto gpuUboMem = logicalDevice->allocate(gpuUboMemReqs, gpuubo.get()); - - uboDescriptorSet1 = descriptorPool->createDescriptorSet(core::smart_refctd_ptr(gpuDescriptorSetLayout1)); - { - video::IGPUDescriptorSet::SWriteDescriptorSet uboWriteDescriptorSet; - uboWriteDescriptorSet.dstSet = uboDescriptorSet1.get(); - uboWriteDescriptorSet.binding = 0; - uboWriteDescriptorSet.count = 1u; - uboWriteDescriptorSet.arrayElement = 0u; - uboWriteDescriptorSet.descriptorType = asset::IDescriptor::E_TYPE::ET_UNIFORM_BUFFER; - video::IGPUDescriptorSet::SDescriptorInfo info; - { - info.desc = gpuubo; - info.info.buffer.offset = 0ull; - info.info.buffer.size = sizeof(SBasicViewParametersAligned); - } - uboWriteDescriptorSet.info = &info; - logicalDevice->updateDescriptorSets(1u, &uboWriteDescriptorSet, 0u, nullptr); - } - - ISampler::SParams samplerParams0 = { ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETBC_FLOAT_OPAQUE_BLACK, ISampler::ETF_LINEAR, ISampler::ETF_LINEAR, ISampler::ESMM_LINEAR, 0u, false, ECO_ALWAYS }; - sampler0 = logicalDevice->createSampler(samplerParams0); - ISampler::SParams samplerParams1 = { ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETC_CLAMP_TO_EDGE, ISampler::ETBC_INT_OPAQUE_BLACK, ISampler::ETF_NEAREST, ISampler::ETF_NEAREST, ISampler::ESMM_NEAREST, 0u, false, ECO_ALWAYS }; - sampler1 = logicalDevice->createSampler(samplerParams1); - - descriptorSet2 = descriptorPool->createDescriptorSet(core::smart_refctd_ptr(gpuDescriptorSetLayout2)); - { - constexpr auto kDescriptorCount = 5; - IGPUDescriptorSet::SWriteDescriptorSet writeDescriptorSet2[kDescriptorCount]; - IGPUDescriptorSet::SDescriptorInfo writeDescriptorInfo[kDescriptorCount]; - for (auto i=0; iupdateDescriptorSets(kDescriptorCount, writeDescriptorSet2, 0u, nullptr); - } - - constexpr uint32_t FRAME_COUNT = 500000u; - - for (uint32_t i=0u; icreateSemaphore(); - renderFinished[i] = logicalDevice->createSemaphore(); - frameComplete[i] = logicalDevice->createFence(video::IGPUFence::ECF_SIGNALED_BIT); - frameUploadDataCompleteSemaphore[i] = logicalDevice->createSemaphore(); - frameUploadDataCompleteFence[i] = logicalDevice->createFence(video::IGPUFence::ECF_UNSIGNALED); - } - - oracle.reportBeginFrameRecord(); - } - - void onAppTerminated_impl() override - { - const auto& fboCreationParams = fbos->begin()[m_acquiredNextFBO]->getCreationParameters(); - auto gpuSourceImageView = fboCreationParams.attachments[0]; - logicalDevice->waitIdle(); - - bool status = ext::ScreenShot::createScreenShot( - logicalDevice.get(), - queues[CommonAPI::InitOutput::EQT_TRANSFER_UP], - renderFinished[m_resourceIx].get(), - gpuSourceImageView.get(), - assetManager.get(), - "ScreenShot.png", - asset::IImage::EL_PRESENT_SRC, - asset::EAF_NONE); - - assert(status); - } - - void workLoopBody() override - { - auto& graphicsQueue = queues[CommonAPI::InitOutput::EQT_GRAPHICS]; - - m_resourceIx++; - if(m_resourceIx >= FRAMES_IN_FLIGHT) { - m_resourceIx = 0; - } - - oracle.reportEndFrameRecord(); - double dt = oracle.getDeltaTimeInMicroSeconds() / 1000.0; - auto nextPresentationTimeStamp = oracle.getNextPresentationTimeStamp(); - oracle.reportBeginFrameRecord(); - - // Input - inputSystem->getDefaultMouse(&mouse); - inputSystem->getDefaultKeyboard(&keyboard); - - cam.beginInputProcessing(nextPresentationTimeStamp); - mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void { cam.mouseProcess(events); }, logger.get()); - keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void { cam.keyboardProcess(events); }, logger.get()); - cam.endInputProcessing(nextPresentationTimeStamp); - - auto& cb = cmdbuf[m_resourceIx]; - auto& fence = frameComplete[m_resourceIx]; - while (logicalDevice->waitForFences(1u,&fence.get(),false,MAX_TIMEOUT)==video::IGPUFence::ES_TIMEOUT) - { - } - - const auto viewMatrix = cam.getViewMatrix(); - const auto viewProjectionMatrix = matrix4SIMD::concatenateBFollowedByAPrecisely( - video::ISurface::getSurfaceTransformationMatrix(swapchain->getPreTransform()), - cam.getConcatenatedMatrix() - ); - - // safe to proceed - cb->begin(IGPUCommandBuffer::EU_NONE); - - // renderpass - swapchain->acquireNextImage(MAX_TIMEOUT,imageAcquire[m_resourceIx].get(),nullptr,&m_acquiredNextFBO); - { - auto mv = viewMatrix; - auto mvp = viewProjectionMatrix; - core::matrix3x4SIMD normalMat; - mv.getSub3x3InverseTranspose(normalMat); - - SBasicViewParametersAligned viewParams; - memcpy(viewParams.uboData.MV, mv.pointer(), sizeof(mv)); - memcpy(viewParams.uboData.MVP, mvp.pointer(), sizeof(mvp)); - memcpy(viewParams.uboData.NormalMat, normalMat.pointer(), sizeof(normalMat)); - - asset::SBufferRange range; - range.buffer = gpuubo; - range.offset = 0ull; - range.size = sizeof(viewParams); - - video::IGPUQueue::SSubmitInfo uploadImageSubmit; - uploadImageSubmit.pSignalSemaphores = &frameUploadDataCompleteSemaphore[m_resourceIx].get(); - uploadImageSubmit.signalSemaphoreCount = 1u; - - // We know the fence is already signal because of how we structured our execution -> frameUploadDataCompleteSemaphore -> signals to Render Frame -> wait for frameComplete fence to finish -> then we know frameUploadCompleteFence is signalled - utilities->getDefaultUpStreamingBuffer()->cull_frees(); // need to cull_frees after fence signalled and before fence is reset again - logicalDevice->resetFences(1, &frameUploadDataCompleteFence[m_resourceIx].get()); - - utilities->updateBufferRangeViaStagingBufferAutoSubmit(range, &viewParams, graphicsQueue, frameUploadDataCompleteFence[m_resourceIx].get(), uploadImageSubmit); - // No need to wait for frameUploadDataCompleteFence in CPU, we'll use semaphores to singal the next stage the upload is complete. - } - - auto graphicsCmdQueueFamIdx = queues[CommonAPI::InitOutput::EQT_GRAPHICS]->getFamilyIndex(); - // TRANSITION outHDRImageViews[m_acquiredNextFBO] to EIL_GENERAL (because of descriptorSets0 -> ComputeShader Writes into the image) - { - IGPUCommandBuffer::SImageMemoryBarrier imageBarriers[3u] = {}; - imageBarriers[0].barrier.srcAccessMask = asset::EAF_NONE; - imageBarriers[0].barrier.dstAccessMask = static_cast(asset::EAF_SHADER_WRITE_BIT); - imageBarriers[0].oldLayout = asset::IImage::EL_UNDEFINED; - imageBarriers[0].newLayout = asset::IImage::EL_GENERAL; - imageBarriers[0].srcQueueFamilyIndex = graphicsCmdQueueFamIdx; - imageBarriers[0].dstQueueFamilyIndex = graphicsCmdQueueFamIdx; - imageBarriers[0].image = outHDRImageViews[m_acquiredNextFBO]->getCreationParameters().image; - imageBarriers[0].subresourceRange.aspectMask = asset::IImage::EAF_COLOR_BIT; - imageBarriers[0].subresourceRange.baseMipLevel = 0u; - imageBarriers[0].subresourceRange.levelCount = 1; - imageBarriers[0].subresourceRange.baseArrayLayer = 0u; - imageBarriers[0].subresourceRange.layerCount = 1; - - imageBarriers[1].barrier.srcAccessMask = asset::EAF_NONE; - imageBarriers[1].barrier.dstAccessMask = static_cast(asset::EAF_SHADER_READ_BIT); - imageBarriers[1].oldLayout = asset::IImage::EL_UNDEFINED; - imageBarriers[1].newLayout = asset::IImage::EL_SHADER_READ_ONLY_OPTIMAL; - imageBarriers[1].srcQueueFamilyIndex = graphicsCmdQueueFamIdx; - imageBarriers[1].dstQueueFamilyIndex = graphicsCmdQueueFamIdx; - imageBarriers[1].image = gpuScrambleImageView->getCreationParameters().image; - imageBarriers[1].subresourceRange.aspectMask = asset::IImage::EAF_COLOR_BIT; - imageBarriers[1].subresourceRange.baseMipLevel = 0u; - imageBarriers[1].subresourceRange.levelCount = 1; - imageBarriers[1].subresourceRange.baseArrayLayer = 0u; - imageBarriers[1].subresourceRange.layerCount = 1; - - imageBarriers[2].barrier.srcAccessMask = asset::EAF_NONE; - imageBarriers[2].barrier.dstAccessMask = static_cast(asset::EAF_SHADER_READ_BIT); - imageBarriers[2].oldLayout = asset::IImage::EL_UNDEFINED; - imageBarriers[2].newLayout = asset::IImage::EL_SHADER_READ_ONLY_OPTIMAL; - imageBarriers[2].srcQueueFamilyIndex = graphicsCmdQueueFamIdx; - imageBarriers[2].dstQueueFamilyIndex = graphicsCmdQueueFamIdx; - imageBarriers[2].image = gpuEnvmapImageView->getCreationParameters().image; - imageBarriers[2].subresourceRange.aspectMask = asset::IImage::EAF_COLOR_BIT; - imageBarriers[2].subresourceRange.baseMipLevel = 0u; - imageBarriers[2].subresourceRange.levelCount = gpuEnvmapImageView->getCreationParameters().subresourceRange.levelCount; - imageBarriers[2].subresourceRange.baseArrayLayer = 0u; - imageBarriers[2].subresourceRange.layerCount = gpuEnvmapImageView->getCreationParameters().subresourceRange.layerCount; - - cb->pipelineBarrier(asset::EPSF_TOP_OF_PIPE_BIT, asset::EPSF_COMPUTE_SHADER_BIT, asset::EDF_NONE, 0u, nullptr, 0u, nullptr, 3u, imageBarriers); - } - - // cube envmap handle - { - cb->bindComputePipeline(gpuComputePipeline.get()); - cb->bindDescriptorSets(EPBP_COMPUTE, gpuComputePipeline->getLayout(), 0u, 1u, &descriptorSets0[m_acquiredNextFBO].get()); - cb->bindDescriptorSets(EPBP_COMPUTE, gpuComputePipeline->getLayout(), 1u, 1u, &uboDescriptorSet1.get()); - cb->bindDescriptorSets(EPBP_COMPUTE, gpuComputePipeline->getLayout(), 2u, 1u, &descriptorSet2.get()); - cb->dispatch(dispatchInfo.workGroupCount[0], dispatchInfo.workGroupCount[1], dispatchInfo.workGroupCount[2]); - } - // TODO: tone mapping and stuff - - // Copy HDR Image to SwapChain - auto srcImgViewCreationParams = outHDRImageViews[m_acquiredNextFBO]->getCreationParameters(); - auto dstImgViewCreationParams = fbos->begin()[m_acquiredNextFBO]->getCreationParameters().attachments[0]->getCreationParameters(); - - // Getting Ready for Blit - // TRANSITION outHDRImageViews[m_acquiredNextFBO] to EIL_TRANSFER_SRC_OPTIMAL - // TRANSITION `fbos[m_acquiredNextFBO]->getCreationParameters().attachments[0]` to EIL_TRANSFER_DST_OPTIMAL - { - IGPUCommandBuffer::SImageMemoryBarrier imageBarriers[2u] = {}; - imageBarriers[0].barrier.srcAccessMask = asset::EAF_NONE; - imageBarriers[0].barrier.dstAccessMask = asset::EAF_TRANSFER_WRITE_BIT; - imageBarriers[0].oldLayout = asset::IImage::EL_UNDEFINED; - imageBarriers[0].newLayout = asset::IImage::EL_TRANSFER_SRC_OPTIMAL; - imageBarriers[0].srcQueueFamilyIndex = graphicsCmdQueueFamIdx; - imageBarriers[0].dstQueueFamilyIndex = graphicsCmdQueueFamIdx; - imageBarriers[0].image = srcImgViewCreationParams.image; - imageBarriers[0].subresourceRange.aspectMask = asset::IImage::EAF_COLOR_BIT; - imageBarriers[0].subresourceRange.baseMipLevel = 0u; - imageBarriers[0].subresourceRange.levelCount = 1; - imageBarriers[0].subresourceRange.baseArrayLayer = 0u; - imageBarriers[0].subresourceRange.layerCount = 1; - - imageBarriers[1].barrier.srcAccessMask = asset::EAF_NONE; - imageBarriers[1].barrier.dstAccessMask = asset::EAF_TRANSFER_WRITE_BIT; - imageBarriers[1].oldLayout = asset::IImage::EL_UNDEFINED; - imageBarriers[1].newLayout = asset::IImage::EL_TRANSFER_DST_OPTIMAL; - imageBarriers[1].srcQueueFamilyIndex = graphicsCmdQueueFamIdx; - imageBarriers[1].dstQueueFamilyIndex = graphicsCmdQueueFamIdx; - imageBarriers[1].image = dstImgViewCreationParams.image; - imageBarriers[1].subresourceRange.aspectMask = asset::IImage::EAF_COLOR_BIT; - imageBarriers[1].subresourceRange.baseMipLevel = 0u; - imageBarriers[1].subresourceRange.levelCount = 1; - imageBarriers[1].subresourceRange.baseArrayLayer = 0u; - imageBarriers[1].subresourceRange.layerCount = 1; - cb->pipelineBarrier(asset::EPSF_TRANSFER_BIT, asset::EPSF_TRANSFER_BIT, asset::EDF_NONE, 0u, nullptr, 0u, nullptr, 2u, imageBarriers); - } - - // Blit Image - { - SImageBlit blit = {}; - blit.srcOffsets[0] = {0, 0, 0}; - blit.srcOffsets[1] = {WIN_W, WIN_H, 1}; - - blit.srcSubresource.aspectMask = srcImgViewCreationParams.subresourceRange.aspectMask; - blit.srcSubresource.mipLevel = srcImgViewCreationParams.subresourceRange.baseMipLevel; - blit.srcSubresource.baseArrayLayer = srcImgViewCreationParams.subresourceRange.baseArrayLayer; - blit.srcSubresource.layerCount = srcImgViewCreationParams.subresourceRange.layerCount; - blit.dstOffsets[0] = {0, 0, 0}; - blit.dstOffsets[1] = {WIN_W, WIN_H, 1}; - blit.dstSubresource.aspectMask = dstImgViewCreationParams.subresourceRange.aspectMask; - blit.dstSubresource.mipLevel = dstImgViewCreationParams.subresourceRange.baseMipLevel; - blit.dstSubresource.baseArrayLayer = dstImgViewCreationParams.subresourceRange.baseArrayLayer; - blit.dstSubresource.layerCount = dstImgViewCreationParams.subresourceRange.layerCount; - - auto srcImg = srcImgViewCreationParams.image; - auto dstImg = dstImgViewCreationParams.image; - - cb->blitImage(srcImg.get(), asset::IImage::EL_TRANSFER_SRC_OPTIMAL, dstImg.get(), asset::IImage::EL_TRANSFER_DST_OPTIMAL, 1u, &blit , ISampler::ETF_NEAREST); - } - - // TRANSITION `fbos[m_acquiredNextFBO]->getCreationParameters().attachments[0]` to EIL_PRESENT - { - IGPUCommandBuffer::SImageMemoryBarrier imageBarriers[1u] = {}; - imageBarriers[0].barrier.srcAccessMask = asset::EAF_TRANSFER_WRITE_BIT; - imageBarriers[0].barrier.dstAccessMask = asset::EAF_NONE; - imageBarriers[0].oldLayout = asset::IImage::EL_TRANSFER_DST_OPTIMAL; - imageBarriers[0].newLayout = asset::IImage::EL_PRESENT_SRC; - imageBarriers[0].srcQueueFamilyIndex = graphicsCmdQueueFamIdx; - imageBarriers[0].dstQueueFamilyIndex = graphicsCmdQueueFamIdx; - imageBarriers[0].image = dstImgViewCreationParams.image; - imageBarriers[0].subresourceRange.aspectMask = asset::IImage::EAF_COLOR_BIT; - imageBarriers[0].subresourceRange.baseMipLevel = 0u; - imageBarriers[0].subresourceRange.levelCount = 1; - imageBarriers[0].subresourceRange.baseArrayLayer = 0u; - imageBarriers[0].subresourceRange.layerCount = 1; - cb->pipelineBarrier(asset::EPSF_TRANSFER_BIT, asset::EPSF_TOP_OF_PIPE_BIT, asset::EDF_NONE, 0u, nullptr, 0u, nullptr, 1u, imageBarriers); - } - - cb->end(); - logicalDevice->resetFences(1, &fence.get()); - - nbl::video::IGPUQueue::SSubmitInfo submit; - submit.commandBufferCount = 1u; - submit.commandBuffers = &cb.get(); - submit.signalSemaphoreCount = 1u; - submit.pSignalSemaphores = &renderFinished[m_resourceIx].get(); - nbl::video::IGPUSemaphore* waitSemaphores[2u] = { imageAcquire[m_resourceIx].get(), frameUploadDataCompleteSemaphore[m_resourceIx].get() }; - asset::E_PIPELINE_STAGE_FLAGS waitStages[2u] = { nbl::asset::EPSF_COLOR_ATTACHMENT_OUTPUT_BIT, nbl::asset::EPSF_RAY_TRACING_SHADER_BIT_KHR} ; - submit.waitSemaphoreCount = 2u; - submit.pWaitSemaphores = waitSemaphores; - submit.pWaitDstStageMask = waitStages; - - graphicsQueue->submit(1u,&submit,fence.get()); - - CommonAPI::Present(logicalDevice.get(), swapchain.get(), queues[CommonAPI::InitOutput::EQT_GRAPHICS], renderFinished[m_resourceIx].get(), m_acquiredNextFBO); - } - - bool keepRunning() override - { - return windowCb->isWindowOpen(); - } - - video::IAPIConnection* getAPIConnection() override - { - return apiConnection.get(); - } - video::ILogicalDevice* getLogicalDevice() override - { - return logicalDevice.get(); - } - video::IGPURenderpass* getRenderpass() override - { - return renderpass.get(); - } - void setSurface(core::smart_refctd_ptr&& s) override - { - surface = std::move(s); - } - void setFBOs(std::vector>& f) override - { - for (int i = 0; i < f.size(); i++) - { - fbos->begin()[i] = core::smart_refctd_ptr(f[i]); - } - } - void setSwapchain(core::smart_refctd_ptr&& s) override - { - swapchain = std::move(s); - } - uint32_t getSwapchainImageCount() override - { - return swapchain->getImageCount(); - } - virtual nbl::asset::E_FORMAT getDepthFormat() override - { - return nbl::asset::EF_D32_SFLOAT; - } -}; - -NBL_COMMON_API_MAIN(RayQuerySampleApp) diff --git a/61_UI/CMakeLists.txt b/61_UI/CMakeLists.txt index a34e46ce6..5d0021f61 100644 --- a/61_UI/CMakeLists.txt +++ b/61_UI/CMakeLists.txt @@ -12,7 +12,9 @@ if(NBL_BUILD_IMGUI) imguizmo "${NBL_EXT_IMGUI_UI_LIB}" ) - - nbl_create_executable_project("${NBL_EXTRA_SOURCES}" "" "${NBL_INCLUDE_SERACH_DIRECTORIES}" "${NBL_LIBRARIES}" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") - LINK_BUILTIN_RESOURCES_TO_TARGET(${EXECUTABLE_NAME} geometryCreatorSpirvBRD) + + # TODO; Arek I removed `NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET` from the last parameter here, doesn't this macro have 4 arguments anyway !? + nbl_create_executable_project("${NBL_EXTRA_SOURCES}" "" "${NBL_INCLUDE_SERACH_DIRECTORIES}" "${NBL_LIBRARIES}") + # TODO: Arek temporarily disabled cause I haven't figured out how to make this target yet + # LINK_BUILTIN_RESOURCES_TO_TARGET(${EXECUTABLE_NAME} nblExamplesGeometrySpirvBRD) endif() \ No newline at end of file diff --git a/61_UI/include/common.hpp b/61_UI/include/common.hpp index a5def7551..fe7d086dd 100644 --- a/61_UI/include/common.hpp +++ b/61_UI/include/common.hpp @@ -1,25 +1,19 @@ -#ifndef __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ -#define __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ +#ifndef _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ +#define _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ -#include -// common api -#include "CCamera.hpp" -#include "SimpleWindowedApplication.hpp" -#include "CEventCallback.hpp" +#include "nbl/examples/examples.hpp" // the example's headers #include "transform.hpp" -#include "CGeomtryCreatorScene.hpp" using namespace nbl; -using namespace core; -using namespace hlsl; -using namespace system; -using namespace asset; -using namespace ui; -using namespace video; -using namespace scene; -using namespace geometrycreator; +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::examples; -#endif // __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ \ No newline at end of file +#endif // _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ \ No newline at end of file diff --git a/61_UI/include/transform.hpp b/61_UI/include/transform.hpp index 88a78f751..fb1672c2f 100644 --- a/61_UI/include/transform.hpp +++ b/61_UI/include/transform.hpp @@ -1,20 +1,23 @@ -#ifndef __NBL_THIS_EXAMPLE_TRANSFORM_H_INCLUDED__ -#define __NBL_THIS_EXAMPLE_TRANSFORM_H_INCLUDED__ +#ifndef _NBL_THIS_EXAMPLE_TRANSFORM_H_INCLUDED_ +#define _NBL_THIS_EXAMPLE_TRANSFORM_H_INCLUDED_ + #include "nbl/ui/ICursorControl.h" + #include "nbl/ext/ImGui/ImGui.h" + #include "imgui/imgui_internal.h" #include "imguizmo/ImGuizmo.h" -static constexpr inline auto OfflineSceneTextureIx = 1u; struct TransformRequestParams { - bool useWindow = true, editTransformDecomposition = false, enableViewManipulate = false; float camDistance = 8.f; + uint8_t sceneTexDescIx = ~0; + bool useWindow = true, editTransformDecomposition = false, enableViewManipulate = false; }; -void EditTransform(float* cameraView, const float* cameraProjection, float* matrix, const TransformRequestParams& params) +nbl::hlsl::uint16_t2 EditTransform(float* cameraView, const float* cameraProjection, float* matrix, const TransformRequestParams& params) { static ImGuizmo::OPERATION mCurrentGizmoOperation(ImGuizmo::TRANSLATE); static ImGuizmo::MODE mCurrentGizmoMode(ImGuizmo::LOCAL); @@ -99,11 +102,12 @@ void EditTransform(float* cameraView, const float* cameraProjection, float* matr rendered is aligned to our texture scene using imgui "cursor" screen positions */ - +// TODO: this shouldn't be handled here I think SImResourceInfo info; - info.textureID = OfflineSceneTextureIx; + info.textureID = params.sceneTexDescIx; info.samplerIx = (uint16_t)nbl::ext::imgui::UI::DefaultSamplerIx::USER; + nbl::hlsl::uint16_t2 retval; if (params.useWindow) { ImGui::SetNextWindowSize(ImVec2(800, 400), ImGuiCond_Appearing); @@ -118,6 +122,7 @@ void EditTransform(float* cameraView, const float* cameraProjection, float* matr ImGui::Image(info, contentRegionSize); ImGuizmo::SetRect(cursorPos.x, cursorPos.y, contentRegionSize.x, contentRegionSize.y); + retval = {contentRegionSize.x,contentRegionSize.y}; viewManipulateRight = cursorPos.x + contentRegionSize.x; viewManipulateTop = cursorPos.y; @@ -137,6 +142,7 @@ void EditTransform(float* cameraView, const float* cameraProjection, float* matr ImGui::Image(info, contentRegionSize); ImGuizmo::SetRect(cursorPos.x, cursorPos.y, contentRegionSize.x, contentRegionSize.y); + retval = {contentRegionSize.x,contentRegionSize.y}; viewManipulateRight = cursorPos.x + contentRegionSize.x; viewManipulateTop = cursorPos.y; @@ -149,6 +155,8 @@ void EditTransform(float* cameraView, const float* cameraProjection, float* matr ImGui::End(); ImGui::PopStyleColor(); + + return retval; } #endif // __NBL_THIS_EXAMPLE_TRANSFORM_H_INCLUDED__ \ No newline at end of file diff --git a/61_UI/main.cpp b/61_UI/main.cpp index 470d5e723..643cab079 100644 --- a/61_UI/main.cpp +++ b/61_UI/main.cpp @@ -5,794 +5,882 @@ #include "common.hpp" /* - Renders scene texture to an offline - framebuffer which color attachment - is then sampled into a imgui window. +Renders scene texture to an offscreen framebuffer whose color attachment is then sampled into a imgui window. - Written with Nabla, it's UI extension - and got integrated with ImGuizmo to - handle scene's object translations. +Written with Nabla's UI extension and got integrated with ImGuizmo to handle scene's object translations. */ - -class UISampleApp final : public examples::SimpleWindowedApplication +class UISampleApp final : public MonoWindowApplication, public BuiltinResourcesApplication { - using device_base_t = examples::SimpleWindowedApplication; - using clock_t = std::chrono::steady_clock; - - _NBL_STATIC_INLINE_CONSTEXPR uint32_t WIN_W = 1280, WIN_H = 720; - - constexpr static inline clock_t::duration DisplayImageDuration = std::chrono::milliseconds(900); + using device_base_t = MonoWindowApplication; + using asset_base_t = BuiltinResourcesApplication; public: inline UISampleApp(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) - : IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) {} - - inline core::vector getSurfaces() const override - { - if (!m_surface) - { - { - auto windowCallback = core::make_smart_refctd_ptr(smart_refctd_ptr(m_inputSystem), smart_refctd_ptr(m_logger)); - IWindow::SCreationParams params = {}; - params.callback = core::make_smart_refctd_ptr(); - params.width = WIN_W; - params.height = WIN_H; - params.x = 32; - params.y = 32; - params.flags = ui::IWindow::ECF_HIDDEN | IWindow::ECF_BORDERLESS | IWindow::ECF_RESIZABLE; - params.windowCaption = "UISampleApp"; - params.callback = windowCallback; - const_cast&>(m_window) = m_winMgr->createWindow(std::move(params)); - } - - auto surface = CSurfaceVulkanWin32::create(smart_refctd_ptr(m_api), smart_refctd_ptr_static_cast(m_window)); - const_cast&>(m_surface) = nbl::video::CSimpleResizeSurface::create(std::move(surface)); - } - - if (m_surface) - return { {m_surface->getSurface()/*,EQF_NONE*/} }; - - return {}; - } + : IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD), + device_base_t({1280,720}, EF_UNKNOWN, _localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) {} inline bool onAppInitialized(smart_refctd_ptr&& system) override { - m_inputSystem = make_smart_refctd_ptr(logger_opt_smart_ptr(smart_refctd_ptr(m_logger))); - + if (!asset_base_t::onAppInitialized(smart_refctd_ptr(system))) + return false; if (!device_base_t::onAppInitialized(smart_refctd_ptr(system))) return false; - m_assetManager = make_smart_refctd_ptr(smart_refctd_ptr(m_system)); - auto* geometry = m_assetManager->getGeometryCreator(); - m_semaphore = m_device->createSemaphore(m_realFrameIx); if (!m_semaphore) return logFail("Failed to Create a Semaphore!"); - ISwapchain::SCreationParams swapchainParams = { .surface = m_surface->getSurface() }; - if (!swapchainParams.deduceFormat(m_physicalDevice)) - return logFail("Could not choose a Surface Format for the Swapchain!"); - - const static IGPURenderpass::SCreationParams::SSubpassDependency dependencies[] = + auto pool = m_device->createCommandPool(getGraphicsQueue()->getFamilyIndex(),IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); + for (auto i = 0u; icreateCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY,{m_cmdBufs.data()+i,1})) + return logFail("Couldn't create Command Buffer!"); + } + + const uint32_t addtionalBufferOwnershipFamilies[] = {getGraphicsQueue()->getFamilyIndex()}; + m_scene = CGeometryCreatorScene::create( { - .srcSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, - .dstSubpass = 0, - .memoryBarrier = - { - .srcStageMask = asset::PIPELINE_STAGE_FLAGS::COPY_BIT, - .srcAccessMask = asset::ACCESS_FLAGS::TRANSFER_WRITE_BIT, - .dstStageMask = asset::PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, - .dstAccessMask = asset::ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT - } - }, - { - .srcSubpass = 0, - .dstSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, - .memoryBarrier = - { - .srcStageMask = asset::PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, - .srcAccessMask = asset::ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT - } + .transferQueue = getTransferUpQueue(), + .utilities = m_utils.get(), + .logger = m_logger.get(), + .addtionalBufferOwnershipFamilies = addtionalBufferOwnershipFamilies }, - IGPURenderpass::SCreationParams::DependenciesEnd - }; - - auto scResources = std::make_unique(m_device.get(), swapchainParams.surfaceFormat.format, dependencies); - auto* renderpass = scResources->getRenderpass(); + CSimpleDebugRenderer::DefaultPolygonGeometryPatch + ); - if (!renderpass) - return logFail("Failed to create Renderpass!"); - - auto gQueue = getGraphicsQueue(); - if (!m_surface || !m_surface->init(gQueue, std::move(scResources), swapchainParams.sharedParams)) - return logFail("Could not create Window & Surface or initialize the Surface!"); - - m_cmdPool = m_device->createCommandPool(gQueue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); - - for (auto i = 0u; i < MaxFramesInFlight; i++) + // for the scene drawing pass { - if (!m_cmdPool) - return logFail("Couldn't create Command Pool!"); - if (!m_cmdPool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY, { m_cmdBufs.data() + i, 1 })) - return logFail("Couldn't create Command Buffer!"); + IGPURenderpass::SCreationParams params = {}; + const IGPURenderpass::SCreationParams::SDepthStencilAttachmentDescription depthAttachments[] = { + {{ + { + .format = sceneRenderDepthFormat, + .samples = IGPUImage::ESCF_1_BIT, + .mayAlias = false + }, + /*.loadOp = */{IGPURenderpass::LOAD_OP::CLEAR}, + /*.storeOp = */{IGPURenderpass::STORE_OP::STORE}, + /*.initialLayout = */{IGPUImage::LAYOUT::UNDEFINED}, + /*.finalLayout = */{IGPUImage::LAYOUT::ATTACHMENT_OPTIMAL} + }}, + IGPURenderpass::SCreationParams::DepthStencilAttachmentsEnd + }; + params.depthStencilAttachments = depthAttachments; + const IGPURenderpass::SCreationParams::SColorAttachmentDescription colorAttachments[] = { + {{ + { + .format = finalSceneRenderFormat, + .samples = IGPUImage::E_SAMPLE_COUNT_FLAGS::ESCF_1_BIT, + .mayAlias = false + }, + /*.loadOp = */IGPURenderpass::LOAD_OP::CLEAR, + /*.storeOp = */IGPURenderpass::STORE_OP::STORE, + /*.initialLayout = */IGPUImage::LAYOUT::UNDEFINED, + /*.finalLayout = */ IGPUImage::LAYOUT::READ_ONLY_OPTIMAL // ImGUI shall read + }}, + IGPURenderpass::SCreationParams::ColorAttachmentsEnd + }; + params.colorAttachments = colorAttachments; + IGPURenderpass::SCreationParams::SSubpassDescription subpasses[] = { + {}, + IGPURenderpass::SCreationParams::SubpassesEnd + }; + subpasses[0].depthStencilAttachment = {{.render={.attachmentIndex=0,.layout=IGPUImage::LAYOUT::ATTACHMENT_OPTIMAL}}}; + subpasses[0].colorAttachments[0] = {.render={.attachmentIndex=0,.layout=IGPUImage::LAYOUT::ATTACHMENT_OPTIMAL}}; + params.subpasses = subpasses; + + const static IGPURenderpass::SCreationParams::SSubpassDependency dependencies[] = { + // wipe-transition of Color to ATTACHMENT_OPTIMAL and depth + { + .srcSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .dstSubpass = 0, + .memoryBarrier = { + // last place where the depth can get modified in previous frame, `COLOR_ATTACHMENT_OUTPUT_BIT` is implicitly later + // while color is sampled by ImGUI + .srcStageMask = PIPELINE_STAGE_FLAGS::LATE_FRAGMENT_TESTS_BIT|PIPELINE_STAGE_FLAGS::FRAGMENT_SHADER_BIT, + // don't want any writes to be available, as we are clearing both attachments + .srcAccessMask = ACCESS_FLAGS::NONE, + // destination needs to wait as early as possible + // TODO: `COLOR_ATTACHMENT_OUTPUT_BIT` shouldn't be needed, because its a logically later stage, see TODO in `ECommonEnums.h` + .dstStageMask = PIPELINE_STAGE_FLAGS::EARLY_FRAGMENT_TESTS_BIT|PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + // because depth and color get cleared first no read mask + .dstAccessMask = ACCESS_FLAGS::DEPTH_STENCIL_ATTACHMENT_WRITE_BIT|ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + } + // leave view offsets and flags default + }, + { + .srcSubpass = 0, + .dstSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .memoryBarrier = { + // last place where the color can get modified, depth is implicitly earlier + .srcStageMask = PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + // only write ops, reads can't be made available, also won't be using depth so don't care about it being visible to anyone else + .srcAccessMask = ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT, + // the ImGUI will sample the color, then next frame we overwrite both attachments + .dstStageMask = PIPELINE_STAGE_FLAGS::FRAGMENT_SHADER_BIT|PIPELINE_STAGE_FLAGS::EARLY_FRAGMENT_TESTS_BIT, + // but we only care about the availability-visibility chain between renderpass and imgui + .dstAccessMask = ACCESS_FLAGS::SAMPLED_READ_BIT + } + // leave view offsets and flags default + }, + IGPURenderpass::SCreationParams::DependenciesEnd + }; + params.dependencies = {}; + m_renderpass = m_device->createRenderpass(std::move(params)); + if (!m_renderpass) + return logFail("Failed to create Scene Renderpass!"); } - - //pass.scene = CScene::create(smart_refctd_ptr(m_utils), smart_refctd_ptr(m_logger), gQueue, geometry); - pass.scene = CScene::create(smart_refctd_ptr(m_utils), smart_refctd_ptr(m_logger), gQueue, geometry); - - nbl::ext::imgui::UI::SCreationParameters params; - - params.resources.texturesInfo = { .setIx = 0u, .bindingIx = 0u }; - params.resources.samplersInfo = { .setIx = 0u, .bindingIx = 1u }; - params.assetManager = m_assetManager; - params.pipelineCache = nullptr; - params.pipelineLayout = nbl::ext::imgui::UI::createDefaultPipelineLayout(m_utils->getLogicalDevice(), params.resources.texturesInfo, params.resources.samplersInfo, TexturesAmount); - params.renderpass = smart_refctd_ptr(renderpass); - params.streamingBuffer = nullptr; - params.subpassIx = 0u; - params.transfer = getTransferUpQueue(); - params.utilities = m_utils; + const auto& geometries = m_scene->getInitParams().geometries; + m_renderer = CSimpleDebugRenderer::create(m_assetMgr.get(),m_renderpass.get(),0,{&geometries.front().get(),geometries.size()}); + // special case { - pass.ui.manager = nbl::ext::imgui::UI::create(std::move(params)); - - if (!pass.ui.manager) - return false; - - // note that we use default layout provided by our extension, but you are free to create your own by filling nbl::ext::imgui::UI::S_CREATION_PARAMETERS::resources - const auto* descriptorSetLayout = pass.ui.manager->getPipeline()->getLayout()->getDescriptorSetLayout(0u); - const auto& params = pass.ui.manager->getCreationParameters(); - - IDescriptorPool::SCreateInfo descriptorPoolInfo = {}; - descriptorPoolInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_SAMPLER)] = (uint32_t)nbl::ext::imgui::UI::DefaultSamplerIx::COUNT; - descriptorPoolInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_SAMPLED_IMAGE)] = TexturesAmount; - descriptorPoolInfo.maxSets = 1u; - descriptorPoolInfo.flags = IDescriptorPool::E_CREATE_FLAGS::ECF_UPDATE_AFTER_BIND_BIT; - - m_descriptorSetPool = m_device->createDescriptorPool(std::move(descriptorPoolInfo)); - assert(m_descriptorSetPool); + const auto& pipelines = m_renderer->getInitParams().pipelines; + auto ix = 0u; + for (const auto& name : m_scene->getInitParams().geometryNames) + { + if (name=="Cone") + m_renderer->getGeometry(ix).pipeline = pipelines[CSimpleDebugRenderer::SInitParams::PipelineType::Cone]; + ix++; + } + } + // we'll only display one thing at a time + m_renderer->m_instances.resize(1); - m_descriptorSetPool->createDescriptorSets(1u, &descriptorSetLayout, &pass.ui.descriptorSet); - assert(pass.ui.descriptorSet); + // Create ImGUI + { + auto scRes = static_cast(m_surface->getSwapchainResources()); + ext::imgui::UI::SCreationParameters params = {}; + params.resources.texturesInfo = {.setIx=0u,.bindingIx=TexturesImGUIBindingIndex}; + params.resources.samplersInfo = {.setIx=0u,.bindingIx=1u}; + params.utilities = m_utils; + params.transfer = getTransferUpQueue(); + params.pipelineLayout = ext::imgui::UI::createDefaultPipelineLayout(m_utils->getLogicalDevice(),params.resources.texturesInfo,params.resources.samplersInfo,MaxImGUITextures); + params.assetManager = make_smart_refctd_ptr(smart_refctd_ptr(m_system)); + params.renderpass = smart_refctd_ptr(scRes->getRenderpass()); + params.subpassIx = 0u; + params.pipelineCache = nullptr; + interface.imGUI = ext::imgui::UI::create(std::move(params)); + if (!interface.imGUI) + return logFail("Failed to create `nbl::ext::imgui::UI` class"); } - pass.ui.manager->registerListener([this]() -> void - { - ImGuiIO& io = ImGui::GetIO(); - camera.setProjectionMatrix([&]() + // create rest of User Interface + { + auto* imgui = interface.imGUI.get(); + // create the suballocated descriptor set + { + // note that we use default layout provided by our extension, but you are free to create your own by filling ext::imgui::UI::S_CREATION_PARAMETERS::resources + const auto* layout = imgui->getPipeline()->getLayout()->getDescriptorSetLayout(0u); + auto pool = m_device->createDescriptorPoolForDSLayouts(IDescriptorPool::E_CREATE_FLAGS::ECF_UPDATE_AFTER_BIND_BIT,{&layout,1}); + auto ds = pool->createDescriptorSet(smart_refctd_ptr(layout)); + interface.subAllocDS = make_smart_refctd_ptr(std::move(ds)); + if (!interface.subAllocDS) + return logFail("Failed to create the descriptor set"); + // make sure Texture Atlas slot is taken for eternity { - static matrix4SIMD projection; - - if (isPerspective) - if(isLH) - projection = matrix4SIMD::buildProjectionMatrixPerspectiveFovLH(core::radians(fov), io.DisplaySize.x / io.DisplaySize.y, zNear, zFar); - else - projection = matrix4SIMD::buildProjectionMatrixPerspectiveFovRH(core::radians(fov), io.DisplaySize.x / io.DisplaySize.y, zNear, zFar); - else - { - float viewHeight = viewWidth * io.DisplaySize.y / io.DisplaySize.x; - - if(isLH) - projection = matrix4SIMD::buildProjectionMatrixOrthoLH(viewWidth, viewHeight, zNear, zFar); - else - projection = matrix4SIMD::buildProjectionMatrixOrthoRH(viewWidth, viewHeight, zNear, zFar); - } - - return projection; - }()); - - ImGuizmo::SetOrthographic(false); - ImGuizmo::BeginFrame(); - - ImGui::SetNextWindowPos(ImVec2(1024, 100), ImGuiCond_Appearing); - ImGui::SetNextWindowSize(ImVec2(256, 256), ImGuiCond_Appearing); - - // create a window and insert the inspector - ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_Appearing); - ImGui::SetNextWindowSize(ImVec2(320, 340), ImGuiCond_Appearing); - ImGui::Begin("Editor"); - - if (ImGui::RadioButton("Full view", !transformParams.useWindow)) - transformParams.useWindow = false; - - ImGui::SameLine(); - - if (ImGui::RadioButton("Window", transformParams.useWindow)) - transformParams.useWindow = true; - - ImGui::Text("Camera"); - bool viewDirty = false; - - if (ImGui::RadioButton("LH", isLH)) - isLH = true; - - ImGui::SameLine(); - - if (ImGui::RadioButton("RH", !isLH)) - isLH = false; - - if (ImGui::RadioButton("Perspective", isPerspective)) - isPerspective = true; - - ImGui::SameLine(); + auto dummy = SubAllocatedDescriptorSet::invalid_value; + interface.subAllocDS->multi_allocate(0,1,&dummy); + assert(dummy==ext::imgui::UI::FontAtlasTexId); + } + // write constant descriptors, note we don't create info & write pair for the samplers because UI extension's are immutable and baked into DS layout + IGPUDescriptorSet::SDescriptorInfo info = {}; + info.desc = smart_refctd_ptr(interface.imGUI->getFontAtlasView()); + info.info.image.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; + const IGPUDescriptorSet::SWriteDescriptorSet write = { + .dstSet = interface.subAllocDS->getDescriptorSet(), + .binding = TexturesImGUIBindingIndex, + .arrayElement = ext::imgui::UI::FontAtlasTexId, + .count = 1, + .info = &info + }; + if (!m_device->updateDescriptorSets({&write,1},{})) + return logFail("Failed to write the descriptor set"); + } + imgui->registerListener([this](){interface();}); + } - if (ImGui::RadioButton("Orthographic", !isPerspective)) - isPerspective = false; + interface.camera.mapKeysToArrows(); - ImGui::Checkbox("Enable \"view manipulate\"", &transformParams.enableViewManipulate); - ImGui::Checkbox("Enable camera movement", &move); - ImGui::SliderFloat("Move speed", &moveSpeed, 0.1f, 10.f); - ImGui::SliderFloat("Rotate speed", &rotateSpeed, 0.1f, 10.f); + onAppInitializedFinish(); + return true; + } - // ImGui::Checkbox("Flip Gizmo's Y axis", &flipGizmoY); // let's not expose it to be changed in UI but keep the logic in case + // + virtual inline bool onAppTerminated() + { + SubAllocatedDescriptorSet::value_type fontAtlasDescIx = ext::imgui::UI::FontAtlasTexId; + IGPUDescriptorSet::SDropDescriptorSet dummy[1]; + interface.subAllocDS->multi_deallocate(dummy,TexturesImGUIBindingIndex,1,&fontAtlasDescIx); + return device_base_t::onAppTerminated(); + } - if (isPerspective) - ImGui::SliderFloat("Fov", &fov, 20.f, 150.f); - else - ImGui::SliderFloat("Ortho width", &viewWidth, 1, 20); + inline IQueue::SSubmitInfo::SSemaphoreInfo renderFrame(const std::chrono::microseconds nextPresentationTimestamp) override + { + // CPU events + update(nextPresentationTimestamp); - ImGui::SliderFloat("zNear", &zNear, 0.1f, 100.f); - ImGui::SliderFloat("zFar", &zFar, 110.f, 10000.f); + const auto& virtualWindowRes = interface.sceneResolution; + if (!m_framebuffer || m_framebuffer->getCreationParameters().width!=virtualWindowRes[0] || m_framebuffer->getCreationParameters().height!=virtualWindowRes[1]) + recreateFramebuffer(virtualWindowRes); - viewDirty |= ImGui::SliderFloat("Distance", &transformParams.camDistance, 1.f, 69.f); + // + const auto resourceIx = m_realFrameIx % MaxFramesInFlight; - if (viewDirty || firstFrame) + auto* const cb = m_cmdBufs.data()[resourceIx].get(); + cb->reset(IGPUCommandBuffer::RESET_FLAGS::RELEASE_RESOURCES_BIT); + cb->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + // clear to black for both things + const IGPUCommandBuffer::SClearColorValue clearValue = { .float32 = {0.f,0.f,0.f,1.f} }; + if (m_framebuffer) + { + cb->beginDebugMarker("UISampleApp Scene Frame"); + { + const IGPUCommandBuffer::SClearDepthStencilValue farValue = { .depth=0.f }; + const IGPUCommandBuffer::SRenderpassBeginInfo renderpassInfo = { - core::vectorSIMDf cameraPosition(cosf(camYAngle)* cosf(camXAngle)* transformParams.camDistance, sinf(camXAngle)* transformParams.camDistance, sinf(camYAngle)* cosf(camXAngle)* transformParams.camDistance); - core::vectorSIMDf cameraTarget(0.f, 0.f, 0.f); - const static core::vectorSIMDf up(0.f, 1.f, 0.f); - - camera.setPosition(cameraPosition); - camera.setTarget(cameraTarget); - camera.setBackupUpVector(up); - - camera.recomputeViewMatrix(); - - firstFrame = false; + .framebuffer = m_framebuffer.get(), + .colorClearValues = &clearValue, + .depthStencilClearValues = &farValue, + .renderArea = { + .offset = {0,0}, + .extent = {virtualWindowRes[0],virtualWindowRes[1]} + } + }; + beginRenderpass(cb,renderpassInfo); + } + // draw scene + { + float32_t3x4 viewMatrix; + float32_t4x4 viewProjMatrix; + // TODO: get rid of legacy matrices + { + const auto& camera = interface.camera; + memcpy(&viewMatrix,camera.getViewMatrix().pointer(),sizeof(viewMatrix)); + memcpy(&viewProjMatrix,camera.getConcatenatedMatrix().pointer(),sizeof(viewProjMatrix)); } + const auto viewParams = CSimpleDebugRenderer::SViewParams(viewMatrix,viewProjMatrix); - ImGui::Text("X: %f Y: %f", io.MousePos.x, io.MousePos.y); - if (ImGuizmo::IsUsing()) + // tear down scene every frame + auto& instance = m_renderer->m_instances[0]; + memcpy(&instance.world,&interface.model,sizeof(instance.world)); + instance.packedGeo = m_renderer->getGeometries().data() + interface.gcIndex; + m_renderer->render(cb,viewParams); + } + cb->endRenderPass(); + cb->endDebugMarker(); + } + { + cb->beginDebugMarker("UISampleApp IMGUI Frame"); + { + auto scRes = static_cast(m_surface->getSwapchainResources()); + const IGPUCommandBuffer::SRenderpassBeginInfo renderpassInfo = { - ImGui::Text("Using gizmo"); - } - else + .framebuffer = scRes->getFramebuffer(device_base_t::getCurrentAcquire().imageIndex), + .colorClearValues = &clearValue, + .depthStencilClearValues = nullptr, + .renderArea = { + .offset = {0,0}, + .extent = {m_window->getWidth(),m_window->getHeight()} + } + }; + beginRenderpass(cb,renderpassInfo); + } + // draw ImGUI + { + auto* imgui = interface.imGUI.get(); + auto* pipeline = imgui->getPipeline(); + cb->bindGraphicsPipeline(pipeline); + // note that we use default UI pipeline layout where uiParams.resources.textures.setIx == uiParams.resources.samplers.setIx + const auto* ds = interface.subAllocDS->getDescriptorSet(); + cb->bindDescriptorSets(EPBP_GRAPHICS,pipeline->getLayout(),imgui->getCreationParameters().resources.texturesInfo.setIx,1u,&ds); + // a timepoint in the future to release streaming resources for geometry + const ISemaphore::SWaitInfo drawFinished = {.semaphore=m_semaphore.get(),.value=m_realFrameIx+1u}; + if (!imgui->render(cb,drawFinished)) { - ImGui::Text(ImGuizmo::IsOver() ? "Over gizmo" : ""); - ImGui::SameLine(); - ImGui::Text(ImGuizmo::IsOver(ImGuizmo::TRANSLATE) ? "Over translate gizmo" : ""); - ImGui::SameLine(); - ImGui::Text(ImGuizmo::IsOver(ImGuizmo::ROTATE) ? "Over rotate gizmo" : ""); - ImGui::SameLine(); - ImGui::Text(ImGuizmo::IsOver(ImGuizmo::SCALE) ? "Over scale gizmo" : ""); + m_logger->log("TODO: need to present acquired image before bailing because its already acquired.",ILogger::ELL_ERROR); + return {}; } - ImGui::Separator(); - - /* - * ImGuizmo expects view & perspective matrix to be column major both with 4x4 layout - * and Nabla uses row major matricies - 3x4 matrix for view & 4x4 for projection - - - VIEW: - - ImGuizmo - - | X[0] Y[0] Z[0] 0.0f | - | X[1] Y[1] Z[1] 0.0f | - | X[2] Y[2] Z[2] 0.0f | - | -Dot(X, eye) -Dot(Y, eye) -Dot(Z, eye) 1.0f | - - Nabla - - | X[0] X[1] X[2] -Dot(X, eye) | - | Y[0] Y[1] Y[2] -Dot(Y, eye) | - | Z[0] Z[1] Z[2] -Dot(Z, eye) | - - = transpose(nbl::core::matrix4SIMD()) - - - PERSPECTIVE [PROJECTION CASE]: - - ImGuizmo + } + cb->endRenderPass(); + cb->endDebugMarker(); + } + cb->end(); - | (temp / temp2) (0.0) (0.0) (0.0) | - | (0.0) (temp / temp3) (0.0) (0.0) | - | ((right + left) / temp2) ((top + bottom) / temp3) ((-zfar - znear) / temp4) (-1.0f) | - | (0.0) (0.0) ((-temp * zfar) / temp4) (0.0) | + //updateGUIDescriptorSet(); - Nabla + IQueue::SSubmitInfo::SSemaphoreInfo retval = + { + .semaphore = m_semaphore.get(), + .value = ++m_realFrameIx, + .stageMask = PIPELINE_STAGE_FLAGS::ALL_GRAPHICS_BITS + }; + const IQueue::SSubmitInfo::SCommandBufferInfo commandBuffers[] = + { + {.cmdbuf = cb } + }; + const IQueue::SSubmitInfo::SSemaphoreInfo acquired[] = { + { + .semaphore = device_base_t::getCurrentAcquire().semaphore, + .value = device_base_t::getCurrentAcquire().acquireCount, + .stageMask = PIPELINE_STAGE_FLAGS::NONE + } + }; + const IQueue::SSubmitInfo infos[] = + { + { + .waitSemaphores = acquired, + .commandBuffers = commandBuffers, + .signalSemaphores = {&retval,1} + } + }; + + if (getGraphicsQueue()->submit(infos) != IQueue::RESULT::SUCCESS) + { + retval.semaphore = nullptr; // so that we don't wait on semaphore that will never signal + m_realFrameIx--; + } - | w (0.0) (0.0) (0.0) | - | (0.0) -h (0.0) (0.0) | - | (0.0) (0.0) (-zFar/(zFar-zNear)) (-zNear*zFar/(zFar-zNear)) | - | (0.0) (0.0) (-1.0) (0.0) | - = transpose() + m_window->setCaption("[Nabla Engine] UI App Test Demo"); + return retval; + } - * - * the ViewManipulate final call (inside EditTransform) returns world space column major matrix for an object, - * note it also modifies input view matrix but projection matrix is immutable - */ + protected: + const video::IGPURenderpass::SCreationParams::SSubpassDependency* getDefaultSubpassDependencies() const override + { + // Subsequent submits don't wait for each other, but they wait for acquire and get waited on by present + const static IGPURenderpass::SCreationParams::SSubpassDependency dependencies[] = { + // don't want any writes to be available, we'll clear, only thing to worry about is the layout transition + { + .srcSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .dstSubpass = 0, + .memoryBarrier = { + .srcStageMask = PIPELINE_STAGE_FLAGS::NONE, // should sync against the semaphore wait anyway + .srcAccessMask = ACCESS_FLAGS::NONE, + // layout transition needs to finish before the color write + .dstStageMask = PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + .dstAccessMask = ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + } + // leave view offsets and flags default + }, + // want layout transition to begin after all color output is done + { + .srcSubpass = 0, + .dstSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .memoryBarrier = { + // last place where the color can get modified, depth is implicitly earlier + .srcStageMask = PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + // only write ops, reads can't be made available + .srcAccessMask = ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + // spec says nothing is needed when presentation is the destination + } + // leave view offsets and flags default + }, + IGPURenderpass::SCreationParams::DependenciesEnd + }; + return dependencies; + } - static struct - { - core::matrix4SIMD view, projection, model; - } imguizmoM16InOut; + private: + inline void update(const std::chrono::microseconds nextPresentationTimestamp) + { + auto& camera = interface.camera; + camera.setMoveSpeed(interface.moveSpeed); + camera.setRotateSpeed(interface.rotateSpeed); - ImGuizmo::SetID(0u); - imguizmoM16InOut.view = core::transpose(matrix4SIMD(camera.getViewMatrix())); - imguizmoM16InOut.projection = core::transpose(camera.getProjectionMatrix()); - imguizmoM16InOut.model = core::transpose(core::matrix4SIMD(pass.scene->object.model)); - { - if (flipGizmoY) // note we allow to flip gizmo just to match our coordinates - imguizmoM16InOut.projection[1][1] *= -1.f; // https://johannesugb.github.io/gpu-programming/why-do-opengl-proj-matrices-fail-in-vulkan/ + m_inputSystem->getDefaultMouse(&mouse); + m_inputSystem->getDefaultKeyboard(&keyboard); - transformParams.editTransformDecomposition = true; - EditTransform(imguizmoM16InOut.view.pointer(), imguizmoM16InOut.projection.pointer(), imguizmoM16InOut.model.pointer(), transformParams); - } + struct + { + std::vector mouse{}; + std::vector keyboard{}; + } uiEvents; - // to Nabla + update camera & model matrices - const auto& view = camera.getViewMatrix(); - const auto& projection = camera.getProjectionMatrix(); + // TODO: should be a member really + static std::chrono::microseconds previousEventTimestamp{}; - // TODO: make it more nicely - const_cast(view) = core::transpose(imguizmoM16InOut.view).extractSub3x4(); // a hack, correct way would be to use inverse matrix and get position + target because now it will bring you back to last position & target when switching from gizmo move to manual move (but from manual to gizmo is ok) - camera.setProjectionMatrix(projection); // update concatanated matrix + // I think begin/end should always be called on camera, just events shouldn't be fed, why? + // If you stop begin/end, whatever keys were up/down get their up/down values frozen leading to + // `perActionDt` becoming obnoxiously large the first time the even processing resumes due to + // `timeDiff` being computed since `lastVirtualUpTimeStamp` + camera.beginInputProcessing(nextPresentationTimestamp); + { + mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void { - static nbl::core::matrix3x4SIMD modelView, normal; - static nbl::core::matrix4SIMD modelViewProjection; + if (interface.move) + camera.mouseProcess(events); // don't capture the events, only let camera handle them with its impl - auto& hook = pass.scene->object; - hook.model = core::transpose(imguizmoM16InOut.model).extractSub3x4(); + for (const auto& e : events) // here capture { - const auto& references = pass.scene->getResources().objects; - const auto type = static_cast(gcIndex); - - const auto& [gpu, meta] = references[type]; - hook.meta.type = type; - hook.meta.name = meta.name; - } - - auto& ubo = hook.viewParameters; + if (e.timeStamp < previousEventTimestamp) + continue; - modelView = nbl::core::concatenateBFollowedByA(view, hook.model); - modelView.getSub3x3InverseTranspose(normal); - modelViewProjection = nbl::core::concatenateBFollowedByA(camera.getConcatenatedMatrix(), hook.model); + previousEventTimestamp = e.timeStamp; + uiEvents.mouse.emplace_back(e); - memcpy(ubo.MVP, modelViewProjection.pointer(), sizeof(ubo.MVP)); - memcpy(ubo.MV, modelView.pointer(), sizeof(ubo.MV)); - memcpy(ubo.NormalMat, normal.pointer(), sizeof(ubo.NormalMat)); - - // object meta display - { - ImGui::Begin("Object"); - ImGui::Text("type: \"%s\"", hook.meta.name.data()); - ImGui::End(); + if (e.type==nbl::ui::SMouseEvent::EET_SCROLL && m_renderer) + { + interface.gcIndex += int16_t(core::sign(e.scrollEvent.verticalScroll)); + interface.gcIndex = core::clamp(interface.gcIndex,0ull,m_renderer->getGeometries().size()-1); + } } - } - - // view matrices editor + }, + m_logger.get() + ); + keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void { - ImGui::Begin("Matrices"); + if (interface.move) + camera.keyboardProcess(events); // don't capture the events, only let camera handle them with its impl - auto addMatrixTable = [&](const char* topText, const char* tableName, const int rows, const int columns, const float* pointer, const bool withSeparator = true) + for (const auto& e : events) // here capture { - ImGui::Text(topText); - if (ImGui::BeginTable(tableName, columns)) - { - for (int y = 0; y < rows; ++y) - { - ImGui::TableNextRow(); - for (int x = 0; x < columns; ++x) - { - ImGui::TableSetColumnIndex(x); - ImGui::Text("%.3f", *(pointer + (y * columns) + x)); - } - } - ImGui::EndTable(); - } + if (e.timeStamp < previousEventTimestamp) + continue; - if (withSeparator) - ImGui::Separator(); - }; + previousEventTimestamp = e.timeStamp; + uiEvents.keyboard.emplace_back(e); + } + }, + m_logger.get() + ); + } + camera.endInputProcessing(nextPresentationTimestamp); - addMatrixTable("Model Matrix", "ModelMatrixTable", 3, 4, pass.scene->object.model.pointer()); - addMatrixTable("Camera View Matrix", "ViewMatrixTable", 3, 4, view.pointer()); - addMatrixTable("Camera View Projection Matrix", "ViewProjectionMatrixTable", 4, 4, projection.pointer(), false); + const auto cursorPosition = m_window->getCursorControl()->getPosition(); - ImGui::End(); - } + ext::imgui::UI::SUpdateParameters params = + { + .mousePosition = float32_t2(cursorPosition.x,cursorPosition.y) - float32_t2(m_window->getX(),m_window->getY()), + .displaySize = {m_window->getWidth(),m_window->getHeight()}, + .mouseEvents = uiEvents.mouse, + .keyboardEvents = uiEvents.keyboard + }; - // Nabla Imgui backend MDI buffer info - // To be 100% accurate and not overly conservative we'd have to explicitly `cull_frees` and defragment each time, - // so unless you do that, don't use this basic info to optimize the size of your IMGUI buffer. - { - auto* streaminingBuffer = pass.ui.manager->getStreamingBuffer(); + interface.objectName = m_scene->getInitParams().geometryNames[interface.gcIndex]; + interface.imGUI->update(params); + } - const size_t total = streaminingBuffer->get_total_size(); // total memory range size for which allocation can be requested - const size_t freeSize = streaminingBuffer->getAddressAllocator().get_free_size(); // max total free bloock memory size we can still allocate from total memory available - const size_t consumedMemory = total - freeSize; // memory currently consumed by streaming buffer + void recreateFramebuffer(const uint16_t2 resolution) + { + auto createImageAndView = [&](E_FORMAT format)->smart_refctd_ptr + { + auto image = m_device->createImage({{ + .type = IGPUImage::ET_2D, + .samples = IGPUImage::ESCF_1_BIT, + .format = format, + .extent = {resolution.x,resolution.y,1}, + .mipLevels = 1, + .arrayLayers = 1, + .usage = IGPUImage::EUF_RENDER_ATTACHMENT_BIT|IGPUImage::EUF_SAMPLED_BIT + }}); + if (!m_device->allocate(image->getMemoryReqs(),image.get()).isValid()) + return nullptr; + IGPUImageView::SCreationParams params = { + .image = std::move(image), + .viewType = IGPUImageView::ET_2D, + .format = format + }; + params.subresourceRange.aspectMask = isDepthOrStencilFormat(format) ? IGPUImage::EAF_DEPTH_BIT:IGPUImage::EAF_COLOR_BIT; + return m_device->createImageView(std::move(params)); + }; + + smart_refctd_ptr colorView; + // detect window minimization + if (resolution.x<0x4000 && resolution.y<0x4000) + { + colorView = createImageAndView(finalSceneRenderFormat); + auto depthView = createImageAndView(sceneRenderDepthFormat); + m_framebuffer = m_device->createFramebuffer({ { + .renderpass = m_renderpass, + .depthStencilAttachments = &depthView.get(), + .colorAttachments = &colorView.get(), + .width = resolution.x, + .height = resolution.y + }}); + } + else + m_framebuffer = nullptr; - float freePercentage = 100.0f * (float)(freeSize) / (float)total; - float allocatedPercentage = (float)(consumedMemory) / (float)total; + // release previous slot and its image + interface.subAllocDS->multi_deallocate(0,1,&interface.renderColorViewDescIndex,{.semaphore=m_semaphore.get(),.value=m_realFrameIx}); + // + if (colorView) + { + interface.subAllocDS->multi_allocate(0,1,&interface.renderColorViewDescIndex); + // update descriptor set + IGPUDescriptorSet::SDescriptorInfo info = {}; + info.desc = colorView; + info.info.image.imageLayout = IGPUImage::LAYOUT::READ_ONLY_OPTIMAL; + const IGPUDescriptorSet::SWriteDescriptorSet write = { + .dstSet = interface.subAllocDS->getDescriptorSet(), + .binding = TexturesImGUIBindingIndex, + .arrayElement = interface.renderColorViewDescIndex, + .count = 1, + .info = &info + }; + m_device->updateDescriptorSets({&write,1},{}); + } + interface.transformParams.sceneTexDescIx = interface.renderColorViewDescIndex; + } - ImVec2 barSize = ImVec2(400, 30); - float windowPadding = 10.0f; - float verticalPadding = ImGui::GetStyle().FramePadding.y; + inline void beginRenderpass(IGPUCommandBuffer* cb, const IGPUCommandBuffer::SRenderpassBeginInfo& info) + { + cb->beginRenderPass(info,IGPUCommandBuffer::SUBPASS_CONTENTS::INLINE); + cb->setScissor(0,1,&info.renderArea); + const SViewport viewport = { + .x = 0, + .y = 0, + .width = static_cast(info.renderArea.extent.width), + .height = static_cast(info.renderArea.extent.height) + }; + cb->setViewport(0u,1u,&viewport); + } - ImGui::SetNextWindowSize(ImVec2(barSize.x + 2 * windowPadding, 110 + verticalPadding), ImGuiCond_Always); - ImGui::Begin("Nabla Imgui MDI Buffer Info", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar); + // Maximum frames which can be simultaneously submitted, used to cycle through our per-frame resources like command buffers + constexpr static inline uint32_t MaxFramesInFlight = 3u; + constexpr static inline auto sceneRenderDepthFormat = EF_D32_SFLOAT; + constexpr static inline auto finalSceneRenderFormat = EF_R8G8B8A8_SRGB; + constexpr static inline auto TexturesImGUIBindingIndex = 0u; + // we create the Descriptor Set with a few slots extra to spare, so we don't have to `waitIdle` the device whenever ImGUI virtual window resizes + constexpr static inline auto MaxImGUITextures = 2u+MaxFramesInFlight; + + // + smart_refctd_ptr m_scene; + smart_refctd_ptr m_renderpass; + smart_refctd_ptr m_renderer; + smart_refctd_ptr m_framebuffer; + // + smart_refctd_ptr m_semaphore; + uint64_t m_realFrameIx = 0; + std::array,MaxFramesInFlight> m_cmdBufs; + // + InputSystem::ChannelReader mouse; + InputSystem::ChannelReader keyboard; + // UI stuff + struct CInterface + { + void operator()() + { + ImGuiIO& io = ImGui::GetIO(); - ImGui::Text("Total Allocated Size: %zu bytes", total); - ImGui::Text("In use: %zu bytes", consumedMemory); - ImGui::Text("Buffer Usage:"); + // TODO: why is this a lambda and not just an assignment in a scope ? + camera.setProjectionMatrix([&]() + { + matrix4SIMD projection; - ImGui::SetCursorPosX(windowPadding); + if (isPerspective) + if(isLH) + projection = matrix4SIMD::buildProjectionMatrixPerspectiveFovLH(core::radians(fov), io.DisplaySize.x / io.DisplaySize.y, zNear, zFar); + else + projection = matrix4SIMD::buildProjectionMatrixPerspectiveFovRH(core::radians(fov), io.DisplaySize.x / io.DisplaySize.y, zNear, zFar); + else + { + float viewHeight = viewWidth * io.DisplaySize.y / io.DisplaySize.x; - if (freePercentage > 70.0f) - ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImVec4(0.0f, 1.0f, 0.0f, 0.4f)); // Green - else if (freePercentage > 30.0f) - ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImVec4(1.0f, 1.0f, 0.0f, 0.4f)); // Yellow + if(isLH) + projection = matrix4SIMD::buildProjectionMatrixOrthoLH(viewWidth, viewHeight, zNear, zFar); else - ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImVec4(1.0f, 0.0f, 0.0f, 0.4f)); // Red + projection = matrix4SIMD::buildProjectionMatrixOrthoRH(viewWidth, viewHeight, zNear, zFar); + } - ImGui::ProgressBar(allocatedPercentage, barSize, ""); + return projection; + }()); - ImGui::PopStyleColor(); + ImGuizmo::SetOrthographic(false); + ImGuizmo::BeginFrame(); - ImDrawList* drawList = ImGui::GetWindowDrawList(); + ImGui::SetNextWindowPos(ImVec2(1024, 100), ImGuiCond_Appearing); + ImGui::SetNextWindowSize(ImVec2(256, 256), ImGuiCond_Appearing); - ImVec2 progressBarPos = ImGui::GetItemRectMin(); - ImVec2 progressBarSize = ImGui::GetItemRectSize(); + // create a window and insert the inspector + ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_Appearing); + ImGui::SetNextWindowSize(ImVec2(320, 340), ImGuiCond_Appearing); + ImGui::Begin("Editor"); - const char* text = "%.2f%% free"; - char textBuffer[64]; - snprintf(textBuffer, sizeof(textBuffer), text, freePercentage); + if (ImGui::RadioButton("Full view", !transformParams.useWindow)) + transformParams.useWindow = false; - ImVec2 textSize = ImGui::CalcTextSize(textBuffer); - ImVec2 textPos = ImVec2 - ( - progressBarPos.x + (progressBarSize.x - textSize.x) * 0.5f, - progressBarPos.y + (progressBarSize.y - textSize.y) * 0.5f - ); + ImGui::SameLine(); - ImVec4 bgColor = ImGui::GetStyleColorVec4(ImGuiCol_WindowBg); - drawList->AddRectFilled - ( - ImVec2(textPos.x - 5, textPos.y - 2), - ImVec2(textPos.x + textSize.x + 5, textPos.y + textSize.y + 2), - ImGui::GetColorU32(bgColor) - ); + if (ImGui::RadioButton("Window", transformParams.useWindow)) + transformParams.useWindow = true; - ImGui::SetCursorScreenPos(textPos); - ImGui::Text("%s", textBuffer); + ImGui::Text("Camera"); + bool viewDirty = false; - ImGui::Dummy(ImVec2(0.0f, verticalPadding)); + if (ImGui::RadioButton("LH", isLH)) + isLH = true; - ImGui::End(); - } + ImGui::SameLine(); - ImGui::End(); - } - ); + if (ImGui::RadioButton("RH", !isLH)) + isLH = false; - m_winMgr->setWindowSize(m_window.get(), WIN_W, WIN_H); - m_surface->recreateSwapchain(); - m_winMgr->show(m_window.get()); - oracle.reportBeginFrameRecord(); - camera.mapKeysToArrows(); + if (ImGui::RadioButton("Perspective", isPerspective)) + isPerspective = true; - return true; - } + ImGui::SameLine(); - bool updateGUIDescriptorSet() - { - // texture atlas + our scene texture, note we don't create info & write pair for the font sampler because UI extension's is immutable and baked into DS layout - static std::array descriptorInfo; - static IGPUDescriptorSet::SWriteDescriptorSet writes[TexturesAmount]; + if (ImGui::RadioButton("Orthographic", !isPerspective)) + isPerspective = false; - descriptorInfo[nbl::ext::imgui::UI::FontAtlasTexId].info.image.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; - descriptorInfo[nbl::ext::imgui::UI::FontAtlasTexId].desc = core::smart_refctd_ptr(pass.ui.manager->getFontAtlasView()); + ImGui::Checkbox("Enable \"view manipulate\"", &transformParams.enableViewManipulate); + ImGui::Checkbox("Enable camera movement", &move); + ImGui::SliderFloat("Move speed", &moveSpeed, 0.1f, 10.f); + ImGui::SliderFloat("Rotate speed", &rotateSpeed, 0.1f, 10.f); - descriptorInfo[OfflineSceneTextureIx].info.image.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; - descriptorInfo[OfflineSceneTextureIx].desc = pass.scene->getResources().attachments.color; + // ImGui::Checkbox("Flip Gizmo's Y axis", &flipGizmoY); // let's not expose it to be changed in UI but keep the logic in case - for (uint32_t i = 0; i < descriptorInfo.size(); ++i) - { - writes[i].dstSet = pass.ui.descriptorSet.get(); - writes[i].binding = 0u; - writes[i].arrayElement = i; - writes[i].count = 1u; - } - writes[nbl::ext::imgui::UI::FontAtlasTexId].info = descriptorInfo.data() + nbl::ext::imgui::UI::FontAtlasTexId; - writes[OfflineSceneTextureIx].info = descriptorInfo.data() + OfflineSceneTextureIx; + if (isPerspective) + ImGui::SliderFloat("Fov", &fov, 20.f, 150.f); + else + ImGui::SliderFloat("Ortho width", &viewWidth, 1, 20); - return m_device->updateDescriptorSets(writes, {}); - } + ImGui::SliderFloat("zNear", &zNear, 0.1f, 100.f); + ImGui::SliderFloat("zFar", &zFar, 110.f, 10000.f); - inline void workLoopBody() override - { - // framesInFlight: ensuring safe execution of command buffers and acquires, `framesInFlight` only affect semaphore waits, don't use this to index your resources because it can change with swapchain recreation. - const uint32_t framesInFlight = core::min(MaxFramesInFlight, m_surface->getMaxAcquiresInFlight()); - // We block for semaphores for 2 reasons here: - // A) Resource: Can't use resource like a command buffer BEFORE previous use is finished! [MaxFramesInFlight] - // B) Acquire: Can't have more acquires in flight than a certain threshold returned by swapchain or your surface helper class. [MaxAcquiresInFlight] - if (m_realFrameIx >= framesInFlight) - { - const ISemaphore::SWaitInfo cbDonePending[] = + viewDirty |= ImGui::SliderFloat("Distance", &transformParams.camDistance, 1.f, 69.f); + + if (viewDirty || firstFrame) { - { - .semaphore = m_semaphore.get(), - .value = m_realFrameIx + 1 - framesInFlight - } - }; - if (m_device->blockForSemaphores(cbDonePending) != ISemaphore::WAIT_RESULT::SUCCESS) - return; - } + core::vectorSIMDf cameraPosition(cosf(camYAngle)* cosf(camXAngle)* transformParams.camDistance, sinf(camXAngle)* transformParams.camDistance, sinf(camYAngle)* cosf(camXAngle)* transformParams.camDistance); + core::vectorSIMDf cameraTarget(0.f, 0.f, 0.f); + const static core::vectorSIMDf up(0.f, 1.f, 0.f); - const auto resourceIx = m_realFrameIx % MaxFramesInFlight; + camera.setPosition(cameraPosition); + camera.setTarget(cameraTarget); + camera.setBackupUpVector(up); - // CPU events - update(); + camera.recomputeViewMatrix(); + } + firstFrame = false; - // render whole scene to offline frame buffer & submit - pass.scene->begin(); - { - pass.scene->update(); - pass.scene->record(); - pass.scene->end(); - } - pass.scene->submit(); + ImGui::Text("X: %f Y: %f", io.MousePos.x, io.MousePos.y); + if (ImGuizmo::IsUsing()) + { + ImGui::Text("Using gizmo"); + } + else + { + ImGui::Text(ImGuizmo::IsOver() ? "Over gizmo" : ""); + ImGui::SameLine(); + ImGui::Text(ImGuizmo::IsOver(ImGuizmo::TRANSLATE) ? "Over translate gizmo" : ""); + ImGui::SameLine(); + ImGui::Text(ImGuizmo::IsOver(ImGuizmo::ROTATE) ? "Over rotate gizmo" : ""); + ImGui::SameLine(); + ImGui::Text(ImGuizmo::IsOver(ImGuizmo::SCALE) ? "Over scale gizmo" : ""); + } + ImGui::Separator(); - auto* const cb = m_cmdBufs.data()[resourceIx].get(); - cb->reset(IGPUCommandBuffer::RESET_FLAGS::RELEASE_RESOURCES_BIT); - cb->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); - cb->beginDebugMarker("UISampleApp IMGUI Frame"); + /* + * ImGuizmo expects view & perspective matrix to be column major both with 4x4 layout + * and Nabla uses row major matricies - 3x4 matrix for view & 4x4 for projection - auto* queue = getGraphicsQueue(); + - VIEW: - asset::SViewport viewport; - { - viewport.minDepth = 1.f; - viewport.maxDepth = 0.f; - viewport.x = 0u; - viewport.y = 0u; - viewport.width = WIN_W; - viewport.height = WIN_H; - } - cb->setViewport(0u, 1u, &viewport); + ImGuizmo - const VkRect2D currentRenderArea = - { - .offset = {0,0}, - .extent = {m_window->getWidth(),m_window->getHeight()} - }; + | X[0] Y[0] Z[0] 0.0f | + | X[1] Y[1] Z[1] 0.0f | + | X[2] Y[2] Z[2] 0.0f | + | -Dot(X, eye) -Dot(Y, eye) -Dot(Z, eye) 1.0f | - IQueue::SSubmitInfo::SCommandBufferInfo commandBuffersInfo[] = {{.cmdbuf = cb }}; + Nabla - // UI render pass - { - auto scRes = static_cast(m_surface->getSwapchainResources()); - const IGPUCommandBuffer::SRenderpassBeginInfo renderpassInfo = - { - .framebuffer = scRes->getFramebuffer(m_currentImageAcquire.imageIndex), - .colorClearValues = &clear.color, - .depthStencilClearValues = nullptr, - .renderArea = currentRenderArea - }; - nbl::video::ISemaphore::SWaitInfo waitInfo = { .semaphore = m_semaphore.get(), .value = m_realFrameIx + 1u }; + | X[0] X[1] X[2] -Dot(X, eye) | + | Y[0] Y[1] Y[2] -Dot(Y, eye) | + | Z[0] Z[1] Z[2] -Dot(Z, eye) | - cb->beginRenderPass(renderpassInfo, IGPUCommandBuffer::SUBPASS_CONTENTS::INLINE); - const auto uiParams = pass.ui.manager->getCreationParameters(); - auto* pipeline = pass.ui.manager->getPipeline(); - cb->bindGraphicsPipeline(pipeline); - cb->bindDescriptorSets(EPBP_GRAPHICS, pipeline->getLayout(), uiParams.resources.texturesInfo.setIx, 1u, &pass.ui.descriptorSet.get()); // note that we use default UI pipeline layout where uiParams.resources.textures.setIx == uiParams.resources.samplers.setIx - - if (!keepRunning()) - return; - - if (!pass.ui.manager->render(cb,waitInfo)) - { - // TODO: need to present acquired image before bailing because its already acquired - return; - } - cb->endRenderPass(); - } - cb->end(); - { - const IQueue::SSubmitInfo::SSemaphoreInfo rendered[] = - { - { - .semaphore = m_semaphore.get(), - .value = ++m_realFrameIx, - .stageMask = PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT - } - }; + = transpose(nbl::core::matrix4SIMD()) - { - { - const IQueue::SSubmitInfo::SSemaphoreInfo acquired[] = - { - { - .semaphore = m_currentImageAcquire.semaphore, - .value = m_currentImageAcquire.acquireCount, - .stageMask = PIPELINE_STAGE_FLAGS::NONE - } - }; - - const IQueue::SSubmitInfo infos[] = - { - { - .waitSemaphores = acquired, - .commandBuffers = commandBuffersInfo, - .signalSemaphores = rendered - } - }; - - const nbl::video::ISemaphore::SWaitInfo waitInfos[] = - { { - .semaphore = pass.scene->semaphore.progress.get(), - .value = pass.scene->semaphore.finishedValue - } }; - - m_device->blockForSemaphores(waitInfos); - - updateGUIDescriptorSet(); - - if (queue->submit(infos) != IQueue::RESULT::SUCCESS) - m_realFrameIx--; - } - } + - PERSPECTIVE [PROJECTION CASE]: - m_window->setCaption("[Nabla Engine] UI App Test Demo"); - m_surface->present(m_currentImageAcquire.imageIndex, rendered); - } - } + ImGuizmo - inline bool keepRunning() override - { - if (m_surface->irrecoverable()) - return false; + | (temp / temp2) (0.0) (0.0) (0.0) | + | (0.0) (temp / temp3) (0.0) (0.0) | + | ((right + left) / temp2) ((top + bottom) / temp3) ((-zfar - znear) / temp4) (-1.0f) | + | (0.0) (0.0) ((-temp * zfar) / temp4) (0.0) | - return true; - } + Nabla - inline bool onAppTerminated() override - { - return device_base_t::onAppTerminated(); - } + | w (0.0) (0.0) (0.0) | + | (0.0) -h (0.0) (0.0) | + | (0.0) (0.0) (-zFar/(zFar-zNear)) (-zNear*zFar/(zFar-zNear)) | + | (0.0) (0.0) (-1.0) (0.0) | - inline void update() - { - camera.setMoveSpeed(moveSpeed); - camera.setRotateSpeed(rotateSpeed); + = transpose() - static std::chrono::microseconds previousEventTimestamp{}; + * + * the ViewManipulate final call (inside EditTransform) returns world space column major matrix for an object, + * note it also modifies input view matrix but projection matrix is immutable + */ - m_inputSystem->getDefaultMouse(&mouse); - m_inputSystem->getDefaultKeyboard(&keyboard); - - auto updatePresentationTimestamp = [&]() - { - m_currentImageAcquire = m_surface->acquireNextImage(); - - oracle.reportEndFrameRecord(); - const auto timestamp = oracle.getNextPresentationTimeStamp(); - oracle.reportBeginFrameRecord(); +// TODO: do all computation using `hlsl::matrix` and its `hlsl::float32_tNxM` aliases + static struct + { + core::matrix4SIMD view, projection, model; + } imguizmoM16InOut; - return timestamp; - }; + ImGuizmo::SetID(0u); - const auto nextPresentationTimestamp = updatePresentationTimestamp(); + imguizmoM16InOut.view = core::transpose(matrix4SIMD(camera.getViewMatrix())); + imguizmoM16InOut.projection = core::transpose(camera.getProjectionMatrix()); + imguizmoM16InOut.model = core::transpose(matrix4SIMD(model)); + { + if (flipGizmoY) // note we allow to flip gizmo just to match our coordinates + imguizmoM16InOut.projection[1][1] *= -1.f; // https://johannesugb.github.io/gpu-programming/why-do-opengl-proj-matrices-fail-in-vulkan/ - struct - { - std::vector mouse{}; - std::vector keyboard{}; - } capturedEvents; + transformParams.editTransformDecomposition = true; + sceneResolution = EditTransform(imguizmoM16InOut.view.pointer(), imguizmoM16InOut.projection.pointer(), imguizmoM16InOut.model.pointer(), transformParams); + } - if (move) camera.beginInputProcessing(nextPresentationTimestamp); - { - mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void + model = core::transpose(imguizmoM16InOut.model).extractSub3x4(); + // to Nabla + update camera & model matrices +// TODO: make it more nicely, extract: +// - Position by computing inverse of the view matrix and grabbing its translation +// - Target from 3rd row without W component of view matrix multiplied by some arbitrary distance value (can be the length of position from origin) and adding the position +// But then set the view matrix this way anyway, because up-vector may not be compatible + const auto& view = camera.getViewMatrix(); + const_cast(view) = core::transpose(imguizmoM16InOut.view).extractSub3x4(); // a hack, correct way would be to use inverse matrix and get position + target because now it will bring you back to last position & target when switching from gizmo move to manual move (but from manual to gizmo is ok) + // update concatanated matrix + const auto& projection = camera.getProjectionMatrix(); + camera.setProjectionMatrix(projection); + + // object meta display { - if (move) - camera.mouseProcess(events); // don't capture the events, only let camera handle them with its impl + ImGui::Begin("Object"); + ImGui::Text("type: \"%s\"", objectName.data()); + ImGui::End(); + } + + // view matrices editor + { + ImGui::Begin("Matrices"); - for (const auto& e : events) // here capture + auto addMatrixTable = [&](const char* topText, const char* tableName, const int rows, const int columns, const float* pointer, const bool withSeparator = true) { - if (e.timeStamp < previousEventTimestamp) - continue; + ImGui::Text(topText); + if (ImGui::BeginTable(tableName, columns)) + { + for (int y = 0; y < rows; ++y) + { + ImGui::TableNextRow(); + for (int x = 0; x < columns; ++x) + { + ImGui::TableSetColumnIndex(x); + ImGui::Text("%.3f", *(pointer + (y * columns) + x)); + } + } + ImGui::EndTable(); + } - previousEventTimestamp = e.timeStamp; - capturedEvents.mouse.emplace_back(e); + if (withSeparator) + ImGui::Separator(); + }; - if (e.type == nbl::ui::SMouseEvent::EET_SCROLL) - gcIndex = std::clamp(int16_t(gcIndex) + int16_t(core::sign(e.scrollEvent.verticalScroll)), int64_t(0), int64_t(OT_COUNT - (uint8_t)1u)); - } - }, m_logger.get()); + addMatrixTable("Model Matrix", "ModelMatrixTable", 3, 4, model.pointer()); + addMatrixTable("Camera View Matrix", "ViewMatrixTable", 3, 4, view.pointer()); + addMatrixTable("Camera View Projection Matrix", "ViewProjectionMatrixTable", 4, 4, projection.pointer(), false); - keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void + ImGui::End(); + } + + // Nabla Imgui backend MDI buffer info + // To be 100% accurate and not overly conservative we'd have to explicitly `cull_frees` and defragment each time, + // so unless you do that, don't use this basic info to optimize the size of your IMGUI buffer. { - if (move) - camera.keyboardProcess(events); // don't capture the events, only let camera handle them with its impl + auto* streaminingBuffer = imGUI->getStreamingBuffer(); - for (const auto& e : events) // here capture - { - if (e.timeStamp < previousEventTimestamp) - continue; + const size_t total = streaminingBuffer->get_total_size(); // total memory range size for which allocation can be requested + const size_t freeSize = streaminingBuffer->getAddressAllocator().get_free_size(); // max total free bloock memory size we can still allocate from total memory available + const size_t consumedMemory = total - freeSize; // memory currently consumed by streaming buffer - previousEventTimestamp = e.timeStamp; - capturedEvents.keyboard.emplace_back(e); - } - }, m_logger.get()); - } - if (move) camera.endInputProcessing(nextPresentationTimestamp); + float freePercentage = 100.0f * (float)(freeSize) / (float)total; + float allocatedPercentage = (float)(consumedMemory) / (float)total; - const auto cursorPosition = m_window->getCursorControl()->getPosition(); + ImVec2 barSize = ImVec2(400, 30); + float windowPadding = 10.0f; + float verticalPadding = ImGui::GetStyle().FramePadding.y; - nbl::ext::imgui::UI::SUpdateParameters params = - { - .mousePosition = nbl::hlsl::float32_t2(cursorPosition.x, cursorPosition.y) - nbl::hlsl::float32_t2(m_window->getX(), m_window->getY()), - .displaySize = { m_window->getWidth(), m_window->getHeight() }, - .mouseEvents = { capturedEvents.mouse.data(), capturedEvents.mouse.size() }, - .keyboardEvents = { capturedEvents.keyboard.data(), capturedEvents.keyboard.size() } - }; + ImGui::SetNextWindowSize(ImVec2(barSize.x + 2 * windowPadding, 110 + verticalPadding), ImGuiCond_Always); + ImGui::Begin("Nabla Imgui MDI Buffer Info", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar); - pass.ui.manager->update(params); - } + ImGui::Text("Total Allocated Size: %zu bytes", total); + ImGui::Text("In use: %zu bytes", consumedMemory); + ImGui::Text("Buffer Usage:"); - private: - // Maximum frames which can be simultaneously submitted, used to cycle through our per-frame resources like command buffers - constexpr static inline uint32_t MaxFramesInFlight = 3u; + ImGui::SetCursorPosX(windowPadding); - smart_refctd_ptr m_window; - smart_refctd_ptr> m_surface; - smart_refctd_ptr m_pipeline; - smart_refctd_ptr m_semaphore; - smart_refctd_ptr m_cmdPool; - uint64_t m_realFrameIx = 0; - std::array, MaxFramesInFlight> m_cmdBufs; - ISimpleManagedSurface::SAcquireResult m_currentImageAcquire = {}; + if (freePercentage > 70.0f) + ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImVec4(0.0f, 1.0f, 0.0f, 0.4f)); // Green + else if (freePercentage > 30.0f) + ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImVec4(1.0f, 1.0f, 0.0f, 0.4f)); // Yellow + else + ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImVec4(1.0f, 0.0f, 0.0f, 0.4f)); // Red - smart_refctd_ptr m_assetManager; - core::smart_refctd_ptr m_inputSystem; - InputSystem::ChannelReader mouse; - InputSystem::ChannelReader keyboard; + ImGui::ProgressBar(allocatedPercentage, barSize, ""); - constexpr static inline auto TexturesAmount = 2u; + ImGui::PopStyleColor(); - core::smart_refctd_ptr m_descriptorSetPool; + ImDrawList* drawList = ImGui::GetWindowDrawList(); - struct C_UI - { - nbl::core::smart_refctd_ptr manager; + ImVec2 progressBarPos = ImGui::GetItemRectMin(); + ImVec2 progressBarSize = ImGui::GetItemRectSize(); - struct - { - core::smart_refctd_ptr gui, scene; - } samplers; + const char* text = "%.2f%% free"; + char textBuffer[64]; + snprintf(textBuffer, sizeof(textBuffer), text, freePercentage); - core::smart_refctd_ptr descriptorSet; - }; + ImVec2 textSize = ImGui::CalcTextSize(textBuffer); + ImVec2 textPos = ImVec2 + ( + progressBarPos.x + (progressBarSize.x - textSize.x) * 0.5f, + progressBarPos.y + (progressBarSize.y - textSize.y) * 0.5f + ); - struct E_APP_PASS - { - nbl::core::smart_refctd_ptr scene; - C_UI ui; - } pass; + ImVec4 bgColor = ImGui::GetStyleColorVec4(ImGuiCol_WindowBg); + drawList->AddRectFilled + ( + ImVec2(textPos.x - 5, textPos.y - 2), + ImVec2(textPos.x + textSize.x + 5, textPos.y + textSize.y + 2), + ImGui::GetColorU32(bgColor) + ); - Camera camera = Camera(core::vectorSIMDf(0, 0, 0), core::vectorSIMDf(0, 0, 0), core::matrix4SIMD()); - video::CDumbPresentationOracle oracle; + ImGui::SetCursorScreenPos(textPos); + ImGui::Text("%s", textBuffer); - uint16_t gcIndex = {}; // note: this is dirty however since I assume only single object in scene I can leave it now, when this example is upgraded to support multiple objects this needs to be changed + ImGui::Dummy(ImVec2(0.0f, verticalPadding)); - TransformRequestParams transformParams; - bool isPerspective = true, isLH = true, flipGizmoY = true, move = false; - float fov = 60.f, zNear = 0.1f, zFar = 10000.f, moveSpeed = 1.f, rotateSpeed = 1.f; - float viewWidth = 10.f; - float camYAngle = 165.f / 180.f * 3.14159f; - float camXAngle = 32.f / 180.f * 3.14159f; + ImGui::End(); + } + + ImGui::End(); + } - bool firstFrame = true; + smart_refctd_ptr imGUI; + // descriptor set + smart_refctd_ptr subAllocDS; + SubAllocatedDescriptorSet::value_type renderColorViewDescIndex = SubAllocatedDescriptorSet::invalid_value; + // + Camera camera = Camera(core::vectorSIMDf(0, 0, 0), core::vectorSIMDf(0, 0, 0), core::matrix4SIMD()); + // mutables + core::matrix3x4SIMD model; + std::string_view objectName; + TransformRequestParams transformParams; + uint16_t2 sceneResolution = {1280,720}; + float fov = 60.f, zNear = 0.1f, zFar = 10000.f, moveSpeed = 1.f, rotateSpeed = 1.f; + float viewWidth = 10.f; + float camYAngle = 165.f / 180.f * 3.14159f; + float camXAngle = 32.f / 180.f * 3.14159f; + uint16_t gcIndex = {}; // note: this is dirty however since I assume only single object in scene I can leave it now, when this example is upgraded to support multiple objects this needs to be changed + bool isPerspective = true, isLH = true, flipGizmoY = true, move = false; + bool firstFrame = true; + } interface; }; NBL_MAIN_FUNC(UISampleApp) \ No newline at end of file diff --git a/62_CAD/main.cpp b/62_CAD/main.cpp index 637c88eda..f873914e2 100644 --- a/62_CAD/main.cpp +++ b/62_CAD/main.cpp @@ -1,17 +1,17 @@ - -using namespace nbl::hlsl; -using namespace nbl; -using namespace core; -using namespace system; -using namespace asset; -using namespace ui; -using namespace video; +// TODO: Copyright notice + +#include "nbl/examples/examples.hpp" + +using namespace nbl; +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +// TODO: probably need to be `using namespace nbl::examples` as well, see other examples -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" -#include "SimpleWindowedApplication.hpp" -#include "InputSystem.hpp" -#include "nbl/video/utilities/CSimpleResizeSurface.h" #include "nbl/ext/FullScreenTriangle/FullScreenTriangle.h" #include "nbl/ext/TextRendering/TextRendering.h" diff --git a/64_EmulatedFloatTest/main.cpp b/64_EmulatedFloatTest/main.cpp index a9ff5fde6..fd3e465e7 100644 --- a/64_EmulatedFloatTest/main.cpp +++ b/64_EmulatedFloatTest/main.cpp @@ -1,35 +1,38 @@ // Copyright (C) 2018-2024 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h + + +#include "nbl/examples/examples.hpp" + #include #include #include #include #include -#include "nbl/application_templates/MonoDeviceApplication.hpp" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" - #include "app_resources/common.hlsl" #include "app_resources/benchmark/common.hlsl" #include "nbl/builtin/hlsl/ieee754.hlsl" #include + using namespace nbl::core; using namespace nbl::hlsl; using namespace nbl::system; using namespace nbl::asset; using namespace nbl::video; using namespace nbl::application_templates; +using namespace nbl::examples; constexpr bool DoTests = true; constexpr bool DoBenchmark = true; -class CompatibilityTest final : public MonoDeviceApplication, public MonoAssetManagerAndBuiltinResourceApplication +class CompatibilityTest final : public MonoDeviceApplication, public BuiltinResourcesApplication { using device_base_t = MonoDeviceApplication; - using asset_base_t = MonoAssetManagerAndBuiltinResourceApplication; + using asset_base_t = BuiltinResourcesApplication; public: CompatibilityTest(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) : IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) {} @@ -255,7 +258,7 @@ class CompatibilityTest final : public MonoDeviceApplication, public MonoAssetMa // Load shaders, set up pipeline { - smart_refctd_ptr shader; + smart_refctd_ptr shader; { IAssetLoader::SAssetLoadParams lp = {}; lp.logger = base.m_logger.get(); @@ -271,12 +274,12 @@ class CompatibilityTest final : public MonoDeviceApplication, public MonoAssetMa // It would be super weird if loading a shader from a file produced more than 1 asset assert(assets.size() == 1); - smart_refctd_ptr source = IAsset::castDown(assets[0]); + smart_refctd_ptr source = IAsset::castDown(assets[0]); auto* compilerSet = base.m_assetMgr->getCompilerSet(); nbl::asset::IShaderCompiler::SCompilerOptions options = {}; - options.stage = source->getStage(); + options.stage = ESS_COMPUTE; options.targetSpirvVersion = base.m_device->getPhysicalDevice()->getLimits().spirvVersion; options.spirvOptimizer = nullptr; options.debugInfoFlags |= IShaderCompiler::E_DEBUG_INFO_FLAGS::EDIF_SOURCE_BIT; @@ -286,9 +289,7 @@ class CompatibilityTest final : public MonoDeviceApplication, public MonoAssetMa auto spirv = compilerSet->compileToSPIRV(source.get(), options); - ILogicalDevice::SShaderCreationParameters params{}; - params.cpushader = spirv.get(); - shader = base.m_device->createShader(params); + shader = base.m_device->compileShader({spirv.get()}); } if (!shader) @@ -923,7 +924,7 @@ class CompatibilityTest final : public MonoDeviceApplication, public MonoAssetMa // Load shaders, set up pipeline { - smart_refctd_ptr shader; + smart_refctd_ptr shader; { IAssetLoader::SAssetLoadParams lp = {}; lp.logger = base.m_logger.get(); @@ -939,12 +940,12 @@ class CompatibilityTest final : public MonoDeviceApplication, public MonoAssetMa // It would be super weird if loading a shader from a file produced more than 1 asset assert(assets.size() == 1); - smart_refctd_ptr source = IAsset::castDown(assets[0]); + smart_refctd_ptr source = IAsset::castDown(assets[0]); auto* compilerSet = base.m_assetMgr->getCompilerSet(); IShaderCompiler::SCompilerOptions options = {}; - options.stage = source->getStage(); + options.stage = ESS_COMPUTE; options.targetSpirvVersion = base.m_device->getPhysicalDevice()->getLimits().spirvVersion; options.spirvOptimizer = nullptr; options.debugInfoFlags |= IShaderCompiler::E_DEBUG_INFO_FLAGS::EDIF_SOURCE_BIT; @@ -954,9 +955,7 @@ class CompatibilityTest final : public MonoDeviceApplication, public MonoAssetMa auto spirv = compilerSet->compileToSPIRV(source.get(), options); - ILogicalDevice::SShaderCreationParameters params{}; - params.cpushader = spirv.get(); - shader = base.m_device->createShader(params); + shader = base.m_device->compileShader({spirv.get()}); } if (!shader) diff --git a/67_RayQueryGeometry/app_resources/common.hlsl b/67_RayQueryGeometry/app_resources/common.hlsl index ecc811e3f..e39e7192b 100644 --- a/67_RayQueryGeometry/app_resources/common.hlsl +++ b/67_RayQueryGeometry/app_resources/common.hlsl @@ -14,6 +14,7 @@ struct SGeomInfo uint32_t vertexStride : 29; uint32_t indexType : 2; // 16 bit, 32 bit or none uint32_t smoothNormals : 1; // flat for cube, rectangle, disk + uint32_t padding; }; struct SPushConstants diff --git a/67_RayQueryGeometry/app_resources/render.comp.hlsl b/67_RayQueryGeometry/app_resources/render.comp.hlsl index e3d78f385..657d0bbf0 100644 --- a/67_RayQueryGeometry/app_resources/render.comp.hlsl +++ b/67_RayQueryGeometry/app_resources/render.comp.hlsl @@ -6,6 +6,7 @@ #include "nbl/builtin/hlsl/spirv_intrinsics/raytracing.hlsl" #include "nbl/builtin/hlsl/bda/__ptr.hlsl" + using namespace nbl::hlsl; [[vk::push_constant]] SPushConstants pc; @@ -13,6 +14,7 @@ using namespace nbl::hlsl; [[vk::binding(0, 0)]] RaytracingAccelerationStructure topLevelAS; [[vk::binding(1, 0)]] RWTexture2D outImage; +[[vk::constant_id(0)]] const float shader_variant = 1.0; float3 unpackNormals3x10(uint32_t v) { @@ -95,6 +97,7 @@ float3 calculateSmoothNormals(int instID, int primID, SGeomInfo geom, float2 bar } [numthreads(WorkgroupSize, WorkgroupSize, 1)] +[shader("compute")] void main(uint32_t3 threadID : SV_DispatchThreadID) { uint2 coords = threadID.xy; @@ -125,27 +128,11 @@ void main(uint32_t3 threadID : SV_DispatchThreadID) const int primID = spirv::rayQueryGetIntersectionPrimitiveIndexKHR(query, true); // TODO: candidate for `bda::__ptr` - const SGeomInfo geom = vk::RawBufferLoad(pc.geometryInfoBuffer + instID * sizeof(SGeomInfo)); - + const SGeomInfo geom = vk::RawBufferLoad(pc.geometryInfoBuffer + instID * sizeof(SGeomInfo),8); + float3 normals; - if (jit::device_capabilities::rayTracingPositionFetch) - { - if (geom.smoothNormals) - { - float2 barycentrics = spirv::rayQueryGetIntersectionBarycentricsKHR(query, true); - normals = calculateSmoothNormals(instID, primID, geom, barycentrics); - } - else - { - float3 pos[3] = spirv::rayQueryGetIntersectionTriangleVertexPositionsKHR(query, true); - normals = cross(pos[1] - pos[0], pos[2] - pos[0]); - } - } - else - { - float2 barycentrics = spirv::rayQueryGetIntersectionBarycentricsKHR(query, true); - normals = calculateSmoothNormals(instID, primID, geom, barycentrics); - } + float2 barycentrics = spirv::rayQueryGetIntersectionBarycentricsKHR(query, true); + normals = calculateSmoothNormals(instID, primID, geom, barycentrics); normals = normalize(normals) * 0.5 + 0.5; color = float4(normals, 1.0); diff --git a/67_RayQueryGeometry/include/common.hpp b/67_RayQueryGeometry/include/common.hpp index 0595c7203..bcf896f55 100644 --- a/67_RayQueryGeometry/include/common.hpp +++ b/67_RayQueryGeometry/include/common.hpp @@ -1,95 +1,18 @@ -#ifndef __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ -#define __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ +#ifndef _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ +#define _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ -#include -#include "nbl/asset/utils/CGeometryCreator.h" -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" - -#include "SimpleWindowedApplication.hpp" - -#include "InputSystem.hpp" -#include "CEventCallback.hpp" - -#include "CCamera.hpp" - -#include -#include +#include "nbl/examples/examples.hpp" using namespace nbl; -using namespace core; -using namespace hlsl; -using namespace system; -using namespace asset; -using namespace ui; -using namespace video; -using namespace scene; +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::application_templates; +using namespace nbl::examples; #include "app_resources/common.hlsl" -namespace nbl::scene -{ -enum ObjectType : uint8_t -{ - OT_CUBE, - OT_SPHERE, - OT_CYLINDER, - OT_RECTANGLE, - OT_DISK, - OT_ARROW, - OT_CONE, - OT_ICOSPHERE, - - OT_COUNT, - OT_UNKNOWN = std::numeric_limits::max() -}; - -struct ObjectMeta -{ - ObjectType type = OT_UNKNOWN; - std::string_view name = "Unknown"; -}; - -struct ObjectDrawHookCpu -{ - nbl::core::matrix3x4SIMD model; - nbl::asset::SBasicViewParameters viewParameters; - ObjectMeta meta; -}; - -enum GeometryShader -{ - GP_BASIC = 0, - GP_CONE, - GP_ICO, - - GP_COUNT -}; - -struct ReferenceObjectCpu -{ - ObjectMeta meta; - GeometryShader shadersType; - nbl::asset::CGeometryCreator::return_type data; -}; - -struct ReferenceObjectGpu -{ - struct Bindings - { - nbl::asset::SBufferBinding vertex, index; - }; - - ObjectMeta meta; - Bindings bindings; - uint32_t vertexStride; - nbl::asset::E_INDEX_TYPE indexType = nbl::asset::E_INDEX_TYPE::EIT_UNKNOWN; - uint32_t indexCount = {}; - - const bool useIndex() const - { - return bindings.index.buffer && (indexType != E_INDEX_TYPE::EIT_UNKNOWN); - } -}; -} - -#endif // __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ \ No newline at end of file +#endif // _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ \ No newline at end of file diff --git a/67_RayQueryGeometry/main.cpp b/67_RayQueryGeometry/main.cpp index dab137cbd..495f3a3e2 100644 --- a/67_RayQueryGeometry/main.cpp +++ b/67_RayQueryGeometry/main.cpp @@ -1,13 +1,12 @@ // Copyright (C) 2018-2024 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h - #include "common.hpp" -class RayQueryGeometryApp final : public examples::SimpleWindowedApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +class RayQueryGeometryApp final : public SimpleWindowedApplication, public MonoAssetManagerAndBuiltinResourceApplication { - using device_base_t = examples::SimpleWindowedApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using device_base_t = SimpleWindowedApplication; + using asset_base_t = MonoAssetManagerAndBuiltinResourceApplication; using clock_t = std::chrono::steady_clock; constexpr static inline uint32_t WIN_W = 1280, WIN_H = 720; @@ -122,15 +121,11 @@ class RayQueryGeometryApp final : public examples::SimpleWindowedApplication, pu return logFail("Could not create HDR Image"); auto assetManager = make_smart_refctd_ptr(smart_refctd_ptr(system)); - auto* geometryCreator = assetManager->getGeometryCreator(); auto cQueue = getComputeQueue(); - // create geometry objects - if (!createGeometries(gQueue, geometryCreator)) - return logFail("Could not create geometries from geometry creator"); - // create blas/tlas + renderDs = //#define TRY_BUILD_FOR_NGFX // Validation errors on the fake Acquire-Presents, TODO fix #ifdef TRY_BUILD_FOR_NGFX // Nsight is special and can't do debugger delay so you can debug your CPU stuff during a capture @@ -142,11 +137,12 @@ class RayQueryGeometryApp final : public examples::SimpleWindowedApplication, pu std::this_thread::yield(); } // Nsight is special and can't capture anything not on the queue that performs the swapchain acquire/release - if (!createAccelerationStructures(gQueue)) + createAccelerationStructureDS(gQueue); #else - if (!createAccelerationStructures(cQueue)) + createAccelerationStructureDS(cQueue); #endif - return logFail("Could not create acceleration structures"); + if (!renderDs) + return logFail("Could not create acceleration structures and descriptor set"); // create pipelines { @@ -164,67 +160,38 @@ class RayQueryGeometryApp final : public examples::SimpleWindowedApplication, pu const auto assets = bundle.getContents(); assert(assets.size() == 1); - smart_refctd_ptr shaderSrc = IAsset::castDown(assets[0]); - shaderSrc->setShaderStage(IShader::E_SHADER_STAGE::ESS_COMPUTE); - auto shader = m_device->createShader(shaderSrc.get()); + smart_refctd_ptr shaderSrc = IAsset::castDown(assets[0]); + auto shader = m_device->compileShader({shaderSrc.get()}); if (!shader) return logFail("Failed to create shader!"); - // descriptors - IGPUDescriptorSetLayout::SBinding bindings[] = { - { - .binding = 0, - .type = asset::IDescriptor::E_TYPE::ET_ACCELERATION_STRUCTURE, - .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, - .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_COMPUTE, - .count = 1, - }, - { - .binding = 1, - .type = asset::IDescriptor::E_TYPE::ET_STORAGE_IMAGE, - .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, - .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_COMPUTE, - .count = 1, - } - }; - auto descriptorSetLayout = m_device->createDescriptorSetLayout(bindings); - - const std::array dsLayoutPtrs = { descriptorSetLayout.get() }; - renderPool = m_device->createDescriptorPoolForDSLayouts(IDescriptorPool::ECF_UPDATE_AFTER_BIND_BIT, std::span(dsLayoutPtrs.begin(), dsLayoutPtrs.end())); - if (!renderPool) - return logFail("Could not create descriptor pool"); - renderDs = renderPool->createDescriptorSet(descriptorSetLayout); - if (!renderDs) - return logFail("Could not create descriptor set"); - SPushConstantRange pcRange = { .stageFlags = IShader::E_SHADER_STAGE::ESS_COMPUTE, .offset = 0u, .size = sizeof(SPushConstants)}; - auto pipelineLayout = m_device->createPipelineLayout({ &pcRange, 1 }, smart_refctd_ptr(descriptorSetLayout), nullptr, nullptr, nullptr); + auto pipelineLayout = m_device->createPipelineLayout({ &pcRange, 1 }, smart_refctd_ptr(renderDs->getLayout()), nullptr, nullptr, nullptr); IGPUComputePipeline::SCreationParams params = {}; params.layout = pipelineLayout.get(); params.shader.shader = shader.get(); + params.shader.entryPoint = "main"; if (!m_device->createComputePipelines(nullptr, { ¶ms, 1 }, &renderPipeline)) return logFail("Failed to create compute pipeline"); } // write descriptors - IGPUDescriptorSet::SDescriptorInfo infos[2]; - infos[0].desc = gpuTlas; - infos[1].desc = m_device->createImageView({ - .flags = IGPUImageView::ECF_NONE, - .subUsages = IGPUImage::E_USAGE_FLAGS::EUF_STORAGE_BIT, - .image = outHDRImage, - .viewType = IGPUImageView::E_TYPE::ET_2D, - .format = asset::EF_R16G16B16A16_SFLOAT - }); - if (!infos[1].desc) - return logFail("Failed to create image view"); - infos[1].info.image.imageLayout = IImage::LAYOUT::GENERAL; - IGPUDescriptorSet::SWriteDescriptorSet writes[3] = { - {.dstSet = renderDs.get(), .binding = 0, .arrayElement = 0, .count = 1, .info = &infos[0]}, - {.dstSet = renderDs.get(), .binding = 1, .arrayElement = 0, .count = 1, .info = &infos[1]} - }; - m_device->updateDescriptorSets(std::span(writes, 2), {}); + { + IGPUDescriptorSet::SDescriptorInfo info = {}; + info.desc = m_device->createImageView({ + .flags = IGPUImageView::ECF_NONE, + .subUsages = IGPUImage::E_USAGE_FLAGS::EUF_STORAGE_BIT, + .image = outHDRImage, + .viewType = IGPUImageView::E_TYPE::ET_2D, + .format = asset::EF_R16G16B16A16_SFLOAT + }); + if (!info.desc) + return logFail("Failed to create image view"); + info.info.image.imageLayout = IImage::LAYOUT::GENERAL; + const IGPUDescriptorSet::SWriteDescriptorSet write = {.dstSet=renderDs.get(), .binding=1, .arrayElement=0, .count=1, .info=&info}; + m_device->updateDescriptorSets({&write,1}, {}); + } // camera { @@ -281,7 +248,6 @@ class RayQueryGeometryApp final : public examples::SimpleWindowedApplication, pu static bool first = true; if (first) { - m_api->startCapture(); first = false; } @@ -291,11 +257,9 @@ class RayQueryGeometryApp final : public examples::SimpleWindowedApplication, pu cmdbuf->beginDebugMarker("RayQueryGeometryApp Frame"); { camera.beginInputProcessing(nextPresentationTimestamp); - mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void { camera.mouseProcess(events); mouseProcess(events); }, m_logger.get()); + mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void { camera.mouseProcess(events); }, m_logger.get()); keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void { camera.keyboardProcess(events); }, m_logger.get()); camera.endInputProcessing(nextPresentationTimestamp); - - const auto type = static_cast(gcIndex); } const auto viewMatrix = camera.getViewMatrix(); @@ -520,82 +484,12 @@ class RayQueryGeometryApp final : public examples::SimpleWindowedApplication, pu return (dim + size - 1) / size; } - smart_refctd_ptr createBuffer(IGPUBuffer::SCreationParams& params) + smart_refctd_ptr createAccelerationStructureDS(video::CThreadSafeQueueAdapter* queue) { - smart_refctd_ptr buffer; - buffer = m_device->createBuffer(std::move(params)); - auto bufReqs = buffer->getMemoryReqs(); - bufReqs.memoryTypeBits &= m_physicalDevice->getDeviceLocalMemoryTypeBits(); - m_device->allocate(bufReqs, buffer.get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); - - return buffer; - } - - smart_refctd_ptr getSingleUseCommandBufferAndBegin(smart_refctd_ptr pool) - { - smart_refctd_ptr cmdbuf; - if (!pool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY, 1u, &cmdbuf)) - return nullptr; - - cmdbuf->reset(IGPUCommandBuffer::RESET_FLAGS::RELEASE_RESOURCES_BIT); - cmdbuf->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); - - return cmdbuf; - } - - void cmdbufSubmitAndWait(smart_refctd_ptr cmdbuf, CThreadSafeQueueAdapter* queue, uint64_t startValue) - { - cmdbuf->end(); - - uint64_t finishedValue = startValue + 1; - - // submit builds - { - auto completed = m_device->createSemaphore(startValue); - - std::array signals; - { - auto& signal = signals.front(); - signal.value = finishedValue; - signal.stageMask = bitflag(PIPELINE_STAGE_FLAGS::ALL_TRANSFER_BITS); - signal.semaphore = completed.get(); - } - - const IQueue::SSubmitInfo::SCommandBufferInfo commandBuffers[1] = { { - .cmdbuf = cmdbuf.get() - } }; - - const IQueue::SSubmitInfo infos[] = - { - { - .waitSemaphores = {}, - .commandBuffers = commandBuffers, - .signalSemaphores = signals - } - }; - - if (queue->submit(infos) != IQueue::RESULT::SUCCESS) - { - m_logger->log("Failed to submit geometry transfer upload operations!", ILogger::ELL_ERROR); - return; - } - - const ISemaphore::SWaitInfo info[] = - { { - .semaphore = completed.get(), - .value = finishedValue - } }; - - m_device->blockForSemaphores(info); - } - } - - bool createGeometries(video::CThreadSafeQueueAdapter* queue, const IGeometryCreator* gc) - { - auto pool = m_device->createCommandPool(queue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); - if (!pool) - return logFail("Couldn't create Command Pool for geometry creation!"); - + // get geometries in ICPUBuffers +#if 1 + return nullptr; +#else std::array objectsCpu; objectsCpu[OT_CUBE] = ReferenceObjectCpu{ .meta = {.type = OT_CUBE, .name = "Cube Mesh" }, .shadersType = GP_BASIC, .data = gc->createCubeMesh(nbl::core::vector3df(1.f, 1.f, 1.f)) }; objectsCpu[OT_SPHERE] = ReferenceObjectCpu{ .meta = {.type = OT_SPHERE, .name = "Sphere Mesh" }, .shadersType = GP_BASIC, .data = gc->createSphereMesh(2, 16, 16) }; @@ -606,163 +500,213 @@ class RayQueryGeometryApp final : public examples::SimpleWindowedApplication, pu objectsCpu[OT_CONE] = ReferenceObjectCpu{ .meta = {.type = OT_CONE, .name = "Cone Mesh" }, .shadersType = GP_CONE, .data = gc->createConeMesh(2, 3, 10) }; objectsCpu[OT_ICOSPHERE] = ReferenceObjectCpu{ .meta = {.type = OT_ICOSPHERE, .name = "Icosphere Mesh" }, .shadersType = GP_ICO, .data = gc->createIcoSphere(1, 3, true) }; - struct ScratchVIBindings - { - nbl::asset::SBufferBinding vertex, index; - }; - std::array scratchBuffers; - //std::array geomInfos; auto geomInfoBuffer = ICPUBuffer::create({ OT_COUNT * sizeof(SGeomInfo) }); - + SGeomInfo* geomInfos = reinterpret_cast(geomInfoBuffer->getPointer()); const uint32_t byteOffsets[OT_COUNT] = { 18, 24, 24, 20, 20, 24, 16, 12 }; // based on normals data position const uint32_t smoothNormals[OT_COUNT] = { 0, 1, 1, 0, 0, 1, 1, 1 }; - for (uint32_t i = 0; i < objectsCpu.size(); i++) + // get ICPUBuffers into ICPUBottomLevelAccelerationStructures + std::array, OT_COUNT> cpuBlas; + for (uint32_t i = 0; i < cpuBlas.size(); i++) { + auto triangles = make_refctd_dynamic_array>>(1u); + auto primitiveCounts = make_refctd_dynamic_array>(1u); + + auto& tri = triangles->front(); + auto& primCount = primitiveCounts->front(); const auto& geom = objectsCpu[i]; - auto& obj = objectsGpu[i]; - auto& scratchObj = scratchBuffers[i]; - obj.meta.name = geom.meta.name; - obj.meta.type = geom.meta.type; + const bool useIndex = geom.data.indexType != EIT_UNKNOWN; + const uint32_t vertexStride = geom.data.inputParams.bindings[0].stride; + const uint32_t numVertices = (geom.data.bindings[0].buffer->getSize()-geom.data.bindings[0].offset) / vertexStride; - obj.indexCount = geom.data.indexCount; - obj.indexType = geom.data.indexType; - obj.vertexStride = geom.data.inputParams.bindings[0].stride; + if (useIndex) + primCount = geom.data.indexCount / 3; + else + primCount = numVertices / 3; - geomInfos[i].indexType = obj.indexType; - geomInfos[i].vertexStride = obj.vertexStride; + geomInfos[i].indexType = geom.data.indexType; + geomInfos[i].vertexStride = vertexStride; geomInfos[i].smoothNormals = smoothNormals[i]; - auto vBuffer = smart_refctd_ptr(geom.data.bindings[0].buffer); // no offset - auto vUsage = bitflag(IGPUBuffer::EUF_STORAGE_BUFFER_BIT) | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF | - IGPUBuffer::EUF_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; - obj.bindings.vertex.offset = 0u; - - auto iBuffer = smart_refctd_ptr(geom.data.indexBuffer.buffer); // no offset - auto iUsage = bitflag(IGPUBuffer::EUF_STORAGE_BUFFER_BIT) | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF | - IGPUBuffer::EUF_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; - obj.bindings.index.offset = 0u; + geom.data.bindings[0].buffer->setContentHash(geom.data.bindings[0].buffer->computeContentHash()); + tri.vertexData[0] = geom.data.bindings[0]; + if (useIndex) + { + geom.data.indexBuffer.buffer->setContentHash(geom.data.indexBuffer.buffer->computeContentHash()); + tri.indexData = geom.data.indexBuffer; + } + tri.maxVertex = numVertices - 1; + tri.vertexStride = vertexStride; + tri.vertexFormat = static_cast(geom.data.inputParams.attributes[0].format); + tri.indexType = geom.data.indexType; + tri.geometryFlags = IGPUBottomLevelAccelerationStructure::GEOMETRY_FLAGS::OPAQUE_BIT; + + auto& blas = cpuBlas[i]; + blas = make_smart_refctd_ptr(); + blas->setGeometries(std::move(triangles), std::move(primitiveCounts)); + + auto blasFlags = bitflag(IGPUBottomLevelAccelerationStructure::BUILD_FLAGS::PREFER_FAST_TRACE_BIT) | IGPUBottomLevelAccelerationStructure::BUILD_FLAGS::ALLOW_COMPACTION_BIT; + if (m_physicalDevice->getProperties().limits.rayTracingPositionFetch) + blasFlags |= IGPUBottomLevelAccelerationStructure::BUILD_FLAGS::ALLOW_DATA_ACCESS; + + blas->setBuildFlags(blasFlags); + blas->setContentHash(blas->computeContentHash()); + } - vBuffer->addUsageFlags(vUsage); - vBuffer->setContentHash(vBuffer->computeContentHash()); - scratchObj.vertex = { .offset = 0, .buffer = vBuffer }; + // get ICPUBottomLevelAccelerationStructure into ICPUTopLevelAccelerationStructure + auto geomInstances = make_refctd_dynamic_array>(OT_COUNT); + { + uint32_t i = 0; + for (auto instance = geomInstances->begin(); instance != geomInstances->end(); instance++, i++) + { + ICPUTopLevelAccelerationStructure::StaticInstance inst; + inst.base.blas = cpuBlas[i]; + inst.base.flags = static_cast(IGPUTopLevelAccelerationStructure::INSTANCE_FLAGS::TRIANGLE_FACING_CULL_DISABLE_BIT); + inst.base.instanceCustomIndex = i; + inst.base.instanceShaderBindingTableRecordOffset = 0; + inst.base.mask = 0xFF; - if (geom.data.indexType != EIT_UNKNOWN) - if (iBuffer) - { - iBuffer->addUsageFlags(iUsage); - iBuffer->setContentHash(iBuffer->computeContentHash()); - } - scratchObj.index = { .offset = 0, .buffer = iBuffer }; + core::matrix3x4SIMD transform; + transform.setTranslation(nbl::core::vectorSIMDf(5.f * i, 0, 0, 0)); + inst.transform = transform; + + instance->instance = inst; + } } - auto cmdbuf = getSingleUseCommandBufferAndBegin(pool); - cmdbuf->beginDebugMarker("Build geometry vertex and index buffers"); + auto cpuTlas = make_smart_refctd_ptr(); + cpuTlas->setInstances(std::move(geomInstances)); + cpuTlas->setBuildFlags(IGPUTopLevelAccelerationStructure::BUILD_FLAGS::PREFER_FAST_TRACE_BIT); + + // descriptor set and layout + ICPUDescriptorSetLayout::SBinding bindings[] = { + { + .binding = 0, + .type = asset::IDescriptor::E_TYPE::ET_ACCELERATION_STRUCTURE, + .createFlags = IDescriptorSetLayoutBase::SBindingBase::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_COMPUTE, + .count = 1, + }, + { + .binding = 1, + .type = asset::IDescriptor::E_TYPE::ET_STORAGE_IMAGE, + .createFlags = IDescriptorSetLayoutBase::SBindingBase::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_COMPUTE, + .count = 1, + } + }; + auto descriptorSet = core::make_smart_refctd_ptr(core::make_smart_refctd_ptr(bindings)); + descriptorSet->getDescriptorInfos(IDescriptorSetLayoutBase::CBindingRedirect::binding_number_t{0},IDescriptor::E_TYPE::ET_ACCELERATION_STRUCTURE).front().desc = cpuTlas; +//#define TEST_REBAR_FALLBACK + // convert with asset converter smart_refctd_ptr converter = CAssetConverter::create({ .device = m_device.get(), .optimizer = {} }); - CAssetConverter::SInputs inputs = {}; + struct MyInputs : CAssetConverter::SInputs + { +#ifndef TEST_REBAR_FALLBACK + inline uint32_t constrainMemoryTypeBits(const size_t groupCopyID, const IAsset* canonicalAsset, const blake3_hash_t& contentHash, const IDeviceMemoryBacked* memoryBacked) const override + { + assert(memoryBacked); + return memoryBacked->getObjectType()!=IDeviceMemoryBacked::EOT_BUFFER ? (~0u):rebarMemoryTypes; + } +#endif + uint32_t rebarMemoryTypes; + } inputs = {}; inputs.logger = m_logger.get(); + inputs.rebarMemoryTypes = m_physicalDevice->getDirectVRAMAccessMemoryTypeBits(); +#ifndef TEST_REBAR_FALLBACK + struct MyAllocator final : public IDeviceMemoryAllocator + { + ILogicalDevice* getDeviceForAllocations() const override {return device;} + + SAllocation allocate(const SAllocateInfo& info) override + { + auto retval = device->allocate(info); + // map what is mappable by default so ReBAR checks succeed + if (retval.isValid() && retval.memory->isMappable()) + retval.memory->map({.offset=0,.length=info.size}); + return retval; + } - std::array tmpBuffers; + ILogicalDevice* device; + } myalloc; + myalloc.device = m_device.get(); + inputs.allocator = &myalloc; +#endif + + CAssetConverter::patch_t tlasPatch = {}; + tlasPatch.compactAfterBuild = true; + std::array,OT_COUNT> tmpBLASPatches = {}; + std::array tmpBuffers; + std::array, OT_COUNT * 2u> tmpBufferPatches; { + tmpBLASPatches.front().compactAfterBuild = true; + std::fill(tmpBLASPatches.begin(),tmpBLASPatches.end(),tmpBLASPatches.front()); + // for (uint32_t i = 0; i < objectsCpu.size(); i++) { - tmpBuffers[2 * i + 0] = scratchBuffers[i].vertex.buffer.get(); - tmpBuffers[2 * i + 1] = scratchBuffers[i].index.buffer.get(); + tmpBuffers[2 * i + 0] = cpuBlas[i]->getTriangleGeometries().front().vertexData[0].buffer.get(); + tmpBuffers[2 * i + 1] = cpuBlas[i]->getTriangleGeometries().front().indexData.buffer.get(); } - + // make sure all buffers are BDA-readable + for (auto& patch : tmpBufferPatches) + patch.usage |= asset::IBuffer::E_USAGE_FLAGS::EUF_SHADER_DEVICE_ADDRESS_BIT; + + std::get>(inputs.assets) = {&descriptorSet.get(),1}; + std::get>(inputs.assets) = {&cpuTlas.get(),1}; + std::get>(inputs.patches) = {&tlasPatch,1}; + std::get>(inputs.assets) = {&cpuBlas.data()->get(),cpuBlas.size()}; + std::get>(inputs.patches) = tmpBLASPatches; std::get>(inputs.assets) = tmpBuffers; + std::get>(inputs.patches) = tmpBufferPatches; } auto reservation = converter->reserve(inputs); - { - auto prepass = [&](const auto & references) -> bool - { - auto objects = reservation.getGPUObjects(); - uint32_t counter = {}; - for (auto& object : objects) - { - auto gpu = object.value; - auto* reference = references[counter]; - - if (reference) - { - if (!gpu) - { - m_logger->log("Failed to convert a CPU object to GPU!", ILogger::ELL_ERROR); - return false; - } - } - counter++; - } - return true; - }; - prepass.template operator() < ICPUBuffer > (tmpBuffers); + constexpr auto XferBufferCount = 2; + std::array,XferBufferCount> xferBufs = {}; + std::array xferBufInfos = {}; + { + auto pool = m_device->createCommandPool(getTransferUpQueue()->getFamilyIndex(),IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT | IGPUCommandPool::CREATE_FLAGS::TRANSIENT_BIT); + pool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY,xferBufs); + xferBufs.front()->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + for (auto i=0; icreateSemaphore(0u); - - std::array cmdbufs = {}; - cmdbufs.front().cmdbuf = cmdbuf.get(); - + auto xferSema = m_device->createSemaphore(0u); + xferSema->setObjectDebugName("Transfer Semaphore"); SIntendedSubmitInfo transfer = {}; - transfer.queue = queue; - transfer.scratchCommandBuffers = cmdbufs; + transfer.queue = getTransferUpQueue(); + transfer.scratchCommandBuffers = xferBufInfos; transfer.scratchSemaphore = { - .semaphore = semaphore.get(), + .semaphore = xferSema.get(), .value = 0u, .stageMask = PIPELINE_STAGE_FLAGS::ALL_TRANSFER_BITS }; - // convert - { - CAssetConverter::SConvertParams params = {}; - params.utilities = m_utils.get(); - params.transfer = &transfer; - - auto future = reservation.convert(params); - if (future.copy() != IQueue::RESULT::SUCCESS) - { - m_logger->log("Failed to await submission feature!", ILogger::ELL_ERROR); - return false; - } - - // assign gpu objects to output - auto&& buffers = reservation.getGPUObjects(); - for (uint32_t i = 0; i < objectsCpu.size(); i++) - { - auto& obj = objectsGpu[i]; - obj.bindings.vertex = { .offset = 0, .buffer = buffers[2 * i + 0].value }; - obj.bindings.index = { .offset = 0, .buffer = buffers[2 * i + 1].value }; - - geomInfos[i].vertexBufferAddress = obj.bindings.vertex.buffer->getDeviceAddress() + byteOffsets[i]; - geomInfos[i].indexBufferAddress = obj.useIndex() ? obj.bindings.index.buffer->getDeviceAddress() : geomInfos[i].vertexBufferAddress; - } - } - + + constexpr auto CompBufferCount = 2; + std::array,CompBufferCount> compBufs = {}; + std::array compBufInfos = {}; { - IGPUBuffer::SCreationParams params; - params.usage = IGPUBuffer::EUF_STORAGE_BUFFER_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; - params.size = OT_COUNT * sizeof(SGeomInfo); - m_utils->createFilledDeviceLocalBufferOnDedMem(SIntendedSubmitInfo{.queue = queue}, std::move(params), geomInfos).move_into(geometryInfoBuffer); + auto pool = m_device->createCommandPool(getComputeQueue()->getFamilyIndex(),IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT|IGPUCommandPool::CREATE_FLAGS::TRANSIENT_BIT); + pool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY,compBufs); + compBufs.front()->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + for (auto i=0; i queryPool = m_device->createQueryPool(std::move(qParams)); - - auto pool = m_device->createCommandPool(queue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT | IGPUCommandPool::CREATE_FLAGS::TRANSIENT_BIT); - if (!pool) - return logFail("Couldn't create Command Pool for blas/tlas creation!"); - - m_api->startCapture(); + auto compSema = m_device->createSemaphore(0u); + compSema->setObjectDebugName("Compute Semaphore"); + SIntendedSubmitInfo compute = {}; + compute.queue = getComputeQueue(); + compute.scratchCommandBuffers = compBufInfos; + compute.scratchSemaphore = { + .semaphore = compSema.get(), + .value = 0u, + .stageMask = PIPELINE_STAGE_FLAGS::ACCELERATION_STRUCTURE_BUILD_BIT|PIPELINE_STAGE_FLAGS::ACCELERATION_STRUCTURE_COPY_BIT + }; + // convert #ifdef TRY_BUILD_FOR_NGFX // NSight is "debugger-challenged" it can't capture anything not happenning "during a frame", so we need to trick it m_currentImageAcquire = m_surface->acquireNextImage(); { @@ -775,273 +719,166 @@ class RayQueryGeometryApp final : public examples::SimpleWindowedApplication, pu } m_currentImageAcquire = m_surface->acquireNextImage(); #endif - size_t totalScratchSize = 0; - const auto scratchOffsetAlignment = m_device->getPhysicalDevice()->getLimits().minAccelerationStructureScratchOffsetAlignment; - - // build bottom level ASes + m_api->startCapture(); + auto gQueue = getGraphicsQueue(); { - IGPUBottomLevelAccelerationStructure::DeviceBuildInfo blasBuildInfos[OT_COUNT]; - uint32_t primitiveCounts[OT_COUNT]; - IGPUBottomLevelAccelerationStructure::Triangles triangles[OT_COUNT]; - uint32_t scratchSizes[OT_COUNT]; - - for (uint32_t i = 0; i < objectsGpu.size(); i++) + smart_refctd_ptr scratchAlloc; { - const auto& obj = objectsGpu[i]; - - const uint32_t vertexStride = obj.vertexStride; - const uint32_t numVertices = obj.bindings.vertex.buffer->getSize() / vertexStride; - if (obj.useIndex()) - primitiveCounts[i] = obj.indexCount / 3; - else - primitiveCounts[i] = numVertices / 3; - - triangles[i].vertexData[0] = obj.bindings.vertex; - triangles[i].indexData = obj.useIndex() ? obj.bindings.index : obj.bindings.vertex; - triangles[i].maxVertex = numVertices - 1; - triangles[i].vertexStride = vertexStride; - triangles[i].vertexFormat = EF_R32G32B32_SFLOAT; - triangles[i].indexType = obj.indexType; - triangles[i].geometryFlags = IGPUBottomLevelAccelerationStructure::GEOMETRY_FLAGS::OPAQUE_BIT; - - auto blasFlags = bitflag(IGPUBottomLevelAccelerationStructure::BUILD_FLAGS::PREFER_FAST_TRACE_BIT) | IGPUBottomLevelAccelerationStructure::BUILD_FLAGS::ALLOW_COMPACTION_BIT; - if (m_physicalDevice->getProperties().limits.rayTracingPositionFetch) - blasFlags |= IGPUBottomLevelAccelerationStructure::BUILD_FLAGS::ALLOW_DATA_ACCESS_KHR; - - blasBuildInfos[i].buildFlags = blasFlags; - blasBuildInfos[i].geometryCount = 1; // only 1 geometry object per blas - blasBuildInfos[i].srcAS = nullptr; - blasBuildInfos[i].dstAS = nullptr; - blasBuildInfos[i].triangles = &triangles[i]; - blasBuildInfos[i].scratch = {}; - - ILogicalDevice::AccelerationStructureBuildSizes buildSizes; - { - const uint32_t maxPrimCount[1] = { primitiveCounts[i] }; - buildSizes = m_device->getAccelerationStructureBuildSizes(blasFlags, false, std::span{&triangles[i], 1}, maxPrimCount); - if (!buildSizes) - return logFail("Failed to get BLAS build sizes"); - } - - scratchSizes[i] = buildSizes.buildScratchSize; - totalScratchSize = core::alignUp(totalScratchSize, scratchOffsetAlignment); - totalScratchSize += buildSizes.buildScratchSize; - - { - IGPUBuffer::SCreationParams params; - params.usage = bitflag(IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT) | IGPUBuffer::EUF_ACCELERATION_STRUCTURE_STORAGE_BIT; - params.size = buildSizes.accelerationStructureSize; - smart_refctd_ptr asBuffer = createBuffer(params); - - IGPUBottomLevelAccelerationStructure::SCreationParams blasParams; - blasParams.bufferRange.buffer = asBuffer; - blasParams.bufferRange.offset = 0u; - blasParams.bufferRange.size = buildSizes.accelerationStructureSize; - blasParams.flags = IGPUBottomLevelAccelerationStructure::SCreationParams::FLAGS::NONE; - gpuBlas[i] = m_device->createBottomLevelAccelerationStructure(std::move(blasParams)); - if (!gpuBlas[i]) - return logFail("Could not create BLAS"); - } - } - - auto cmdbufBlas = getSingleUseCommandBufferAndBegin(pool); - cmdbufBlas->beginDebugMarker("Build BLAS"); + constexpr auto MaxAlignment = 256; + constexpr auto MinAllocationSize = 1024; + const auto scratchSize = core::alignUp(reservation.getMinASBuildScratchSize(false),MaxAlignment); + + + IGPUBuffer::SCreationParams creationParams = {}; + creationParams.size = scratchSize; + creationParams.usage = IGPUBuffer::EUF_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT|IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT|IGPUBuffer::EUF_STORAGE_BUFFER_BIT; +#ifdef TEST_REBAR_FALLBACK + creationParams.usage |= IGPUBuffer::EUF_TRANSFER_DST_BIT; + core::unordered_set sharingSet = {compute.queue->getFamilyIndex(),transfer.queue->getFamilyIndex()}; + core::vector sharingIndices(sharingSet.begin(),sharingSet.end()); + if (sharingIndices.size()>1) + creationParams.queueFamilyIndexCount = sharingIndices.size(); + creationParams.queueFamilyIndices = sharingIndices.data(); +#endif + auto scratchBuffer = m_device->createBuffer(std::move(creationParams)); - cmdbufBlas->resetQueryPool(queryPool.get(), 0, objectsGpu.size()); + auto reqs = scratchBuffer->getMemoryReqs(); +#ifndef TEST_REBAR_FALLBACK + reqs.memoryTypeBits &= m_physicalDevice->getDirectVRAMAccessMemoryTypeBits(); +#endif + auto allocation = m_device->allocate(reqs,scratchBuffer.get(),IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); +#ifndef TEST_REBAR_FALLBACK + allocation.memory->map({.offset=0,.length=reqs.size}); +#endif - smart_refctd_ptr scratchBuffer; - { - IGPUBuffer::SCreationParams params; - params.usage = bitflag(IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT) | IGPUBuffer::EUF_STORAGE_BUFFER_BIT; - params.size = totalScratchSize; - scratchBuffer = createBuffer(params); + scratchAlloc = make_smart_refctd_ptr( + SBufferRange{0ull,scratchSize,std::move(scratchBuffer)}, + core::allocator(),MaxAlignment,MinAllocationSize + ); } - uint32_t queryCount = 0; - IGPUBottomLevelAccelerationStructure::BuildRangeInfo buildRangeInfos[OT_COUNT]; - IGPUBottomLevelAccelerationStructure::BuildRangeInfo* pRangeInfos[OT_COUNT]; - for (uint32_t i = 0; i < objectsGpu.size(); i++) + struct MyParams final : CAssetConverter::SConvertParams { - blasBuildInfos[i].dstAS = gpuBlas[i].get(); - blasBuildInfos[i].scratch.buffer = scratchBuffer; - if (i == 0) + inline uint32_t getFinalOwnerQueueFamily(const IGPUBuffer* buffer, const core::blake3_hash_t& createdFrom) override { - blasBuildInfos[i].scratch.offset = 0u; + return finalUser; } - else + inline uint32_t getFinalOwnerQueueFamily(const IGPUAccelerationStructure* image, const core::blake3_hash_t& createdFrom) override { - const auto unalignedOffset = blasBuildInfos[i - 1].scratch.offset + scratchSizes[i - 1]; - blasBuildInfos[i].scratch.offset = core::alignUp(unalignedOffset, scratchOffsetAlignment); + return finalUser; } - buildRangeInfos[i].primitiveCount = primitiveCounts[i]; - buildRangeInfos[i].primitiveByteOffset = 0u; - buildRangeInfos[i].firstVertex = 0u; - buildRangeInfos[i].transformByteOffset = 0u; - - pRangeInfos[i] = &buildRangeInfos[i]; - } - - if (!cmdbufBlas->buildAccelerationStructures({ blasBuildInfos, OT_COUNT }, pRangeInfos)) - return logFail("Failed to build BLAS"); + uint8_t finalUser; + } params = {}; + params.utilities = m_utils.get(); + params.transfer = &transfer; + params.compute = &compute; + params.scratchForDeviceASBuild = scratchAlloc.get(); + params.finalUser = gQueue->getFamilyIndex(); + auto future = reservation.convert(params); + if (future.copy() != IQueue::RESULT::SUCCESS) { - SMemoryBarrier memBarrier; - memBarrier.srcStageMask = PIPELINE_STAGE_FLAGS::ACCELERATION_STRUCTURE_BUILD_BIT; - memBarrier.srcAccessMask = ACCESS_FLAGS::ACCELERATION_STRUCTURE_WRITE_BIT; - memBarrier.dstStageMask = PIPELINE_STAGE_FLAGS::ACCELERATION_STRUCTURE_BUILD_BIT; - memBarrier.dstAccessMask = ACCESS_FLAGS::ACCELERATION_STRUCTURE_READ_BIT; - cmdbufBlas->pipelineBarrier(E_DEPENDENCY_FLAGS::EDF_NONE, { .memBarriers = {&memBarrier, 1} }); + m_logger->log("Failed to await submission feature!", ILogger::ELL_ERROR); + return {}; } - const IGPUAccelerationStructure* ases[OT_COUNT]; - for (uint32_t i = 0; i < objectsGpu.size(); i++) - ases[i] = gpuBlas[i].get(); - if (!cmdbufBlas->writeAccelerationStructureProperties({ ases, OT_COUNT }, IQueryPool::ACCELERATION_STRUCTURE_COMPACTED_SIZE, - queryPool.get(), queryCount++)) - return logFail("Failed to write acceleration structure properties!"); - - cmdbufBlas->endDebugMarker(); - cmdbufSubmitAndWait(cmdbufBlas, queue, 39); - } - - auto cmdbufCompact = getSingleUseCommandBufferAndBegin(pool); - cmdbufCompact->beginDebugMarker("Compact BLAS"); - - // compact blas - { - std::array asSizes{ 0 }; - if (!m_device->getQueryPoolResults(queryPool.get(), 0, objectsGpu.size(), asSizes.data(), sizeof(size_t), IQueryPool::WAIT_BIT)) - return logFail("Could not get query pool results for AS sizes"); - - std::array, OT_COUNT> cleanupBlas; - for (uint32_t i = 0; i < objectsGpu.size(); i++) + // assign gpu objects to output + for (const auto& buffer : reservation.getGPUObjects()) + retainedBuffers.push_back(buffer.value); + for (uint32_t i = 0; i < objectsCpu.size(); i++) { - cleanupBlas[i] = gpuBlas[i]; - { - IGPUBuffer::SCreationParams params; - params.usage = bitflag(IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT) | IGPUBuffer::EUF_ACCELERATION_STRUCTURE_STORAGE_BIT; - params.size = asSizes[i]; - smart_refctd_ptr asBuffer = createBuffer(params); - - IGPUBottomLevelAccelerationStructure::SCreationParams blasParams; - blasParams.bufferRange.buffer = asBuffer; - blasParams.bufferRange.offset = 0u; - blasParams.bufferRange.size = asSizes[i]; - blasParams.flags = IGPUBottomLevelAccelerationStructure::SCreationParams::FLAGS::NONE; - gpuBlas[i] = m_device->createBottomLevelAccelerationStructure(std::move(blasParams)); - if (!gpuBlas[i]) - return logFail("Could not create compacted BLAS"); - } + auto vBuffer = retainedBuffers[2 * i + 0].get(); + auto iBuffer = retainedBuffers[2 * i + 1].get(); + const auto& geom = objectsCpu[i]; + const bool useIndex = geom.data.indexType != EIT_UNKNOWN; - IGPUBottomLevelAccelerationStructure::CopyInfo copyInfo; - copyInfo.src = cleanupBlas[i].get(); - copyInfo.dst = gpuBlas[i].get(); - copyInfo.mode = IGPUBottomLevelAccelerationStructure::COPY_MODE::COMPACT; - if (!cmdbufCompact->copyAccelerationStructure(copyInfo)) - return logFail("Failed to copy AS to compact"); + geomInfos[i].vertexBufferAddress = vBuffer->getDeviceAddress() + byteOffsets[i]; + geomInfos[i].indexBufferAddress = useIndex ? iBuffer->getDeviceAddress():0x0ull; } } - cmdbufCompact->endDebugMarker(); - cmdbufSubmitAndWait(cmdbufCompact, queue, 40); - - auto cmdbufTlas = getSingleUseCommandBufferAndBegin(pool); - cmdbufTlas->beginDebugMarker("Build TLAS"); - - // build top level AS + // { - const uint32_t instancesCount = objectsGpu.size(); - IGPUTopLevelAccelerationStructure::DeviceStaticInstance instances[OT_COUNT]; - for (uint32_t i = 0; i < instancesCount; i++) - { - core::matrix3x4SIMD transform; - transform.setTranslation(nbl::core::vectorSIMDf(5.f * i, 0, 0, 0)); - instances[i].base.blas.deviceAddress = gpuBlas[i]->getReferenceForDeviceOperations().deviceAddress; - instances[i].base.mask = 0xFF; - instances[i].base.instanceCustomIndex = i; - instances[i].base.instanceShaderBindingTableRecordOffset = 0; - instances[i].base.flags = static_cast(IGPUTopLevelAccelerationStructure::INSTANCE_FLAGS::TRIANGLE_FACING_CULL_DISABLE_BIT); - instances[i].transform = transform; - } - - { - size_t bufSize = instancesCount * sizeof(IGPUTopLevelAccelerationStructure::DeviceStaticInstance); - IGPUBuffer::SCreationParams params; - params.usage = bitflag(IGPUBuffer::EUF_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT) | IGPUBuffer::EUF_STORAGE_BUFFER_BIT | - IGPUBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; - params.size = bufSize; - instancesBuffer = createBuffer(params); - - SBufferRange range = { .offset = 0u, .size = bufSize, .buffer = instancesBuffer }; - cmdbufTlas->updateBuffer(range, instances); - } - - // make sure instances upload complete first - { - SMemoryBarrier memBarrier; - memBarrier.srcStageMask = PIPELINE_STAGE_FLAGS::ALL_TRANSFER_BITS; - memBarrier.srcAccessMask = ACCESS_FLAGS::TRANSFER_WRITE_BIT; - memBarrier.dstStageMask = PIPELINE_STAGE_FLAGS::ACCELERATION_STRUCTURE_BUILD_BIT; - memBarrier.dstAccessMask = ACCESS_FLAGS::ACCELERATION_STRUCTURE_WRITE_BIT; - cmdbufTlas->pipelineBarrier(E_DEPENDENCY_FLAGS::EDF_NONE, { .memBarriers = {&memBarrier, 1} }); - } - - auto tlasFlags = bitflag(IGPUTopLevelAccelerationStructure::BUILD_FLAGS::PREFER_FAST_TRACE_BIT); - - IGPUTopLevelAccelerationStructure::DeviceBuildInfo tlasBuildInfo; - tlasBuildInfo.buildFlags = tlasFlags; - tlasBuildInfo.srcAS = nullptr; - tlasBuildInfo.dstAS = nullptr; - tlasBuildInfo.instanceData.buffer = instancesBuffer; - tlasBuildInfo.instanceData.offset = 0u; - tlasBuildInfo.scratch = {}; - - auto buildSizes = m_device->getAccelerationStructureBuildSizes(tlasFlags, false, instancesCount); - if (!buildSizes) - return logFail("Failed to get TLAS build sizes"); + IGPUBuffer::SCreationParams params; + params.usage = IGPUBuffer::EUF_STORAGE_BUFFER_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; + params.size = OT_COUNT * sizeof(SGeomInfo); + m_utils->createFilledDeviceLocalBufferOnDedMem(SIntendedSubmitInfo{ .queue = gQueue }, std::move(params), geomInfos).move_into(geometryInfoBuffer); + } + // acquire ownership + { + smart_refctd_ptr cmdbuf; { - IGPUBuffer::SCreationParams params; - params.usage = bitflag(IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT) | IGPUBuffer::EUF_ACCELERATION_STRUCTURE_STORAGE_BIT; - params.size = buildSizes.accelerationStructureSize; - smart_refctd_ptr asBuffer = createBuffer(params); - - IGPUTopLevelAccelerationStructure::SCreationParams tlasParams; - tlasParams.bufferRange.buffer = asBuffer; - tlasParams.bufferRange.offset = 0u; - tlasParams.bufferRange.size = buildSizes.accelerationStructureSize; - tlasParams.flags = IGPUTopLevelAccelerationStructure::SCreationParams::FLAGS::NONE; - gpuTlas = m_device->createTopLevelAccelerationStructure(std::move(tlasParams)); - if (!gpuTlas) - return logFail("Could not create TLAS"); + const auto gQFI = gQueue->getFamilyIndex(); + m_device->createCommandPool(gQFI,IGPUCommandPool::CREATE_FLAGS::TRANSIENT_BIT)->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY,{&cmdbuf,1}); + cmdbuf->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + { + core::vector> bufBarriers; + auto acquireBufferRange = [&bufBarriers](const uint8_t otherQueueFamilyIndex, const SBufferRange& bufferRange) + { + bufBarriers.push_back({ + .barrier = { + .dep = { + .srcStageMask = PIPELINE_STAGE_FLAGS::NONE, + .srcAccessMask = ACCESS_FLAGS::NONE, + .dstStageMask = PIPELINE_STAGE_FLAGS::COMPUTE_SHADER_BIT, + // we don't care what exactly, uncomplex our code + .dstAccessMask = ACCESS_FLAGS::SHADER_READ_BITS + }, + .ownershipOp = IGPUCommandBuffer::SOwnershipTransferBarrier::OWNERSHIP_OP::ACQUIRE, + .otherQueueFamilyIndex = otherQueueFamilyIndex + }, + .range = bufferRange + }); + }; +#ifdef TEST_REBAR_FALLBACK + if (const auto otherQueueFamilyIndex=transfer.queue->getFamilyIndex(); gQFI!=otherQueueFamilyIndex) + for (const auto& buffer : reservation.getGPUObjects()) + { + const auto& buff = buffer.value; + if (buff) + acquireBufferRange(otherQueueFamilyIndex,{.offset=0,.size=buff->getSize(),.buffer=buff}); + } +#endif + if (const auto otherQueueFamilyIndex=compute.queue->getFamilyIndex(); gQFI!=otherQueueFamilyIndex) + { + auto acquireAS = [&acquireBufferRange,otherQueueFamilyIndex](const IGPUAccelerationStructure* as) + { + acquireBufferRange(otherQueueFamilyIndex,as->getCreationParams().bufferRange); + }; + for (const auto& blas : reservation.getGPUObjects()) + acquireAS(blas.value.get()); + acquireAS(reservation.getGPUObjects().front().value.get()); + } + if (!bufBarriers.empty()) + cmdbuf->pipelineBarrier(asset::E_DEPENDENCY_FLAGS::EDF_NONE,{.memBarriers={},.bufBarriers=bufBarriers}); + } + cmdbuf->end(); } - - smart_refctd_ptr scratchBuffer; + if (!cmdbuf->empty()) { - IGPUBuffer::SCreationParams params; - params.usage = bitflag(IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT) | IGPUBuffer::EUF_STORAGE_BUFFER_BIT; - params.size = buildSizes.buildScratchSize; - scratchBuffer = createBuffer(params); + const IQueue::SSubmitInfo::SCommandBufferInfo cmdbufInfo = { + .cmdbuf = cmdbuf.get() + }; + const IQueue::SSubmitInfo::SSemaphoreInfo signal = { + .semaphore = compute.scratchSemaphore.semaphore, + .value = compute.getFutureScratchSemaphore().value, + .stageMask = asset::PIPELINE_STAGE_FLAGS::ALL_COMMANDS_BITS + }; + auto wait = signal; + wait.value--; + const IQueue::SSubmitInfo info = { + .waitSemaphores = {&wait,1}, // we already waited with the host on the AS build + .commandBuffers = {&cmdbufInfo,1}, + .signalSemaphores = {&signal,1} + }; + if (const auto retval=gQueue->submit({&info,1}); retval!=IQueue::RESULT::SUCCESS) + m_logger->log("Failed to transfer ownership with code %d!",system::ILogger::ELL_ERROR,retval); } - - tlasBuildInfo.dstAS = gpuTlas.get(); - tlasBuildInfo.scratch.buffer = scratchBuffer; - tlasBuildInfo.scratch.offset = 0u; - - IGPUTopLevelAccelerationStructure::BuildRangeInfo buildRangeInfo[1u]; - buildRangeInfo[0].instanceCount = instancesCount; - buildRangeInfo[0].instanceByteOffset = 0u; - IGPUTopLevelAccelerationStructure::BuildRangeInfo* pRangeInfos; - pRangeInfos = &buildRangeInfo[0]; - - if (!cmdbufTlas->buildAccelerationStructures({ &tlasBuildInfo, 1 }, pRangeInfos)) - return logFail("Failed to build TLAS"); } - - cmdbufTlas->endDebugMarker(); - cmdbufSubmitAndWait(cmdbufTlas, queue, 45); - +#undef TEST_REBAR_FALLBACK + #ifdef TRY_BUILD_FOR_NGFX { const IQueue::SSubmitInfo::SSemaphoreInfo acquired[] = { { @@ -1054,7 +891,8 @@ class RayQueryGeometryApp final : public examples::SimpleWindowedApplication, pu #endif m_api->endCapture(); - return true; + return reservation.getGPUObjects().front().value; +#endif } @@ -1072,31 +910,12 @@ class RayQueryGeometryApp final : public examples::SimpleWindowedApplication, pu Camera camera = Camera(core::vectorSIMDf(0, 0, 0), core::vectorSIMDf(0, 0, 0), core::matrix4SIMD()); video::CDumbPresentationOracle oracle; - std::array objectsGpu; - - std::array, OT_COUNT> gpuBlas; - smart_refctd_ptr gpuTlas; - smart_refctd_ptr instancesBuffer; - smart_refctd_ptr geometryInfoBuffer; + core::vector> retainedBuffers; smart_refctd_ptr outHDRImage; smart_refctd_ptr renderPipeline; smart_refctd_ptr renderDs; - smart_refctd_ptr renderPool; - - uint16_t gcIndex = {}; - - void mouseProcess(const nbl::ui::IMouseEventChannel::range_t& events) - { - for (auto eventIt = events.begin(); eventIt != events.end(); eventIt++) - { - auto ev = *eventIt; - - if (ev.type == nbl::ui::SMouseEvent::EET_SCROLL) - gcIndex = std::clamp(int16_t(gcIndex) + int16_t(core::sign(ev.scrollEvent.verticalScroll)), int64_t(0), int64_t(OT_COUNT - (uint8_t)1u)); - } - } }; NBL_MAIN_FUNC(RayQueryGeometryApp) \ No newline at end of file diff --git a/68_JpegLoading/main.cpp b/68_JpegLoading/main.cpp index 5ef9b637d..663b40759 100644 --- a/68_JpegLoading/main.cpp +++ b/68_JpegLoading/main.cpp @@ -1,22 +1,26 @@ // Copyright (C) 2018-2024 - DevSH GrapMonoAssetManagerAndBuiltinResourceApplicationhics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" + + +#include "nbl/examples/examples.hpp" #include #include "nlohmann/json.hpp" #include "argparse/argparse.hpp" + using json = nlohmann::json; using namespace nbl; -using namespace core; -using namespace hlsl; -using namespace system; -using namespace asset; -using namespace ui; -using namespace video; +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::examples; class ThreadPool { @@ -76,11 +80,11 @@ using task_t = std::function; std::atomic m_shouldStop = false; }; -class JpegLoaderApp final : public application_templates::MonoAssetManagerAndBuiltinResourceApplication +class JpegLoaderApp final : public BuiltinResourcesApplication { using clock_t = std::chrono::steady_clock; using clock_resolution_t = std::chrono::milliseconds; - using base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using base_t = BuiltinResourcesApplication; public: using base_t::base_t; diff --git a/70_FLIPFluids/app_resources/compute/advectParticles.comp.hlsl b/70_FLIPFluids/app_resources/compute/advectParticles.comp.hlsl index 2d329ac85..64e94f262 100644 --- a/70_FLIPFluids/app_resources/compute/advectParticles.comp.hlsl +++ b/70_FLIPFluids/app_resources/compute/advectParticles.comp.hlsl @@ -26,6 +26,7 @@ using namespace nbl::hlsl; // TODO: delta time push constant? (but then for CI need a commandline `-fixed-timestep=MS` and `-frames=N` option too) [numthreads(WorkgroupSize, 1, 1)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { uint32_t pid = ID.x; diff --git a/70_FLIPFluids/app_resources/compute/applyBodyForces.comp.hlsl b/70_FLIPFluids/app_resources/compute/applyBodyForces.comp.hlsl index 8ffc5e821..b2c1e0b3f 100644 --- a/70_FLIPFluids/app_resources/compute/applyBodyForces.comp.hlsl +++ b/70_FLIPFluids/app_resources/compute/applyBodyForces.comp.hlsl @@ -14,6 +14,7 @@ cbuffer GridData // TODO: can this kernel be fused with any preceeding/succeeding it? [numthreads(WorkgroupGridDim, WorkgroupGridDim, WorkgroupGridDim)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { // only gravity for now diff --git a/70_FLIPFluids/app_resources/compute/diffusion.comp.hlsl b/70_FLIPFluids/app_resources/compute/diffusion.comp.hlsl index 43a57ed38..e53c91d2d 100644 --- a/70_FLIPFluids/app_resources/compute/diffusion.comp.hlsl +++ b/70_FLIPFluids/app_resources/compute/diffusion.comp.hlsl @@ -34,6 +34,7 @@ groupshared uint16_t3 sAxisCellMat[14][14][14]; // TODO: `uint16_t` per axis is groupshared float16_t3 sDiffusion[14][14][14]; [numthreads(WorkgroupGridDim, WorkgroupGridDim, WorkgroupGridDim)] +[shader("compute")] void setAxisCellMaterial(uint32_t3 ID : SV_DispatchThreadID) { int3 cellIdx = ID; diff --git a/70_FLIPFluids/app_resources/compute/genParticleVertices.comp.hlsl b/70_FLIPFluids/app_resources/compute/genParticleVertices.comp.hlsl index b66db1ca2..4c4a76690 100644 --- a/70_FLIPFluids/app_resources/compute/genParticleVertices.comp.hlsl +++ b/70_FLIPFluids/app_resources/compute/genParticleVertices.comp.hlsl @@ -57,6 +57,7 @@ static const float2 quadUVs[4] = { using namespace nbl::hlsl; [numthreads(WorkgroupSize, 1, 1)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { uint32_t pid = ID.x; diff --git a/70_FLIPFluids/app_resources/compute/particlesInit.comp.hlsl b/70_FLIPFluids/app_resources/compute/particlesInit.comp.hlsl index 173929b10..27bf4366f 100644 --- a/70_FLIPFluids/app_resources/compute/particlesInit.comp.hlsl +++ b/70_FLIPFluids/app_resources/compute/particlesInit.comp.hlsl @@ -17,6 +17,7 @@ cbuffer GridData }; [numthreads(WorkgroupSize, 1, 1)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { uint32_t pid = ID.x; diff --git a/70_FLIPFluids/app_resources/compute/prepareCellUpdate.comp.hlsl b/70_FLIPFluids/app_resources/compute/prepareCellUpdate.comp.hlsl index fe82fe946..157da5bb8 100644 --- a/70_FLIPFluids/app_resources/compute/prepareCellUpdate.comp.hlsl +++ b/70_FLIPFluids/app_resources/compute/prepareCellUpdate.comp.hlsl @@ -42,6 +42,7 @@ float getWeight(float3 pPos, float3 cPos, float invSpacing) } [numthreads(WorkgroupSize, 1, 1)] +[shader("compute")] void main(uint32_t3 ID : SV_DispatchThreadID) { uint pid = ID.x; diff --git a/70_FLIPFluids/app_resources/compute/pressureSolver.comp.hlsl b/70_FLIPFluids/app_resources/compute/pressureSolver.comp.hlsl index 668b15c31..b5db995c5 100644 --- a/70_FLIPFluids/app_resources/compute/pressureSolver.comp.hlsl +++ b/70_FLIPFluids/app_resources/compute/pressureSolver.comp.hlsl @@ -36,6 +36,7 @@ groupshared float sDivergence[14][14][14]; groupshared float sPressure[14][14][14]; [numthreads(WorkgroupGridDim, WorkgroupGridDim, WorkgroupGridDim)] +[shader("compute")] void calculateNegativeDivergence(uint32_t3 ID : SV_DispatchThreadID) { int3 cellIdx = ID; diff --git a/70_FLIPFluids/app_resources/compute/updateFluidCells.comp.hlsl b/70_FLIPFluids/app_resources/compute/updateFluidCells.comp.hlsl index 9d7fabd52..62ddfd822 100644 --- a/70_FLIPFluids/app_resources/compute/updateFluidCells.comp.hlsl +++ b/70_FLIPFluids/app_resources/compute/updateFluidCells.comp.hlsl @@ -40,6 +40,7 @@ void updateFluidCells(uint32_t3 ID : SV_DispatchThreadID) } [numthreads(WorkgroupGridDim, WorkgroupGridDim, WorkgroupGridDim)] +[shader("compute")] void updateNeighborFluidCells(uint32_t3 ID : SV_DispatchThreadID) { int3 cIdx = ID; diff --git a/70_FLIPFluids/app_resources/fluidParticles.fragment.hlsl b/70_FLIPFluids/app_resources/fluidParticles.fragment.hlsl index e556ce8ed..cac1bfa4a 100644 --- a/70_FLIPFluids/app_resources/fluidParticles.fragment.hlsl +++ b/70_FLIPFluids/app_resources/fluidParticles.fragment.hlsl @@ -9,6 +9,7 @@ cbuffer CameraData // TODO: BDA instead of UBO, one less thing in DSLayout SMVPParams camParams; }; +[shader("pixel")] float4 main(PSInput input, out float depthTest : SV_DEPTHGREATEREQUAL) : SV_TARGET { float3 N; diff --git a/70_FLIPFluids/app_resources/fluidParticles.vertex.hlsl b/70_FLIPFluids/app_resources/fluidParticles.vertex.hlsl index 4708083c6..89d37eb6f 100644 --- a/70_FLIPFluids/app_resources/fluidParticles.vertex.hlsl +++ b/70_FLIPFluids/app_resources/fluidParticles.vertex.hlsl @@ -14,6 +14,7 @@ struct SPushConstants #include "nbl/builtin/hlsl/bda/__ptr.hlsl" using namespace nbl::hlsl; +[shader("vertex")] PSInput main(uint vertexID : SV_VertexID) { PSInput output; diff --git a/70_FLIPFluids/main.cpp b/70_FLIPFluids/main.cpp index 93e753b68..66596c526 100644 --- a/70_FLIPFluids/main.cpp +++ b/70_FLIPFluids/main.cpp @@ -1,28 +1,27 @@ -#include +// Copyright (C) 2024-2025 - DevSH Graphics Programming Sp. z O.O. +// This file is part of the "Nabla Engine". +// For conditions of distribution and use, see copyright notice in nabla.h -#include "nbl/application_templates/MonoAssetManagerAndBuiltinResourceApplication.hpp" -#include "SimpleWindowedApplication.hpp" -#include "InputSystem.hpp" -#include "CCamera.hpp" -#include "glm/glm/glm.hpp" -#include -#include +#include "nbl/examples/examples.hpp" +// TODO: why is it not in nabla.h ? +#include "nbl/asset/metadata/CHLSLMetadata.h" -using namespace nbl::hlsl; using namespace nbl; -using namespace core; -using namespace hlsl; -using namespace system; -using namespace asset; -using namespace ui; -using namespace video; +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::examples; #include "app_resources/common.hlsl" #include "app_resources/gridUtils.hlsl" #include "app_resources/render_common.hlsl" #include "app_resources/descriptor_bindings.hlsl" + enum SimPresets { CENTER_DROP, @@ -165,10 +164,10 @@ class CEventCallback : public ISimpleManagedSurface::ICallback nbl::system::logger_opt_smart_ptr m_logger = nullptr; }; -class FLIPFluidsApp final : public examples::SimpleWindowedApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +class FLIPFluidsApp final : public SimpleWindowedApplication, public BuiltinResourcesApplication { - using device_base_t = examples::SimpleWindowedApplication; - using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using device_base_t = SimpleWindowedApplication; + using asset_base_t = BuiltinResourcesApplication; using clock_t = std::chrono::steady_clock; constexpr static inline uint32_t WIN_WIDTH = 1280, WIN_HEIGHT = 720; @@ -1401,7 +1400,7 @@ class FLIPFluidsApp final : public examples::SimpleWindowedApplication, public a numParticles = m_gridData.particleInitSize.x * m_gridData.particleInitSize.y * m_gridData.particleInitSize.z * particlesPerCell; } - smart_refctd_ptr compileShader(const std::string& filePath, const std::string& entryPoint = "main") + smart_refctd_ptr compileShader(const std::string& filePath, const std::string& entryPoint = "main") { IAssetLoader::SAssetLoadParams lparams = {}; lparams.logger = m_logger.get(); @@ -1415,14 +1414,16 @@ class FLIPFluidsApp final : public examples::SimpleWindowedApplication, public a const auto assets = bundle.getContents(); assert(assets.size() == 1); - smart_refctd_ptr shaderSrc = IAsset::castDown(assets[0]); + smart_refctd_ptr shaderSrc = IAsset::castDown(assets[0]); + const auto hlslMetadata = static_cast(bundle.getMetadata()); + const auto shaderStage = hlslMetadata->shaderStages->front(); - smart_refctd_ptr shader = shaderSrc; + smart_refctd_ptr shader = shaderSrc; if (entryPoint != "main") { auto compiler = make_smart_refctd_ptr(smart_refctd_ptr(m_system)); CHLSLCompiler::SOptions options = {}; - options.stage = shaderSrc->getStage(); + options.stage = shaderStage; if (!(options.stage == IShader::E_SHADER_STAGE::ESS_COMPUTE || options.stage == IShader::E_SHADER_STAGE::ESS_FRAGMENT)) options.stage = IShader::E_SHADER_STAGE::ESS_VERTEX; options.targetSpirvVersion = m_device->getPhysicalDevice()->getLimits().spirvVersion; @@ -1443,7 +1444,7 @@ class FLIPFluidsApp final : public examples::SimpleWindowedApplication, public a shader = compiler->compileToSPIRV((const char*)shaderSrc->getContent()->getPointer(), options); } - return m_device->createShader(shader.get()); + return m_device->compileShader({ shader.get() }); } // TODO: there's a method in IUtilities for this @@ -1562,7 +1563,7 @@ class FLIPFluidsApp final : public examples::SimpleWindowedApplication, public a // init shaders and pipeline - auto compileShader = [&](const std::string& filePath, IShader::E_SHADER_STAGE stage) -> smart_refctd_ptr + auto compileShader = [&](const std::string& filePath) -> smart_refctd_ptr { IAssetLoader::SAssetLoadParams lparams = {}; lparams.logger = m_logger.get(); @@ -1576,15 +1577,14 @@ class FLIPFluidsApp final : public examples::SimpleWindowedApplication, public a const auto assets = bundle.getContents(); assert(assets.size() == 1); - smart_refctd_ptr shaderSrc = IAsset::castDown(assets[0]); - shaderSrc->setShaderStage(stage); + smart_refctd_ptr shaderSrc = IAsset::castDown(assets[0]); if (!shaderSrc) return nullptr; - return m_device->createShader(shaderSrc.get()); + return m_device->compileShader({ shaderSrc.get() }); }; - auto vs = compileShader("app_resources/fluidParticles.vertex.hlsl", IShader::E_SHADER_STAGE::ESS_VERTEX); - auto fs = compileShader("app_resources/fluidParticles.fragment.hlsl", IShader::E_SHADER_STAGE::ESS_FRAGMENT); + auto vs = compileShader("app_resources/fluidParticles.vertex.hlsl"); + auto fs = compileShader("app_resources/fluidParticles.fragment.hlsl"); smart_refctd_ptr descriptorSetLayout1; { @@ -1629,11 +1629,6 @@ class FLIPFluidsApp final : public examples::SimpleWindowedApplication, public a blendParams.blendParams[0u].colorWriteMask = (1u << 0u) | (1u << 1u) | (1u << 2u) | (1u << 3u); { - IGPUShader::SSpecInfo specInfo[3] = { - {.shader = vs.get()}, - {.shader = fs.get()}, - }; - const asset::SPushConstantRange pcRange = { .stageFlags = IShader::E_SHADER_STAGE::ESS_VERTEX, .offset = 0, .size = sizeof(uint64_t) }; const auto pipelineLayout = m_device->createPipelineLayout({ &pcRange , 1 }, nullptr, smart_refctd_ptr(descriptorSetLayout1), nullptr, nullptr); @@ -1643,7 +1638,8 @@ class FLIPFluidsApp final : public examples::SimpleWindowedApplication, public a IGPUGraphicsPipeline::SCreationParams params[1] = {}; params[0].layout = pipelineLayout.get(); - params[0].shaders = specInfo; + params[0].vertexShader = { .shader = vs.get(), .entryPoint = "main", }; + params[0].fragmentShader = { .shader = fs.get(), .entryPoint = "main", }; params[0].cached = { .vertexInput = { }, diff --git a/71_RayTracingPipeline/CMakeLists.txt b/71_RayTracingPipeline/CMakeLists.txt new file mode 100644 index 000000000..07b0fd396 --- /dev/null +++ b/71_RayTracingPipeline/CMakeLists.txt @@ -0,0 +1,37 @@ +include(common RESULT_VARIABLE RES) +if(NOT RES) + message(FATAL_ERROR "common.cmake not found. Should be in {repo_root}/cmake directory") +endif() + +if(NBL_BUILD_IMGUI) + set(NBL_INCLUDE_SERACH_DIRECTORIES + "${CMAKE_CURRENT_SOURCE_DIR}/include" + ) + + list(APPEND NBL_LIBRARIES + imtestengine + "${NBL_EXT_IMGUI_UI_LIB}" + ) + + nbl_create_executable_project("" "" "${NBL_INCLUDE_SERACH_DIRECTORIES}" "${NBL_LIBRARIES}" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") + + if(NBL_EMBED_BUILTIN_RESOURCES) + set(_BR_TARGET_ ${EXECUTABLE_NAME}_builtinResourceData) + set(RESOURCE_DIR "app_resources") + + get_filename_component(_SEARCH_DIRECTORIES_ "${CMAKE_CURRENT_SOURCE_DIR}" ABSOLUTE) + get_filename_component(_OUTPUT_DIRECTORY_SOURCE_ "${CMAKE_CURRENT_BINARY_DIR}/src" ABSOLUTE) + get_filename_component(_OUTPUT_DIRECTORY_HEADER_ "${CMAKE_CURRENT_BINARY_DIR}/include" ABSOLUTE) + + file(GLOB_RECURSE BUILTIN_RESOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/${RESOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/${RESOURCE_DIR}/*") + foreach(RES_FILE ${BUILTIN_RESOURCE_FILES}) + LIST_BUILTIN_RESOURCE(RESOURCES_TO_EMBED "${RES_FILE}") + endforeach() + + ADD_CUSTOM_BUILTIN_RESOURCES(${_BR_TARGET_} RESOURCES_TO_EMBED "${_SEARCH_DIRECTORIES_}" "${RESOURCE_DIR}" "nbl::this_example::builtin" "${_OUTPUT_DIRECTORY_HEADER_}" "${_OUTPUT_DIRECTORY_SOURCE_}") + + LINK_BUILTIN_RESOURCES_TO_TARGET(${EXECUTABLE_NAME} ${_BR_TARGET_}) + endif() +endif() + + diff --git a/71_RayTracingPipeline/Readme.md b/71_RayTracingPipeline/Readme.md new file mode 100644 index 000000000..4317be9c3 --- /dev/null +++ b/71_RayTracingPipeline/Readme.md @@ -0,0 +1,11 @@ +# Vulkan Ray Tracing Pipeline Demo +![finalResult](docs/Images/final_result.png) + +The scene is rendered using two ray. The first ray(primary ray) is shoot from the camera/generation shader and the second ray(occlusion ray) is shoot from the closest hit shader. +To test intersection shader, the acceleration structures consist of two types of geometries. The cubes are stored as triangle geometries while the spheres are stored as procedural geometries. +To test callable shader, we calculate lighting information of different type in its own callable shader + +## Shader Table Layout +![shaderBindingTable](docs/Images/shader_binding_table.png) + + diff --git a/71_RayTracingPipeline/app_resources/common.hlsl b/71_RayTracingPipeline/app_resources/common.hlsl new file mode 100644 index 000000000..18b67085a --- /dev/null +++ b/71_RayTracingPipeline/app_resources/common.hlsl @@ -0,0 +1,396 @@ +#ifndef RQG_COMMON_HLSL +#define RQG_COMMON_HLSL + +#include "nbl/builtin/hlsl/cpp_compat.hlsl" +#include "nbl/builtin/hlsl/cpp_compat/basic.h" +#include "nbl/builtin/hlsl/random/pcg.hlsl" + +NBL_CONSTEXPR uint32_t WorkgroupSize = 16; +NBL_CONSTEXPR uint32_t MAX_UNORM_10 = 1023; +NBL_CONSTEXPR uint32_t MAX_UNORM_22 = 4194303; + +inline uint32_t packUnorm10(float32_t v) +{ + return trunc(v * float32_t(MAX_UNORM_10) + 0.5f); +} + +inline float32_t unpackUnorm10(uint32_t packed) +{ + return float32_t(packed & 0x3ff) * (1.0f / float32_t(MAX_UNORM_10)); +} + +inline uint32_t packUnorm22(float32_t v) +{ + const float maxValue = float32_t(MAX_UNORM_22); + return trunc(v * maxValue + 0.5f); +} + +inline float32_t unpackUnorm22(uint32_t packed) +{ + const float maxValue = float32_t(MAX_UNORM_22); + return float32_t(packed & 0x3fffff) * (1.0f / maxValue); +} + +inline uint32_t packUnorm3x10(float32_t3 v) +{ + return (packUnorm10(v.z) << 20 | (packUnorm10(v.y) << 10 | packUnorm10(v.x))); +} + +inline float32_t3 unpackUnorm3x10(uint32_t packed) +{ + return float32_t3(unpackUnorm10(packed), unpackUnorm10(packed >> 10), unpackUnorm10(packed >> 20)); +} + +struct Material +{ + float32_t3 ambient; + float32_t3 diffuse; + float32_t3 specular; + float32_t shininess; + float32_t alpha; + + bool isTransparent() NBL_CONST_MEMBER_FUNC + { + return alpha < 1.0; + } + + bool alphaTest(const float32_t xi) NBL_CONST_MEMBER_FUNC + { + return xi > alpha; + } +}; + +struct MaterialPacked +{ + uint32_t ambient; + uint32_t diffuse; + uint32_t specular; + uint32_t shininess: 22; + uint32_t alpha : 10; + + bool isTransparent() NBL_CONST_MEMBER_FUNC + { + return alpha != MAX_UNORM_10; + } + + bool alphaTest(const uint32_t xi) NBL_CONST_MEMBER_FUNC + { + return (xi>>22) > alpha; + } +}; + +struct SProceduralGeomInfo +{ + MaterialPacked material; + float32_t3 center; + float32_t radius; +}; + + +struct STriangleGeomInfo +{ + MaterialPacked material; + uint64_t vertexBufferAddress; + uint64_t indexBufferAddress; + + uint32_t vertexStride : 26; + uint32_t objType: 3; + uint32_t indexType : 2; // 16 bit, 32 bit or none + uint32_t smoothNormals : 1; // flat for cube, rectangle, disk + +}; + +enum E_GEOM_TYPE : uint16_t +{ + EGT_TRIANGLES, + EGT_PROCEDURAL, + EGT_COUNT +}; + +enum E_RAY_TYPE : uint16_t +{ + ERT_PRIMARY, // Ray shoot from camera + ERT_OCCLUSION, + ERT_COUNT +}; + +enum E_MISS_TYPE : uint16_t +{ + EMT_PRIMARY, + EMT_OCCLUSION, + EMT_COUNT +}; + +enum E_LIGHT_TYPE : uint16_t +{ + ELT_DIRECTIONAL, + ELT_POINT, + ELT_SPOT, + ELT_COUNT +}; + +struct Light +{ + float32_t3 direction; + float32_t3 position; + float32_t outerCutoff; + uint16_t type; + + +#ifndef __HLSL_VERSION + bool operator==(const Light&) const = default; +#endif + +}; + +static const float LightIntensity = 100.0f; + +struct SPushConstants +{ + uint64_t proceduralGeomInfoBuffer; + uint64_t triangleGeomInfoBuffer; + + float32_t3 camPos; + uint32_t frameCounter; + float32_t4x4 invMVP; + + Light light; +}; + + +struct RayLight +{ + float32_t3 inHitPosition; + float32_t outLightDistance; + float32_t3 outLightDir; + float32_t outIntensity; +}; + +#ifdef __HLSL_VERSION + +struct [raypayload] OcclusionPayload +{ + // TODO: will this break DXC? Tbh should come from push constant or some autoexposure feedback + // NBL_CONSTEXPR_STATIC_INLINE float32_t MinAttenuation = 1.f/1024.f; + + float32_t attenuation : read(caller,anyhit,miss) : write(caller,anyhit,miss); +}; + +struct MaterialId +{ + const static uint32_t PROCEDURAL_FLAG = (1 << 31); + const static uint32_t PROCEDURAL_MASK = ~PROCEDURAL_FLAG; + + uint32_t data; + + static MaterialId createProcedural(uint32_t index) + { + MaterialId id; + id.data = index | PROCEDURAL_FLAG; + return id; + } + + static MaterialId createTriangle(uint32_t index) + { + MaterialId id; + id.data = index; + return id; + } + + uint32_t getMaterialIndex() + { + return data & PROCEDURAL_MASK; + } + + bool isHitProceduralGeom() + { + return data & PROCEDURAL_FLAG; + } +}; + +struct [raypayload] PrimaryPayload +{ + using generator_t = nbl::hlsl::random::Pcg; + + float32_t3 worldNormal : read(caller) : write(closesthit); + float32_t rayDistance : read(caller) : write(closesthit,miss); + generator_t pcg : read(anyhit) : write(caller,anyhit); + MaterialId materialId : read(caller) : write(closesthit); + +}; + +struct ProceduralHitAttribute +{ + float32_t3 center; +}; + +enum ObjectType : uint32_t // matches c++ +{ + OT_CUBE = 0, + OT_SPHERE, + OT_CYLINDER, + OT_RECTANGLE, + OT_DISK, + OT_ARROW, + OT_CONE, + OT_ICOSPHERE, + + OT_COUNT +}; + +static uint32_t s_offsetsToNormalBytes[OT_COUNT] = { 18, 24, 24, 20, 20, 24, 16, 12 }; // based on normals data position + +float32_t3 computeDiffuse(Material mat, float32_t3 light_dir, float32_t3 normal) +{ + float32_t dotNL = max(dot(normal, light_dir), 0.0); + float32_t3 c = mat.diffuse * dotNL; + return c; +} + +float32_t3 computeSpecular(Material mat, float32_t3 view_dir, + float32_t3 light_dir, float32_t3 normal) +{ + const float32_t kPi = 3.14159265; + const float32_t kShininess = max(mat.shininess, 4.0); + + // Specular + const float32_t kEnergyConservation = (2.0 + kShininess) / (2.0 * kPi); + float32_t3 V = normalize(-view_dir); + float32_t3 R = reflect(-light_dir, normal); + float32_t specular = kEnergyConservation * pow(max(dot(V, R), 0.0), kShininess); + + return float32_t3(mat.specular * specular); +} + +float3 unpackNormals3x10(uint32_t v) +{ + // host side changes float32_t3 to EF_A2B10G10R10_SNORM_PACK32 + // follows unpacking scheme from https://github.com/KhronosGroup/SPIRV-Cross/blob/main/reference/shaders-hlsl/frag/unorm-snorm-packing.frag + int signedValue = int(v); + int3 pn = int3(signedValue << 22, signedValue << 12, signedValue << 2) >> 22; + return clamp(float3(pn) / 511.0, -1.0, 1.0); +} + +float32_t3 fetchVertexNormal(int instID, int primID, STriangleGeomInfo geom, float2 bary) +{ + uint idxOffset = primID * 3; + + const uint indexType = geom.indexType; + const uint vertexStride = geom.vertexStride; + + const uint32_t objType = geom.objType; + const uint64_t indexBufferAddress = geom.indexBufferAddress; + + uint i0, i1, i2; + switch (indexType) + { + case 0: // EIT_16BIT + { + i0 = uint32_t(vk::RawBufferLoad < uint16_t > (indexBufferAddress + (idxOffset + 0) * sizeof(uint16_t), 2u)); + i1 = uint32_t(vk::RawBufferLoad < uint16_t > (indexBufferAddress + (idxOffset + 1) * sizeof(uint16_t), 2u)); + i2 = uint32_t(vk::RawBufferLoad < uint16_t > (indexBufferAddress + (idxOffset + 2) * sizeof(uint16_t), 2u)); + } + break; + case 1: // EIT_32BIT + { + i0 = vk::RawBufferLoad < uint32_t > (indexBufferAddress + (idxOffset + 0) * sizeof(uint32_t)); + i1 = vk::RawBufferLoad < uint32_t > (indexBufferAddress + (idxOffset + 1) * sizeof(uint32_t)); + i2 = vk::RawBufferLoad < uint32_t > (indexBufferAddress + (idxOffset + 2) * sizeof(uint32_t)); + } + break; + default: // EIT_NONE + { + i0 = idxOffset; + i1 = idxOffset + 1; + i2 = idxOffset + 2; + } + } + + const uint64_t normalVertexBufferAddress = geom.vertexBufferAddress + s_offsetsToNormalBytes[objType]; + float3 n0, n1, n2; + switch (objType) + { + case OT_CUBE: + { + uint32_t v0 = vk::RawBufferLoad < uint32_t > (normalVertexBufferAddress + i0 * vertexStride, 2u); + uint32_t v1 = vk::RawBufferLoad < uint32_t > (normalVertexBufferAddress + i1 * vertexStride, 2u); + uint32_t v2 = vk::RawBufferLoad < uint32_t > (normalVertexBufferAddress + i2 * vertexStride, 2u); + + n0 = normalize(nbl::hlsl::spirv::unpackSnorm4x8(v0).xyz); + n1 = normalize(nbl::hlsl::spirv::unpackSnorm4x8(v1).xyz); + n2 = normalize(nbl::hlsl::spirv::unpackSnorm4x8(v2).xyz); + } + break; + case OT_SPHERE: + case OT_CYLINDER: + case OT_ARROW: + case OT_CONE: + { + uint32_t v0 = vk::RawBufferLoad < uint32_t > (normalVertexBufferAddress + i0 * vertexStride); + uint32_t v1 = vk::RawBufferLoad < uint32_t > (normalVertexBufferAddress + i1 * vertexStride); + uint32_t v2 = vk::RawBufferLoad < uint32_t > (normalVertexBufferAddress + i2 * vertexStride); + + n0 = normalize(unpackNormals3x10(v0)); + n1 = normalize(unpackNormals3x10(v1)); + n2 = normalize(unpackNormals3x10(v2)); + } + break; + case OT_RECTANGLE: + case OT_DISK: + case OT_ICOSPHERE: + default: + { + n0 = vk::RawBufferLoad < float3 > (normalVertexBufferAddress + i0 * vertexStride); + n1 = vk::RawBufferLoad < float3 > (normalVertexBufferAddress + i1 * vertexStride); + n2 = vk::RawBufferLoad < float3 > (normalVertexBufferAddress + i2 * vertexStride); + } + } + + float3 barycentrics = float3(0.0, bary); + barycentrics.x = 1.0 - barycentrics.y - barycentrics.z; + return normalize(barycentrics.x * n0 + barycentrics.y * n1 + barycentrics.z * n2); +} +#endif + +namespace nbl +{ +namespace hlsl +{ +namespace impl +{ + +template<> +struct static_cast_helper +{ + static inline Material cast(MaterialPacked packed) + { + Material material; + material.ambient = unpackUnorm3x10(packed.ambient); + material.diffuse = unpackUnorm3x10(packed.diffuse); + material.specular = unpackUnorm3x10(packed.specular); + material.shininess = unpackUnorm22(packed.shininess); + material.alpha = unpackUnorm10(packed.alpha); + return material; + } +}; + +template<> +struct static_cast_helper +{ + static inline MaterialPacked cast(Material material) + { + MaterialPacked packed; + packed.ambient = packUnorm3x10(material.ambient); + packed.diffuse = packUnorm3x10(material.diffuse); + packed.specular = packUnorm3x10(material.specular); + packed.shininess = packUnorm22(material.shininess); + packed.alpha = packUnorm10(material.alpha); + return packed; + } +}; + +} +} +} + +#endif // RQG_COMMON_HLSL diff --git a/71_RayTracingPipeline/app_resources/light_directional.rcall.hlsl b/71_RayTracingPipeline/app_resources/light_directional.rcall.hlsl new file mode 100644 index 000000000..1eb18be34 --- /dev/null +++ b/71_RayTracingPipeline/app_resources/light_directional.rcall.hlsl @@ -0,0 +1,11 @@ +#include "common.hlsl" + +[[vk::push_constant]] SPushConstants pc; + +[shader("callable")] +void main(inout RayLight cLight) +{ + cLight.outLightDir = normalize(-pc.light.direction); + cLight.outIntensity = 1; + cLight.outLightDistance = 10000000; +} diff --git a/71_RayTracingPipeline/app_resources/light_point.rcall.hlsl b/71_RayTracingPipeline/app_resources/light_point.rcall.hlsl new file mode 100644 index 000000000..2265a98e7 --- /dev/null +++ b/71_RayTracingPipeline/app_resources/light_point.rcall.hlsl @@ -0,0 +1,13 @@ +#include "common.hlsl" + +[[vk::push_constant]] SPushConstants pc; + +[shader("callable")] +void main(inout RayLight cLight) +{ + float32_t3 lDir = pc.light.position - cLight.inHitPosition; + float lightDistance = length(lDir); + cLight.outIntensity = LightIntensity / (lightDistance * lightDistance); + cLight.outLightDir = normalize(lDir); + cLight.outLightDistance = lightDistance; +} \ No newline at end of file diff --git a/71_RayTracingPipeline/app_resources/light_spot.rcall.hlsl b/71_RayTracingPipeline/app_resources/light_spot.rcall.hlsl new file mode 100644 index 000000000..f298e4643 --- /dev/null +++ b/71_RayTracingPipeline/app_resources/light_spot.rcall.hlsl @@ -0,0 +1,16 @@ +#include "common.hlsl" + +[[vk::push_constant]] SPushConstants pc; + +[shader("callable")] +void main(inout RayLight cLight) +{ + float32_t3 lDir = pc.light.position - cLight.inHitPosition; + cLight.outLightDistance = length(lDir); + cLight.outIntensity = LightIntensity / (cLight.outLightDistance * cLight.outLightDistance); + cLight.outLightDir = normalize(lDir); + float theta = dot(cLight.outLightDir, normalize(-pc.light.direction)); + float epsilon = 1.f - pc.light.outerCutoff; + float spotIntensity = clamp((theta - pc.light.outerCutoff) / epsilon, 0.0, 1.0); + cLight.outIntensity *= spotIntensity; +} diff --git a/71_RayTracingPipeline/app_resources/present.frag.hlsl b/71_RayTracingPipeline/app_resources/present.frag.hlsl new file mode 100644 index 000000000..00ab6e31d --- /dev/null +++ b/71_RayTracingPipeline/app_resources/present.frag.hlsl @@ -0,0 +1,19 @@ +// Copyright (C) 2024-2024 - DevSH Graphics Programming Sp. z O.O. +// This file is part of the "Nabla Engine". +// For conditions of distribution and use, see copyright notice in nabla.h + +#pragma wave shader_stage(fragment) + +// vertex shader is provided by the fullScreenTriangle extension +#include +using namespace nbl::hlsl; +using namespace ext::FullScreenTriangle; + +// binding 0 set 0 +[[vk::combinedImageSampler]] [[vk::binding(0, 0)]] Texture2D texture; +[[vk::combinedImageSampler]] [[vk::binding(0, 0)]] SamplerState samplerState; + +[[vk::location(0)]] float32_t4 main(SVertexAttributes vxAttr) : SV_Target0 +{ + return float32_t4(texture.Sample(samplerState, vxAttr.uv).rgb, 1.0f); +} diff --git a/71_RayTracingPipeline/app_resources/raytrace.rahit.hlsl b/71_RayTracingPipeline/app_resources/raytrace.rahit.hlsl new file mode 100644 index 000000000..97713b3ec --- /dev/null +++ b/71_RayTracingPipeline/app_resources/raytrace.rahit.hlsl @@ -0,0 +1,14 @@ +#include "common.hlsl" + +[[vk::push_constant]] SPushConstants pc; + +[shader("anyhit")] +void main(inout PrimaryPayload payload, in BuiltInTriangleIntersectionAttributes attribs) +{ + const int instID = InstanceID(); + const STriangleGeomInfo geom = vk::RawBufferLoad < STriangleGeomInfo > (pc.triangleGeomInfoBuffer + instID * sizeof(STriangleGeomInfo)); + + const uint32_t bitpattern = payload.pcg(); + if (geom.material.alphaTest(bitpattern)) + IgnoreHit(); +} diff --git a/71_RayTracingPipeline/app_resources/raytrace.rchit.hlsl b/71_RayTracingPipeline/app_resources/raytrace.rchit.hlsl new file mode 100644 index 000000000..cf68e52eb --- /dev/null +++ b/71_RayTracingPipeline/app_resources/raytrace.rchit.hlsl @@ -0,0 +1,20 @@ +#include "common.hlsl" + +[[vk::push_constant]] SPushConstants pc; + + +[shader("closesthit")] +void main(inout PrimaryPayload payload, in BuiltInTriangleIntersectionAttributes attribs) +{ + const int instID = InstanceID(); + const int primID = PrimitiveIndex(); + const STriangleGeomInfo geom = vk::RawBufferLoad < STriangleGeomInfo > (pc.triangleGeomInfoBuffer + instID * sizeof(STriangleGeomInfo)); + const float32_t3 vertexNormal = fetchVertexNormal(instID, primID, geom, attribs.barycentrics); + const float32_t3 worldNormal = normalize(mul(vertexNormal, WorldToObject3x4()).xyz); + + payload.materialId = MaterialId::createTriangle(instID); + + payload.worldNormal = worldNormal; + payload.rayDistance = RayTCurrent(); + +} \ No newline at end of file diff --git a/71_RayTracingPipeline/app_resources/raytrace.rgen.hlsl b/71_RayTracingPipeline/app_resources/raytrace.rgen.hlsl new file mode 100644 index 000000000..55b014d07 --- /dev/null +++ b/71_RayTracingPipeline/app_resources/raytrace.rgen.hlsl @@ -0,0 +1,130 @@ +#include "common.hlsl" + +#include "nbl/builtin/hlsl/jit/device_capabilities.hlsl" +#include "nbl/builtin/hlsl/random/xoroshiro.hlsl" + +#include "nbl/builtin/hlsl/glsl_compat/core.hlsl" +#include "nbl/builtin/hlsl/spirv_intrinsics/raytracing.hlsl" + +static const int32_t s_sampleCount = 10; +static const float32_t3 s_clearColor = float32_t3(0.3, 0.3, 0.8); + +[[vk::push_constant]] SPushConstants pc; + +[[vk::binding(0, 0)]] RaytracingAccelerationStructure topLevelAS; + +[[vk::binding(1, 0)]] RWTexture2D colorImage; + +float32_t nextRandomUnorm(inout nbl::hlsl::Xoroshiro64StarStar rnd) +{ + return float32_t(rnd()) / float32_t(0xFFFFFFFF); +} + +[shader("raygeneration")] +void main() +{ + const uint32_t3 launchID = DispatchRaysIndex(); + const uint32_t3 launchSize = DispatchRaysDimensions(); + const uint32_t2 coords = launchID.xy; + + const uint32_t seed1 = nbl::hlsl::random::Pcg::create(pc.frameCounter)(); + const uint32_t seed2 = nbl::hlsl::random::Pcg::create(launchID.y * launchSize.x + launchID.x)(); + nbl::hlsl::Xoroshiro64StarStar rnd = nbl::hlsl::Xoroshiro64StarStar::construct(uint32_t2(seed1, seed2)); + + float32_t3 hitValues = float32_t3(0, 0, 0); + for (uint32_t sample_i = 0; sample_i < s_sampleCount; sample_i++) + { + const float32_t r1 = nextRandomUnorm(rnd); + const float32_t r2 = nextRandomUnorm(rnd); + const float32_t2 subpixelJitter = pc.frameCounter == 0 ? float32_t2(0.5f, 0.5f) : float32_t2(r1, r2); + + const float32_t2 pixelCenter = float32_t2(coords) + subpixelJitter; + const float32_t2 inUV = pixelCenter / float32_t2(launchSize.xy); + + const float32_t2 d = inUV * 2.0 - 1.0; + const float32_t4 tmp = mul(pc.invMVP, float32_t4(d.x, d.y, 1, 1)); + const float32_t3 targetPos = tmp.xyz / tmp.w; + + const float32_t3 camDirection = normalize(targetPos - pc.camPos); + + RayDesc rayDesc; + rayDesc.Origin = pc.camPos; + rayDesc.Direction = camDirection; + rayDesc.TMin = 0.01; + rayDesc.TMax = 10000.0; + + PrimaryPayload payload; + payload.pcg = PrimaryPayload::generator_t::create(rnd()); + TraceRay(topLevelAS, RAY_FLAG_NONE, 0xff, ERT_PRIMARY, 0, EMT_PRIMARY, rayDesc, payload); + + const float32_t rayDistance = payload.rayDistance; + if (rayDistance < 0) + { + hitValues += s_clearColor; + continue; + } + + const float32_t3 worldPosition = pc.camPos + (camDirection * rayDistance); + + // make sure to call with least live state + RayLight cLight; + cLight.inHitPosition = worldPosition; + CallShader(pc.light.type, cLight); + + const float32_t3 worldNormal = payload.worldNormal; + + Material material; + MaterialId materialId = payload.materialId; + // we use negative index to indicate that this is a procedural geometry + if (materialId.isHitProceduralGeom()) + { + const MaterialPacked materialPacked = vk::RawBufferLoad(pc.proceduralGeomInfoBuffer + materialId.getMaterialIndex() * sizeof(SProceduralGeomInfo)); + material = nbl::hlsl::_static_cast(materialPacked); + } + else + { + const MaterialPacked materialPacked = vk::RawBufferLoad(pc.triangleGeomInfoBuffer + materialId.getMaterialIndex() * sizeof(STriangleGeomInfo)); + material = nbl::hlsl::_static_cast(materialPacked); + } + + float32_t attenuation = 1; + + if (dot(worldNormal, cLight.outLightDir) > 0) + { + RayDesc rayDesc; + rayDesc.Origin = worldPosition; + rayDesc.Direction = cLight.outLightDir; + rayDesc.TMin = 0.01; + rayDesc.TMax = cLight.outLightDistance; + + OcclusionPayload occlusionPayload; + // negative means its a hit, the miss shader will flip it back around to positive + occlusionPayload.attenuation = -1.f; + // abuse of miss shader to mean "not hit shader" solves us having to call closest hit shaders + uint32_t shadowRayFlags = RAY_FLAG_ACCEPT_FIRST_HIT_AND_END_SEARCH | RAY_FLAG_SKIP_CLOSEST_HIT_SHADER; + TraceRay(topLevelAS, shadowRayFlags, 0xFF, ERT_OCCLUSION, 0, EMT_OCCLUSION, rayDesc, occlusionPayload); + + attenuation = occlusionPayload.attenuation; + if (occlusionPayload.attenuation > 1.f/1024.f) + { + const float32_t3 diffuse = computeDiffuse(material, cLight.outLightDir, worldNormal); + const float32_t3 specular = computeSpecular(material, camDirection, cLight.outLightDir, worldNormal); + hitValues += (cLight.outIntensity * attenuation * (diffuse + specular)); + } + } + hitValues += material.ambient; + } + + const float32_t3 hitValue = hitValues / s_sampleCount; + + if (pc.frameCounter > 0) + { + float32_t a = 1.0f / float32_t(pc.frameCounter + 1); + float32_t3 oldColor = colorImage[coords].xyz; + colorImage[coords] = float32_t4(lerp(oldColor, hitValue, a), 1.0f); + } + else + { + colorImage[coords] = float32_t4(hitValue, 1.0f); + } +} diff --git a/71_RayTracingPipeline/app_resources/raytrace.rint.hlsl b/71_RayTracingPipeline/app_resources/raytrace.rint.hlsl new file mode 100644 index 000000000..d081c9248 --- /dev/null +++ b/71_RayTracingPipeline/app_resources/raytrace.rint.hlsl @@ -0,0 +1,47 @@ +#include "common.hlsl" + +[[vk::push_constant]] SPushConstants pc; + +struct Ray +{ + float32_t3 origin; + float32_t3 direction; +}; + +// Ray-Sphere intersection +// http://viclw17.github.io/2018/07/16/raytracing-ray-sphere-intersection/ +float32_t hitSphere(SProceduralGeomInfo s, Ray r) +{ + float32_t3 oc = r.origin - s.center; + float32_t a = dot(r.direction, r.direction); + float32_t b = 2.0 * dot(oc, r.direction); + float32_t c = dot(oc, oc) - s.radius * s.radius; + float32_t discriminant = b * b - 4 * a * c; + + // return whatever, if the discriminant is negative, it will produce a NaN, and NaN will compare false + return (-b - sqrt(discriminant)) / (2.0 * a); +} + +[shader("intersection")] +void main() +{ + Ray ray; + ray.origin = WorldRayOrigin(); + ray.direction = WorldRayDirection(); + + const int primID = PrimitiveIndex(); + + // Sphere data + SProceduralGeomInfo sphere = vk::RawBufferLoad(pc.proceduralGeomInfoBuffer + primID * sizeof(SProceduralGeomInfo)); + + const float32_t tHit = hitSphere(sphere, ray); + + ProceduralHitAttribute hitAttrib; + + // Report hit point + if (tHit > 0) + { + hitAttrib.center = sphere.center; + ReportHit(tHit, 0, hitAttrib); + } +} \ No newline at end of file diff --git a/71_RayTracingPipeline/app_resources/raytrace.rmiss.hlsl b/71_RayTracingPipeline/app_resources/raytrace.rmiss.hlsl new file mode 100644 index 000000000..5ccfed470 --- /dev/null +++ b/71_RayTracingPipeline/app_resources/raytrace.rmiss.hlsl @@ -0,0 +1,7 @@ +#include "common.hlsl" + +[shader("miss")] +void main(inout PrimaryPayload payload) +{ + payload.rayDistance = -1; +} diff --git a/71_RayTracingPipeline/app_resources/raytrace_procedural.rchit.hlsl b/71_RayTracingPipeline/app_resources/raytrace_procedural.rchit.hlsl new file mode 100644 index 000000000..df9ef9623 --- /dev/null +++ b/71_RayTracingPipeline/app_resources/raytrace_procedural.rchit.hlsl @@ -0,0 +1,16 @@ +#include "common.hlsl" + +[[vk::push_constant]] SPushConstants pc; + +[shader("closesthit")] +void main(inout PrimaryPayload payload, in ProceduralHitAttribute attrib) +{ + const float32_t3 worldPosition = WorldRayOrigin() + WorldRayDirection() * RayTCurrent(); + const float32_t3 worldNormal = normalize(worldPosition - attrib.center); + + payload.materialId = MaterialId::createProcedural(PrimitiveIndex()); // we use negative value to indicate that this is procedural + + payload.worldNormal = worldNormal; + payload.rayDistance = RayTCurrent(); + +} \ No newline at end of file diff --git a/71_RayTracingPipeline/app_resources/raytrace_shadow.rahit.hlsl b/71_RayTracingPipeline/app_resources/raytrace_shadow.rahit.hlsl new file mode 100644 index 000000000..a3432b812 --- /dev/null +++ b/71_RayTracingPipeline/app_resources/raytrace_shadow.rahit.hlsl @@ -0,0 +1,20 @@ +#include "common.hlsl" +#include "nbl/builtin/hlsl/spirv_intrinsics/raytracing.hlsl" + +[[vk::push_constant]] SPushConstants pc; + +[shader("anyhit")] +void main(inout OcclusionPayload payload, in BuiltInTriangleIntersectionAttributes attribs) +{ + const int instID = InstanceID(); + const STriangleGeomInfo geom = vk::RawBufferLoad < STriangleGeomInfo > (pc.triangleGeomInfoBuffer + instID * sizeof(STriangleGeomInfo)); + const Material material = nbl::hlsl::_static_cast(geom.material); + + const float attenuation = (1.f-material.alpha) * payload.attenuation; + // DXC cogegens weird things in the presence of termination instructions + payload.attenuation = attenuation; + // arbitrary constant, whatever you want the smallest attenuation to be. Remember until miss, the attenuatio is negative + if (attenuation > -1.f/1024.f) + AcceptHitAndEndSearch(); + IgnoreHit(); +} diff --git a/71_RayTracingPipeline/app_resources/raytrace_shadow.rmiss.hlsl b/71_RayTracingPipeline/app_resources/raytrace_shadow.rmiss.hlsl new file mode 100644 index 000000000..441a1b42a --- /dev/null +++ b/71_RayTracingPipeline/app_resources/raytrace_shadow.rmiss.hlsl @@ -0,0 +1,8 @@ +#include "common.hlsl" + +[shader("miss")] +void main(inout OcclusionPayload payload) +{ + // make positive + payload.attenuation = -payload.attenuation; +} diff --git a/71_RayTracingPipeline/docs/Images/final_result.png b/71_RayTracingPipeline/docs/Images/final_result.png new file mode 100644 index 000000000..af1f2b9b8 Binary files /dev/null and b/71_RayTracingPipeline/docs/Images/final_result.png differ diff --git a/71_RayTracingPipeline/docs/Images/shader_binding_table.png b/71_RayTracingPipeline/docs/Images/shader_binding_table.png new file mode 100644 index 000000000..b146adeec Binary files /dev/null and b/71_RayTracingPipeline/docs/Images/shader_binding_table.png differ diff --git a/71_RayTracingPipeline/include/common.hpp b/71_RayTracingPipeline/include/common.hpp new file mode 100644 index 000000000..184d424c7 --- /dev/null +++ b/71_RayTracingPipeline/include/common.hpp @@ -0,0 +1,84 @@ +#ifndef _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ +#define _NBL_THIS_EXAMPLE_COMMON_H_INCLUDED_ + +#include "nbl/examples/examples.hpp" + +using namespace nbl; +using namespace nbl::core; +using namespace nbl::hlsl; +using namespace nbl::system; +using namespace nbl::asset; +using namespace nbl::ui; +using namespace nbl::video; +using namespace nbl::application_templates; +using namespace nbl::examples; + +#include "nbl/ui/ICursorControl.h" +#include "nbl/ext/ImGui/ImGui.h" +#include "imgui/imgui_internal.h" + +#include "app_resources/common.hlsl" + +namespace nbl::scene +{ + +enum ObjectType : uint8_t +{ + OT_CUBE, + OT_SPHERE, + OT_CYLINDER, + OT_RECTANGLE, + OT_DISK, + OT_ARROW, + OT_CONE, + OT_ICOSPHERE, + + OT_COUNT, + OT_UNKNOWN = std::numeric_limits::max() +}; + +static constexpr uint32_t s_smoothNormals[OT_COUNT] = { 0, 1, 1, 0, 0, 1, 1, 1 }; + +struct ObjectMeta +{ + ObjectType type = OT_UNKNOWN; + std::string_view name = "Unknown"; +}; + +struct ObjectDrawHookCpu +{ + nbl::core::matrix3x4SIMD model; + ObjectMeta meta; +}; + +struct ReferenceObjectCpu +{ + ObjectMeta meta; + core::smart_refctd_ptr data; + Material material; + core::matrix3x4SIMD transform; +}; + +struct ReferenceObjectGpu +{ + struct Bindings + { + nbl::asset::SBufferBinding vertex, index; + }; + + ObjectMeta meta; + Bindings bindings; + uint32_t vertexStride; + nbl::asset::E_INDEX_TYPE indexType = nbl::asset::E_INDEX_TYPE::EIT_UNKNOWN; + uint32_t indexCount = {}; + MaterialPacked material; + core::matrix3x4SIMD transform; + + const bool useIndex() const + { + return bindings.index.buffer && (indexType != E_INDEX_TYPE::EIT_UNKNOWN); + } +}; +} + +#endif // __NBL_THIS_EXAMPLE_COMMON_H_INCLUDED__ diff --git a/71_RayTracingPipeline/main.cpp b/71_RayTracingPipeline/main.cpp new file mode 100644 index 000000000..382e5cccb --- /dev/null +++ b/71_RayTracingPipeline/main.cpp @@ -0,0 +1,1539 @@ +// Copyright (C) 2018-2024 - DevSH Graphics Programming Sp. z O.O. +// This file is part of the "Nabla Engine". +// For conditions of distribution and use, see copyright notice in nabla.h +#include "common.hpp" + +#include "nbl/ext/FullScreenTriangle/FullScreenTriangle.h" +#include "nbl/builtin/hlsl/indirect_commands.hlsl" + + +class RaytracingPipelineApp final : public SimpleWindowedApplication, public application_templates::MonoAssetManagerAndBuiltinResourceApplication +{ + using device_base_t = SimpleWindowedApplication; + using asset_base_t = application_templates::MonoAssetManagerAndBuiltinResourceApplication; + using clock_t = std::chrono::steady_clock; + + constexpr static inline uint32_t WIN_W = 1280, WIN_H = 720; + constexpr static inline uint32_t MaxFramesInFlight = 3u; + constexpr static inline uint8_t MaxUITextureCount = 1u; + constexpr static inline uint32_t NumberOfProceduralGeometries = 5; + + static constexpr const char* s_lightTypeNames[E_LIGHT_TYPE::ELT_COUNT] = { + "Directional", + "Point", + "Spot" + }; + + struct ShaderBindingTable + { + SBufferRange raygenGroupRange; + SBufferRange hitGroupsRange; + uint32_t hitGroupsStride; + SBufferRange missGroupsRange; + uint32_t missGroupsStride; + SBufferRange callableGroupsRange; + uint32_t callableGroupsStride; + }; + + +public: + inline RaytracingPipelineApp(const path& _localInputCWD, const path& _localOutputCWD, const path& _sharedInputCWD, const path& _sharedOutputCWD) + : IApplicationFramework(_localInputCWD, _localOutputCWD, _sharedInputCWD, _sharedOutputCWD) + { + } + + inline SPhysicalDeviceFeatures getRequiredDeviceFeatures() const override + { + auto retval = device_base_t::getRequiredDeviceFeatures(); + retval.rayTracingPipeline = true; + retval.accelerationStructure = true; + retval.rayQuery = true; + return retval; + } + + inline SPhysicalDeviceFeatures getPreferredDeviceFeatures() const override + { + auto retval = device_base_t::getPreferredDeviceFeatures(); + retval.accelerationStructureHostCommands = true; + return retval; + } + + inline core::vector getSurfaces() const override + { + if (!m_surface) + { + { + auto windowCallback = core::make_smart_refctd_ptr(smart_refctd_ptr(m_inputSystem), smart_refctd_ptr(m_logger)); + IWindow::SCreationParams params = {}; + params.callback = core::make_smart_refctd_ptr(); + params.width = WIN_W; + params.height = WIN_H; + params.x = 32; + params.y = 32; + params.flags = ui::IWindow::ECF_HIDDEN | IWindow::ECF_BORDERLESS | IWindow::ECF_RESIZABLE; + params.windowCaption = "RaytracingPipelineApp"; + params.callback = windowCallback; + const_cast&>(m_window) = m_winMgr->createWindow(std::move(params)); + } + + auto surface = CSurfaceVulkanWin32::create(smart_refctd_ptr(m_api), smart_refctd_ptr_static_cast(m_window)); + const_cast&>(m_surface) = CSimpleResizeSurface::create(std::move(surface)); + } + + if (m_surface) + return { {m_surface->getSurface()/*,EQF_NONE*/} }; + + return {}; + } + + // so that we can use the same queue for asset converter and rendering + inline core::vector getQueueRequirements() const override + { + auto reqs = device_base_t::getQueueRequirements(); + reqs.front().requiredFlags |= IQueue::FAMILY_FLAGS::COMPUTE_BIT; + return reqs; + } + + inline bool onAppInitialized(smart_refctd_ptr&& system) override + { + m_inputSystem = make_smart_refctd_ptr(logger_opt_smart_ptr(smart_refctd_ptr(m_logger))); + + if (!device_base_t::onAppInitialized(smart_refctd_ptr(system))) + return false; + + if (!asset_base_t::onAppInitialized(smart_refctd_ptr(system))) + return false; + + smart_refctd_ptr shaderReadCache = nullptr; + smart_refctd_ptr shaderWriteCache = core::make_smart_refctd_ptr(); + auto shaderCachePath = localOutputCWD / "main_pipeline_shader_cache.bin"; + + { + core::smart_refctd_ptr shaderReadCacheFile; + { + system::ISystem::future_t> future; + m_system->createFile(future, shaderCachePath.c_str(), system::IFile::ECF_READ); + if (future.wait()) + { + future.acquire().move_into(shaderReadCacheFile); + if (shaderReadCacheFile) + { + const size_t size = shaderReadCacheFile->getSize(); + if (size > 0ull) + { + std::vector contents(size); + system::IFile::success_t succ; + shaderReadCacheFile->read(succ, contents.data(), 0, size); + if (succ) + shaderReadCache = IShaderCompiler::CCache::deserialize(contents); + } + } + } + else + m_logger->log("Failed Openning Shader Cache File.", ILogger::ELL_ERROR); + } + + } + + // Load Custom Shader + auto loadCompileAndCreateShader = [&](const std::string& relPath) -> smart_refctd_ptr + { + IAssetLoader::SAssetLoadParams lp = {}; + lp.logger = m_logger.get(); + lp.workingDirectory = ""; // virtual root + auto assetBundle = m_assetMgr->getAsset(relPath, lp); + const auto assets = assetBundle.getContents(); + if (assets.empty()) + return nullptr; + + // lets go straight from ICPUSpecializedShader to IGPUSpecializedShader + auto sourceRaw = IAsset::castDown(assets[0]); + if (!sourceRaw) + return nullptr; + + return m_device->compileShader({ sourceRaw.get(), nullptr, shaderReadCache.get(), shaderWriteCache.get() }); + }; + + // load shaders + const auto raygenShader = loadCompileAndCreateShader("app_resources/raytrace.rgen.hlsl"); + const auto closestHitShader = loadCompileAndCreateShader("app_resources/raytrace.rchit.hlsl"); + const auto proceduralClosestHitShader = loadCompileAndCreateShader("app_resources/raytrace_procedural.rchit.hlsl"); + const auto intersectionHitShader = loadCompileAndCreateShader("app_resources/raytrace.rint.hlsl"); + const auto anyHitShaderColorPayload = loadCompileAndCreateShader("app_resources/raytrace.rahit.hlsl"); + const auto anyHitShaderShadowPayload = loadCompileAndCreateShader("app_resources/raytrace_shadow.rahit.hlsl"); + const auto missShader = loadCompileAndCreateShader("app_resources/raytrace.rmiss.hlsl"); + const auto missShadowShader = loadCompileAndCreateShader("app_resources/raytrace_shadow.rmiss.hlsl"); + const auto directionalLightCallShader = loadCompileAndCreateShader("app_resources/light_directional.rcall.hlsl"); + const auto pointLightCallShader = loadCompileAndCreateShader("app_resources/light_point.rcall.hlsl"); + const auto spotLightCallShader = loadCompileAndCreateShader("app_resources/light_spot.rcall.hlsl"); + const auto fragmentShader = loadCompileAndCreateShader("app_resources/present.frag.hlsl"); + + core::smart_refctd_ptr shaderWriteCacheFile; + { + system::ISystem::future_t> future; + m_system->deleteFile(shaderCachePath); // temp solution instead of trimming, to make sure we won't have corrupted json + m_system->createFile(future, shaderCachePath.c_str(), system::IFile::ECF_WRITE); + if (future.wait()) + { + future.acquire().move_into(shaderWriteCacheFile); + if (shaderWriteCacheFile) + { + auto serializedCache = shaderWriteCache->serialize(); + if (shaderWriteCacheFile) + { + system::IFile::success_t succ; + shaderWriteCacheFile->write(succ, serializedCache->getPointer(), 0, serializedCache->getSize()); + if (!succ) + m_logger->log("Failed Writing To Shader Cache File.", ILogger::ELL_ERROR); + } + } + else + m_logger->log("Failed Creating Shader Cache File.", ILogger::ELL_ERROR); + } + else + m_logger->log("Failed Creating Shader Cache File.", ILogger::ELL_ERROR); + } + + m_semaphore = m_device->createSemaphore(m_realFrameIx); + if (!m_semaphore) + return logFail("Failed to Create a Semaphore!"); + + auto gQueue = getGraphicsQueue(); + + // Create renderpass and init surface + nbl::video::IGPURenderpass* renderpass; + { + ISwapchain::SCreationParams swapchainParams = { .surface = smart_refctd_ptr(m_surface->getSurface()) }; + if (!swapchainParams.deduceFormat(m_physicalDevice)) + return logFail("Could not choose a Surface Format for the Swapchain!"); + + const static IGPURenderpass::SCreationParams::SSubpassDependency dependencies[] = + { + { + .srcSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .dstSubpass = 0, + .memoryBarrier = + { + .srcStageMask = asset::PIPELINE_STAGE_FLAGS::COPY_BIT, + .srcAccessMask = asset::ACCESS_FLAGS::TRANSFER_WRITE_BIT, + .dstStageMask = asset::PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + .dstAccessMask = asset::ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + } + }, + { + .srcSubpass = 0, + .dstSubpass = IGPURenderpass::SCreationParams::SSubpassDependency::External, + .memoryBarrier = + { + .srcStageMask = asset::PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = asset::ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + } + }, + IGPURenderpass::SCreationParams::DependenciesEnd + }; + + auto scResources = std::make_unique(m_device.get(), swapchainParams.surfaceFormat.format, dependencies); + renderpass = scResources->getRenderpass(); + + if (!renderpass) + return logFail("Failed to create Renderpass!"); + + if (!m_surface || !m_surface->init(gQueue, std::move(scResources), swapchainParams.sharedParams)) + return logFail("Could not create Window & Surface or initialize the Surface!"); + } + + auto pool = m_device->createCommandPool(gQueue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); + + m_converter = CAssetConverter::create({ .device = m_device.get(), .optimizer = {} }); + + for (auto i = 0u; i < MaxFramesInFlight; i++) + { + if (!pool) + return logFail("Couldn't create Command Pool!"); + if (!pool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY, { m_cmdBufs.data() + i, 1 })) + return logFail("Couldn't create Command Buffer!"); + } + + m_winMgr->setWindowSize(m_window.get(), WIN_W, WIN_H); + m_surface->recreateSwapchain(); + + + // create output images + m_hdrImage = m_device->createImage({ + { + .type = IGPUImage::ET_2D, + .samples = ICPUImage::ESCF_1_BIT, + .format = EF_R16G16B16A16_SFLOAT, + .extent = {WIN_W, WIN_H, 1}, + .mipLevels = 1, + .arrayLayers = 1, + .flags = IImage::ECF_NONE, + .usage = bitflag(IImage::EUF_STORAGE_BIT) | IImage::EUF_TRANSFER_SRC_BIT | IImage::EUF_SAMPLED_BIT + } + }); + + if (!m_hdrImage || !m_device->allocate(m_hdrImage->getMemoryReqs(), m_hdrImage.get()).isValid()) + return logFail("Could not create HDR Image"); + + m_hdrImageView = m_device->createImageView({ + .flags = IGPUImageView::ECF_NONE, + .subUsages = IGPUImage::E_USAGE_FLAGS::EUF_STORAGE_BIT | IGPUImage::E_USAGE_FLAGS::EUF_SAMPLED_BIT, + .image = m_hdrImage, + .viewType = IGPUImageView::E_TYPE::ET_2D, + .format = asset::EF_R16G16B16A16_SFLOAT + }); + + + + // ray trace pipeline and descriptor set layout setup + { + const IGPUDescriptorSetLayout::SBinding bindings[] = { + { + .binding = 0, + .type = asset::IDescriptor::E_TYPE::ET_ACCELERATION_STRUCTURE, + .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_RAYGEN, + .count = 1, + }, + { + .binding = 1, + .type = asset::IDescriptor::E_TYPE::ET_STORAGE_IMAGE, + .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_RAYGEN, + .count = 1, + } + }; + const auto descriptorSetLayout = m_device->createDescriptorSetLayout(bindings); + + const std::array dsLayoutPtrs = { descriptorSetLayout.get() }; + m_rayTracingDsPool = m_device->createDescriptorPoolForDSLayouts(IDescriptorPool::ECF_UPDATE_AFTER_BIND_BIT, std::span(dsLayoutPtrs.begin(), dsLayoutPtrs.end())); + m_rayTracingDs = m_rayTracingDsPool->createDescriptorSet(descriptorSetLayout); + + const SPushConstantRange pcRange = { + .stageFlags = IShader::E_SHADER_STAGE::ESS_ALL_RAY_TRACING, + .offset = 0u, + .size = sizeof(SPushConstants), + }; + const auto pipelineLayout = m_device->createPipelineLayout({ &pcRange, 1 }, smart_refctd_ptr(descriptorSetLayout), nullptr, nullptr, nullptr); + + IGPURayTracingPipeline::SCreationParams params = {}; + params.layout = pipelineLayout.get(); + using RayTracingFlags = IGPURayTracingPipeline::SCreationParams::FLAGS; + params.flags = core::bitflag(RayTracingFlags::NO_NULL_MISS_SHADERS) | + RayTracingFlags::NO_NULL_INTERSECTION_SHADERS | + RayTracingFlags::NO_NULL_ANY_HIT_SHADERS; + + auto& shaderGroups = params.shaderGroups; + + shaderGroups.raygen = { .shader = raygenShader.get(), .entryPoint = "main" }; + + IGPUPipelineBase::SShaderSpecInfo missGroups[EMT_COUNT]; + missGroups[EMT_PRIMARY] = { .shader = missShader.get(), .entryPoint = "main" }; + missGroups[EMT_OCCLUSION] = { .shader = missShadowShader.get(), .entryPoint = "main" }; + shaderGroups.misses = missGroups; + + auto getHitGroupIndex = [](E_GEOM_TYPE geomType, E_RAY_TYPE rayType) + { + return geomType * ERT_COUNT + rayType; + }; + IGPURayTracingPipeline::SHitGroup hitGroups[E_RAY_TYPE::ERT_COUNT * E_GEOM_TYPE::EGT_COUNT]; + hitGroups[getHitGroupIndex(EGT_TRIANGLES, ERT_PRIMARY)] = { + .closestHit = { .shader = closestHitShader.get(), .entryPoint = "main" }, + .anyHit = { .shader = anyHitShaderColorPayload.get(), .entryPoint = "main" }, + }; + hitGroups[getHitGroupIndex(EGT_TRIANGLES, ERT_OCCLUSION)] = { + .anyHit = { .shader = anyHitShaderShadowPayload.get(), .entryPoint = "main" }, + }; + hitGroups[getHitGroupIndex(EGT_PROCEDURAL, ERT_PRIMARY)] = { + .closestHit = { .shader = proceduralClosestHitShader.get(), .entryPoint = "main" }, + .anyHit = { .shader = anyHitShaderColorPayload.get(), .entryPoint = "main" }, + .intersection = { .shader = intersectionHitShader.get(), .entryPoint = "main" }, + }; + hitGroups[getHitGroupIndex(EGT_PROCEDURAL, ERT_OCCLUSION)] = { + .anyHit = { .shader = anyHitShaderShadowPayload.get(), .entryPoint = "main" }, + .intersection = { .shader = intersectionHitShader.get(), .entryPoint = "main" }, + }; + shaderGroups.hits = hitGroups; + + IGPUPipelineBase::SShaderSpecInfo callableGroups[ELT_COUNT]; + callableGroups[ELT_DIRECTIONAL] = { .shader = directionalLightCallShader.get(), .entryPoint = "main" }; + callableGroups[ELT_POINT] = { .shader = pointLightCallShader.get(), .entryPoint = "main" }; + callableGroups[ELT_SPOT] = { .shader = spotLightCallShader.get(), .entryPoint = "main" }; + shaderGroups.callables = callableGroups; + + params.cached.maxRecursionDepth = 1; + params.cached.dynamicStackSize = true; + + if (!m_device->createRayTracingPipelines(nullptr, { ¶ms, 1 }, &m_rayTracingPipeline)) + return logFail("Failed to create ray tracing pipeline"); + + calculateRayTracingStackSize(m_rayTracingPipeline); + + if (!createShaderBindingTable(m_rayTracingPipeline)) + return logFail("Could not create shader binding table"); + + } + + auto assetManager = make_smart_refctd_ptr(smart_refctd_ptr(system)); + + if (!createIndirectBuffer()) + return logFail("Could not create indirect buffer"); + + if (!createAccelerationStructuresFromGeometry()) + return logFail("Could not create acceleration structures from geometry creator"); + + ISampler::SParams samplerParams = { + .AnisotropicFilter = 0 + }; + auto defaultSampler = m_device->createSampler(samplerParams); + + { + const IGPUDescriptorSetLayout::SBinding bindings[] = { + { + .binding = 0u, + .type = nbl::asset::IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER, + .createFlags = ICPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, + .stageFlags = IShader::E_SHADER_STAGE::ESS_FRAGMENT, + .count = 1u, + .immutableSamplers = &defaultSampler + } + }; + auto gpuPresentDescriptorSetLayout = m_device->createDescriptorSetLayout(bindings); + const video::IGPUDescriptorSetLayout* const layouts[] = { gpuPresentDescriptorSetLayout.get() }; + const uint32_t setCounts[] = { 1u }; + m_presentDsPool = m_device->createDescriptorPoolForDSLayouts(IDescriptorPool::E_CREATE_FLAGS::ECF_NONE, layouts, setCounts); + m_presentDs = m_presentDsPool->createDescriptorSet(gpuPresentDescriptorSetLayout); + + auto scRes = static_cast(m_surface->getSwapchainResources()); + ext::FullScreenTriangle::ProtoPipeline fsTriProtoPPln(m_assetMgr.get(), m_device.get(), m_logger.get()); + if (!fsTriProtoPPln) + return logFail("Failed to create Full Screen Triangle protopipeline or load its vertex shader!"); + + const IGPUPipelineBase::SShaderSpecInfo fragSpec = { + .shader = fragmentShader.get(), + .entryPoint = "main", + }; + + auto presentLayout = m_device->createPipelineLayout( + {}, + core::smart_refctd_ptr(gpuPresentDescriptorSetLayout), + nullptr, + nullptr, + nullptr + ); + m_presentPipeline = fsTriProtoPPln.createPipeline(fragSpec, presentLayout.get(), scRes->getRenderpass()); + if (!m_presentPipeline) + return logFail("Could not create Graphics Pipeline!"); + } + + // write descriptors + IGPUDescriptorSet::SDescriptorInfo infos[3]; + infos[0].desc = m_gpuTlas; + + infos[1].desc = m_hdrImageView; + if (!infos[1].desc) + return logFail("Failed to create image view"); + infos[1].info.image.imageLayout = IImage::LAYOUT::GENERAL; + + infos[2].desc = m_hdrImageView; + infos[2].info.image.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; + + IGPUDescriptorSet::SWriteDescriptorSet writes[] = { + {.dstSet = m_rayTracingDs.get(), .binding = 0, .arrayElement = 0, .count = 1, .info = &infos[0]}, + {.dstSet = m_rayTracingDs.get(), .binding = 1, .arrayElement = 0, .count = 1, .info = &infos[1]}, + {.dstSet = m_presentDs.get(), .binding = 0, .arrayElement = 0, .count = 1, .info = &infos[2] }, + }; + m_device->updateDescriptorSets(std::span(writes), {}); + + // gui descriptor setup + { + using binding_flags_t = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS; + { + IGPUSampler::SParams params; + params.AnisotropicFilter = 1u; + params.TextureWrapU = ETC_REPEAT; + params.TextureWrapV = ETC_REPEAT; + params.TextureWrapW = ETC_REPEAT; + + m_ui.samplers.gui = m_device->createSampler(params); + m_ui.samplers.gui->setObjectDebugName("Nabla IMGUI UI Sampler"); + } + + std::array, 69u> immutableSamplers; + for (auto& it : immutableSamplers) + it = smart_refctd_ptr(m_ui.samplers.scene); + + immutableSamplers[nbl::ext::imgui::UI::FontAtlasTexId] = smart_refctd_ptr(m_ui.samplers.gui); + + nbl::ext::imgui::UI::SCreationParameters params; + + params.resources.texturesInfo = { .setIx = 0u, .bindingIx = 0u }; + params.resources.samplersInfo = { .setIx = 0u, .bindingIx = 1u }; + params.assetManager = m_assetMgr; + params.pipelineCache = nullptr; + params.pipelineLayout = nbl::ext::imgui::UI::createDefaultPipelineLayout(m_utils->getLogicalDevice(), params.resources.texturesInfo, params.resources.samplersInfo, MaxUITextureCount); + params.renderpass = smart_refctd_ptr(renderpass); + params.streamingBuffer = nullptr; + params.subpassIx = 0u; + params.transfer = getGraphicsQueue(); + params.utilities = m_utils; + { + m_ui.manager = ext::imgui::UI::create(std::move(params)); + + // note that we use default layout provided by our extension, but you are free to create your own by filling nbl::ext::imgui::UI::S_CREATION_PARAMETERS::resources + const auto* descriptorSetLayout = m_ui.manager->getPipeline()->getLayout()->getDescriptorSetLayout(0u); + const auto& params = m_ui.manager->getCreationParameters(); + + IDescriptorPool::SCreateInfo descriptorPoolInfo = {}; + descriptorPoolInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_SAMPLER)] = (uint32_t)nbl::ext::imgui::UI::DefaultSamplerIx::COUNT; + descriptorPoolInfo.maxDescriptorCount[static_cast(asset::IDescriptor::E_TYPE::ET_SAMPLED_IMAGE)] = MaxUITextureCount; + descriptorPoolInfo.maxSets = 1u; + descriptorPoolInfo.flags = IDescriptorPool::E_CREATE_FLAGS::ECF_UPDATE_AFTER_BIND_BIT; + + m_guiDescriptorSetPool = m_device->createDescriptorPool(std::move(descriptorPoolInfo)); + assert(m_guiDescriptorSetPool); + + m_guiDescriptorSetPool->createDescriptorSets(1u, &descriptorSetLayout, &m_ui.descriptorSet); + assert(m_ui.descriptorSet); + } + } + + m_ui.manager->registerListener( + [this]() -> void { + ImGuiIO& io = ImGui::GetIO(); + + m_camera.setProjectionMatrix([&]() + { + static matrix4SIMD projection; + + projection = matrix4SIMD::buildProjectionMatrixPerspectiveFovRH( + core::radians(m_cameraSetting.fov), + io.DisplaySize.x / io.DisplaySize.y, + m_cameraSetting.zNear, + m_cameraSetting.zFar); + + return projection; + }()); + + ImGui::SetNextWindowPos(ImVec2(1024, 100), ImGuiCond_Appearing); + ImGui::SetNextWindowSize(ImVec2(256, 256), ImGuiCond_Appearing); + + // create a window and insert the inspector + ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_Appearing); + ImGui::SetNextWindowSize(ImVec2(320, 340), ImGuiCond_Appearing); + ImGui::Begin("Controls"); + + ImGui::SameLine(); + + ImGui::Text("Camera"); + + ImGui::SliderFloat("Move speed", &m_cameraSetting.moveSpeed, 0.1f, 10.f); + ImGui::SliderFloat("Rotate speed", &m_cameraSetting.rotateSpeed, 0.1f, 10.f); + ImGui::SliderFloat("Fov", &m_cameraSetting.fov, 20.f, 150.f); + ImGui::SliderFloat("zNear", &m_cameraSetting.zNear, 0.1f, 100.f); + ImGui::SliderFloat("zFar", &m_cameraSetting.zFar, 110.f, 10000.f); + Light m_oldLight = m_light; + int light_type = m_light.type; + ImGui::ListBox("LightType", &light_type, s_lightTypeNames, ELT_COUNT); + m_light.type = static_cast(light_type); + if (m_light.type == ELT_DIRECTIONAL) + { + ImGui::SliderFloat3("Light Direction", &m_light.direction.x, -1.f, 1.f); + } + else if (m_light.type == ELT_POINT) + { + ImGui::SliderFloat3("Light Position", &m_light.position.x, -20.f, 20.f); + } + else if (m_light.type == ELT_SPOT) + { + ImGui::SliderFloat3("Light Direction", &m_light.direction.x, -1.f, 1.f); + ImGui::SliderFloat3("Light Position", &m_light.position.x, -20.f, 20.f); + + float32_t dOuterCutoff = hlsl::degrees(acos(m_light.outerCutoff)); + if (ImGui::SliderFloat("Light Outer Cutoff", &dOuterCutoff, 0.0f, 45.0f)) + { + m_light.outerCutoff = cos(hlsl::radians(dOuterCutoff)); + } + } + ImGui::Checkbox("Use Indirect Command", &m_useIndirectCommand); + if (m_light != m_oldLight) + { + m_frameAccumulationCounter = 0; + } + + ImGui::Text("X: %f Y: %f", io.MousePos.x, io.MousePos.y); + + ImGui::End(); + } + ); + + // Set Camera + { + core::vectorSIMDf cameraPosition(0, 5, -10); + matrix4SIMD proj = matrix4SIMD::buildProjectionMatrixPerspectiveFovRH( + core::radians(60.0f), + WIN_W / WIN_H, + 0.01f, + 500.0f + ); + m_camera = Camera(cameraPosition, core::vectorSIMDf(0, 0, 0), proj); + } + + m_winMgr->setWindowSize(m_window.get(), WIN_W, WIN_H); + m_surface->recreateSwapchain(); + m_winMgr->show(m_window.get()); + m_oracle.reportBeginFrameRecord(); + m_camera.mapKeysToWASD(); + + return true; + } + + bool updateGUIDescriptorSet() + { + // texture atlas, note we don't create info & write pair for the font sampler because UI extension's is immutable and baked into DS layout + static std::array descriptorInfo; + static IGPUDescriptorSet::SWriteDescriptorSet writes[MaxUITextureCount]; + + descriptorInfo[nbl::ext::imgui::UI::FontAtlasTexId].info.image.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; + descriptorInfo[nbl::ext::imgui::UI::FontAtlasTexId].desc = smart_refctd_ptr(m_ui.manager->getFontAtlasView()); + + for (uint32_t i = 0; i < descriptorInfo.size(); ++i) + { + writes[i].dstSet = m_ui.descriptorSet.get(); + writes[i].binding = 0u; + writes[i].arrayElement = i; + writes[i].count = 1u; + } + writes[nbl::ext::imgui::UI::FontAtlasTexId].info = descriptorInfo.data() + nbl::ext::imgui::UI::FontAtlasTexId; + + return m_device->updateDescriptorSets(writes, {}); + } + + inline void workLoopBody() override + { + // framesInFlight: ensuring safe execution of command buffers and acquires, `framesInFlight` only affect semaphore waits, don't use this to index your resources because it can change with swapchain recreation. + const uint32_t framesInFlight = core::min(MaxFramesInFlight, m_surface->getMaxAcquiresInFlight()); + // We block for semaphores for 2 reasons here: + // A) Resource: Can't use resource like a command buffer BEFORE previous use is finished! [MaxFramesInFlight] + // B) Acquire: Can't have more acquires in flight than a certain threshold returned by swapchain or your surface helper class. [MaxAcquiresInFlight] + if (m_realFrameIx >= framesInFlight) + { + const ISemaphore::SWaitInfo cbDonePending[] = + { + { + .semaphore = m_semaphore.get(), + .value = m_realFrameIx + 1 - framesInFlight + } + }; + if (m_device->blockForSemaphores(cbDonePending) != ISemaphore::WAIT_RESULT::SUCCESS) + return; + } + const auto resourceIx = m_realFrameIx % MaxFramesInFlight; + + m_api->startCapture(); + + update(); + + auto queue = getGraphicsQueue(); + auto cmdbuf = m_cmdBufs[resourceIx].get(); + + if (!keepRunning()) + return; + + cmdbuf->reset(IGPUCommandBuffer::RESET_FLAGS::RELEASE_RESOURCES_BIT); + cmdbuf->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + cmdbuf->beginDebugMarker("RaytracingPipelineApp Frame"); + + const auto viewMatrix = m_camera.getViewMatrix(); + const auto projectionMatrix = m_camera.getProjectionMatrix(); + const auto viewProjectionMatrix = m_camera.getConcatenatedMatrix(); + + core::matrix3x4SIMD modelMatrix; + modelMatrix.setTranslation(nbl::core::vectorSIMDf(0, 0, 0, 0)); + modelMatrix.setRotation(quaternion(0, 0, 0)); + + core::matrix4SIMD modelViewProjectionMatrix = core::concatenateBFollowedByA(viewProjectionMatrix, modelMatrix); + if (m_cachedModelViewProjectionMatrix != modelViewProjectionMatrix) + { + m_frameAccumulationCounter = 0; + m_cachedModelViewProjectionMatrix = modelViewProjectionMatrix; + } + core::matrix4SIMD invModelViewProjectionMatrix; + modelViewProjectionMatrix.getInverseTransform(invModelViewProjectionMatrix); + + { + IGPUCommandBuffer::SPipelineBarrierDependencyInfo::image_barrier_t imageBarriers[1]; + imageBarriers[0].barrier = { + .dep = { + .srcStageMask = PIPELINE_STAGE_FLAGS::FRAGMENT_SHADER_BIT, // previous frame read from framgent shader + .srcAccessMask = ACCESS_FLAGS::SHADER_READ_BITS, + .dstStageMask = PIPELINE_STAGE_FLAGS::RAY_TRACING_SHADER_BIT, + .dstAccessMask = ACCESS_FLAGS::SHADER_WRITE_BITS + } + }; + imageBarriers[0].image = m_hdrImage.get(); + imageBarriers[0].subresourceRange = { + .aspectMask = IImage::EAF_COLOR_BIT, + .baseMipLevel = 0u, + .levelCount = 1u, + .baseArrayLayer = 0u, + .layerCount = 1u + }; + imageBarriers[0].oldLayout = m_frameAccumulationCounter == 0 ? IImage::LAYOUT::UNDEFINED : IImage::LAYOUT::READ_ONLY_OPTIMAL; + imageBarriers[0].newLayout = IImage::LAYOUT::GENERAL; + cmdbuf->pipelineBarrier(E_DEPENDENCY_FLAGS::EDF_NONE, { .imgBarriers = imageBarriers }); + } + + // Trace Rays Pass + { + SPushConstants pc; + pc.light = m_light; + pc.proceduralGeomInfoBuffer = m_proceduralGeomInfoBuffer->getDeviceAddress(); + pc.triangleGeomInfoBuffer = m_triangleGeomInfoBuffer->getDeviceAddress(); + pc.frameCounter = m_frameAccumulationCounter; + const core::vector3df camPos = m_camera.getPosition().getAsVector3df(); + pc.camPos = { camPos.X, camPos.Y, camPos.Z }; + memcpy(&pc.invMVP, invModelViewProjectionMatrix.pointer(), sizeof(pc.invMVP)); + + cmdbuf->bindRayTracingPipeline(m_rayTracingPipeline.get()); + cmdbuf->setRayTracingPipelineStackSize(m_rayTracingStackSize); + cmdbuf->pushConstants(m_rayTracingPipeline->getLayout(), IShader::E_SHADER_STAGE::ESS_ALL_RAY_TRACING, 0, sizeof(SPushConstants), &pc); + cmdbuf->bindDescriptorSets(EPBP_RAY_TRACING, m_rayTracingPipeline->getLayout(), 0, 1, &m_rayTracingDs.get()); + if (m_useIndirectCommand) + { + cmdbuf->traceRaysIndirect( + SBufferBinding{ + .offset = 0, + .buffer = m_indirectBuffer, + }); + } + else + { + cmdbuf->traceRays( + m_shaderBindingTable.raygenGroupRange, + m_shaderBindingTable.missGroupsRange, m_shaderBindingTable.missGroupsStride, + m_shaderBindingTable.hitGroupsRange, m_shaderBindingTable.hitGroupsStride, + m_shaderBindingTable.callableGroupsRange, m_shaderBindingTable.callableGroupsStride, + WIN_W, WIN_H, 1); + } + } + + // pipeline barrier + { + IGPUCommandBuffer::SPipelineBarrierDependencyInfo::image_barrier_t imageBarriers[1]; + imageBarriers[0].barrier = { + .dep = { + .srcStageMask = PIPELINE_STAGE_FLAGS::RAY_TRACING_SHADER_BIT, + .srcAccessMask = ACCESS_FLAGS::SHADER_WRITE_BITS, + .dstStageMask = PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, + .dstAccessMask = ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT + } + }; + imageBarriers[0].image = m_hdrImage.get(); + imageBarriers[0].subresourceRange = { + .aspectMask = IImage::EAF_COLOR_BIT, + .baseMipLevel = 0u, + .levelCount = 1u, + .baseArrayLayer = 0u, + .layerCount = 1u + }; + imageBarriers[0].oldLayout = IImage::LAYOUT::GENERAL; + imageBarriers[0].newLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; + + cmdbuf->pipelineBarrier(E_DEPENDENCY_FLAGS::EDF_NONE, { .imgBarriers = imageBarriers }); + } + + { + asset::SViewport viewport; + { + viewport.minDepth = 1.f; + viewport.maxDepth = 0.f; + viewport.x = 0u; + viewport.y = 0u; + viewport.width = WIN_W; + viewport.height = WIN_H; + } + cmdbuf->setViewport(0u, 1u, &viewport); + + + VkRect2D defaultScisors[] = { {.offset = {(int32_t)viewport.x, (int32_t)viewport.y}, .extent = {(uint32_t)viewport.width, (uint32_t)viewport.height}} }; + cmdbuf->setScissor(defaultScisors); + + auto scRes = static_cast(m_surface->getSwapchainResources()); + const VkRect2D currentRenderArea = + { + .offset = {0,0}, + .extent = {m_window->getWidth(),m_window->getHeight()} + }; + const IGPUCommandBuffer::SClearColorValue clearColor = { .float32 = {0.f,0.f,0.f,1.f} }; + const IGPUCommandBuffer::SRenderpassBeginInfo info = + { + .framebuffer = scRes->getFramebuffer(m_currentImageAcquire.imageIndex), + .colorClearValues = &clearColor, + .depthStencilClearValues = nullptr, + .renderArea = currentRenderArea + }; + nbl::video::ISemaphore::SWaitInfo waitInfo = { .semaphore = m_semaphore.get(), .value = m_realFrameIx + 1u }; + + cmdbuf->beginRenderPass(info, IGPUCommandBuffer::SUBPASS_CONTENTS::INLINE); + + cmdbuf->bindGraphicsPipeline(m_presentPipeline.get()); + cmdbuf->bindDescriptorSets(EPBP_GRAPHICS, m_presentPipeline->getLayout(), 0, 1u, &m_presentDs.get()); + ext::FullScreenTriangle::recordDrawCall(cmdbuf); + + const auto uiParams = m_ui.manager->getCreationParameters(); + auto* uiPipeline = m_ui.manager->getPipeline(); + cmdbuf->bindGraphicsPipeline(uiPipeline); + cmdbuf->bindDescriptorSets(EPBP_GRAPHICS, uiPipeline->getLayout(), uiParams.resources.texturesInfo.setIx, 1u, &m_ui.descriptorSet.get()); + m_ui.manager->render(cmdbuf, waitInfo); + + cmdbuf->endRenderPass(); + + } + + cmdbuf->endDebugMarker(); + cmdbuf->end(); + + { + const IQueue::SSubmitInfo::SSemaphoreInfo rendered[] = + { + { + .semaphore = m_semaphore.get(), + .value = ++m_realFrameIx, + .stageMask = PIPELINE_STAGE_FLAGS::ALL_TRANSFER_BITS + } + }; + { + { + const IQueue::SSubmitInfo::SCommandBufferInfo commandBuffers[] = + { + {.cmdbuf = cmdbuf } + }; + + const IQueue::SSubmitInfo::SSemaphoreInfo acquired[] = + { + { + .semaphore = m_currentImageAcquire.semaphore, + .value = m_currentImageAcquire.acquireCount, + .stageMask = PIPELINE_STAGE_FLAGS::NONE + } + }; + const IQueue::SSubmitInfo infos[] = + { + { + .waitSemaphores = acquired, + .commandBuffers = commandBuffers, + .signalSemaphores = rendered + } + }; + + updateGUIDescriptorSet(); + + if (queue->submit(infos) != IQueue::RESULT::SUCCESS) + m_realFrameIx--; + } + } + + m_window->setCaption("[Nabla Engine] Ray Tracing Pipeline"); + m_surface->present(m_currentImageAcquire.imageIndex, rendered); + } + m_api->endCapture(); + m_frameAccumulationCounter++; + } + + inline void update() + { + m_camera.setMoveSpeed(m_cameraSetting.moveSpeed); + m_camera.setRotateSpeed(m_cameraSetting.rotateSpeed); + + static std::chrono::microseconds previousEventTimestamp{}; + + m_inputSystem->getDefaultMouse(&m_mouse); + m_inputSystem->getDefaultKeyboard(&m_keyboard); + + auto updatePresentationTimestamp = [&]() + { + m_currentImageAcquire = m_surface->acquireNextImage(); + + m_oracle.reportEndFrameRecord(); + const auto timestamp = m_oracle.getNextPresentationTimeStamp(); + m_oracle.reportBeginFrameRecord(); + + return timestamp; + }; + + const auto nextPresentationTimestamp = updatePresentationTimestamp(); + + struct + { + std::vector mouse{}; + std::vector keyboard{}; + } capturedEvents; + + m_camera.beginInputProcessing(nextPresentationTimestamp); + { + const auto& io = ImGui::GetIO(); + m_mouse.consumeEvents([&](const IMouseEventChannel::range_t& events) -> void + { + if (!io.WantCaptureMouse) + m_camera.mouseProcess(events); // don't capture the events, only let camera handle them with its impl + + for (const auto& e : events) // here capture + { + if (e.timeStamp < previousEventTimestamp) + continue; + + previousEventTimestamp = e.timeStamp; + capturedEvents.mouse.emplace_back(e); + + } + }, m_logger.get()); + + m_keyboard.consumeEvents([&](const IKeyboardEventChannel::range_t& events) -> void + { + if (!io.WantCaptureKeyboard) + m_camera.keyboardProcess(events); // don't capture the events, only let camera handle them with its impl + + for (const auto& e : events) // here capture + { + if (e.timeStamp < previousEventTimestamp) + continue; + + previousEventTimestamp = e.timeStamp; + capturedEvents.keyboard.emplace_back(e); + } + }, m_logger.get()); + + } + m_camera.endInputProcessing(nextPresentationTimestamp); + + const core::SRange mouseEvents(capturedEvents.mouse.data(), capturedEvents.mouse.data() + capturedEvents.mouse.size()); + const core::SRange keyboardEvents(capturedEvents.keyboard.data(), capturedEvents.keyboard.data() + capturedEvents.keyboard.size()); + const auto cursorPosition = m_window->getCursorControl()->getPosition(); + const auto mousePosition = float32_t2(cursorPosition.x, cursorPosition.y) - float32_t2(m_window->getX(), m_window->getY()); + + const ext::imgui::UI::SUpdateParameters params = + { + .mousePosition = mousePosition, + .displaySize = { m_window->getWidth(), m_window->getHeight() }, + .mouseEvents = mouseEvents, + .keyboardEvents = keyboardEvents + }; + + m_ui.manager->update(params); + } + + inline bool keepRunning() override + { + if (m_surface->irrecoverable()) + return false; + + return true; + } + + inline bool onAppTerminated() override + { + return device_base_t::onAppTerminated(); + } + +private: + uint32_t getWorkgroupCount(uint32_t dim, uint32_t size) + { + return (dim + size - 1) / size; + } + + bool createIndirectBuffer() + { + const auto getBufferRangeAddress = [](const SBufferRange& range) + { + return range.buffer->getDeviceAddress() + range.offset; + }; + const auto command = TraceRaysIndirectCommand_t{ + .raygenShaderRecordAddress = getBufferRangeAddress(m_shaderBindingTable.raygenGroupRange), + .raygenShaderRecordSize = m_shaderBindingTable.raygenGroupRange.size, + .missShaderBindingTableAddress = getBufferRangeAddress(m_shaderBindingTable.missGroupsRange), + .missShaderBindingTableSize = m_shaderBindingTable.missGroupsRange.size, + .missShaderBindingTableStride = m_shaderBindingTable.missGroupsStride, + .hitShaderBindingTableAddress = getBufferRangeAddress(m_shaderBindingTable.hitGroupsRange), + .hitShaderBindingTableSize = m_shaderBindingTable.hitGroupsRange.size, + .hitShaderBindingTableStride = m_shaderBindingTable.hitGroupsStride, + .callableShaderBindingTableAddress = getBufferRangeAddress(m_shaderBindingTable.callableGroupsRange), + .callableShaderBindingTableSize = m_shaderBindingTable.callableGroupsRange.size, + .callableShaderBindingTableStride = m_shaderBindingTable.callableGroupsStride, + .width = WIN_W, + .height = WIN_H, + .depth = 1, + }; + IGPUBuffer::SCreationParams params; + params.usage = IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_INDIRECT_BUFFER_BIT | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; + params.size = sizeof(TraceRaysIndirectCommand_t); + m_utils->createFilledDeviceLocalBufferOnDedMem(SIntendedSubmitInfo{ .queue = getGraphicsQueue() }, std::move(params), &command).move_into(m_indirectBuffer); + return true; + } + + void calculateRayTracingStackSize(const smart_refctd_ptr& pipeline) + { + const auto raygenStackSize = pipeline->getRaygenStackSize(); + auto getMaxSize = [&](auto ranges, auto valProj) -> uint16_t + { + auto maxValue = 0; + for (const auto& val : ranges) + { + maxValue = std::max(maxValue, std::invoke(valProj, val)); + } + return maxValue; + }; + + const auto closestHitStackMax = getMaxSize(pipeline->getHitStackSizes(), &IGPURayTracingPipeline::SHitGroupStackSize::closestHit); + const auto anyHitStackMax = getMaxSize(pipeline->getHitStackSizes(), &IGPURayTracingPipeline::SHitGroupStackSize::anyHit); + const auto intersectionStackMax = getMaxSize(pipeline->getHitStackSizes(), &IGPURayTracingPipeline::SHitGroupStackSize::intersection); + const auto missStackMax = getMaxSize(pipeline->getMissStackSizes(), std::identity{}); + const auto callableStackMax = getMaxSize(pipeline->getCallableStackSizes(), std::identity{}); + auto firstDepthStackSizeMax = std::max(closestHitStackMax, missStackMax); + firstDepthStackSizeMax = std::max(firstDepthStackSizeMax, intersectionStackMax + anyHitStackMax); + m_rayTracingStackSize = raygenStackSize + std::max(firstDepthStackSizeMax, callableStackMax); + } + + bool createShaderBindingTable(const smart_refctd_ptr& pipeline) + { + const auto& limits = m_device->getPhysicalDevice()->getLimits(); + const auto handleSize = SPhysicalDeviceLimits::ShaderGroupHandleSize; + const auto handleSizeAligned = nbl::core::alignUp(handleSize, limits.shaderGroupHandleAlignment); + + auto& raygenRange = m_shaderBindingTable.raygenGroupRange; + + auto& hitRange = m_shaderBindingTable.hitGroupsRange; + const auto hitHandles = pipeline->getHitHandles(); + + auto& missRange = m_shaderBindingTable.missGroupsRange; + const auto missHandles = pipeline->getMissHandles(); + + auto& callableRange = m_shaderBindingTable.callableGroupsRange; + const auto callableHandles = pipeline->getCallableHandles(); + + raygenRange = { + .offset = 0, + .size = core::alignUp(handleSizeAligned, limits.shaderGroupBaseAlignment) + }; + + missRange = { + .offset = raygenRange.size, + .size = core::alignUp(missHandles.size() * handleSizeAligned, limits.shaderGroupBaseAlignment), + }; + m_shaderBindingTable.missGroupsStride = handleSizeAligned; + + hitRange = { + .offset = missRange.offset + missRange.size, + .size = core::alignUp(hitHandles.size() * handleSizeAligned, limits.shaderGroupBaseAlignment), + }; + m_shaderBindingTable.hitGroupsStride = handleSizeAligned; + + callableRange = { + .offset = hitRange.offset + hitRange.size, + .size = core::alignUp(callableHandles.size() * handleSizeAligned, limits.shaderGroupBaseAlignment), + }; + m_shaderBindingTable.callableGroupsStride = handleSizeAligned; + + const auto bufferSize = raygenRange.size + missRange.size + hitRange.size + callableRange.size; + + ICPUBuffer::SCreationParams cpuBufferParams; + cpuBufferParams.size = bufferSize; + auto cpuBuffer = ICPUBuffer::create(std::move(cpuBufferParams)); + uint8_t* pData = reinterpret_cast(cpuBuffer->getPointer()); + + // copy raygen region + memcpy(pData, &pipeline->getRaygen(), handleSize); + + // copy miss region + uint8_t* pMissData = pData + missRange.offset; + for (const auto& handle : missHandles) + { + memcpy(pMissData, &handle, handleSize); + pMissData += m_shaderBindingTable.missGroupsStride; + } + + // copy hit region + uint8_t* pHitData = pData + hitRange.offset; + for (const auto& handle : hitHandles) + { + memcpy(pHitData, &handle, handleSize); + pHitData += m_shaderBindingTable.hitGroupsStride; + } + + // copy callable region + uint8_t* pCallableData = pData + callableRange.offset; + for (const auto& handle : callableHandles) + { + memcpy(pCallableData, &handle, handleSize); + pCallableData += m_shaderBindingTable.callableGroupsStride; + } + + { + IGPUBuffer::SCreationParams params; + params.usage = IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT | IGPUBuffer::EUF_SHADER_BINDING_TABLE_BIT; + params.size = bufferSize; + m_utils->createFilledDeviceLocalBufferOnDedMem(SIntendedSubmitInfo{ .queue = getGraphicsQueue() }, std::move(params), pData).move_into(raygenRange.buffer); + missRange.buffer = core::smart_refctd_ptr(raygenRange.buffer); + hitRange.buffer = core::smart_refctd_ptr(raygenRange.buffer); + callableRange.buffer = core::smart_refctd_ptr(raygenRange.buffer); + } + + return true; + } + + bool createAccelerationStructuresFromGeometry() + { + auto queue = getGraphicsQueue(); + // get geometries into ICPUBuffers + auto pool = m_device->createCommandPool(queue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); + if (!pool) + return logFail("Couldn't create Command Pool for geometry creation!"); + + const auto defaultMaterial = Material{ + .ambient = {0.2, 0.1, 0.1}, + .diffuse = {0.8, 0.3, 0.3}, + .specular = {0.8, 0.8, 0.8}, + .shininess = 1.0f, + .alpha = 1.0f, + }; + + auto getTranslationMatrix = [](float32_t x, float32_t y, float32_t z) + { + core::matrix3x4SIMD transform; + transform.setTranslation(nbl::core::vectorSIMDf(x, y, z, 0)); + return transform; + }; + + core::matrix3x4SIMD planeTransform; + planeTransform.setRotation(quaternion::fromAngleAxis(core::radians(-90.0f), vector3df_SIMD{ 1, 0, 0 })); + + // triangles geometries + auto geometryCreator = make_smart_refctd_ptr(); + + const auto cpuObjects = std::array{ + scene::ReferenceObjectCpu { + .meta = {.type = scene::OT_RECTANGLE, .name = "Plane Mesh"}, + .data = geometryCreator->createRectangle({10, 10}), + .material = defaultMaterial, + .transform = planeTransform, + }, + scene::ReferenceObjectCpu { + .meta = {.type = scene::OT_CUBE, .name = "Cube Mesh"}, + .data = geometryCreator->createCube({1, 1, 1}), + .material = defaultMaterial, + .transform = getTranslationMatrix(0, 0.5f, 0), + }, + scene::ReferenceObjectCpu { + .meta = {.type = scene::OT_CUBE, .name = "Cube Mesh 2"}, + .data = geometryCreator->createCube({1.5, 1.5, 1.5}), + .material = Material{ + .ambient = {0.1, 0.1, 0.2}, + .diffuse = {0.2, 0.2, 0.8}, + .specular = {0.8, 0.8, 0.8}, + .shininess = 1.0f, + .alpha = 1.0f, + }, + .transform = getTranslationMatrix(-5.0f, 1.0f, 0), + }, + scene::ReferenceObjectCpu { + .meta = {.type = scene::OT_CUBE, .name = "Transparent Cube Mesh"}, + .data = geometryCreator->createCube({1.5, 1.5, 1.5}), + .material = Material{ + .ambient = {0.1, 0.2, 0.1}, + .diffuse = {0.2, 0.8, 0.2}, + .specular = {0.8, 0.8, 0.8}, + .shininess = 1.0f, + .alpha = 0.2, + }, + .transform = getTranslationMatrix(5.0f, 1.0f, 0), + }, + }; + + // procedural geometries + using Aabb = IGPUBottomLevelAccelerationStructure::AABB_t; + + smart_refctd_ptr cpuProcBuffer; + { + ICPUBuffer::SCreationParams params; + params.size = NumberOfProceduralGeometries * sizeof(Aabb); + cpuProcBuffer = ICPUBuffer::create(std::move(params)); + } + + core::vector proceduralGeoms; + proceduralGeoms.reserve(NumberOfProceduralGeometries); + auto proceduralGeometries = reinterpret_cast(cpuProcBuffer->getPointer()); + for (int32_t i = 0; i < NumberOfProceduralGeometries; i++) + { + const auto middle_i = NumberOfProceduralGeometries / 2.0; + SProceduralGeomInfo sphere = { + .material = hlsl::_static_cast(Material{ + .ambient = {0.1, 0.05 * i, 0.1}, + .diffuse = {0.3, 0.2 * i, 0.3}, + .specular = {0.8, 0.8, 0.8}, + .shininess = 1.0f, + }), + .center = float32_t3((i - middle_i) * 4.0, 2, 5.0), + .radius = 1, + }; + + proceduralGeoms.push_back(sphere); + const auto sphereMin = sphere.center - sphere.radius; + const auto sphereMax = sphere.center + sphere.radius; + proceduralGeometries[i] = { + vector3d(sphereMin.x, sphereMin.y, sphereMin.z), + vector3d(sphereMax.x, sphereMax.y, sphereMax.z) + }; + } + + { + IGPUBuffer::SCreationParams params; + params.usage = IGPUBuffer::EUF_STORAGE_BUFFER_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; + params.size = proceduralGeoms.size() * sizeof(SProceduralGeomInfo); + m_utils->createFilledDeviceLocalBufferOnDedMem(SIntendedSubmitInfo{ .queue = queue }, std::move(params), proceduralGeoms.data()).move_into(m_proceduralGeomInfoBuffer); + } + + // get ICPUBuffers into ICPUBLAS + // TODO use one BLAS and multiple triangles/aabbs in one + const auto blasCount = std::size(cpuObjects) + 1; + const auto proceduralBlasIdx = std::size(cpuObjects); + + std::array, std::size(cpuObjects)+1u> cpuBlasList; + for (uint32_t i = 0; i < blasCount; i++) + { + auto& blas = cpuBlasList[i]; + blas = make_smart_refctd_ptr(); + + if (i == proceduralBlasIdx) + { + auto aabbs = make_refctd_dynamic_array>>(1u); + auto primitiveCounts = make_refctd_dynamic_array>(1u); + + auto& aabb = aabbs->front(); + auto& primCount = primitiveCounts->front(); + + primCount = NumberOfProceduralGeometries; + aabb.data = { .offset = 0, .buffer = cpuProcBuffer }; + aabb.stride = sizeof(IGPUBottomLevelAccelerationStructure::AABB_t); + aabb.geometryFlags = IGPUBottomLevelAccelerationStructure::GEOMETRY_FLAGS::OPAQUE_BIT; // only allow opaque for now + + blas->setGeometries(std::move(aabbs), std::move(primitiveCounts)); + } + else + { + auto triangles = make_refctd_dynamic_array>>(cpuObjects[i].data->exportForBLAS()); + auto primitiveCounts = make_refctd_dynamic_array>(1u); + + auto& tri = triangles->front(); + + auto& primCount = primitiveCounts->front(); + primCount = cpuObjects[i].data->getPrimitiveCount(); + + tri.geometryFlags = cpuObjects[i].material.isTransparent() ? + IGPUBottomLevelAccelerationStructure::GEOMETRY_FLAGS::NO_DUPLICATE_ANY_HIT_INVOCATION_BIT : + IGPUBottomLevelAccelerationStructure::GEOMETRY_FLAGS::OPAQUE_BIT; + + blas->setGeometries(std::move(triangles), std::move(primitiveCounts)); + } + + auto blasFlags = bitflag(IGPUBottomLevelAccelerationStructure::BUILD_FLAGS::PREFER_FAST_TRACE_BIT) | IGPUBottomLevelAccelerationStructure::BUILD_FLAGS::ALLOW_COMPACTION_BIT; + if (i == proceduralBlasIdx) + blasFlags |= IGPUBottomLevelAccelerationStructure::BUILD_FLAGS::GEOMETRY_TYPE_IS_AABB_BIT; + + blas->setBuildFlags(blasFlags); + blas->setContentHash(blas->computeContentHash()); + } + + auto geomInfoBuffer = ICPUBuffer::create({ std::size(cpuObjects) * sizeof(STriangleGeomInfo) }); + STriangleGeomInfo* geomInfos = reinterpret_cast(geomInfoBuffer->getPointer()); + + // get ICPUBLAS into ICPUTLAS + auto geomInstances = make_refctd_dynamic_array>(blasCount); + { + uint32_t i = 0; + for (auto instance = geomInstances->begin(); instance != geomInstances->end(); instance++, i++) + { + const auto isProceduralInstance = i == proceduralBlasIdx; + ICPUTopLevelAccelerationStructure::StaticInstance inst; + inst.base.blas = cpuBlasList[i]; + inst.base.flags = static_cast(IGPUTopLevelAccelerationStructure::INSTANCE_FLAGS::TRIANGLE_FACING_CULL_DISABLE_BIT); + inst.base.instanceCustomIndex = i; + inst.base.instanceShaderBindingTableRecordOffset = isProceduralInstance ? 2 : 0;; + inst.base.mask = 0xFF; + inst.transform = isProceduralInstance ? matrix3x4SIMD() : cpuObjects[i].transform; + + instance->instance = inst; + } + } + + auto cpuTlas = make_smart_refctd_ptr(); + cpuTlas->setInstances(std::move(geomInstances)); + cpuTlas->setBuildFlags(IGPUTopLevelAccelerationStructure::BUILD_FLAGS::PREFER_FAST_TRACE_BIT); + + // convert with asset converter + smart_refctd_ptr converter = CAssetConverter::create({ .device = m_device.get(), .optimizer = {} }); + struct MyInputs : CAssetConverter::SInputs + { + // For the GPU Buffers to be directly writeable and so that we don't need a Transfer Queue submit at all + inline uint32_t constrainMemoryTypeBits(const size_t groupCopyID, const IAsset* canonicalAsset, const blake3_hash_t& contentHash, const IDeviceMemoryBacked* memoryBacked) const override + { + assert(memoryBacked); + return memoryBacked->getObjectType() != IDeviceMemoryBacked::EOT_BUFFER ? (~0u) : rebarMemoryTypes; + } + + uint32_t rebarMemoryTypes; + } inputs = {}; + inputs.logger = m_logger.get(); + inputs.rebarMemoryTypes = m_physicalDevice->getDirectVRAMAccessMemoryTypeBits(); + // the allocator needs to be overriden to hand out memory ranges which have already been mapped so that the ReBAR fast-path can kick in + // (multiple buffers can be bound to same memory, but memory can only be mapped once at one place, so Asset Converter can't do it) + struct MyAllocator final : public IDeviceMemoryAllocator + { + ILogicalDevice* getDeviceForAllocations() const override { return device; } + + SAllocation allocate(const SAllocateInfo& info) override + { + auto retval = device->allocate(info); + // map what is mappable by default so ReBAR checks succeed + if (retval.isValid() && retval.memory->isMappable()) + retval.memory->map({ .offset = 0,.length = info.size }); + return retval; + } + + ILogicalDevice* device; + } myalloc; + myalloc.device = m_device.get(); + inputs.allocator = &myalloc; + + std::array tmpTlas; + std::array tmpGeometries; + std::array tmpBuffers; + { + tmpTlas[0] = cpuTlas.get(); + tmpBuffers[0] = cpuProcBuffer.get(); + for (uint32_t i = 0; i < cpuObjects.size(); i++) + { + tmpGeometries[i] = cpuObjects[i].data.get(); + } + + std::get>(inputs.assets) = tmpTlas; + std::get>(inputs.assets) = tmpBuffers; + std::get>(inputs.assets) = tmpGeometries; + } + + auto reservation = converter->reserve(inputs); + { + auto prepass = [&](const auto & references) -> bool + { + auto objects = reservation.getGPUObjects(); + uint32_t counter = {}; + for (auto& object : objects) + { + auto gpu = object.value; + auto* reference = references[counter]; + + if (reference) + { + if (!gpu) + { + m_logger->log("Failed to convert a CPU object to GPU!", ILogger::ELL_ERROR); + return false; + } + } + counter++; + } + return true; + }; + + prepass.template operator() < ICPUTopLevelAccelerationStructure > (tmpTlas); + prepass.template operator() < ICPUBuffer > (tmpBuffers); + } + + constexpr auto CompBufferCount = 2; + std::array, CompBufferCount> compBufs = {}; + std::array compBufInfos = {}; + { + auto pool = m_device->createCommandPool(queue->getFamilyIndex(), IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT | IGPUCommandPool::CREATE_FLAGS::TRANSIENT_BIT); + pool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY, compBufs); + compBufs.front()->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + for (auto i = 0; i < CompBufferCount; i++) + compBufInfos[i].cmdbuf = compBufs[i].get(); + } + auto compSema = m_device->createSemaphore(0u); + SIntendedSubmitInfo compute = {}; + compute.queue = queue; + compute.scratchCommandBuffers = compBufInfos; + compute.scratchSemaphore = { + .semaphore = compSema.get(), + .value = 0u, + .stageMask = PIPELINE_STAGE_FLAGS::ACCELERATION_STRUCTURE_BUILD_BIT | PIPELINE_STAGE_FLAGS::ACCELERATION_STRUCTURE_COPY_BIT + }; + // convert + { + smart_refctd_ptr scratchAlloc; + { + constexpr auto MaxAlignment = 256; + constexpr auto MinAllocationSize = 1024; + const auto scratchSize = core::alignUp(reservation.getMaxASBuildScratchSize(false), MaxAlignment); + + + IGPUBuffer::SCreationParams creationParams = {}; + creationParams.size = scratchSize; + creationParams.usage = IGPUBuffer::EUF_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT | IGPUBuffer::EUF_STORAGE_BUFFER_BIT; + auto scratchBuffer = m_device->createBuffer(std::move(creationParams)); + + auto reqs = scratchBuffer->getMemoryReqs(); + reqs.memoryTypeBits &= m_physicalDevice->getDirectVRAMAccessMemoryTypeBits(); + + auto allocation = m_device->allocate(reqs, scratchBuffer.get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); + allocation.memory->map({ .offset = 0,.length = reqs.size }); + + scratchAlloc = make_smart_refctd_ptr( + SBufferRange{0ull, scratchSize, std::move(scratchBuffer)}, + core::allocator(), MaxAlignment, MinAllocationSize + ); + } + + struct MyParams final : CAssetConverter::SConvertParams + { + inline uint32_t getFinalOwnerQueueFamily(const IGPUBuffer* buffer, const core::blake3_hash_t& createdFrom) override + { + return finalUser; + } + inline uint32_t getFinalOwnerQueueFamily(const IGPUAccelerationStructure* image, const core::blake3_hash_t& createdFrom) override + { + return finalUser; + } + + uint8_t finalUser; + } params = {}; + params.utilities = m_utils.get(); + params.compute = &compute; + params.scratchForDeviceASBuild = scratchAlloc.get(); + params.finalUser = queue->getFamilyIndex(); + + auto future = reservation.convert(params); + if (future.copy() != IQueue::RESULT::SUCCESS) + { + m_logger->log("Failed to await submission feature!", ILogger::ELL_ERROR); + return false; + } + // 2 submits, BLAS build, TLAS build, DO NOT ADD COMPACTIONS IN THIS EXAMPLE! + if (compute.getFutureScratchSemaphore().value>3) + m_logger->log("Overflow submitted on Compute Queue despite using ReBAR (no transfer submits or usage of staging buffer) and providing a AS Build Scratch Buffer of correctly queried max size!",system::ILogger::ELL_ERROR); + + // assign gpu objects to output + auto&& tlases = reservation.getGPUObjects(); + m_gpuTlas = tlases[0].value; + auto&& buffers = reservation.getGPUObjects(); + + m_proceduralAabbBuffer = buffers[2 * proceduralBlasIdx].value; + + for (uint32_t i = 0; i < cpuObjects.size(); i++) + { + const auto& cpuObject = cpuObjects[i]; + const auto& cpuBlas = cpuBlasList[i]; + const auto& geometry = cpuBlas->getTriangleGeometries()[0]; + const uint64_t vertexBufferAddress = buffers[2 * i].value->getDeviceAddress(); + const uint64_t indexBufferAddress = buffers[(2 * i) + 1].value->getDeviceAddress(); + geomInfos[i] = { + .material = hlsl::_static_cast(cpuObject.material), + .vertexBufferAddress = vertexBufferAddress, + .indexBufferAddress = geometry.indexData.buffer ? indexBufferAddress : vertexBufferAddress, + .vertexStride = geometry.vertexStride, + .objType = cpuObject.meta.type, + .indexType = geometry.indexType, + .smoothNormals = scene::s_smoothNormals[cpuObject.meta.type], + }; + } + } + + { + IGPUBuffer::SCreationParams params; + params.usage = IGPUBuffer::EUF_STORAGE_BUFFER_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_INLINE_UPDATE_VIA_CMDBUF | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT; + params.size = geomInfoBuffer->getSize(); + m_utils->createFilledDeviceLocalBufferOnDedMem(SIntendedSubmitInfo{ .queue = queue }, std::move(params), geomInfos).move_into(m_triangleGeomInfoBuffer); + } + + return true; + } + + smart_refctd_ptr m_window; + smart_refctd_ptr> m_surface; + smart_refctd_ptr m_semaphore; + uint64_t m_realFrameIx = 0; + uint32_t m_frameAccumulationCounter = 0; + std::array, MaxFramesInFlight> m_cmdBufs; + ISimpleManagedSurface::SAcquireResult m_currentImageAcquire = {}; + + core::smart_refctd_ptr m_inputSystem; + InputSystem::ChannelReader m_mouse; + InputSystem::ChannelReader m_keyboard; + + struct CameraSetting + { + float fov = 60.f; + float zNear = 0.1f; + float zFar = 10000.f; + float moveSpeed = 1.f; + float rotateSpeed = 1.f; + float viewWidth = 10.f; + float camYAngle = 165.f / 180.f * 3.14159f; + float camXAngle = 32.f / 180.f * 3.14159f; + + } m_cameraSetting; + Camera m_camera = Camera(core::vectorSIMDf(0, 0, 0), core::vectorSIMDf(0, 0, 0), core::matrix4SIMD()); + + Light m_light = { + .direction = {-1.0f, -1.0f, -0.4f}, + .position = {10.0f, 15.0f, 8.0f}, + .outerCutoff = 0.866025404f, // {cos(radians(30.0f))}, + .type = ELT_DIRECTIONAL + }; + + video::CDumbPresentationOracle m_oracle; + + struct C_UI + { + nbl::core::smart_refctd_ptr manager; + + struct + { + core::smart_refctd_ptr gui, scene; + } samplers; + + core::smart_refctd_ptr descriptorSet; + } m_ui; + core::smart_refctd_ptr m_guiDescriptorSetPool; + + core::vector m_gpuIntersectionSpheres; + uint32_t m_intersectionHitGroupIdx; + + smart_refctd_ptr m_gpuTlas; + smart_refctd_ptr m_instanceBuffer; + + smart_refctd_ptr m_triangleGeomInfoBuffer; + smart_refctd_ptr m_proceduralGeomInfoBuffer; + smart_refctd_ptr m_proceduralAabbBuffer; + smart_refctd_ptr m_indirectBuffer; + + smart_refctd_ptr m_hdrImage; + smart_refctd_ptr m_hdrImageView; + + smart_refctd_ptr m_rayTracingDsPool; + smart_refctd_ptr m_rayTracingDs; + smart_refctd_ptr m_rayTracingPipeline; + uint64_t m_rayTracingStackSize; + ShaderBindingTable m_shaderBindingTable; + + smart_refctd_ptr m_presentDs; + smart_refctd_ptr m_presentDsPool; + smart_refctd_ptr m_presentPipeline; + + smart_refctd_ptr m_converter; + + + core::matrix4SIMD m_cachedModelViewProjectionMatrix; + bool m_useIndirectCommand = false; + +}; +NBL_MAIN_FUNC(RaytracingPipelineApp) \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index fb03f95a4..fd303c3c3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,100 +2,104 @@ # This file is part of the "Nabla Engine". # For conditions of distribution and use, see copyright notice in nabla.h -function(NBL_HOOK_COMMON_API NBL_EXCLUDE_TARGETS_LIST) - if(NOT TARGET nblCommonAPI) - message(FATAL_ERROR "nblCommonAPI not defined!") - endif() - - NBL_GET_ALL_TARGETS(NBL_TARGETS) - - foreach(NBL_TARGET IN LISTS NBL_TARGETS) - # TODO: exclude builtin targets created by examples as well - doesn't impact anything at all now - if(NOT ${NBL_TARGET} IN_LIST NBL_EXCLUDE_TARGETS_LIST) - - target_include_directories(${NBL_TARGET} PRIVATE $) - target_link_libraries(${NBL_TARGET} PRIVATE nblCommonAPI) - endif() - endforeach() -endfunction() - -# PCH & CommonAPI library for Nabla framework examples -add_subdirectory(common EXCLUDE_FROM_ALL) - if(NBL_BUILD_EXAMPLES) + project(NablaExamples) + if(NBL_BUILD_ANDROID) nbl_android_create_media_storage_apk() endif() + #! Common api library & precompiled headers for Nabla framework examples + add_subdirectory(common EXCLUDE_FROM_ALL) + + #! use "EXCLUDE_FROM_ALL" to exclude an example from the NablaExamples project + #[[ + useful if we don't want the example to be tested by CI but still want + the example's project to be generated + + https://cmake.org/cmake/help/latest/prop_tgt/EXCLUDE_FROM_ALL.html + ]] + # showcase the use of `nbl::core`,`nbl::system` and `nbl::asset` - add_subdirectory(01_HelloCoreSystemAsset EXCLUDE_FROM_ALL) + add_subdirectory(01_HelloCoreSystemAsset) # showcase the use of `system::IApplicationFramework` and `nbl::video` - add_subdirectory(02_HelloCompute EXCLUDE_FROM_ALL) + add_subdirectory(02_HelloCompute) # showcase physical device selection, resource embedding and the use of identical headers in HLSL and C++ - add_subdirectory(03_DeviceSelectionAndSharedSources EXCLUDE_FROM_ALL) + add_subdirectory(03_DeviceSelectionAndSharedSources) # showcase the creation of windows and polling for input - add_subdirectory(04_HelloUI EXCLUDE_FROM_ALL) + add_subdirectory(04_HelloUI) # showcase the semi-advanced use of Nabla's Streaming Buffers and BDA - add_subdirectory(05_StreamingAndBufferDeviceAddressApp EXCLUDE_FROM_ALL) + add_subdirectory(05_StreamingAndBufferDeviceAddressApp) # showcase the use of a graphics queue - add_subdirectory(06_HelloGraphicsQueue EXCLUDE_FROM_ALL) + add_subdirectory(06_HelloGraphicsQueue) # showcase the set-up of multiple queues - add_subdirectory(07_StagingAndMultipleQueues EXCLUDE_FROM_ALL) + add_subdirectory(07_StagingAndMultipleQueues) # showcase the set-up of a swapchain and picking of a matching device - add_subdirectory(08_HelloSwapchain EXCLUDE_FROM_ALL) - add_subdirectory(09_GeometryCreator EXCLUDE_FROM_ALL) - # demonstrate the counting sort utility - add_subdirectory(10_CountingSort EXCLUDE_FROM_ALL) + add_subdirectory(08_HelloSwapchain) + add_subdirectory(09_GeometryCreator) + # demonstrate the counting sort utility + add_subdirectory(10_CountingSort) # showcase use of FFT for post-FX Bloom effect - add_subdirectory(11_FFT EXCLUDE_FROM_ALL) - + add_subdirectory(11_FFT) + # + add_subdirectory(12_MeshLoaders EXCLUDE_FROM_ALL) # Waiting for a refactor - #add_subdirectory(27_PLYSTLDemo EXCLUDE_FROM_ALL) - #add_subdirectory(29_SpecializationConstants EXCLUDE_FROM_ALL) - #add_subdirectory(33_Draw3DLine EXCLUDE_FROM_ALL) + #add_subdirectory(27_PLYSTLDemo) + #add_subdirectory(33_Draw3DLine) # Unit Test Examples - add_subdirectory(20_AllocatorTest EXCLUDE_FROM_ALL) - add_subdirectory(21_LRUCacheUnitTest EXCLUDE_FROM_ALL) - add_subdirectory(22_CppCompat EXCLUDE_FROM_ALL) - add_subdirectory(23_ArithmeticUnitTest EXCLUDE_FROM_ALL) - add_subdirectory(24_ColorSpaceTest EXCLUDE_FROM_ALL) + add_subdirectory(20_AllocatorTest) + add_subdirectory(21_LRUCacheUnitTest) + add_subdirectory(22_CppCompat) + add_subdirectory(23_Arithmetic2UnitTest) + add_subdirectory(24_ColorSpaceTest) add_subdirectory(25_FilterTest EXCLUDE_FROM_ALL) - add_subdirectory(26_Blur EXCLUDE_FROM_ALL) - add_subdirectory(27_MPMCScheduler EXCLUDE_FROM_ALL) - add_subdirectory(28_FFTBloom EXCLUDE_FROM_ALL) - # add_subdirectory(36_CUDAInterop EXCLUDE_FROM_ALL) + add_subdirectory(26_Blur) + add_subdirectory(27_MPMCScheduler) + add_subdirectory(28_FFTBloom) + add_subdirectory(29_Arithmetic2Bench) + # add_subdirectory(36_CUDAInterop) # Showcase compute pathtracing - add_subdirectory(30_ComputeShaderPathTracer EXCLUDE_FROM_ALL) + add_subdirectory(30_ComputeShaderPathTracer) + + add_subdirectory(31_HLSLPathTracer EXCLUDE_FROM_ALL) - add_subdirectory(38_EXRSplit EXCLUDE_FROM_ALL) + add_subdirectory(38_EXRSplit) # if (NBL_BUILD_MITSUBA_LOADER AND NBL_BUILD_OPTIX) - # add_subdirectory(39_DenoiserTonemapper EXCLUDE_FROM_ALL) + # add_subdirectory(39_DenoiserTonemapper) # endif() - add_subdirectory(42_FragmentShaderPathTracer EXCLUDE_FROM_ALL) - #add_subdirectory(43_SumAndCDFFilters EXCLUDE_FROM_ALL) - #add_subdirectory(45_BRDFEvalTest EXCLUDE_FROM_ALL) - #add_subdirectory(46_SamplingValidation EXCLUDE_FROM_ALL) + #add_subdirectory(43_SumAndCDFFilters) add_subdirectory(47_DerivMapTest EXCLUDE_FROM_ALL) - add_subdirectory(53_ComputeShaders EXCLUDE_FROM_ALL) add_subdirectory(54_Transformations EXCLUDE_FROM_ALL) add_subdirectory(55_RGB18E7S3 EXCLUDE_FROM_ALL) - add_subdirectory(56_RayQuery EXCLUDE_FROM_ALL) - add_subdirectory(60_ClusteredRendering EXCLUDE_FROM_ALL) - add_subdirectory(61_UI EXCLUDE_FROM_ALL) - add_subdirectory(62_CAD EXCLUDE_FROM_ALL) + add_subdirectory(61_UI) + add_subdirectory(62_CAD EXCLUDE_FROM_ALL) # TODO: Erfan, Przemek, Francisco and co. need to resurrect this add_subdirectory(62_SchusslerTest EXCLUDE_FROM_ALL) - add_subdirectory(64_EmulatedFloatTest EXCLUDE_FROM_ALL) + add_subdirectory(64_EmulatedFloatTest) add_subdirectory(0_ImportanceSamplingEnvMaps EXCLUDE_FROM_ALL) #TODO: integrate back into 42 add_subdirectory(66_HLSLBxDFTests EXCLUDE_FROM_ALL) - add_subdirectory(67_RayQueryGeometry EXCLUDE_FROM_ALL) - add_subdirectory(68_JpegLoading EXCLUDE_FROM_ALL) + add_subdirectory(67_RayQueryGeometry EXCLUDE_FROM_ALL) # TODO: resurrect before `mesh_loaders` merge + add_subdirectory(68_JpegLoading) - add_subdirectory(70_FLIPFluids EXCLUDE_FROM_ALL) + add_subdirectory(70_FLIPFluids) + add_subdirectory(71_RayTracingPipeline EXCLUDE_FROM_ALL) # TODO: resurrect before `mesh_loaders` merge + + # add new examples *before* NBL_GET_ALL_TARGETS invocation, it gathers recursively all targets created so far in this subdirectory + NBL_GET_ALL_TARGETS(TARGETS) + + # we want to loop only over the examples so we exclude examples' interface libraries created in common subdirectory + list(REMOVE_ITEM TARGETS ${NBL_EXAMPLES_API_TARGET} ${NBL_EXAMPLES_API_LIBRARIES}) + + # we link common example api library and force examples to reuse its PCH + foreach(T IN LISTS TARGETS) + target_link_libraries(${T} PUBLIC ${NBL_EXAMPLES_API_TARGET}) + target_include_directories(${T} PUBLIC $) + target_precompile_headers(${T} REUSE_FROM "${NBL_EXAMPLES_API_TARGET}") + endforeach() - NBL_HOOK_COMMON_API("${NBL_COMMON_API_TARGETS}") -endif() + NBL_ADJUST_FOLDERS(examples) +endif() \ No newline at end of file diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index d9073f273..3a55e7a26 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -1,28 +1,48 @@ -########################################### -# TODO: the way it should work is following (remove the comment once all done!) -# - one top PCH which includes -> currently not done -# - sources used only within examples splitted into "common libraries" (optional -> with options to toggle if include them to build tree), each common library should reuse the above top PCH -# - examples_tests CMake loop over example targets and hook the interface library with NBL_HOOK_COMMON_API [done] -# - each common library should declare ONLY interface and never expose source definition into headers nor any 3rdparty stuff! -## +#! Examples API proxy library +#[[ + We create the Nabla Examples API as a static library extension, this + allows all examples to reuse a single precompiled header (PCH) + instead of generating their own -# interface libraries don't have build rules (except custom commands however it doesn't matter here) but properties -add_library(nblCommonAPI INTERFACE) -set(NBL_COMMON_API_INCLUDE_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include") -target_include_directories(nblCommonAPI INTERFACE "${NBL_COMMON_API_INCLUDE_DIRECTORY}") + The PCH includes Nabla.h + example common interface headers and takes + around 1 GB per configuration, so sharing it avoids significant disk space waste +]] -add_subdirectory(src EXCLUDE_FROM_ALL) +nbl_create_ext_library_project(ExamplesAPI "" "${CMAKE_CURRENT_SOURCE_DIR}/src/nbl/examples/pch.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/include" "" "") -########## <- -# TODO: disable this CommonPCH thing! + DEPRICATED! -# TODO: move asset converer into separate library +set_target_properties(${LIB_NAME} PROPERTIES DISABLE_PRECOMPILE_HEADERS OFF) +target_precompile_headers(${LIB_NAME} PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include/nbl/examples/PCH.hpp") -nbl_create_ext_library_project(CommonAPI "" "${CMAKE_CURRENT_SOURCE_DIR}/src/empty.cpp" "" "" "") -set(NBL_EXECUTABLE_COMMON_API_TARGET "${LIB_NAME}" CACHE INTERNAL "") +#! Examples API common libraries +#[[ + The rule is to avoid creating additional libraries as part of the examples' common + interface in order to prevent generating another precompiled header (PCH) and wasting disk space -add_subdirectory(CommonPCH EXCLUDE_FROM_ALL) + If you have new utilities that could be shared across examples then try to implement them as header only + and include in the PCH or in `examples.h` *if you cannot* (open the header to see details) -#target_precompile_headers("${NBL_EXECUTABLE_COMMON_API_TARGET}" REUSE_FROM "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") -########## <- + but If you have a good reason to create library because you cannot make it header only + AND you *can REUSE* the examples' PCH then go ahead anyway and put it under `src/nbl/examples`, + otherwise keep it header only - a good example would be to use our embedded-whatever-you-want tool + which does create library but can reuse example's PCH +]] -set(NBL_COMMON_API_TARGETS nblCommonAPI ${NBL_COMMON_API_TARGETS} ${NBL_EXECUTABLE_COMMON_API_TARGET} PARENT_SCOPE) +#! NOTE: as I write it we don't have any targets there yet +add_subdirectory("src/nbl/examples" EXCLUDE_FROM_ALL) + +NBL_GET_ALL_TARGETS(TARGETS) +list(REMOVE_ITEM TARGETS ${LIB_NAME}) + +# the Examples API proxy library CMake target name +#[[ + this one gets linked to each executable automatically +]] +set(NBL_EXAMPLES_API_TARGET ${LIB_NAME} PARENT_SCOPE) + +#! names of CMake targets created in src/nbl/examples +#[[ + if your example wants to use anything from src/nbl/examples + then you must target_link_libraries() the lib you want as we + don't link all those libraries to each executable automatically +]] +set(NBL_EXAMPLES_API_LIBRARIES ${TARGETS} PARENT_SCOPE) \ No newline at end of file diff --git a/common/CommonAPI.h b/common/CommonAPI.h deleted file mode 100644 index aca8c0741..000000000 --- a/common/CommonAPI.h +++ /dev/null @@ -1,111 +0,0 @@ -#ifndef __NBL_COMMON_API_H_INCLUDED__ -#define __NBL_COMMON_API_H_INCLUDED__ - -#include - -#include "MonoSystemMonoLoggerApplication.hpp" - -#include "nbl/ui/CGraphicalApplicationAndroid.h" -#include "nbl/ui/CWindowManagerAndroid.h" - -// TODO: see TODO below -// TODO: make these include themselves via `nabla.h` - -#include "nbl/video/utilities/SPhysicalDeviceFilter.h" - -#if 0 -class CommonAPI -{ - CommonAPI() = delete; -public: - class CommonAPIEventCallback : public nbl::ui::IWindow::IEventCallback - { - public: - CommonAPIEventCallback(nbl::core::smart_refctd_ptr&& inputSystem, nbl::system::logger_opt_smart_ptr&& logger) : m_inputSystem(std::move(inputSystem)), m_logger(std::move(logger)), m_gotWindowClosedMsg(false){} - CommonAPIEventCallback() {} - bool isWindowOpen() const {return !m_gotWindowClosedMsg;} - void setLogger(nbl::system::logger_opt_smart_ptr& logger) - { - m_logger = logger; - } - void setInputSystem(nbl::core::smart_refctd_ptr&& inputSystem) - { - m_inputSystem = std::move(inputSystem); - } - private: - - bool onWindowClosed_impl() override - { - m_logger.log("Window closed"); - m_gotWindowClosedMsg = true; - return true; - } - - void onMouseConnected_impl(nbl::core::smart_refctd_ptr&& mch) override - { - m_logger.log("A mouse %p has been connected", nbl::system::ILogger::ELL_INFO, mch.get()); - m_inputSystem.get()->add(m_inputSystem.get()->m_mouse,std::move(mch)); - } - void onMouseDisconnected_impl(nbl::ui::IMouseEventChannel* mch) override - { - m_logger.log("A mouse %p has been disconnected", nbl::system::ILogger::ELL_INFO, mch); - m_inputSystem.get()->remove(m_inputSystem.get()->m_mouse,mch); - } - void onKeyboardConnected_impl(nbl::core::smart_refctd_ptr&& kbch) override - { - m_logger.log("A keyboard %p has been connected", nbl::system::ILogger::ELL_INFO, kbch.get()); - m_inputSystem.get()->add(m_inputSystem.get()->m_keyboard,std::move(kbch)); - } - void onKeyboardDisconnected_impl(nbl::ui::IKeyboardEventChannel* kbch) override - { - m_logger.log("A keyboard %p has been disconnected", nbl::system::ILogger::ELL_INFO, kbch); - m_inputSystem.get()->remove(m_inputSystem.get()->m_keyboard,kbch); - } - - private: - nbl::core::smart_refctd_ptr m_inputSystem = nullptr; - nbl::system::logger_opt_smart_ptr m_logger = nullptr; - bool m_gotWindowClosedMsg; - }; - - // old code from init - { - // ... - - result.inputSystem = nbl::core::make_smart_refctd_ptr(system::logger_opt_smart_ptr(nbl::core::smart_refctd_ptr(result.logger))); - result.assetManager = nbl::core::make_smart_refctd_ptr(nbl::core::smart_refctd_ptr(result.system), nbl::core::smart_refctd_ptr(result.compilerSet)); // we should let user choose it? - - if (!headlessCompute) - { - params.windowCb->setInputSystem(nbl::core::smart_refctd_ptr(result.inputSystem)); - if (!params.window) - { - #ifdef _NBL_PLATFORM_WINDOWS_ - result.windowManager = ui::IWindowManagerWin32::create(); // on the Windows path - #elif defined(_NBL_PLATFORM_LINUX_) - result.windowManager = nbl::core::make_smart_refctd_ptr(); // on the Android path - #else - #error "Unsupported platform" - #endif - - nbl::ui::IWindow::SCreationParams windowsCreationParams; - windowsCreationParams.width = params.windowWidth; - windowsCreationParams.height = params.windowHeight; - windowsCreationParams.x = 64u; - windowsCreationParams.y = 64u; - windowsCreationParams.flags = nbl::ui::IWindow::ECF_RESIZABLE; - windowsCreationParams.windowCaption = params.appName.data(); - windowsCreationParams.callback = params.windowCb; - - params.window = result.windowManager->createWindow(std::move(windowsCreationParams)); - } - params.windowCb = nbl::core::smart_refctd_ptr((CommonAPIEventCallback*) params.window->getEventCallback()); - } - - // ... - } -}; - -#endif - -#endif diff --git a/common/CommonPCH/CMakeLists.txt b/common/CommonPCH/CMakeLists.txt deleted file mode 100644 index 5e62f885f..000000000 --- a/common/CommonPCH/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -include(common RESULT_VARIABLE RES) -if(NOT RES) - message(FATAL_ERROR "common.cmake not found. Should be in '${NBL_ROOT_PATH}/cmake' directory") -endif() - -nbl_create_executable_project("" "" "" "" "") - -set(NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET "${EXECUTABLE_NAME}" CACHE INTERNAL "") -get_target_property(NBL_NABLA_TARGET_SOURCE_DIR Nabla SOURCE_DIR) -set_target_properties("${EXECUTABLE_NAME}" PROPERTIES DISABLE_PRECOMPILE_HEADERS OFF) -target_precompile_headers("${EXECUTABLE_NAME}" PUBLIC - "${CMAKE_CURRENT_SOURCE_DIR}/PCH.hpp" # Common PCH for examples - "${NBL_NABLA_TARGET_SOURCE_DIR}/pch.h" # Nabla's PCH -) -unset(NBL_NABLA_TARGET_SOURCE_DIR) \ No newline at end of file diff --git a/common/CommonPCH/PCH.hpp b/common/CommonPCH/PCH.hpp deleted file mode 100644 index 5b9d6a433..000000000 --- a/common/CommonPCH/PCH.hpp +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (C) 2018-2022 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h -#ifndef _EXAMPLES_COMMON_PCH_HPP_ -#define _EXAMPLES_COMMON_PCH_HPP_ - -#include - -#include -#include -#include - -#endif // _EXAMPLES_COMMON_PCH_HPP_ \ No newline at end of file diff --git a/common/CommonPCH/main.cpp b/common/CommonPCH/main.cpp deleted file mode 100644 index c19ee3c45..000000000 --- a/common/CommonPCH/main.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (C) 2018-2022 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -int main(int argc, char** argv) -{ - return 0; -} - diff --git a/common/include/CEventCallback.hpp b/common/include/CEventCallback.hpp deleted file mode 100644 index 2d4e36932..000000000 --- a/common/include/CEventCallback.hpp +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef __NBL_C_EVENT_CALLBACK_HPP_INCLUDED__ -#define __NBL_C_EVENT_CALLBACK_HPP_INCLUDED__ - -#include "nbl/video/utilities/CSimpleResizeSurface.h" -#include "InputSystem.hpp" - -class CEventCallback : public nbl::video::ISimpleManagedSurface::ICallback -{ -public: - CEventCallback(nbl::core::smart_refctd_ptr&& m_inputSystem, nbl::system::logger_opt_smart_ptr&& logger) : m_inputSystem(std::move(m_inputSystem)), m_logger(std::move(logger)) {} - CEventCallback() {} - - void setLogger(nbl::system::logger_opt_smart_ptr& logger) - { - m_logger = logger; - } - void setInputSystem(nbl::core::smart_refctd_ptr&& m_inputSystem) - { - m_inputSystem = std::move(m_inputSystem); - } -private: - - void onMouseConnected_impl(nbl::core::smart_refctd_ptr&& mch) override - { - m_logger.log("A mouse %p has been connected", nbl::system::ILogger::ELL_INFO, mch.get()); - m_inputSystem.get()->add(m_inputSystem.get()->m_mouse, std::move(mch)); - } - void onMouseDisconnected_impl(nbl::ui::IMouseEventChannel* mch) override - { - m_logger.log("A mouse %p has been disconnected", nbl::system::ILogger::ELL_INFO, mch); - m_inputSystem.get()->remove(m_inputSystem.get()->m_mouse, mch); - } - void onKeyboardConnected_impl(nbl::core::smart_refctd_ptr&& kbch) override - { - m_logger.log("A keyboard %p has been connected", nbl::system::ILogger::ELL_INFO, kbch.get()); - m_inputSystem.get()->add(m_inputSystem.get()->m_keyboard, std::move(kbch)); - } - void onKeyboardDisconnected_impl(nbl::ui::IKeyboardEventChannel* kbch) override - { - m_logger.log("A keyboard %p has been disconnected", nbl::system::ILogger::ELL_INFO, kbch); - m_inputSystem.get()->remove(m_inputSystem.get()->m_keyboard, kbch); - } - -private: - nbl::core::smart_refctd_ptr m_inputSystem = nullptr; - nbl::system::logger_opt_smart_ptr m_logger = nullptr; -}; - -#endif // __NBL_C_EVENT_CALLBACK_HPP_INCLUDED__ \ No newline at end of file diff --git a/common/include/CGeomtryCreatorScene.hpp b/common/include/CGeomtryCreatorScene.hpp deleted file mode 100644 index 0d9bc6edd..000000000 --- a/common/include/CGeomtryCreatorScene.hpp +++ /dev/null @@ -1,1346 +0,0 @@ -#ifndef _NBL_GEOMETRY_CREATOR_SCENE_H_INCLUDED_ -#define _NBL_GEOMETRY_CREATOR_SCENE_H_INCLUDED_ - -#include - -#include "nbl/asset/utils/CGeometryCreator.h" -#include "SBasicViewParameters.hlsl" -#include "geometry/creator/spirv/builtin/CArchive.h" -#include "geometry/creator/spirv/builtin/builtinResources.h" - -namespace nbl::scene::geometrycreator -{ - -enum ObjectType : uint8_t -{ - OT_CUBE, - OT_SPHERE, - OT_CYLINDER, - OT_RECTANGLE, - OT_DISK, - OT_ARROW, - OT_CONE, - OT_ICOSPHERE, - - OT_COUNT, - OT_UNKNOWN = std::numeric_limits::max() -}; - -struct ObjectMeta -{ - ObjectType type = OT_UNKNOWN; - std::string_view name = "Unknown"; -}; - -constexpr static inline struct ClearValues -{ - nbl::video::IGPUCommandBuffer::SClearColorValue color = { .float32 = {0.f,0.f,0.f,1.f} }; - nbl::video::IGPUCommandBuffer::SClearDepthStencilValue depth = { .depth = 0.f }; -} clear; - -#define TYPES_IMPL_BOILERPLATE(WithConverter) struct Types \ -{ \ - using descriptor_set_layout_t = std::conditional_t; \ - using pipeline_layout_t = std::conditional_t; \ - using renderpass_t = std::conditional_t; \ - using image_view_t = std::conditional_t; \ - using image_t = std::conditional_t; \ - using buffer_t = std::conditional_t; \ - using shader_t = std::conditional_t; \ - using graphics_pipeline_t = std::conditional_t; \ - using descriptor_set = std::conditional_t; \ -} - -template -struct ResourcesBundleBase -{ - TYPES_IMPL_BOILERPLATE(withAssetConverter); - - struct ReferenceObject - { - struct Bindings - { - nbl::asset::SBufferBinding vertex, index; - }; - - nbl::core::smart_refctd_ptr pipeline = nullptr; - - Bindings bindings; - nbl::asset::E_INDEX_TYPE indexType = nbl::asset::E_INDEX_TYPE::EIT_UNKNOWN; - uint32_t indexCount = {}; - }; - - using ReferenceDrawHook = std::pair; - - nbl::core::smart_refctd_ptr renderpass; - std::array objects; - nbl::asset::SBufferBinding ubo; - - struct - { - nbl::core::smart_refctd_ptr color, depth; - } attachments; - - nbl::core::smart_refctd_ptr descriptorSet; -}; - -struct ResourcesBundle : public ResourcesBundleBase -{ - using base_t = ResourcesBundleBase; -}; - -#define EXPOSE_NABLA_NAMESPACES() using namespace nbl; \ -using namespace core; \ -using namespace asset; \ -using namespace video; \ -using namespace scene; \ -using namespace system - -template -class ResourceBuilder -{ -public: - TYPES_IMPL_BOILERPLATE(withAssetConverter); - - using this_t = ResourceBuilder; - - ResourceBuilder(nbl::video::IUtilities* const _utilities, nbl::video::IGPUCommandBuffer* const _commandBuffer, nbl::system::ILogger* const _logger, const nbl::asset::IGeometryCreator* const _geometryCreator) - : utilities(_utilities), commandBuffer(_commandBuffer), logger(_logger), geometries(_geometryCreator) - { - assert(utilities); - assert(logger); - } - - /* - if (withAssetConverter) then - -> .build cpu objects - else - -> .build gpu objects & record any resource update upload transfers into command buffer - */ - - inline bool build() - { - EXPOSE_NABLA_NAMESPACES(); - - if constexpr (!withAssetConverter) - { - commandBuffer->reset(IGPUCommandBuffer::RESET_FLAGS::RELEASE_RESOURCES_BIT); - commandBuffer->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); - commandBuffer->beginDebugMarker("Resources builder's buffers upload [manual]"); - } - - using functor_t = std::function; - - auto work = std::to_array - ({ - functor_t(std::bind(&this_t::createDescriptorSetLayout, this)), - functor_t(std::bind(&this_t::createPipelineLayout, this)), - functor_t(std::bind(&this_t::createRenderpass, this)), - functor_t(std::bind(&this_t::createFramebufferAttachments, this)), - functor_t(std::bind(&this_t::createShaders, this)), - functor_t(std::bind(&this_t::createGeometries, this)), - functor_t(std::bind(&this_t::createViewParametersUboBuffer, this)), - functor_t(std::bind(&this_t::createDescriptorSet, this)) - }); - - for (auto& task : work) - if (!task()) - return false; - - if constexpr (!withAssetConverter) - commandBuffer->end(); - - return true; - } - - /* - if (withAssetConverter) then - -> .convert cpu objects to gpu & update gpu buffers - else - -> update gpu buffers - */ - - inline bool finalize(ResourcesBundle& output, nbl::video::CThreadSafeQueueAdapter* transferCapableQueue) - { - EXPOSE_NABLA_NAMESPACES(); - - // TODO: use multiple command buffers - std::array commandBuffers = {}; - { - commandBuffers.front().cmdbuf = commandBuffer; - } - - if constexpr (withAssetConverter) - { - // note that asset converter records basic transfer uploads itself, we only begin the recording with ONE_TIME_SUBMIT_BIT - commandBuffer->reset(IGPUCommandBuffer::RESET_FLAGS::RELEASE_RESOURCES_BIT); - commandBuffer->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); - commandBuffer->beginDebugMarker("Resources builder's buffers upload [asset converter]"); - - // asset converter - scratch at this point has ready to convert cpu resources - smart_refctd_ptr converter = CAssetConverter::create({ .device = utilities->getLogicalDevice(),.optimizer = {} }); - CAssetConverter::SInputs inputs = {}; - inputs.logger = logger; - - struct ProxyCpuHooks - { - using object_size_t = std::tuple_size; - - std::array renderpass; - std::array pipelines; - std::array buffers; - std::array attachments; - std::array descriptorSet; - } hooks; - - enum AttachmentIx - { - AI_COLOR = 0u, - AI_DEPTH = 1u, - - AI_COUNT - }; - - // gather CPU assets into span memory views - { - hooks.renderpass.front() = scratch.renderpass.get(); - for (uint32_t i = 0u; i < hooks.pipelines.size(); ++i) - { - auto& [reference, meta] = scratch.objects[static_cast(i)]; - hooks.pipelines[i] = reference.pipeline.get(); - - // [[ [vertex, index] [vertex, index] [vertex, index] ... [ubo] ]] - hooks.buffers[2u * i + 0u] = reference.bindings.vertex.buffer.get(); - hooks.buffers[2u * i + 1u] = reference.bindings.index.buffer.get(); - } - hooks.buffers.back() = scratch.ubo.buffer.get(); - hooks.attachments[AI_COLOR] = scratch.attachments.color.get(); - hooks.attachments[AI_DEPTH] = scratch.attachments.depth.get(); - hooks.descriptorSet.front() = scratch.descriptorSet.get(); - } - - // assign the CPU hooks to converter's inputs - { - std::get>(inputs.assets) = hooks.renderpass; - std::get>(inputs.assets) = hooks.pipelines; - std::get>(inputs.assets) = hooks.buffers; - // std::get>(inputs.assets) = hooks.attachments; // NOTE: THIS IS NOT IMPLEMENTED YET IN CONVERTER! - std::get>(inputs.assets) = hooks.descriptorSet; - } - - // reserve and create the GPU object handles - auto reservation = converter->reserve(inputs); - { - auto prepass = [&](const auto& references) -> bool - { - // retrieve the reserved handles - auto objects = reservation.getGPUObjects(); - - uint32_t counter = {}; - for (auto& object : objects) - { - // anything that fails to be reserved is a nullptr in the span of GPU Objects - auto gpu = object.value; - auto* reference = references[counter]; - - if (reference) - { - // validate - if (!gpu) // throw errors only if corresponding cpu hook was VALID (eg. we may have nullptr for some index buffers in the span for converter but it's OK, I'm too lazy to filter them before passing to the converter inputs and don't want to deal with dynamic alloc) - { - logger->log("Failed to convert a CPU object to GPU!", ILogger::ELL_ERROR); - return false; - } - } - - ++counter; - } - - return true; - }; - - prepass.template operator() < ICPURenderpass > (hooks.renderpass); - prepass.template operator() < ICPUGraphicsPipeline > (hooks.pipelines); - prepass.template operator() < ICPUBuffer > (hooks.buffers); - // validate.template operator() < ICPUImageView > (hooks.attachments); - prepass.template operator() < ICPUDescriptorSet > (hooks.descriptorSet); - } - - auto semaphore = utilities->getLogicalDevice()->createSemaphore(0u); - - // TODO: compute submit as well for the images' mipmaps - SIntendedSubmitInfo transfer = {}; - transfer.queue = transferCapableQueue; - transfer.scratchCommandBuffers = commandBuffers; - transfer.scratchSemaphore = { - .semaphore = semaphore.get(), - .value = 0u, - .stageMask = PIPELINE_STAGE_FLAGS::ALL_TRANSFER_BITS - }; - // issue the convert call - { - CAssetConverter::SConvertParams params = {}; - params.utilities = utilities; - params.transfer = &transfer; - - // basically it records all data uploads and submits them right away - auto future = reservation.convert(params); - if (future.copy()!=IQueue::RESULT::SUCCESS) - { - logger->log("Failed to await submission feature!", ILogger::ELL_ERROR); - return false; - } - - // assign gpu objects to output - auto& base = static_cast(output); - { - auto&& [renderpass, pipelines, buffers, descriptorSet] = std::make_tuple(reservation.getGPUObjects().front().value, reservation.getGPUObjects(), reservation.getGPUObjects(), reservation.getGPUObjects().front().value); - { - base.renderpass = renderpass; - for (uint32_t i = 0u; i < pipelines.size(); ++i) - { - const auto type = static_cast(i); - const auto& [rcpu, rmeta] = scratch.objects[type]; - auto& [gpu, meta] = base.objects[type]; - - gpu.pipeline = pipelines[i].value; - // [[ [vertex, index] [vertex, index] [vertex, index] ... [ubo] ]] - gpu.bindings.vertex = {.offset = 0u, .buffer = buffers[2u * i + 0u].value}; - gpu.bindings.index = {.offset = 0u, .buffer = buffers[2u * i + 1u].value}; - - gpu.indexCount = rcpu.indexCount; - gpu.indexType = rcpu.indexType; - meta.name = rmeta.name; - meta.type = rmeta.type; - } - base.ubo = {.offset = 0u, .buffer = buffers.back().value}; - base.descriptorSet = descriptorSet; - - /* - // base.attachments.color = attachments[AI_COLOR].value; - // base.attachments.depth = attachments[AI_DEPTH].value; - - note conversion of image views is not yet supported by the asset converter - - it's complicated, we have to kinda temporary ignore DRY a bit here to not break the design which is correct - - TEMPORARY: we patch attachments by allocating them ourselves here given cpu instances & parameters - TODO: remove following code once asset converter works with image views & update stuff - */ - - for (uint32_t i = 0u; i < AI_COUNT; ++i) - { - const auto* reference = hooks.attachments[i]; - auto& out = (i == AI_COLOR ? base.attachments.color : base.attachments.depth); - - const auto& viewParams = reference->getCreationParameters(); - const auto& imageParams = viewParams.image->getCreationParameters(); - - auto image = utilities->getLogicalDevice()->createImage - ( - IGPUImage::SCreationParams - ({ - .type = imageParams.type, - .samples = imageParams.samples, - .format = imageParams.format, - .extent = imageParams.extent, - .mipLevels = imageParams.mipLevels, - .arrayLayers = imageParams.arrayLayers, - .usage = imageParams.usage - }) - ); - - if (!image) - { - logger->log("Could not create image!", ILogger::ELL_ERROR); - return false; - } - - bool IS_DEPTH = isDepthOrStencilFormat(imageParams.format); - std::string_view DEBUG_NAME = IS_DEPTH ? "UI Scene Depth Attachment Image" : "UI Scene Color Attachment Image"; - image->setObjectDebugName(DEBUG_NAME.data()); - - if (!utilities->getLogicalDevice()->allocate(image->getMemoryReqs(), image.get()).isValid()) - { - logger->log("Could not allocate memory for an image!", ILogger::ELL_ERROR); - return false; - } - - out = utilities->getLogicalDevice()->createImageView - ( - IGPUImageView::SCreationParams - ({ - .flags = viewParams.flags, - .subUsages = viewParams.subUsages, - .image = std::move(image), - .viewType = viewParams.viewType, - .format = viewParams.format, - .subresourceRange = viewParams.subresourceRange - }) - ); - - if (!out) - { - logger->log("Could not create image view!", ILogger::ELL_ERROR); - return false; - } - } - - logger->log("Image View attachments has been allocated by hand after asset converter successful submit becasuse it doesn't support converting them yet!", ILogger::ELL_WARNING); - } - } - } - } - else - { - auto completed = utilities->getLogicalDevice()->createSemaphore(0u); - - std::array signals; - { - auto& signal = signals.front(); - signal.value = 1; - signal.stageMask = bitflag(PIPELINE_STAGE_FLAGS::ALL_TRANSFER_BITS); - signal.semaphore = completed.get(); - } - - const IQueue::SSubmitInfo infos [] = - { - { - .waitSemaphores = {}, - .commandBuffers = commandBuffers, // note that here our command buffer is already recorded! - .signalSemaphores = signals - } - }; - - if (transferCapableQueue->submit(infos) != IQueue::RESULT::SUCCESS) - { - logger->log("Failed to submit transfer upload operations!", ILogger::ELL_ERROR); - return false; - } - - const ISemaphore::SWaitInfo info [] = - { { - .semaphore = completed.get(), - .value = 1 - } }; - - utilities->getLogicalDevice()->blockForSemaphores(info); - - static_cast(output) = static_cast(scratch); // scratch has all ready to use allocated gpu resources with uploaded memory so now just assign resources to base output - } - - // write the descriptor set - { - // descriptor write ubo - IGPUDescriptorSet::SWriteDescriptorSet write; - write.dstSet = output.descriptorSet.get(); - write.binding = 0; - write.arrayElement = 0u; - write.count = 1u; - - IGPUDescriptorSet::SDescriptorInfo info; - { - info.desc = smart_refctd_ptr(output.ubo.buffer); - info.info.buffer.offset = output.ubo.offset; - info.info.buffer.size = output.ubo.buffer->getSize(); - } - - write.info = &info; - - if(!utilities->getLogicalDevice()->updateDescriptorSets(1u, &write, 0u, nullptr)) - { - logger->log("Could not write descriptor set!", ILogger::ELL_ERROR); - return false; - } - } - - return true; - } - -private: - bool createDescriptorSetLayout() - { - EXPOSE_NABLA_NAMESPACES(); - - typename Types::descriptor_set_layout_t::SBinding bindings[] = - { - { - .binding = 0u, - .type = IDescriptor::E_TYPE::ET_UNIFORM_BUFFER, - .createFlags = Types::descriptor_set_layout_t::SBinding::E_CREATE_FLAGS::ECF_NONE, - .stageFlags = IShader::E_SHADER_STAGE::ESS_VERTEX | IShader::E_SHADER_STAGE::ESS_FRAGMENT, - .count = 1u, - } - }; - - if constexpr (withAssetConverter) - scratch.descriptorSetLayout = make_smart_refctd_ptr(bindings); - else - scratch.descriptorSetLayout = utilities->getLogicalDevice()->createDescriptorSetLayout(bindings); - - if (!scratch.descriptorSetLayout) - { - logger->log("Could not descriptor set layout!", ILogger::ELL_ERROR); - return false; - } - - return true; - } - - bool createDescriptorSet() - { - EXPOSE_NABLA_NAMESPACES(); - - if constexpr (withAssetConverter) - scratch.descriptorSet = make_smart_refctd_ptr(smart_refctd_ptr(scratch.descriptorSetLayout)); - else - { - const IGPUDescriptorSetLayout* const layouts[] = { scratch.descriptorSetLayout.get()}; - const uint32_t setCounts[] = { 1u }; - - // note descriptor set has back smart pointer to its pool, so we dont need to keep it explicitly - auto pool = utilities->getLogicalDevice()->createDescriptorPoolForDSLayouts(IDescriptorPool::E_CREATE_FLAGS::ECF_NONE, layouts, setCounts); - - if (!pool) - { - logger->log("Could not create Descriptor Pool!", ILogger::ELL_ERROR); - return false; - } - - pool->createDescriptorSets(layouts, &scratch.descriptorSet); - } - - if (!scratch.descriptorSet) - { - logger->log("Could not create Descriptor Set!", ILogger::ELL_ERROR); - return false; - } - - return true; - } - - bool createPipelineLayout() - { - EXPOSE_NABLA_NAMESPACES(); - - const std::span range = {}; - - if constexpr (withAssetConverter) - scratch.pipelineLayout = make_smart_refctd_ptr(range, nullptr, smart_refctd_ptr(scratch.descriptorSetLayout), nullptr, nullptr); - else - scratch.pipelineLayout = utilities->getLogicalDevice()->createPipelineLayout(range, nullptr, smart_refctd_ptr(scratch.descriptorSetLayout), nullptr, nullptr); - - if (!scratch.pipelineLayout) - { - logger->log("Could not create pipeline layout!", ILogger::ELL_ERROR); - return false; - } - - return true; - } - - bool createRenderpass() - { - EXPOSE_NABLA_NAMESPACES(); - - static constexpr Types::renderpass_t::SCreationParams::SColorAttachmentDescription colorAttachments[] = - { - { - { - { - .format = ColorFboAttachmentFormat, - .samples = Samples, - .mayAlias = false - }, - /* .loadOp = */ Types::renderpass_t::LOAD_OP::CLEAR, - /* .storeOp = */ Types::renderpass_t::STORE_OP::STORE, - /* .initialLayout = */ Types::image_t::LAYOUT::UNDEFINED, - /* .finalLayout = */ Types::image_t::LAYOUT::READ_ONLY_OPTIMAL - } - }, - Types::renderpass_t::SCreationParams::ColorAttachmentsEnd - }; - - static constexpr Types::renderpass_t::SCreationParams::SDepthStencilAttachmentDescription depthAttachments[] = - { - { - { - { - .format = DepthFboAttachmentFormat, - .samples = Samples, - .mayAlias = false - }, - /* .loadOp = */ {Types::renderpass_t::LOAD_OP::CLEAR}, - /* .storeOp = */ {Types::renderpass_t::STORE_OP::STORE}, - /* .initialLayout = */ {Types::image_t::LAYOUT::UNDEFINED}, - /* .finalLayout = */ {Types::image_t::LAYOUT::ATTACHMENT_OPTIMAL} - } - }, - Types::renderpass_t::SCreationParams::DepthStencilAttachmentsEnd - }; - - typename Types::renderpass_t::SCreationParams::SSubpassDescription subpasses[] = - { - {}, - Types::renderpass_t::SCreationParams::SubpassesEnd - }; - - subpasses[0].depthStencilAttachment.render = { .attachmentIndex = 0u,.layout = Types::image_t::LAYOUT::ATTACHMENT_OPTIMAL }; - subpasses[0].colorAttachments[0] = { .render = {.attachmentIndex = 0u, .layout = Types::image_t::LAYOUT::ATTACHMENT_OPTIMAL } }; - - static constexpr Types::renderpass_t::SCreationParams::SSubpassDependency dependencies[] = - { - // wipe-transition of Color to ATTACHMENT_OPTIMAL - { - .srcSubpass = Types::renderpass_t::SCreationParams::SSubpassDependency::External, - .dstSubpass = 0, - .memoryBarrier = - { - // - .srcStageMask = PIPELINE_STAGE_FLAGS::FRAGMENT_SHADER_BIT, - // only write ops, reads can't be made available - .srcAccessMask = ACCESS_FLAGS::SAMPLED_READ_BIT, - // destination needs to wait as early as possible - .dstStageMask = PIPELINE_STAGE_FLAGS::EARLY_FRAGMENT_TESTS_BIT | PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, - // because of depth test needing a read and a write - .dstAccessMask = ACCESS_FLAGS::DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | ACCESS_FLAGS::DEPTH_STENCIL_ATTACHMENT_READ_BIT | ACCESS_FLAGS::COLOR_ATTACHMENT_READ_BIT | ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT - } - // leave view offsets and flags default - }, - // color from ATTACHMENT_OPTIMAL to PRESENT_SRC - { - .srcSubpass = 0, - .dstSubpass = Types::renderpass_t::SCreationParams::SSubpassDependency::External, - .memoryBarrier = - { - // last place where the depth can get modified - .srcStageMask = PIPELINE_STAGE_FLAGS::COLOR_ATTACHMENT_OUTPUT_BIT, - // only write ops, reads can't be made available - .srcAccessMask = ACCESS_FLAGS::COLOR_ATTACHMENT_WRITE_BIT, - // - .dstStageMask = PIPELINE_STAGE_FLAGS::FRAGMENT_SHADER_BIT, - // - .dstAccessMask = ACCESS_FLAGS::SAMPLED_READ_BIT - // - } - // leave view offsets and flags default - }, - Types::renderpass_t::SCreationParams::DependenciesEnd - }; - - typename Types::renderpass_t::SCreationParams params = {}; - params.colorAttachments = colorAttachments; - params.depthStencilAttachments = depthAttachments; - params.subpasses = subpasses; - params.dependencies = dependencies; - - if constexpr (withAssetConverter) - scratch.renderpass = ICPURenderpass::create(params); - else - scratch.renderpass = utilities->getLogicalDevice()->createRenderpass(params); - - if (!scratch.renderpass) - { - logger->log("Could not create render pass!", ILogger::ELL_ERROR); - return false; - } - - return true; - } - - bool createFramebufferAttachments() - { - EXPOSE_NABLA_NAMESPACES(); - - auto createImageView = [&](smart_refctd_ptr& outView) -> smart_refctd_ptr - { - constexpr bool IS_DEPTH = isDepthOrStencilFormat(); - constexpr auto USAGE = [](const bool isDepth) - { - bitflag usage = Types::image_t::EUF_RENDER_ATTACHMENT_BIT; - - if (!isDepth) - usage |= Types::image_t::EUF_SAMPLED_BIT; - - return usage; - }(IS_DEPTH); - constexpr auto ASPECT = IS_DEPTH ? IImage::E_ASPECT_FLAGS::EAF_DEPTH_BIT : IImage::E_ASPECT_FLAGS::EAF_COLOR_BIT; - constexpr std::string_view DEBUG_NAME = IS_DEPTH ? "UI Scene Depth Attachment Image" : "UI Scene Color Attachment Image"; - { - smart_refctd_ptr image; - { - auto params = typename Types::image_t::SCreationParams( - { - .type = Types::image_t::ET_2D, - .samples = Samples, - .format = format, - .extent = { FramebufferW, FramebufferH, 1u }, - .mipLevels = 1u, - .arrayLayers = 1u, - .usage = USAGE - }); - - if constexpr (withAssetConverter) - image = ICPUImage::create(params); - else - image = utilities->getLogicalDevice()->createImage(std::move(params)); - } - - if (!image) - { - logger->log("Could not create image!", ILogger::ELL_ERROR); - return nullptr; - } - - if constexpr (withAssetConverter) - { - auto dummyBuffer = ICPUBuffer::create({ FramebufferW * FramebufferH * getTexelOrBlockBytesize() }); - dummyBuffer->setContentHash(dummyBuffer->computeContentHash()); - - auto regions = make_refctd_dynamic_array>(1u); - auto& region = regions->front(); - - region.imageSubresource = { .aspectMask = ASPECT, .mipLevel = 0u, .baseArrayLayer = 0u, .layerCount = 0u }; - region.bufferOffset = 0u; - region.bufferRowLength = IImageAssetHandlerBase::calcPitchInBlocks(FramebufferW, getTexelOrBlockBytesize()); - region.bufferImageHeight = 0u; - region.imageOffset = { 0u, 0u, 0u }; - region.imageExtent = { FramebufferW, FramebufferH, 1u }; - - if (!image->setBufferAndRegions(std::move(dummyBuffer), regions)) - { - logger->log("Could not set image's regions!", ILogger::ELL_ERROR); - return nullptr; - } - image->setContentHash(image->computeContentHash()); - } - else - { - image->setObjectDebugName(DEBUG_NAME.data()); - - if (!utilities->getLogicalDevice()->allocate(image->getMemoryReqs(), image.get()).isValid()) - { - logger->log("Could not allocate memory for an image!", ILogger::ELL_ERROR); - return nullptr; - } - } - - auto params = typename Types::image_view_t::SCreationParams - ({ - .flags = Types::image_view_t::ECF_NONE, - .subUsages = USAGE, - .image = std::move(image), - .viewType = Types::image_view_t::ET_2D, - .format = format, - .subresourceRange = { .aspectMask = ASPECT, .baseMipLevel = 0u, .levelCount = 1u, .baseArrayLayer = 0u, .layerCount = 1u } - }); - - if constexpr (withAssetConverter) - outView = make_smart_refctd_ptr(std::move(params)); - else - outView = utilities->getLogicalDevice()->createImageView(std::move(params)); - - if (!outView) - { - logger->log("Could not create image view!", ILogger::ELL_ERROR); - return nullptr; - } - - return smart_refctd_ptr(outView); - } - }; - - const bool allocated = createImageView.template operator() < ColorFboAttachmentFormat > (scratch.attachments.color) && createImageView.template operator() < DepthFboAttachmentFormat > (scratch.attachments.depth); - - if (!allocated) - { - logger->log("Could not allocate frame buffer's attachments!", ILogger::ELL_ERROR); - return false; - } - - return true; - } - - bool createShaders() - { - EXPOSE_NABLA_NAMESPACES(); - - auto createShader = [&](IShader::E_SHADER_STAGE stage, smart_refctd_ptr& outShader) -> smart_refctd_ptr - { - // TODO: use SPIRV loader & our ::system ns to get those cpu shaders, do not create myself (shit I forgot it exists) - - const SBuiltinFile& in = ::geometry::creator::spirv::builtin::get_resource(); - const auto buffer = ICPUBuffer::create({ { in.size }, (void*)in.contents, core::getNullMemoryResource() }, adopt_memory); - auto shader = make_smart_refctd_ptr(smart_refctd_ptr(buffer), stage, IShader::E_CONTENT_TYPE::ECT_SPIRV, ""); // must create cpu instance regardless underlying type - - if constexpr (withAssetConverter) - { - buffer->setContentHash(buffer->computeContentHash()); - outShader = std::move(shader); - } - else - outShader = utilities->getLogicalDevice()->createShader(shader.get()); - - return outShader; - }; - - typename ResourcesBundleScratch::Shaders& basic = scratch.shaders[GeometriesCpu::GP_BASIC]; - createShader.template operator() < NBL_CORE_UNIQUE_STRING_LITERAL_TYPE("geometryCreator/spirv/gc.basic.vertex.spv") > (IShader::E_SHADER_STAGE::ESS_VERTEX, basic.vertex); - createShader.template operator() < NBL_CORE_UNIQUE_STRING_LITERAL_TYPE("geometryCreator/spirv/gc.basic.fragment.spv") > (IShader::E_SHADER_STAGE::ESS_FRAGMENT, basic.fragment); - - typename ResourcesBundleScratch::Shaders& cone = scratch.shaders[GeometriesCpu::GP_CONE]; - createShader.template operator() < NBL_CORE_UNIQUE_STRING_LITERAL_TYPE("geometryCreator/spirv/gc.cone.vertex.spv") > (IShader::E_SHADER_STAGE::ESS_VERTEX, cone.vertex); - createShader.template operator() < NBL_CORE_UNIQUE_STRING_LITERAL_TYPE("geometryCreator/spirv/gc.basic.fragment.spv") > (IShader::E_SHADER_STAGE::ESS_FRAGMENT, cone.fragment); // note we reuse fragment from basic! - - typename ResourcesBundleScratch::Shaders& ico = scratch.shaders[GeometriesCpu::GP_ICO]; - createShader.template operator() < NBL_CORE_UNIQUE_STRING_LITERAL_TYPE("geometryCreator/spirv/gc.ico.vertex.spv") > (IShader::E_SHADER_STAGE::ESS_VERTEX, ico.vertex); - createShader.template operator() < NBL_CORE_UNIQUE_STRING_LITERAL_TYPE("geometryCreator/spirv/gc.basic.fragment.spv") > (IShader::E_SHADER_STAGE::ESS_FRAGMENT, ico.fragment); // note we reuse fragment from basic! - - for (const auto& it : scratch.shaders) - { - if (!it.vertex || !it.fragment) - { - logger->log("Could not create shaders!", ILogger::ELL_ERROR); - return false; - } - } - - return true; - } - - bool createGeometries() - { - EXPOSE_NABLA_NAMESPACES(); - - for (uint32_t i = 0; i < geometries.objects.size(); ++i) - { - const auto& inGeometry = geometries.objects[i]; - auto& [obj, meta] = scratch.objects[i]; - - bool status = true; - - meta.name = inGeometry.meta.name; - meta.type = inGeometry.meta.type; - - struct - { - SBlendParams blend; - SRasterizationParams rasterization; - typename Types::graphics_pipeline_t::SCreationParams pipeline; - } params; - - { - params.blend.logicOp = ELO_NO_OP; - - auto& b = params.blend.blendParams[0]; - b.srcColorFactor = EBF_SRC_ALPHA; - b.dstColorFactor = EBF_ONE_MINUS_SRC_ALPHA; - b.colorBlendOp = EBO_ADD; - b.srcAlphaFactor = EBF_SRC_ALPHA; - b.dstAlphaFactor = EBF_SRC_ALPHA; - b.alphaBlendOp = EBO_ADD; - b.colorWriteMask = (1u << 0u) | (1u << 1u) | (1u << 2u) | (1u << 3u); - } - - params.rasterization.faceCullingMode = EFCM_NONE; - { - const typename Types::shader_t::SSpecInfo info [] = - { - {.entryPoint = "VSMain", .shader = scratch.shaders[inGeometry.shadersType].vertex.get() }, - {.entryPoint = "PSMain", .shader = scratch.shaders[inGeometry.shadersType].fragment.get() } - }; - - params.pipeline.layout = scratch.pipelineLayout.get(); - params.pipeline.shaders = info; - params.pipeline.renderpass = scratch.renderpass.get(); - params.pipeline.cached = { .vertexInput = inGeometry.data.inputParams, .primitiveAssembly = inGeometry.data.assemblyParams, .rasterization = params.rasterization, .blend = params.blend, .subpassIx = 0u }; - - obj.indexCount = inGeometry.data.indexCount; - obj.indexType = inGeometry.data.indexType; - - // TODO: cache pipeline & try lookup for existing one first maybe - - // similar issue like with shaders again, in this case gpu contructor allows for extra cache parameters + there is no constructor you can use to fire make_smart_refctd_ptr yourself for cpu - if constexpr (withAssetConverter) - obj.pipeline = ICPUGraphicsPipeline::create(params.pipeline); - else - { - const std::array info = { { params.pipeline } }; - utilities->getLogicalDevice()->createGraphicsPipelines(nullptr, info, &obj.pipeline); - } - - if (!obj.pipeline) - { - logger->log("Could not create graphics pipeline for [%s] object!", ILogger::ELL_ERROR, meta.name.data()); - status = false; - } - - // object buffers - auto createVIBuffers = [&]() -> bool - { - using ibuffer_t = ::nbl::asset::IBuffer; // seems to be ambigous, both asset & core namespaces has IBuffer - - // note: similar issue like with shaders, this time with cpu-gpu constructors differing in arguments - auto vBuffer = smart_refctd_ptr(inGeometry.data.bindings[0].buffer); // no offset - constexpr static auto VERTEX_USAGE = bitflag(ibuffer_t::EUF_VERTEX_BUFFER_BIT) | ibuffer_t::EUF_TRANSFER_DST_BIT | ibuffer_t::EUF_INLINE_UPDATE_VIA_CMDBUF; - obj.bindings.vertex.offset = 0u; - - auto iBuffer = smart_refctd_ptr(inGeometry.data.indexBuffer.buffer); // no offset - constexpr static auto INDEX_USAGE = bitflag(ibuffer_t::EUF_INDEX_BUFFER_BIT) | ibuffer_t::EUF_VERTEX_BUFFER_BIT | ibuffer_t::EUF_TRANSFER_DST_BIT | ibuffer_t::EUF_INLINE_UPDATE_VIA_CMDBUF; - obj.bindings.index.offset = 0u; - - if constexpr (withAssetConverter) - { - if (!vBuffer) - return false; - - vBuffer->addUsageFlags(VERTEX_USAGE); - vBuffer->setContentHash(vBuffer->computeContentHash()); - obj.bindings.vertex = { .offset = 0u, .buffer = vBuffer }; - - if (inGeometry.data.indexType != EIT_UNKNOWN) - if (iBuffer) - { - iBuffer->addUsageFlags(INDEX_USAGE); - iBuffer->setContentHash(iBuffer->computeContentHash()); - } - else - return false; - - obj.bindings.index = { .offset = 0u, .buffer = iBuffer }; - } - else - { - auto vertexBuffer = utilities->getLogicalDevice()->createBuffer(IGPUBuffer::SCreationParams({ .size = vBuffer->getSize(), .usage = VERTEX_USAGE })); - auto indexBuffer = iBuffer ? utilities->getLogicalDevice()->createBuffer(IGPUBuffer::SCreationParams({ .size = iBuffer->getSize(), .usage = INDEX_USAGE })) : nullptr; - - if (!vertexBuffer) - return false; - - if (inGeometry.data.indexType != EIT_UNKNOWN) - if (!indexBuffer) - return false; - - const auto mask = utilities->getLogicalDevice()->getPhysicalDevice()->getUpStreamingMemoryTypeBits(); - for (auto it : { vertexBuffer , indexBuffer }) - { - if (it) - { - auto reqs = it->getMemoryReqs(); - reqs.memoryTypeBits &= mask; - - utilities->getLogicalDevice()->allocate(reqs, it.get()); - } - } - - // record transfer uploads - obj.bindings.vertex = { .offset = 0u, .buffer = std::move(vertexBuffer) }; - { - const SBufferRange range = { .offset = obj.bindings.vertex.offset, .size = obj.bindings.vertex.buffer->getSize(), .buffer = obj.bindings.vertex.buffer }; - if (!commandBuffer->updateBuffer(range, vBuffer->getPointer())) - { - logger->log("Could not record vertex buffer transfer upload for [%s] object!", ILogger::ELL_ERROR, meta.name.data()); - status = false; - } - } - obj.bindings.index = { .offset = 0u, .buffer = std::move(indexBuffer) }; - { - if (iBuffer) - { - const SBufferRange range = { .offset = obj.bindings.index.offset, .size = obj.bindings.index.buffer->getSize(), .buffer = obj.bindings.index.buffer }; - - if (!commandBuffer->updateBuffer(range, iBuffer->getPointer())) - { - logger->log("Could not record index buffer transfer upload for [%s] object!", ILogger::ELL_ERROR, meta.name.data()); - status = false; - } - } - } - } - - return true; - }; - - if (!createVIBuffers()) - { - logger->log("Could not create buffers for [%s] object!", ILogger::ELL_ERROR, meta.name.data()); - status = false; - } - - if (!status) - { - logger->log("[%s] object will not be created!", ILogger::ELL_ERROR, meta.name.data()); - - obj.bindings.vertex = {}; - obj.bindings.index = {}; - obj.indexCount = 0u; - obj.indexType = E_INDEX_TYPE::EIT_UNKNOWN; - obj.pipeline = nullptr; - - continue; - } - } - } - - return true; - } - - bool createViewParametersUboBuffer() - { - EXPOSE_NABLA_NAMESPACES(); - - using ibuffer_t = ::nbl::asset::IBuffer; // seems to be ambigous, both asset & core namespaces has IBuffer - constexpr static auto UboUsage = bitflag(ibuffer_t::EUF_UNIFORM_BUFFER_BIT) | ibuffer_t::EUF_TRANSFER_DST_BIT | ibuffer_t::EUF_INLINE_UPDATE_VIA_CMDBUF; - - if constexpr (withAssetConverter) - { - auto uboBuffer = ICPUBuffer::create({ sizeof(SBasicViewParameters) }); - uboBuffer->addUsageFlags(UboUsage); - uboBuffer->setContentHash(uboBuffer->computeContentHash()); - scratch.ubo = { .offset = 0u, .buffer = std::move(uboBuffer) }; - } - else - { - const auto mask = utilities->getLogicalDevice()->getPhysicalDevice()->getUpStreamingMemoryTypeBits(); - auto uboBuffer = utilities->getLogicalDevice()->createBuffer(IGPUBuffer::SCreationParams({ .size = sizeof(SBasicViewParameters), .usage = UboUsage })); - - if (!uboBuffer) - return false; - - for (auto it : { uboBuffer }) - { - IDeviceMemoryBacked::SDeviceMemoryRequirements reqs = it->getMemoryReqs(); - reqs.memoryTypeBits &= mask; - - utilities->getLogicalDevice()->allocate(reqs, it.get()); - } - - scratch.ubo = { .offset = 0u, .buffer = std::move(uboBuffer) }; - } - - return true; - } - - struct GeometriesCpu - { - enum GeometryShader - { - GP_BASIC = 0, - GP_CONE, - GP_ICO, - - GP_COUNT - }; - - struct ReferenceObjectCpu - { - ObjectMeta meta; - GeometryShader shadersType; - nbl::asset::CGeometryCreator::return_type data; - }; - - GeometriesCpu(const nbl::asset::IGeometryCreator* _gc) - : gc(_gc), - objects - ({ - ReferenceObjectCpu {.meta = {.type = OT_CUBE, .name = "Cube Mesh" }, .shadersType = GP_BASIC, .data = gc->createCubeMesh(nbl::core::vector3df(1.f, 1.f, 1.f)) }, - ReferenceObjectCpu {.meta = {.type = OT_SPHERE, .name = "Sphere Mesh" }, .shadersType = GP_BASIC, .data = gc->createSphereMesh(2, 16, 16) }, - ReferenceObjectCpu {.meta = {.type = OT_CYLINDER, .name = "Cylinder Mesh" }, .shadersType = GP_BASIC, .data = gc->createCylinderMesh(2, 2, 20) }, - ReferenceObjectCpu {.meta = {.type = OT_RECTANGLE, .name = "Rectangle Mesh" }, .shadersType = GP_BASIC, .data = gc->createRectangleMesh(nbl::core::vector2df_SIMD(1.5, 3)) }, - ReferenceObjectCpu {.meta = {.type = OT_DISK, .name = "Disk Mesh" }, .shadersType = GP_BASIC, .data = gc->createDiskMesh(2, 30) }, - ReferenceObjectCpu {.meta = {.type = OT_ARROW, .name = "Arrow Mesh" }, .shadersType = GP_BASIC, .data = gc->createArrowMesh() }, - ReferenceObjectCpu {.meta = {.type = OT_CONE, .name = "Cone Mesh" }, .shadersType = GP_CONE, .data = gc->createConeMesh(2, 3, 10) }, - ReferenceObjectCpu {.meta = {.type = OT_ICOSPHERE, .name = "Icoshpere Mesh" }, .shadersType = GP_ICO, .data = gc->createIcoSphere(1, 3, true) } - }) - { - gc = nullptr; // one shot - } - - private: - const nbl::asset::IGeometryCreator* gc; - - public: - const std::array objects; - }; - - using resources_bundle_base_t = ResourcesBundleBase; - - struct ResourcesBundleScratch : public resources_bundle_base_t - { - using Types = resources_bundle_base_t::Types; - - ResourcesBundleScratch() - : resources_bundle_base_t() {} - - struct Shaders - { - nbl::core::smart_refctd_ptr vertex = nullptr, fragment = nullptr; - }; - - nbl::core::smart_refctd_ptr descriptorSetLayout; - nbl::core::smart_refctd_ptr pipelineLayout; - std::array shaders; - }; - - // TODO: we could make those params templated with default values like below - static constexpr auto FramebufferW = 1280u, FramebufferH = 720u; - static constexpr auto ColorFboAttachmentFormat = nbl::asset::EF_R8G8B8A8_SRGB, DepthFboAttachmentFormat = nbl::asset::EF_D16_UNORM; - static constexpr auto Samples = nbl::video::IGPUImage::ESCF_1_BIT; - - ResourcesBundleScratch scratch; - - nbl::video::IUtilities* const utilities; - nbl::video::IGPUCommandBuffer* const commandBuffer; - nbl::system::ILogger* const logger; - GeometriesCpu geometries; -}; - -#undef TYPES_IMPL_BOILERPLATE - -struct ObjectDrawHookCpu -{ - nbl::core::matrix3x4SIMD model; - nbl::asset::SBasicViewParameters viewParameters; - ObjectMeta meta; -}; - -/* - Rendering to offline framebuffer which we don't present, color - scene attachment texture we use for second UI renderpass - sampling it & rendering into desired GUI area. - - The scene can be created from simple geometry - using our Geomtry Creator class. -*/ - -class CScene final : public nbl::core::IReferenceCounted -{ -public: - ObjectDrawHookCpu object; // TODO: this could be a vector (to not complicate the example I leave it single object), we would need a better system for drawing then to make only 1 max 2 indirect draw calls (indexed and not indexed objects) - - struct - { - const uint32_t startedValue = 0, finishedValue = 0x45; - nbl::core::smart_refctd_ptr progress; - } semaphore; - - struct CreateResourcesDirectlyWithDevice { using Builder = ResourceBuilder; }; - struct CreateResourcesWithAssetConverter { using Builder = ResourceBuilder; }; - - ~CScene() {} - - static inline nbl::core::smart_refctd_ptr createCommandBuffer(nbl::video::ILogicalDevice* const device, nbl::system::ILogger* const logger, const uint32_t familyIx) - { - EXPOSE_NABLA_NAMESPACES(); - auto pool = device->createCommandPool(familyIx, IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT); - - if (!pool) - { - logger->log("Couldn't create Command Pool!", ILogger::ELL_ERROR); - return nullptr; - } - - nbl::core::smart_refctd_ptr cmd; - - if (!pool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY, { &cmd , 1 })) - { - logger->log("Couldn't create Command Buffer!", ILogger::ELL_ERROR); - return nullptr; - } - - return cmd; - } - - template - static auto create(Args&&... args) -> decltype(auto) - { - EXPOSE_NABLA_NAMESPACES(); - - /* - user should call the constructor's args without last argument explicitly, this is a trick to make constructor templated, - eg.create(smart_refctd_ptr(device), smart_refctd_ptr(logger), queuePointer, geometryPointer) - */ - - auto* scene = new CScene(std::forward(args)..., CreateWith {}); - smart_refctd_ptr smart(scene, dont_grab); - - return smart; - } - - inline void begin() - { - EXPOSE_NABLA_NAMESPACES(); - - m_commandBuffer->reset(IGPUCommandBuffer::RESET_FLAGS::RELEASE_RESOURCES_BIT); - m_commandBuffer->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); - m_commandBuffer->beginDebugMarker("UISampleApp Offline Scene Frame"); - - semaphore.progress = m_utilities->getLogicalDevice()->createSemaphore(semaphore.startedValue); - } - - inline void record() - { - EXPOSE_NABLA_NAMESPACES(); - - const struct - { - const uint32_t width, height; - } fbo = { .width = m_frameBuffer->getCreationParameters().width, .height = m_frameBuffer->getCreationParameters().height }; - - SViewport viewport; - { - viewport.minDepth = 1.f; - viewport.maxDepth = 0.f; - viewport.x = 0u; - viewport.y = 0u; - viewport.width = fbo.width; - viewport.height = fbo.height; - } - - m_commandBuffer->setViewport(0u, 1u, &viewport); - - VkRect2D scissor = {}; - scissor.offset = { 0, 0 }; - scissor.extent = { fbo.width, fbo.height }; - m_commandBuffer->setScissor(0u, 1u, &scissor); - - const VkRect2D renderArea = - { - .offset = { 0,0 }, - .extent = { fbo.width, fbo.height } - }; - - const IGPUCommandBuffer::SRenderpassBeginInfo info = - { - .framebuffer = m_frameBuffer.get(), - .colorClearValues = &clear.color, - .depthStencilClearValues = &clear.depth, - .renderArea = renderArea - }; - - m_commandBuffer->beginRenderPass(info, IGPUCommandBuffer::SUBPASS_CONTENTS::INLINE); - - const auto& [hook, meta] = resources.objects[object.meta.type]; - auto* rawPipeline = hook.pipeline.get(); - - SBufferBinding vertex = hook.bindings.vertex, index = hook.bindings.index; - - m_commandBuffer->bindGraphicsPipeline(rawPipeline); - m_commandBuffer->bindDescriptorSets(EPBP_GRAPHICS, rawPipeline->getLayout(), 1, 1, &resources.descriptorSet.get()); - m_commandBuffer->bindVertexBuffers(0, 1, &vertex); - - if (index.buffer && hook.indexType != EIT_UNKNOWN) - { - m_commandBuffer->bindIndexBuffer(index, hook.indexType); - m_commandBuffer->drawIndexed(hook.indexCount, 1, 0, 0, 0); - } - else - m_commandBuffer->draw(hook.indexCount, 1, 0, 0); - - m_commandBuffer->endRenderPass(); - } - - inline void end() - { - m_commandBuffer->end(); - } - - inline bool submit() - { - EXPOSE_NABLA_NAMESPACES(); - - const IQueue::SSubmitInfo::SCommandBufferInfo buffers[] = - { - { .cmdbuf = m_commandBuffer.get() } - }; - - const IQueue::SSubmitInfo::SSemaphoreInfo signals[] = { {.semaphore = semaphore.progress.get(),.value = semaphore.finishedValue,.stageMask = PIPELINE_STAGE_FLAGS::FRAMEBUFFER_SPACE_BITS} }; - - const IQueue::SSubmitInfo infos[] = - { - { - .waitSemaphores = {}, - .commandBuffers = buffers, - .signalSemaphores = signals - } - }; - - return queue->submit(infos) == IQueue::RESULT::SUCCESS; - } - - // note: must be updated outside render pass - inline void update() - { - EXPOSE_NABLA_NAMESPACES(); - - SBufferRange range; - range.buffer = smart_refctd_ptr(resources.ubo.buffer); - range.size = resources.ubo.buffer->getSize(); - - m_commandBuffer->updateBuffer(range, &object.viewParameters); - } - - inline decltype(auto) getResources() - { - return (resources); // note: do not remove "()" - it makes the return type lvalue reference instead of copy - } - -private: - template // TODO: enforce constraints, only those 2 above are valid - CScene(nbl::core::smart_refctd_ptr _utilities, nbl::core::smart_refctd_ptr _logger, nbl::video::CThreadSafeQueueAdapter* _graphicsQueue, const nbl::asset::IGeometryCreator* _geometryCreator, CreateWith createWith = {}) - : m_utilities(nbl::core::smart_refctd_ptr(_utilities)), m_logger(nbl::core::smart_refctd_ptr(_logger)), queue(_graphicsQueue) - { - EXPOSE_NABLA_NAMESPACES(); - using Builder = typename CreateWith::Builder; - - m_commandBuffer = createCommandBuffer(m_utilities->getLogicalDevice(), m_utilities->getLogger(), queue->getFamilyIndex()); - Builder builder(m_utilities.get(), m_commandBuffer.get(), m_logger.get(), _geometryCreator); - - // gpu resources - if (builder.build()) - { - if (!builder.finalize(resources, queue)) - m_logger->log("Could not finalize resource objects to gpu objects!", ILogger::ELL_ERROR); - } - else - m_logger->log("Could not build resource objects!", ILogger::ELL_ERROR); - - // frame buffer - { - const auto extent = resources.attachments.color->getCreationParameters().image->getCreationParameters().extent; - - IGPUFramebuffer::SCreationParams params = - { - { - .renderpass = smart_refctd_ptr(resources.renderpass), - .depthStencilAttachments = &resources.attachments.depth.get(), - .colorAttachments = &resources.attachments.color.get(), - .width = extent.width, - .height = extent.height, - .layers = 1u - } - }; - - m_frameBuffer = m_utilities->getLogicalDevice()->createFramebuffer(std::move(params)); - - if (!m_frameBuffer) - { - m_logger->log("Could not create frame buffer!", ILogger::ELL_ERROR); - return; - } - } - } - - nbl::core::smart_refctd_ptr m_utilities; - nbl::core::smart_refctd_ptr m_logger; - - nbl::video::CThreadSafeQueueAdapter* queue; - nbl::core::smart_refctd_ptr m_commandBuffer; - - nbl::core::smart_refctd_ptr m_frameBuffer; - - ResourcesBundle resources; -}; - -} // nbl::scene::geometrycreator - -#endif // _NBL_GEOMETRY_CREATOR_SCENE_H_INCLUDED_ \ No newline at end of file diff --git a/common/include/SBasicViewParameters.hlsl b/common/include/SBasicViewParameters.hlsl deleted file mode 100644 index 0d0990186..000000000 --- a/common/include/SBasicViewParameters.hlsl +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef _S_BASIC_VIEW_PARAMETERS_COMMON_HLSL_ -#define _S_BASIC_VIEW_PARAMETERS_COMMON_HLSL_ - -#ifdef __HLSL_VERSION -struct SBasicViewParameters //! matches CPU version size & alignment (160, 4) -{ - float4x4 MVP; - float3x4 MV; - float3x3 normalMat; -}; -#endif // _S_BASIC_VIEW_PARAMETERS_COMMON_HLSL_ - -#endif - -/* - do not remove this text, WAVE is so bad that you can get errors if no proper ending xD -*/ \ No newline at end of file diff --git a/common/include/nbl/examples/PCH.hpp b/common/include/nbl/examples/PCH.hpp new file mode 100644 index 000000000..0905465c2 --- /dev/null +++ b/common/include/nbl/examples/PCH.hpp @@ -0,0 +1,28 @@ +// Copyright (C) 2018-2025 - DevSH Graphics Programming Sp. z O.O. +// This file is part of the "Nabla Engine". +// For conditions of distribution and use, see copyright notice in nabla.h +#ifndef _NBL_EXAMPLES_PCH_HPP_ +#define _NBL_EXAMPLES_PCH_HPP_ + +//! Precompiled header (PCH) for Nabla Examples +/* + NOTE: currently our whole public and private interface is broken + and private headers leak to public includes +*/ + +//! Nabla declarations +#include "nabla.h" + +//! Common example interface headers +#include "nbl/examples/common/SimpleWindowedApplication.hpp" +#include "nbl/examples/common/MonoWindowApplication.hpp" +#include "nbl/examples/common/InputSystem.hpp" +#include "nbl/examples/common/CEventCallback.hpp" + +#include "nbl/examples/cameras/CCamera.hpp" + +#include "nbl/examples/geometry/CGeometryCreatorScene.hpp" +#include "nbl/examples/geometry/CSimpleDebugRenderer.hpp" + + +#endif // _NBL_EXAMPLES_COMMON_PCH_HPP_ \ No newline at end of file diff --git a/common/include/CCamera.hpp b/common/include/nbl/examples/cameras/CCamera.hpp similarity index 99% rename from common/include/CCamera.hpp rename to common/include/nbl/examples/cameras/CCamera.hpp index 1b0fe9c0f..3b3cd38d8 100644 --- a/common/include/CCamera.hpp +++ b/common/include/nbl/examples/cameras/CCamera.hpp @@ -1,16 +1,18 @@ // Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h +#ifndef _NBL_COMMON_CAMERA_IMPL_ +#define _NBL_COMMON_CAMERA_IMPL_ -#ifndef _CAMERA_IMPL_ -#define _CAMERA_IMPL_ #include + #include #include #include #include + class Camera { public: @@ -322,5 +324,4 @@ class Camera std::chrono::microseconds nextPresentationTimeStamp, lastVirtualUpTimeStamp; }; - -#endif // _CAMERA_IMPL_ \ No newline at end of file +#endif \ No newline at end of file diff --git a/common/include/nbl/examples/common/BuiltinResourcesApplication.hpp b/common/include/nbl/examples/common/BuiltinResourcesApplication.hpp new file mode 100644 index 000000000..aa1949ecd --- /dev/null +++ b/common/include/nbl/examples/common/BuiltinResourcesApplication.hpp @@ -0,0 +1,68 @@ +// Copyright (C) 2023-2025 - DevSH Graphics Programming Sp. z O.O. +// This file is part of the "Nabla Engine". +// For conditions of distribution and use, see copyright notice in nabla.h +#ifndef _NBL_EXAMPLES_BUILTIN_RESOURCE_APPLICATION_HPP_INCLUDED_ +#define _NBL_EXAMPLES_BUILTIN_RESOURCE_APPLICATION_HPP_INCLUDED_ + + +// we need a system, logger and an asset manager +#include "nbl/application_templates/MonoAssetManagerApplication.hpp" + +#ifdef NBL_EMBED_BUILTIN_RESOURCES +// TODO: the include/header `nbl/examples` archive +// TODO: the source `nbl/examples` archive +// TODO: the build `nbl/examples` archive +#if __has_include("nbl/this_example/builtin/CArchive.h") + #include "nbl/this_example/builtin/CArchive.h" +#endif +#endif + + +namespace nbl::examples +{ + +// Virtual Inheritance because apps might end up doing diamond inheritance +class BuiltinResourcesApplication : public virtual application_templates::MonoAssetManagerApplication +{ + using base_t = MonoAssetManagerApplication; + + public: + using base_t::base_t; + + protected: + // need this one for skipping passing all args into ApplicationFramework + BuiltinResourcesApplication() = default; + + virtual bool onAppInitialized(core::smart_refctd_ptr&& system) override + { + if (!base_t::onAppInitialized(std::move(system))) + return false; + + using namespace core; + + smart_refctd_ptr examplesHeaderArch,examplesSourceArch,examplesBuildArch,thisExampleArch; + #ifdef NBL_EMBED_BUILTIN_RESOURCES +// TODO: the 3 examples archives + #ifdef _NBL_THIS_EXAMPLE_BUILTIN_C_ARCHIVE_H_ + thisExampleArch = make_smart_refctd_ptr(smart_refctd_ptr(m_logger)); + #endif + #else + examplesHeaderArch = make_smart_refctd_ptr(localInputCWD/"../common/include/nbl/examples",smart_refctd_ptr(m_logger),m_system.get()); + examplesSourceArch = make_smart_refctd_ptr(localInputCWD/"../common/src/nbl/examples",smart_refctd_ptr(m_logger),m_system.get()); +// TODO: examplesBuildArch = + thisExampleArch = make_smart_refctd_ptr(localInputCWD/"app_resources",smart_refctd_ptr(m_logger),m_system.get()); + #endif + // yes all 3 aliases are meant to be the same + m_system->mount(std::move(examplesHeaderArch),"nbl/examples"); + m_system->mount(std::move(examplesSourceArch),"nbl/examples"); +// m_system->mount(std::move(examplesBuildArch),"nbl/examples"); + if (thisExampleArch) + m_system->mount(std::move(thisExampleArch),"app_resources"); + + return true; + } +}; + +} + +#endif // _CAMERA_IMPL_ \ No newline at end of file diff --git a/common/include/nbl/examples/common/CEventCallback.hpp b/common/include/nbl/examples/common/CEventCallback.hpp new file mode 100644 index 000000000..cae6dc7de --- /dev/null +++ b/common/include/nbl/examples/common/CEventCallback.hpp @@ -0,0 +1,54 @@ +#ifndef _NBL_EXAMPLES_COMMON_C_EVENT_CALLBACK_HPP_INCLUDED_ +#define _NBL_EXAMPLES_COMMON_C_EVENT_CALLBACK_HPP_INCLUDED_ + + +#include "nbl/video/utilities/CSimpleResizeSurface.h" + +#include "nbl/examples/common/InputSystem.hpp" + + +namespace nbl::examples +{ +class CEventCallback : public nbl::video::ISimpleManagedSurface::ICallback +{ + public: + CEventCallback(nbl::core::smart_refctd_ptr&& m_inputSystem, nbl::system::logger_opt_smart_ptr&& logger) : m_inputSystem(std::move(m_inputSystem)), m_logger(std::move(logger)) {} + CEventCallback() {} + + void setLogger(nbl::system::logger_opt_smart_ptr& logger) + { + m_logger = logger; + } + void setInputSystem(nbl::core::smart_refctd_ptr&& m_inputSystem) + { + m_inputSystem = std::move(m_inputSystem); + } + + private: + void onMouseConnected_impl(nbl::core::smart_refctd_ptr&& mch) override + { + m_logger.log("A mouse %p has been connected", nbl::system::ILogger::ELL_INFO, mch.get()); + m_inputSystem.get()->add(m_inputSystem.get()->m_mouse, std::move(mch)); + } + void onMouseDisconnected_impl(nbl::ui::IMouseEventChannel* mch) override + { + m_logger.log("A mouse %p has been disconnected", nbl::system::ILogger::ELL_INFO, mch); + m_inputSystem.get()->remove(m_inputSystem.get()->m_mouse, mch); + } + void onKeyboardConnected_impl(nbl::core::smart_refctd_ptr&& kbch) override + { + m_logger.log("A keyboard %p has been connected", nbl::system::ILogger::ELL_INFO, kbch.get()); + m_inputSystem.get()->add(m_inputSystem.get()->m_keyboard, std::move(kbch)); + } + void onKeyboardDisconnected_impl(nbl::ui::IKeyboardEventChannel* kbch) override + { + m_logger.log("A keyboard %p has been disconnected", nbl::system::ILogger::ELL_INFO, kbch); + m_inputSystem.get()->remove(m_inputSystem.get()->m_keyboard, kbch); + } + + private: + nbl::core::smart_refctd_ptr m_inputSystem = nullptr; + nbl::system::logger_opt_smart_ptr m_logger = nullptr; +}; +} +#endif \ No newline at end of file diff --git a/common/include/nbl/examples/common/CSwapchainFramebuffersAndDepth.hpp b/common/include/nbl/examples/common/CSwapchainFramebuffersAndDepth.hpp new file mode 100644 index 000000000..c7d780fdf --- /dev/null +++ b/common/include/nbl/examples/common/CSwapchainFramebuffersAndDepth.hpp @@ -0,0 +1,108 @@ +// Copyright (C) 2023-2025 - DevSH Graphics Programming Sp. z O.O. +// This file is part of the "Nabla Engine". +// For conditions of distribution and use, see copyright notice in nabla.h +#ifndef _NBL_EXAMPLES_COMMON_C_SWAPCHAIN_FRAMEBUFFERS_AND_DEPTH_HPP_INCLUDED_ +#define _NBL_EXAMPLES_COMMON_C_SWAPCHAIN_FRAMEBUFFERS_AND_DEPTH_HPP_INCLUDED_ + +// Build on top of the previous one +#include "nbl/application_templates/BasicMultiQueueApplication.hpp" + +namespace nbl::examples +{ + +class CSwapchainFramebuffersAndDepth final : public video::CDefaultSwapchainFramebuffers +{ + using base_t = CDefaultSwapchainFramebuffers; + + public: + template + inline CSwapchainFramebuffersAndDepth(video::ILogicalDevice* device, const asset::E_FORMAT _desiredDepthFormat, Args&&... args) : base_t(device,std::forward(args)...) + { + // user didn't want any depth + if (_desiredDepthFormat==asset::EF_UNKNOWN) + return; + + using namespace nbl::asset; + using namespace nbl::video; + const IPhysicalDevice::SImageFormatPromotionRequest req = { + .originalFormat = _desiredDepthFormat, + .usages = {IGPUImage::EUF_RENDER_ATTACHMENT_BIT} + }; + m_depthFormat = m_device->getPhysicalDevice()->promoteImageFormat(req,IGPUImage::TILING::OPTIMAL); + + const static IGPURenderpass::SCreationParams::SDepthStencilAttachmentDescription depthAttachments[] = { + {{ + { + .format = m_depthFormat, + .samples = IGPUImage::ESCF_1_BIT, + .mayAlias = false + }, + /*.loadOp = */{IGPURenderpass::LOAD_OP::CLEAR}, + /*.storeOp = */{IGPURenderpass::STORE_OP::STORE}, + /*.initialLayout = */{IGPUImage::LAYOUT::UNDEFINED}, // because we clear we don't care about contents + /*.finalLayout = */{IGPUImage::LAYOUT::ATTACHMENT_OPTIMAL} + }}, + IGPURenderpass::SCreationParams::DepthStencilAttachmentsEnd + }; + m_params.depthStencilAttachments = depthAttachments; + + static IGPURenderpass::SCreationParams::SSubpassDescription subpasses[] = { + m_params.subpasses[0], + IGPURenderpass::SCreationParams::SubpassesEnd + }; + subpasses[0].depthStencilAttachment.render = { .attachmentIndex = 0,.layout = IGPUImage::LAYOUT::ATTACHMENT_OPTIMAL }; + m_params.subpasses = subpasses; + } + + protected: + inline bool onCreateSwapchain_impl(const uint8_t qFam) override + { + using namespace nbl::asset; + using namespace nbl::video; + if (m_depthFormat!=asset::EF_UNKNOWN) + { + // DOCS: why are we not using `m_device` here? any particular reason? + auto device = const_cast(m_renderpass->getOriginDevice()); + + const auto depthFormat = m_renderpass->getCreationParameters().depthStencilAttachments[0].format; + const auto& sharedParams = getSwapchain()->getCreationParameters().sharedParams; + auto image = device->createImage({ IImage::SCreationParams{ + .type = IGPUImage::ET_2D, + .samples = IGPUImage::ESCF_1_BIT, + .format = depthFormat, + .extent = {sharedParams.width,sharedParams.height,1}, + .mipLevels = 1, + .arrayLayers = 1, + .depthUsage = IGPUImage::EUF_RENDER_ATTACHMENT_BIT + } }); + + device->allocate(image->getMemoryReqs(), image.get()); + + m_depthBuffer = device->createImageView({ + .flags = IGPUImageView::ECF_NONE, + .subUsages = IGPUImage::EUF_RENDER_ATTACHMENT_BIT, + .image = std::move(image), + .viewType = IGPUImageView::ET_2D, + .format = depthFormat, + .subresourceRange = {IGPUImage::EAF_DEPTH_BIT,0,1,0,1} + }); + } + const auto retval = base_t::onCreateSwapchain_impl(qFam); + m_depthBuffer = nullptr; + return retval; + } + + inline core::smart_refctd_ptr createFramebuffer(video::IGPUFramebuffer::SCreationParams&& params) override + { + if (m_depthBuffer) + params.depthStencilAttachments = &m_depthBuffer.get(); + return m_device->createFramebuffer(std::move(params)); + } + + asset::E_FORMAT m_depthFormat = asset::EF_UNKNOWN; + // only used to pass a parameter from `onCreateSwapchain_impl` to `createFramebuffer` + core::smart_refctd_ptr m_depthBuffer; +}; + +} +#endif \ No newline at end of file diff --git a/common/include/InputSystem.hpp b/common/include/nbl/examples/common/InputSystem.hpp similarity index 84% rename from common/include/InputSystem.hpp rename to common/include/nbl/examples/common/InputSystem.hpp index c42b738d0..c30fc1212 100644 --- a/common/include/InputSystem.hpp +++ b/common/include/nbl/examples/common/InputSystem.hpp @@ -4,16 +4,19 @@ #ifndef _NBL_EXAMPLES_COMMON_INPUT_SYSTEM_HPP_INCLUDED_ #define _NBL_EXAMPLES_COMMON_INPUT_SYSTEM_HPP_INCLUDED_ -class InputSystem : public nbl::core::IReferenceCounted +namespace nbl::examples +{ + +class InputSystem : public core::IReferenceCounted { public: template struct Channels { - nbl::core::mutex lock; + core::mutex lock; std::condition_variable added; - nbl::core::vector> channels; - nbl::core::vector timeStamps; + core::vector> channels; + core::vector timeStamps; uint32_t defaultChannelIndex = 0; }; // TODO: move to "nbl/ui/InputEventChannel.h" once the interface of this utility struct matures, also maybe rename to `Consumer` ? @@ -21,7 +24,7 @@ class InputSystem : public nbl::core::IReferenceCounted struct ChannelReader { template - inline void consumeEvents(F&& processFunc, nbl::system::logger_opt_ptr logger=nullptr) + inline void consumeEvents(F&& processFunc, system::logger_opt_ptr logger=nullptr) { auto events = channel->getEvents(); const auto frontBufferCapacity = channel->getFrontBufferCapacity(); @@ -29,7 +32,7 @@ class InputSystem : public nbl::core::IReferenceCounted { logger.log( "Detected overflow, %d unconsumed events in channel of size %d!", - nbl::system::ILogger::ELL_ERROR,events.size()-consumedCounter,frontBufferCapacity + system::ILogger::ELL_ERROR,events.size()-consumedCounter,frontBufferCapacity ); consumedCounter = events.size()-frontBufferCapacity; } @@ -38,22 +41,22 @@ class InputSystem : public nbl::core::IReferenceCounted consumedCounter = events.size(); } - nbl::core::smart_refctd_ptr channel = nullptr; + core::smart_refctd_ptr channel = nullptr; uint64_t consumedCounter = 0ull; }; - InputSystem(nbl::system::logger_opt_smart_ptr&& logger) : m_logger(std::move(logger)) {} + InputSystem(system::logger_opt_smart_ptr&& logger) : m_logger(std::move(logger)) {} - void getDefaultMouse(ChannelReader* reader) + void getDefaultMouse(ChannelReader* reader) { getDefault(m_mouse,reader); } - void getDefaultKeyboard(ChannelReader* reader) + void getDefaultKeyboard(ChannelReader* reader) { getDefault(m_keyboard,reader); } template - void add(Channels& channels, nbl::core::smart_refctd_ptr&& channel) + void add(Channels& channels, core::smart_refctd_ptr&& channel) { std::unique_lock lock(channels.lock); channels.channels.push_back(std::move(channel)); @@ -94,7 +97,7 @@ class InputSystem : public nbl::core::IReferenceCounted std::unique_lock lock(channels.lock); while (channels.channels.empty()) { - m_logger.log("Waiting For Input Device to be connected...",nbl::system::ILogger::ELL_INFO); + m_logger.log("Waiting For Input Device to be connected...",system::ILogger::ELL_INFO); channels.added.wait(lock); } @@ -159,7 +162,7 @@ class InputSystem : public nbl::core::IReferenceCounted } if(defaultIdx != newDefaultIdx) { - m_logger.log("Default InputChannel for ChannelType changed from %u to %u",nbl::system::ILogger::ELL_INFO, defaultIdx, newDefaultIdx); + m_logger.log("Default InputChannel for ChannelType changed from %u to %u",system::ILogger::ELL_INFO, defaultIdx, newDefaultIdx); defaultIdx = newDefaultIdx; channels.defaultChannelIndex = newDefaultIdx; @@ -177,10 +180,10 @@ class InputSystem : public nbl::core::IReferenceCounted reader->consumedCounter = consumedCounter; } - nbl::system::logger_opt_smart_ptr m_logger; - Channels m_mouse; - Channels m_keyboard; + system::logger_opt_smart_ptr m_logger; + Channels m_mouse; + Channels m_keyboard; }; - +} #endif diff --git a/common/include/nbl/examples/common/MonoWindowApplication.hpp b/common/include/nbl/examples/common/MonoWindowApplication.hpp new file mode 100644 index 000000000..0f18012c0 --- /dev/null +++ b/common/include/nbl/examples/common/MonoWindowApplication.hpp @@ -0,0 +1,189 @@ +// Copyright (C) 2023-2023 - DevSH Graphics Programming Sp. z O.O. +// This file is part of the "Nabla Engine". +// For conditions of distribution and use, see copyright notice in nabla.h +#ifndef _NBL_EXAMPLES_COMMON_MONO_WINDOW_APPLICATION_HPP_INCLUDED_ +#define _NBL_EXAMPLES_COMMON_MONO_WINDOW_APPLICATION_HPP_INCLUDED_ + +// Build on top of the previous one +#include "nbl/examples/common/SimpleWindowedApplication.hpp" +#include "nbl/examples/common/CSwapchainFramebuffersAndDepth.hpp" +#include "nbl/examples/common/CEventCallback.hpp" + +namespace nbl::examples +{ + +// Virtual Inheritance because apps might end up doing diamond inheritance +class MonoWindowApplication : public virtual SimpleWindowedApplication +{ + using base_t = SimpleWindowedApplication; + + public: + // Maximum frames which can be simultaneously submitted, used to cycle through our per-frame resources like command buffers + constexpr static inline uint8_t MaxFramesInFlight = 3; + + template + MonoWindowApplication(const hlsl::uint16_t2 _initialResolution, const asset::E_FORMAT _depthFormat, Args&&... args) : + base_t(std::forward(args)...), m_initialResolution(_initialResolution), m_depthFormat(_depthFormat) {} + + // + inline core::vector getSurfaces() const override final + { + if (!m_surface) + { + using namespace nbl::core; + using namespace nbl::ui; + using namespace nbl::video; + { + auto windowCallback = make_smart_refctd_ptr(smart_refctd_ptr(m_inputSystem),smart_refctd_ptr(m_logger)); + IWindow::SCreationParams params = {}; + params.callback = make_smart_refctd_ptr(); + params.width = m_initialResolution[0]; + params.height = m_initialResolution[1]; + params.x = 32; + params.y = 32; + params.flags = ui::IWindow::ECF_HIDDEN | IWindow::ECF_BORDERLESS | IWindow::ECF_RESIZABLE; + params.windowCaption = "MonoWindowApplication"; + params.callback = windowCallback; + const_cast&>(m_window) = m_winMgr->createWindow(std::move(params)); + } + + auto surface = CSurfaceVulkanWin32::create(smart_refctd_ptr(m_api), smart_refctd_ptr_static_cast(m_window)); + const_cast&>(m_surface) = CSimpleResizeSurface::create(std::move(surface)); + } + + if (m_surface) + return { {m_surface->getSurface()/*,EQF_NONE*/} }; + + return {}; + } + + virtual inline bool onAppInitialized(core::smart_refctd_ptr&& system) override + { + using namespace nbl::core; + using namespace nbl::video; + // want to have a usable system and logger first + if (!MonoSystemMonoLoggerApplication::onAppInitialized(std::move(system))) + return false; + + m_inputSystem = make_smart_refctd_ptr(system::logger_opt_smart_ptr(smart_refctd_ptr(m_logger))); + if (!base_t::onAppInitialized(std::move(system))) + return false; + + ISwapchain::SCreationParams swapchainParams = { .surface = smart_refctd_ptr(m_surface->getSurface()) }; + if (!swapchainParams.deduceFormat(m_physicalDevice)) + return logFail("Could not choose a Surface Format for the Swapchain!"); + + // TODO: option without depth + auto scResources = std::make_unique(m_device.get(),m_depthFormat,swapchainParams.surfaceFormat.format,getDefaultSubpassDependencies()); + auto* renderpass = scResources->getRenderpass(); + + if (!renderpass) + return logFail("Failed to create Renderpass!"); + + auto gQueue = getGraphicsQueue(); + if (!m_surface || !m_surface->init(gQueue,std::move(scResources),swapchainParams.sharedParams)) + return logFail("Could not create Window & Surface or initialize the Surface!"); + + m_winMgr->setWindowSize(m_window.get(),m_initialResolution[0],m_initialResolution[1]); + m_surface->recreateSwapchain(); + + return true; + } + + // we do slight inversion of control here + inline void workLoopBody() override final + { + using namespace nbl::core; + using namespace nbl::video; + // framesInFlight: ensuring safe execution of command buffers and acquires, `framesInFlight` only affect semaphore waits, don't use this to index your resources because it can change with swapchain recreation. + const uint32_t framesInFlightCount = hlsl::min(MaxFramesInFlight,m_surface->getMaxAcquiresInFlight()); + // We block for semaphores for 2 reasons here: + // A) Resource: Can't use resource like a command buffer BEFORE previous use is finished! [MaxFramesInFlight] + // B) Acquire: Can't have more acquires in flight than a certain threshold returned by swapchain or your surface helper class. [MaxAcquiresInFlight] + if (m_framesInFlight.size()>=framesInFlightCount) + { + const ISemaphore::SWaitInfo framesDone[] = + { + { + .semaphore = m_framesInFlight.front().semaphore.get(), + .value = m_framesInFlight.front().value + } + }; + if (m_device->blockForSemaphores(framesDone)!=ISemaphore::WAIT_RESULT::SUCCESS) + return; + m_framesInFlight.pop_front(); + } + + auto updatePresentationTimestamp = [&]() + { + m_currentImageAcquire = m_surface->acquireNextImage(); + + // TODO: better frame pacing than this + oracle.reportEndFrameRecord(); + const auto timestamp = oracle.getNextPresentationTimeStamp(); + oracle.reportBeginFrameRecord(); + + return timestamp; + }; + + const auto nextPresentationTimestamp = updatePresentationTimestamp(); + + if (!m_currentImageAcquire) + return; + + const IQueue::SSubmitInfo::SSemaphoreInfo rendered[] = {renderFrame(nextPresentationTimestamp)}; + m_surface->present(m_currentImageAcquire.imageIndex,rendered); + if (rendered->semaphore) + m_framesInFlight.emplace_back(smart_refctd_ptr(rendered->semaphore),rendered->value); + } + + // + virtual inline bool keepRunning() override + { + if (m_surface->irrecoverable()) + return false; + + return true; + } + + // + virtual inline bool onAppTerminated() + { + m_inputSystem = nullptr; + m_device->waitIdle(); + m_framesInFlight.clear(); + m_surface = nullptr; + m_window = nullptr; + return base_t::onAppTerminated(); + } + + protected: + inline void onAppInitializedFinish() + { + m_winMgr->show(m_window.get()); + oracle.reportBeginFrameRecord(); + } + inline const auto& getCurrentAcquire() const {return m_currentImageAcquire;} + + virtual const video::IGPURenderpass::SCreationParams::SSubpassDependency* getDefaultSubpassDependencies() const = 0; + virtual video::IQueue::SSubmitInfo::SSemaphoreInfo renderFrame(const std::chrono::microseconds nextPresentationTimestamp) = 0; + + const hlsl::uint16_t2 m_initialResolution; + const asset::E_FORMAT m_depthFormat; + core::smart_refctd_ptr m_inputSystem; + core::smart_refctd_ptr m_window; + core::smart_refctd_ptr> m_surface; + + private: + struct SSubmittedFrame + { + core::smart_refctd_ptr semaphore; + uint64_t value; + }; + core::deque m_framesInFlight; + video::ISimpleManagedSurface::SAcquireResult m_currentImageAcquire = {}; + video::CDumbPresentationOracle oracle; +}; + +} +#endif \ No newline at end of file diff --git a/common/include/nbl/examples/common/SBasicViewParameters.hlsl b/common/include/nbl/examples/common/SBasicViewParameters.hlsl new file mode 100644 index 000000000..b7ad31cb6 --- /dev/null +++ b/common/include/nbl/examples/common/SBasicViewParameters.hlsl @@ -0,0 +1,29 @@ +#ifndef _NBL_EXAMPLES_S_BASIC_VIEW_PARAMETERS_HLSL_ +#define _NBL_EXAMPLES_S_BASIC_VIEW_PARAMETERS_HLSL_ + + +#include "nbl/builtin/hlsl/cpp_compat/matrix.hlsl" + + +namespace nbl +{ +namespace hlsl +{ +namespace examples +{ + +struct SBasicViewParameters +{ + float32_t4x4 MVP; + float32_t3x4 MV; + float32_t3x3 normalMat; +}; + +} +} +} +#endif + +/* + do not remove this text, WAVE is so bad that you can get errors if no proper ending xD +*/ \ No newline at end of file diff --git a/common/include/SimpleWindowedApplication.hpp b/common/include/nbl/examples/common/SimpleWindowedApplication.hpp similarity index 99% rename from common/include/SimpleWindowedApplication.hpp rename to common/include/nbl/examples/common/SimpleWindowedApplication.hpp index 802a93188..ddb510eb7 100644 --- a/common/include/SimpleWindowedApplication.hpp +++ b/common/include/nbl/examples/common/SimpleWindowedApplication.hpp @@ -88,5 +88,4 @@ class SimpleWindowedApplication : public virtual application_templates::BasicMul }; } - -#endif // _CAMERA_IMPL_ \ No newline at end of file +#endif \ No newline at end of file diff --git a/common/include/nbl/examples/examples.hpp b/common/include/nbl/examples/examples.hpp new file mode 100644 index 000000000..d82303514 --- /dev/null +++ b/common/include/nbl/examples/examples.hpp @@ -0,0 +1,24 @@ +// Copyright (C) 2018-2025 - DevSH Graphics Programming Sp. z O.O. +// This file is part of the "Nabla Engine". +// For conditions of distribution and use, see copyright notice in nabla.h +#ifndef _NBL_EXAMPLES_HPP_ +#define _NBL_EXAMPLES_HPP_ + + +//! Precompiled header shared across all examples +#include "nbl/examples/PCH.hpp" + +//! Example specific headers that must not be included in the PCH +/* + NOTE: Add here if they depend on preprocessor definitions + or macros that are specific to individual example targets + (eg. defined in CMake) +*/ + +// #include "..." + +// Cannot be in PCH because depens on definition of `this_example` for Example's builtins +#include "nbl/examples/common/BuiltinResourcesApplication.hpp" + + +#endif // _NBL_EXAMPLES_HPP_ \ No newline at end of file diff --git a/common/include/nbl/examples/geometry/CGeometryCreatorScene.hpp b/common/include/nbl/examples/geometry/CGeometryCreatorScene.hpp new file mode 100644 index 000000000..2798cfed7 --- /dev/null +++ b/common/include/nbl/examples/geometry/CGeometryCreatorScene.hpp @@ -0,0 +1,187 @@ +#ifndef _NBL_EXAMPLES_C_GEOMETRY_CREATOR_SCENE_H_INCLUDED_ +#define _NBL_EXAMPLES_C_GEOMETRY_CREATOR_SCENE_H_INCLUDED_ + + +#include +#include "nbl/asset/utils/CGeometryCreator.h" + + +namespace nbl::examples +{ + +class CGeometryCreatorScene : public core::IReferenceCounted +{ +#define EXPOSE_NABLA_NAMESPACES \ + using namespace nbl::core; \ + using namespace nbl::system; \ + using namespace nbl::asset; \ + using namespace nbl::video + public: + // + struct SCreateParams + { + video::IQueue* transferQueue; + video::IUtilities* utilities; + system::ILogger* logger; + std::span addtionalBufferOwnershipFamilies = {}; + }; + static inline core::smart_refctd_ptr create(SCreateParams&& params, const video::CAssetConverter::patch_t& geometryPatch) + { + EXPOSE_NABLA_NAMESPACES; + auto* logger = params.logger; + assert(logger); + if (!params.transferQueue) + { + logger->log("Pass a non-null `IQueue* transferQueue`!",ILogger::ELL_ERROR); + return nullptr; + } + if (!params.utilities) + { + logger->log("Pass a non-null `IUtilities* utilities`!",ILogger::ELL_ERROR); + return nullptr; + } + + + SInitParams init = {}; + core::vector> geometries; + // create out geometries + { + auto addGeometry = [&init,&geometries](const std::string_view name, smart_refctd_ptr&& geom)->void + { + init.geometryNames.emplace_back(name); + geometries.push_back(std::move(geom)); + }; + + auto creator = core::make_smart_refctd_ptr(); + /* TODO: others + ReferenceObjectCpu {.meta = {.type = OT_CUBE, .name = "Cube Mesh" }, .shadersType = GP_BASIC, .data = gc->createCubeMesh(nbl::core::vector3df(1.f, 1.f, 1.f)) }, + ReferenceObjectCpu {.meta = {.type = OT_SPHERE, .name = "Sphere Mesh" }, .shadersType = GP_BASIC, .data = gc->createSphereMesh(2, 16, 16) }, + ReferenceObjectCpu {.meta = {.type = OT_CYLINDER, .name = "Cylinder Mesh" }, .shadersType = GP_BASIC, .data = gc->createCylinderMesh(2, 2, 20) }, + ReferenceObjectCpu {.meta = {.type = OT_RECTANGLE, .name = "Rectangle Mesh" }, .shadersType = GP_BASIC, .data = gc->createRectangleMesh(nbl::core::vector2df_SIMD(1.5, 3)) }, + ReferenceObjectCpu {.meta = {.type = OT_DISK, .name = "Disk Mesh" }, .shadersType = GP_BASIC, .data = gc->createDiskMesh(2, 30) }, + ReferenceObjectCpu {.meta = {.type = OT_ARROW, .name = "Arrow Mesh" }, .shadersType = GP_BASIC, .data = gc->createArrowMesh() }, + ReferenceObjectCpu {.meta = {.type = OT_CONE, .name = "Cone Mesh" }, .shadersType = GP_CONE, .data = gc->createConeMesh(2, 3, 10) }, + ReferenceObjectCpu {.meta = {.type = OT_ICOSPHERE, .name = "Icoshpere Mesh" }, .shadersType = GP_ICO, .data = gc->createIcoSphere(1, 3, true) } + */ + addGeometry("Cube",creator->createCube({1.f,1.f,1.f})); + addGeometry("Rectangle",creator->createRectangle({1.5f,3.f})); + addGeometry("Disk",creator->createDisk(2.f,30)); + } + init.geometries.reserve(init.geometryNames.size()); + + // convert the geometries + { + auto device = params.utilities->getLogicalDevice(); + smart_refctd_ptr converter = CAssetConverter::create({.device=device}); + + + const auto transferFamily = params.transferQueue->getFamilyIndex(); + + struct SInputs : CAssetConverter::SInputs + { + virtual inline std::span getSharedOwnershipQueueFamilies(const size_t groupCopyID, const asset::ICPUBuffer* buffer, const CAssetConverter::patch_t& patch) const + { + return sharedBufferOwnership; + } + + core::vector sharedBufferOwnership; + } inputs = {}; + core::vector> patches(geometries.size(),geometryPatch); + { + inputs.logger = logger; + std::get>(inputs.assets) = {&geometries.front().get(),geometries.size()}; + std::get>(inputs.patches) = patches; + // set up shared ownership so we don't have to + core::unordered_set families; + families.insert(transferFamily); + families.insert(params.addtionalBufferOwnershipFamilies.begin(),params.addtionalBufferOwnershipFamilies.end()); + if (families.size()>1) + for (const auto fam : families) + inputs.sharedBufferOwnership.push_back(fam); + } + + // reserve + auto reservation = converter->reserve(inputs); + if (!reservation) + { + logger->log("Failed to reserve GPU objects for CPU->GPU conversion!",ILogger::ELL_ERROR); + return nullptr; + } + + // convert + { + auto semaphore = device->createSemaphore(0u); + + constexpr auto MultiBuffering = 2; + std::array,MultiBuffering> commandBuffers = {}; + { + auto pool = device->createCommandPool(transferFamily,IGPUCommandPool::CREATE_FLAGS::RESET_COMMAND_BUFFER_BIT|IGPUCommandPool::CREATE_FLAGS::TRANSIENT_BIT); + pool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY,commandBuffers,smart_refctd_ptr(logger)); + } + commandBuffers.front()->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); + + std::array commandBufferSubmits; + for (auto i=0; ilog("Failed to await submission feature!", ILogger::ELL_ERROR); + return nullptr; + } + } + + // assign outputs + { + auto inIt = reservation.getGPUObjects().data(); + for (auto outIt=init.geometryNames.begin(); outIt!=init.geometryNames.end(); inIt++) + { + if (inIt->value) + { + init.geometries.push_back(inIt->value); + outIt++; + } + else + { + logger->log("Failed to convert ICPUPolygonGeometry %s to GPU!",ILogger::ELL_ERROR,outIt->c_str()); + outIt = init.geometryNames.erase(outIt); + } + } + } + } + + return smart_refctd_ptr(new CGeometryCreatorScene(std::move(init)),dont_grab); + } + + // + struct SInitParams + { + core::vector> geometries; + core::vector geometryNames; + }; + const SInitParams& getInitParams() const {return m_init;} + + protected: + inline CGeometryCreatorScene(SInitParams&& _init) : m_init(std::move(_init)) {} + + SInitParams m_init; +#undef EXPOSE_NABLA_NAMESPACES +}; + +} +#endif \ No newline at end of file diff --git a/common/include/nbl/examples/geometry/CSimpleDebugRenderer.hpp b/common/include/nbl/examples/geometry/CSimpleDebugRenderer.hpp new file mode 100644 index 000000000..969b3afd8 --- /dev/null +++ b/common/include/nbl/examples/geometry/CSimpleDebugRenderer.hpp @@ -0,0 +1,424 @@ +#ifndef _NBL_EXAMPLES_C_SIMPLE_DEBUG_RENDERER_H_INCLUDED_ +#define _NBL_EXAMPLES_C_SIMPLE_DEBUG_RENDERER_H_INCLUDED_ + + +#include "nbl/builtin/hlsl/math/linalg/fast_affine.hlsl" +#include "nbl/examples/geometry/SPushConstants.hlsl" + +// TODO: Arek bring back +//#include "nbl/examples/geometry/spirv/builtin/CArchive.h" +//#include "nbl/examples/geometry/spirv/builtin/builtinResources.h" + + +namespace nbl::examples +{ + +class CSimpleDebugRenderer final : public core::IReferenceCounted +{ +#define EXPOSE_NABLA_NAMESPACES \ + using namespace nbl::core; \ + using namespace nbl::system; \ + using namespace nbl::asset; \ + using namespace nbl::video + + public: + // + constexpr static inline uint16_t VertexAttrubUTBDescBinding = 0; + // + struct SViewParams + { + inline SViewParams(const hlsl::float32_t3x4& _view, const hlsl::float32_t4x4& _viewProj) + { + view = _view; + viewProj = _viewProj; + using namespace nbl::hlsl; + normal = transpose(inverse(float32_t3x3(view))); + } + + inline auto computeForInstance(hlsl::float32_t3x4 world) const + { + using namespace nbl::hlsl; + hlsl::examples::geometry_creator_scene::SInstanceMatrices retval = { + .worldViewProj = float32_t4x4(math::linalg::promoted_mul(float64_t4x4(viewProj),float64_t3x4(world))) + }; + const auto sub3x3 = mul(float64_t3x3(viewProj),float64_t3x3(world)); + retval.normal = float32_t3x3(transpose(inverse(sub3x3))); + return retval; + } + + hlsl::float32_t3x4 view; + hlsl::float32_t4x4 viewProj; + hlsl::float32_t3x3 normal; + }; + // + struct SPackedGeometry + { + core::smart_refctd_ptr pipeline = {}; + asset::SBufferBinding indexBuffer = {}; + uint32_t elementCount = 0; + // indices into the descriptor set + uint8_t positionView = 0; + uint8_t normalView = 0; + uint8_t uvView = 0; + asset::E_INDEX_TYPE indexType = asset::EIT_UNKNOWN; + }; + // + struct SInstance + { + using SPushConstants = hlsl::examples::geometry_creator_scene::SPushConstants; + inline SPushConstants computePushConstants(const SViewParams& viewParams) const + { + using namespace hlsl; + return { + .matrices = viewParams.computeForInstance(world), + .positionView = packedGeo->positionView, + .normalView = packedGeo->normalView, + .uvView = packedGeo->uvView + }; + } + + hlsl::float32_t3x4 world; + const SPackedGeometry* packedGeo; + }; + + // + constexpr static inline auto DefaultPolygonGeometryPatch = []()->video::CAssetConverter::patch_t + { + // we want to use the vertex data through UTBs + using usage_f = video::IGPUBuffer::E_USAGE_FLAGS; + video::CAssetConverter::patch_t patch = {}; + patch.positionBufferUsages = usage_f::EUF_UNIFORM_TEXEL_BUFFER_BIT; + patch.indexBufferUsages = usage_f::EUF_INDEX_BUFFER_BIT; + patch.otherBufferUsages = usage_f::EUF_UNIFORM_TEXEL_BUFFER_BIT; + return patch; + }(); + + // + static inline core::smart_refctd_ptr create(asset::IAssetManager* assMan, video::IGPURenderpass* renderpass, const uint32_t subpassIX) + { + EXPOSE_NABLA_NAMESPACES; + + if (!renderpass) + return nullptr; + auto device = const_cast(renderpass->getOriginDevice()); + auto logger = device->getLogger(); + + if (!assMan) + return nullptr; + + // load shader + smart_refctd_ptr shader; + { + const auto bundle = assMan->getAsset("nbl/examples/geometry/shaders/unified.hlsl",{}); +// TODO: Arek + //const auto bundle = assMan->getAsset("nbl/examples/geometry/shaders/unified.spv",{}); + const auto contents = bundle.getContents(); + if (contents.empty() || bundle.getAssetType()!=IAsset::ET_SHADER) + return nullptr; + shader = IAsset::castDown(contents[0]); + shader = device->compileShader({.source=shader.get()}); + if (!shader) + return nullptr; + } + + SInitParams init; + + // create descriptor set + { + // create Descriptor Set Layout + smart_refctd_ptr dsLayout; + { + using binding_flags_t = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS; + const IGPUDescriptorSetLayout::SBinding bindings[] = + { + { + .binding = VertexAttrubUTBDescBinding, + .type = IDescriptor::E_TYPE::ET_UNIFORM_TEXEL_BUFFER, + // need this trifecta of flags for `SubAllocatedDescriptorSet` to accept the binding as suballocatable + .createFlags = binding_flags_t::ECF_UPDATE_AFTER_BIND_BIT|binding_flags_t::ECF_UPDATE_UNUSED_WHILE_PENDING_BIT |binding_flags_t::ECF_PARTIALLY_BOUND_BIT, + .stageFlags = IShader::E_SHADER_STAGE::ESS_VERTEX|IShader::E_SHADER_STAGE::ESS_FRAGMENT, + .count = SInstance::SPushConstants::DescriptorCount + } + }; + dsLayout = device->createDescriptorSetLayout(bindings); + if (!dsLayout) + { + logger->log("Could not create descriptor set layout!",ILogger::ELL_ERROR); + return nullptr; + } + } + + // create Descriptor Set + auto pool = device->createDescriptorPoolForDSLayouts(IDescriptorPool::ECF_UPDATE_AFTER_BIND_BIT,{&dsLayout.get(),1}); + auto ds = pool->createDescriptorSet(std::move(dsLayout)); + if (!ds) + { + logger->log("Could not descriptor set!",ILogger::ELL_ERROR); + return nullptr; + } + init.subAllocDS = make_smart_refctd_ptr(std::move(ds)); + } + + // create pipeline layout + const SPushConstantRange ranges[] = {{ + .stageFlags = hlsl::ShaderStage::ESS_VERTEX, + .offset = 0, + .size = sizeof(SInstance::SPushConstants), + }}; + init.layout = device->createPipelineLayout(ranges,smart_refctd_ptr(init.subAllocDS->getDescriptorSet()->getLayout())); + + // create pipelines + using pipeline_e = SInitParams::PipelineType; + { + IGPUGraphicsPipeline::SCreationParams params[pipeline_e::Count] = {}; + params[pipeline_e::BasicTriangleList].vertexShader = {.shader=shader.get(),.entryPoint="BasicVS"}; + params[pipeline_e::BasicTriangleList].fragmentShader = {.shader=shader.get(),.entryPoint="BasicFS"}; + params[pipeline_e::BasicTriangleFan].vertexShader = {.shader=shader.get(),.entryPoint="BasicVS"}; + params[pipeline_e::BasicTriangleFan].fragmentShader = {.shader=shader.get(),.entryPoint="BasicFS"}; + params[pipeline_e::Cone].vertexShader = {.shader=shader.get(),.entryPoint="ConeVS"}; + params[pipeline_e::Cone].fragmentShader = {.shader=shader.get(),.entryPoint="ConeFS"}; + for (auto i=0; i(i); + switch (type) + { + case pipeline_e::BasicTriangleFan: + primitiveAssembly.primitiveType = E_PRIMITIVE_TOPOLOGY::EPT_TRIANGLE_FAN; + break; + default: + primitiveAssembly.primitiveType = E_PRIMITIVE_TOPOLOGY::EPT_TRIANGLE_LIST; + break; + } + primitiveAssembly.primitiveRestartEnable = false; + primitiveAssembly.tessPatchVertCount = 3; + rasterization.faceCullingMode = EFCM_NONE; + params[i].cached.subpassIx = subpassIX; + params[i].renderpass = renderpass; + } + if (!device->createGraphicsPipelines(nullptr,params,init.pipelines)) + { + logger->log("Could not create Graphics Pipelines!",ILogger::ELL_ERROR); + return nullptr; + } + } + + return smart_refctd_ptr(new CSimpleDebugRenderer(std::move(init)),dont_grab); + } + + // + static inline core::smart_refctd_ptr create(asset::IAssetManager* assMan, video::IGPURenderpass* renderpass, const uint32_t subpassIX, const std::span geometries) + { + auto retval = create(assMan,renderpass,subpassIX); + if (retval) + retval->addGeometries(geometries); + return retval; + } + + // + struct SInitParams + { + enum PipelineType : uint8_t + { + BasicTriangleList, + BasicTriangleFan, + Cone, // special case + Count + }; + + core::smart_refctd_ptr subAllocDS; + core::smart_refctd_ptr layout; + core::smart_refctd_ptr pipelines[PipelineType::Count]; + }; + inline const SInitParams& getInitParams() const {return m_params;} + + // + inline bool addGeometries(const std::span geometries) + { + EXPOSE_NABLA_NAMESPACES; + if (geometries.empty()) + return false; + auto device = const_cast(m_params.layout->getOriginDevice()); + + core::vector writes; + core::vector infos; + auto allocateUTB = [&](const IGeometry::SDataView& view)->uint8_t + { + if (!view) + return SInstance::SPushConstants::DescriptorCount; + auto index = SubAllocatedDescriptorSet::invalid_value; + if (m_params.subAllocDS->multi_allocate(VertexAttrubUTBDescBinding,1,&index)!=0) + return SInstance::SPushConstants::DescriptorCount; + const auto retval = infos.size(); + infos.emplace_back().desc = device->createBufferView(view.src,view.composed.format); + writes.emplace_back() = { + .dstSet = m_params.subAllocDS->getDescriptorSet(), + .binding = VertexAttrubUTBDescBinding, + .arrayElement = index, + .count = 1, + .info = reinterpret_cast(retval) + }; + return retval; + }; + + auto sizeToSet = m_geoms.size(); + auto resetGeoms = core::makeRAIIExiter([&]()->void + { + for (auto& write : writes) + immediateDealloc(write.arrayElement); + m_geoms.resize(sizeToSet); + } + ); + for (const auto geom : geometries) + { + // could also check device origin on all buffers + if (!geom->valid()) + return false; + auto& out = m_geoms.emplace_back(); + using pipeline_e = SInitParams::PipelineType; + switch (geom->getIndexingCallback()->knownTopology()) + { + case E_PRIMITIVE_TOPOLOGY::EPT_TRIANGLE_FAN: + out.pipeline = m_params.pipelines[pipeline_e::BasicTriangleFan]; + break; + default: + out.pipeline = m_params.pipelines[pipeline_e::BasicTriangleList]; + break; + } + if (const auto& view=geom->getIndexView(); view) + { + out.indexBuffer.offset = view.src.offset; + out.indexBuffer.buffer = view.src.buffer; + switch (view.composed.format) + { + case E_FORMAT::EF_R16_UINT: + out.indexType = EIT_16BIT; + break; + case E_FORMAT::EF_R32_UINT: + out.indexType = EIT_32BIT; + break; + default: + return false; + } + } + out.elementCount = geom->getVertexReferenceCount(); + out.positionView = allocateUTB(geom->getPositionView()); + out.normalView = allocateUTB(geom->getNormalView()); + // the first view is usually the UV + if (const auto& auxViews = geom->getAuxAttributeViews(); !auxViews.empty()) + out.uvView = allocateUTB(auxViews.front()); + } + + // no geometry + if (infos.empty()) + return false; + + // unbase our pointers + for (auto& write : writes) + write.info = infos.data()+reinterpret_cast(write.info); + if (!device->updateDescriptorSets(writes,{})) + return false; + + // retain + writes.clear(); + sizeToSet = m_geoms.size(); + return true; + } + + // + inline void removeGeometry(const uint32_t ix, const video::ISemaphore::SWaitInfo& info) + { + EXPOSE_NABLA_NAMESPACES; + if (ix>=m_geoms.size()) + return; + + core::vector deferredFree; + deferredFree.reserve(3); + auto deallocate = [&](SubAllocatedDescriptorSet::value_type index)->void + { + if (info.semaphore) + deferredFree.push_back(index); + else + immediateDealloc(index); + }; + auto geo = m_geoms.begin() + ix; + deallocate(geo->positionView); + deallocate(geo->normalView); + deallocate(geo->uvView); + m_geoms.erase(geo); + + if (deferredFree.empty()) + return; + + core::vector nullify(deferredFree.size()); + const_cast(m_params.layout->getOriginDevice())->nullifyDescriptors(nullify); + } + + // + inline void clearGeometries(const video::ISemaphore::SWaitInfo& info) + { + // back to front to avoid O(n^2) resize + while (!m_geoms.empty()) + removeGeometry(m_geoms.size()-1,info); + } + + // + inline const auto& getGeometries() const {return m_geoms;} + inline auto& getGeometry(const uint32_t ix) {return m_geoms[ix];} + + // + inline void render(video::IGPUCommandBuffer* cmdbuf, const SViewParams& viewParams) const + { + EXPOSE_NABLA_NAMESPACES; + + cmdbuf->beginDebugMarker("CSimpleDebugRenderer::render"); + + const auto* layout = m_params.layout.get(); + const auto ds = m_params.subAllocDS->getDescriptorSet(); + cmdbuf->bindDescriptorSets(E_PIPELINE_BIND_POINT::EPBP_GRAPHICS,layout,0,1,&ds); + + for (const auto& instance : m_instances) + { + const auto* geo = instance.packedGeo; + cmdbuf->bindGraphicsPipeline(geo->pipeline.get()); + const auto pc = instance.computePushConstants(viewParams); + cmdbuf->pushConstants(layout,hlsl::ShaderStage::ESS_VERTEX,0,sizeof(pc),&pc); + if (geo->indexBuffer) + { + cmdbuf->bindIndexBuffer(geo->indexBuffer,geo->indexType); + cmdbuf->drawIndexed(geo->elementCount,1,0,0,0); + } + else + cmdbuf->draw(geo->elementCount,1,0,0); + } + cmdbuf->endDebugMarker(); + } + + core::vector m_instances; + + protected: + inline CSimpleDebugRenderer(SInitParams&& _params) : m_params(std::move(_params)) {} + inline ~CSimpleDebugRenderer() + { + // clean shutdown, can also make SubAllocatedDescriptorSet resillient against that, and issue `device->waitIdle` if not everything is freed + const_cast(m_params.layout->getOriginDevice())->waitIdle(); + clearGeometries({}); + } + + inline void immediateDealloc(video::SubAllocatedDescriptorSet::value_type index) + { + video::IGPUDescriptorSet::SDropDescriptorSet dummy[1]; + m_params.subAllocDS->multi_deallocate(dummy,VertexAttrubUTBDescBinding,1,&index); + } + + SInitParams m_params; + core::vector m_geoms; +#undef EXPOSE_NABLA_NAMESPACES +}; + +} +#endif \ No newline at end of file diff --git a/common/include/nbl/examples/geometry/SPushConstants.hlsl b/common/include/nbl/examples/geometry/SPushConstants.hlsl new file mode 100644 index 000000000..932210d0d --- /dev/null +++ b/common/include/nbl/examples/geometry/SPushConstants.hlsl @@ -0,0 +1,44 @@ +#ifndef _NBL_EXAMPLES_S_PUSH_CONSTANTS_HLSL_ +#define _NBL_EXAMPLES_S_PUSH_CONSTANTS_HLSL_ + + +#include "nbl/builtin/hlsl/cpp_compat.hlsl" + + +namespace nbl +{ +namespace hlsl +{ +namespace examples +{ +namespace geometry_creator_scene +{ + +struct SInstanceMatrices +{ + float32_t4x4 worldViewProj; + float32_t3x3 normal; +}; + +struct SPushConstants +{ + // no idea if DXC still has this bug with Push Constant static variables +#ifndef __HLSL_VERSiON + NBL_CONSTEXPR_STATIC_INLINE uint32_t DescriptorCount = 255; +#endif + + SInstanceMatrices matrices; + uint32_t positionView : 11; + uint32_t normalView : 10; + uint32_t uvView : 11; +}; + +} +} +} +} +#endif + +/* + do not remove this text, WAVE is so bad that you can get errors if no proper ending xD +*/ \ No newline at end of file diff --git a/common/include/nbl/examples/workgroup/DataAccessors.hlsl b/common/include/nbl/examples/workgroup/DataAccessors.hlsl new file mode 100644 index 000000000..ca5915f2c --- /dev/null +++ b/common/include/nbl/examples/workgroup/DataAccessors.hlsl @@ -0,0 +1,131 @@ +#ifndef _NBL_EXAMPLES_WORKGROUP_DATA_ACCESSORS_HLSL_ +#define _NBL_EXAMPLES_WORKGROUP_DATA_ACCESSORS_HLSL_ + + +#include "nbl/builtin/hlsl/bda/legacy_bda_accessor.hlsl" + + +namespace nbl +{ +namespace hlsl +{ +namespace examples +{ +namespace workgroup +{ + +struct ScratchProxy +{ + template + void get(const uint32_t ix, NBL_REF_ARG(AccessType) value) + { + value = scratch[ix]; + } + template + void set(const uint32_t ix, const AccessType value) + { + scratch[ix] = value; + } + + uint32_t atomicOr(const uint32_t ix, const uint32_t value) + { + return glsl::atomicOr(scratch[ix],value); + } + + void workgroupExecutionAndMemoryBarrier() + { + glsl::barrier(); + //glsl::memoryBarrierShared(); implied by the above + } +}; + +template +struct DataProxy +{ + using dtype_t = vector; + // function template AccessType should be the same as dtype_t + + static DataProxy create(const uint64_t inputBuf, const uint64_t outputBuf) + { + DataProxy retval; + const uint32_t workgroupOffset = glsl::gl_WorkGroupID().x * VirtualWorkgroupSize * sizeof(dtype_t); + retval.accessor = DoubleLegacyBdaAccessor::create(inputBuf + workgroupOffset, outputBuf + workgroupOffset); + return retval; + } + + template + void get(const IndexType ix, NBL_REF_ARG(AccessType) value) + { + accessor.get(ix, value); + } + template + void set(const IndexType ix, const AccessType value) + { + accessor.set(ix, value); + } + + void workgroupExecutionAndMemoryBarrier() + { + glsl::barrier(); + //glsl::memoryBarrierShared(); implied by the above + } + + DoubleLegacyBdaAccessor accessor; +}; + +template +struct PreloadedDataProxy +{ + using dtype_t = vector; + + NBL_CONSTEXPR_STATIC_INLINE uint16_t WorkgroupSize = uint16_t(1u) << WorkgroupSizeLog2; + NBL_CONSTEXPR_STATIC_INLINE uint16_t PreloadedDataCount = VirtualWorkgroupSize / WorkgroupSize; + + static PreloadedDataProxy create(const uint64_t inputBuf, const uint64_t outputBuf) + { + PreloadedDataProxy retval; + retval.data = DataProxy::create(inputBuf, outputBuf); + return retval; + } + + template + void get(const IndexType ix, NBL_REF_ARG(AccessType) value) + { + value = preloaded[ix>>WorkgroupSizeLog2]; + } + template + void set(const IndexType ix, const AccessType value) + { + preloaded[ix>>WorkgroupSizeLog2] = value; + } + + void preload() + { + const uint16_t invocationIndex = hlsl::workgroup::SubgroupContiguousIndex(); + [unroll] + for (uint16_t idx = 0; idx < PreloadedDataCount; idx++) + data.template get(idx * WorkgroupSize + invocationIndex, preloaded[idx]); + } + void unload() + { + const uint16_t invocationIndex = hlsl::workgroup::SubgroupContiguousIndex(); + [unroll] + for (uint16_t idx = 0; idx < PreloadedDataCount; idx++) + data.template set(idx * WorkgroupSize + invocationIndex, preloaded[idx]); + } + + void workgroupExecutionAndMemoryBarrier() + { + glsl::barrier(); + //glsl::memoryBarrierShared(); implied by the above + } + + DataProxy data; + dtype_t preloaded[PreloadedDataCount]; +}; + +} +} +} +} +#endif diff --git a/common/src/CMakeLists.txt b/common/src/CMakeLists.txt deleted file mode 100644 index 1399b949e..000000000 --- a/common/src/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ -# we add common libraries -# add_subdirectory(camera EXCLUDE_FROM_ALL) # header only currently -add_subdirectory(geometry EXCLUDE_FROM_ALL) - -# we get all available targets inclusive & below this directory -NBL_GET_ALL_TARGETS(NBL_SUBDIRECTORY_TARGETS) - -# then we expose common include search directories to all common libraries + create link interface -foreach(NBL_TARGET IN LISTS NBL_SUBDIRECTORY_TARGETS) - target_include_directories(${NBL_TARGET} PUBLIC $) - target_link_libraries(nblCommonAPI INTERFACE ${NBL_TARGET}) -endforeach() - -set(NBL_COMMON_API_TARGETS ${NBL_SUBDIRECTORY_TARGETS} PARENT_SCOPE) \ No newline at end of file diff --git a/common/src/camera/CMakeLists.txt b/common/src/camera/CMakeLists.txt deleted file mode 100644 index eedf690aa..000000000 --- a/common/src/camera/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -# header only currently - -#set(NBL_LIB_SOURCES -# "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp" -#) - -#nbl_create_ext_library_project(Camera "" "${NBL_LIB_SOURCES}" "" "" "") \ No newline at end of file diff --git a/common/src/empty.cpp b/common/src/empty.cpp deleted file mode 100644 index e69de29bb..000000000 diff --git a/common/src/geometry/CMakeLists.txt b/common/src/geometry/CMakeLists.txt deleted file mode 100644 index fb33ec637..000000000 --- a/common/src/geometry/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_subdirectory(creator EXCLUDE_FROM_ALL) \ No newline at end of file diff --git a/common/src/geometry/creator/CMakeLists.txt b/common/src/geometry/creator/CMakeLists.txt deleted file mode 100644 index 336d32fe5..000000000 --- a/common/src/geometry/creator/CMakeLists.txt +++ /dev/null @@ -1,69 +0,0 @@ -# shaders IO directories -set(NBL_THIS_EXAMPLE_INPUT_SHADERS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/shaders") -get_filename_component(_THIS_EXAMPLE_SPIRV_BR_BUNDLE_SEARCH_DIRECTORY_ "${CMAKE_CURRENT_BINARY_DIR}/shaders/include" ABSOLUTE) -get_filename_component(_THIS_EXAMPLE_SPIRV_BR_OUTPUT_DIRECTORY_HEADER_ "${CMAKE_CURRENT_BINARY_DIR}/builtin/include" ABSOLUTE) -get_filename_component(_THIS_EXAMPLE_SPIRV_BR_OUTPUT_DIRECTORY_SOURCE_ "${CMAKE_CURRENT_BINARY_DIR}/builtin/src" ABSOLUTE) -set(NBL_THIS_EXAMPLE_OUTPUT_SPIRV_DIRECTORY "${_THIS_EXAMPLE_SPIRV_BR_BUNDLE_SEARCH_DIRECTORY_}/nbl/geometryCreator/spirv") - -# list of input source shaders -set(NBL_THIS_EXAMPLE_INPUT_SHADERS - # geometry creator - "${NBL_THIS_EXAMPLE_INPUT_SHADERS_DIRECTORY}/gc.basic.fragment.hlsl" - "${NBL_THIS_EXAMPLE_INPUT_SHADERS_DIRECTORY}/gc.basic.vertex.hlsl" - "${NBL_THIS_EXAMPLE_INPUT_SHADERS_DIRECTORY}/gc.cone.vertex.hlsl" - "${NBL_THIS_EXAMPLE_INPUT_SHADERS_DIRECTORY}/gc.ico.vertex.hlsl" - - # grid - "${NBL_THIS_EXAMPLE_INPUT_SHADERS_DIRECTORY}/grid.vertex.hlsl" - "${NBL_THIS_EXAMPLE_INPUT_SHADERS_DIRECTORY}/grid.fragment.hlsl" -) - -file(GLOB_RECURSE NBL_THIS_EXAMPLE_INPUT_COMMONS CONFIGURE_DEPENDS "${NBL_THIS_EXAMPLE_INPUT_SHADERS_DIRECTORY}/template/*.hlsl") - -include("${NBL_ROOT_PATH}/src/nbl/builtin/utils.cmake") - -foreach(NBL_INPUT_SHADER IN LISTS NBL_THIS_EXAMPLE_INPUT_SHADERS) - cmake_path(GET NBL_INPUT_SHADER FILENAME NBL_INPUT_SHADER_FILENAME) - cmake_path(GET NBL_INPUT_SHADER_FILENAME STEM LAST_ONLY NBL_SHADER_STEM) # filename without .hlsl extension - cmake_path(GET NBL_SHADER_STEM EXTENSION LAST_ONLY NBL_SHADER_TYPE) # . - - set(NBL_OUTPUT_SPIRV_FILENAME "${NBL_SHADER_STEM}.spv") - set(NBL_OUTPUT_SPIRV_PATH "${NBL_THIS_EXAMPLE_OUTPUT_SPIRV_DIRECTORY}/${NBL_OUTPUT_SPIRV_FILENAME}") - - if(NBL_SHADER_TYPE STREQUAL .vertex) - set(NBL_NSC_COMPILE_OPTIONS -T vs_6_7 -E VSMain) - elseif(NBL_SHADER_TYPE STREQUAL .geometry) - set(NBL_NSC_COMPILE_OPTIONS -T gs_6_7 -E GSMain) - elseif(NBL_SHADER_TYPE STREQUAL .fragment) - set(NBL_NSC_COMPILE_OPTIONS -T ps_6_7 -E PSMain) - else() - message(FATAL_ERROR "Input shader is supposed to be ..hlsl!") - endif() - - set(NBL_NSC_COMPILE_COMMAND - "$" - -Fc "${NBL_OUTPUT_SPIRV_PATH}" - -I "${NBL_COMMON_API_INCLUDE_DIRECTORY}" - ${NBL_NSC_COMPILE_OPTIONS} # this should come from shader's [#pragma WAVE ] but our NSC doesn't seem to work properly currently - "${NBL_INPUT_SHADER}" - ) - - set(NBL_DEPENDS - "${NBL_INPUT_SHADER}" - ${NBL_THIS_EXAMPLE_INPUT_COMMONS} - ) - - add_custom_command(OUTPUT "${NBL_OUTPUT_SPIRV_PATH}" - COMMAND ${NBL_NSC_COMPILE_COMMAND} - DEPENDS ${NBL_DEPENDS} - WORKING_DIRECTORY "${NBL_THIS_EXAMPLE_INPUT_SHADERS_DIRECTORY}" - COMMENT "Generating \"${NBL_OUTPUT_SPIRV_PATH}\"" - VERBATIM - COMMAND_EXPAND_LISTS - ) - - list(APPEND NBL_THIS_EXAMPLE_OUTPUT_SPIRV_BUILTINS "${NBL_OUTPUT_SPIRV_PATH}") - LIST_BUILTIN_RESOURCE(GEOMETRY_CREATOR_SPIRV_RESOURCES_TO_EMBED "geometryCreator/spirv/${NBL_OUTPUT_SPIRV_FILENAME}") -endforeach() - -ADD_CUSTOM_BUILTIN_RESOURCES(geometryCreatorSpirvBRD GEOMETRY_CREATOR_SPIRV_RESOURCES_TO_EMBED "${_THIS_EXAMPLE_SPIRV_BR_BUNDLE_SEARCH_DIRECTORY_}" "nbl" "geometry::creator::spirv::builtin" "${_THIS_EXAMPLE_SPIRV_BR_OUTPUT_DIRECTORY_HEADER_}" "${_THIS_EXAMPLE_SPIRV_BR_OUTPUT_DIRECTORY_SOURCE_}" "STATIC" "INTERNAL") \ No newline at end of file diff --git a/common/src/geometry/creator/shaders/gc.basic.fragment.hlsl b/common/src/geometry/creator/shaders/gc.basic.fragment.hlsl deleted file mode 100644 index 3dc9b9f1d..000000000 --- a/common/src/geometry/creator/shaders/gc.basic.fragment.hlsl +++ /dev/null @@ -1,6 +0,0 @@ -#include "template/gc.common.hlsl" - -float4 PSMain(PSInput input) : SV_Target0 -{ - return input.color; -} \ No newline at end of file diff --git a/common/src/geometry/creator/shaders/gc.basic.vertex.hlsl b/common/src/geometry/creator/shaders/gc.basic.vertex.hlsl deleted file mode 100644 index 1afd468d9..000000000 --- a/common/src/geometry/creator/shaders/gc.basic.vertex.hlsl +++ /dev/null @@ -1,6 +0,0 @@ -#include "template/gc.basic.vertex.input.hlsl" -#include "template/gc.vertex.hlsl" - -/* - do not remove this text, WAVE is so bad that you can get errors if no proper ending xD -*/ diff --git a/common/src/geometry/creator/shaders/gc.cone.vertex.hlsl b/common/src/geometry/creator/shaders/gc.cone.vertex.hlsl deleted file mode 100644 index ee0c42431..000000000 --- a/common/src/geometry/creator/shaders/gc.cone.vertex.hlsl +++ /dev/null @@ -1,6 +0,0 @@ -#include "template/gc.cone.vertex.input.hlsl" -#include "template/gc.vertex.hlsl" - -/* - do not remove this text, WAVE is so bad that you can get errors if no proper ending xD -*/ diff --git a/common/src/geometry/creator/shaders/gc.ico.vertex.hlsl b/common/src/geometry/creator/shaders/gc.ico.vertex.hlsl deleted file mode 100644 index d63fdc809..000000000 --- a/common/src/geometry/creator/shaders/gc.ico.vertex.hlsl +++ /dev/null @@ -1,6 +0,0 @@ -#include "template/gc.ico.vertex.input.hlsl" -#include "template/gc.vertex.hlsl" - -/* - do not remove this text, WAVE is so bad that you can get errors if no proper ending xD -*/ diff --git a/common/src/geometry/creator/shaders/grid.fragment.hlsl b/common/src/geometry/creator/shaders/grid.fragment.hlsl deleted file mode 100644 index 4b4c1e691..000000000 --- a/common/src/geometry/creator/shaders/grid.fragment.hlsl +++ /dev/null @@ -1,12 +0,0 @@ -#include "template/grid.common.hlsl" - -float4 PSMain(PSInput input) : SV_Target0 -{ - float2 uv = (input.uv - float2(0.5, 0.5)) + 0.5 / 30.0; - float grid = gridTextureGradBox(uv, ddx(input.uv), ddy(input.uv)); - float4 fragColor = float4(1.0 - grid, 1.0 - grid, 1.0 - grid, 1.0); - fragColor *= 0.25; - fragColor *= 0.3 + 0.6 * smoothstep(0.0, 0.1, 1.0 - length(input.uv) / 5.5); - - return fragColor; -} \ No newline at end of file diff --git a/common/src/geometry/creator/shaders/template/gc.basic.vertex.input.hlsl b/common/src/geometry/creator/shaders/template/gc.basic.vertex.input.hlsl deleted file mode 100644 index d9e2fa172..000000000 --- a/common/src/geometry/creator/shaders/template/gc.basic.vertex.input.hlsl +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef _THIS_EXAMPLE_GC_BASIC_VERTEX_INPUT_HLSL_ -#define _THIS_EXAMPLE_GC_BASIC_VERTEX_INPUT_HLSL_ - -struct VSInput -{ - [[vk::location(0)]] float3 position : POSITION; - [[vk::location(1)]] float4 color : COLOR; - [[vk::location(2)]] float2 uv : TEXCOORD; - [[vk::location(3)]] float3 normal : NORMAL; -}; - -#endif // _THIS_EXAMPLE_GC_BASIC_VERTEX_INPUT_HLSL_ - -/* - do not remove this text, WAVE is so bad that you can get errors if no proper ending xD -*/ diff --git a/common/src/geometry/creator/shaders/template/gc.common.hlsl b/common/src/geometry/creator/shaders/template/gc.common.hlsl deleted file mode 100644 index 4590cd4a3..000000000 --- a/common/src/geometry/creator/shaders/template/gc.common.hlsl +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef _THIS_EXAMPLE_GC_COMMON_HLSL_ -#define _THIS_EXAMPLE_GC_COMMON_HLSL_ - -#ifdef __HLSL_VERSION - struct PSInput - { - float4 position : SV_Position; - float4 color : COLOR0; - }; -#endif // __HLSL_VERSION - -#include "SBasicViewParameters.hlsl" - -#endif // _THIS_EXAMPLE_GC_COMMON_HLSL_ - -/* - do not remove this text, WAVE is so bad that you can get errors if no proper ending xD -*/ \ No newline at end of file diff --git a/common/src/geometry/creator/shaders/template/gc.cone.vertex.input.hlsl b/common/src/geometry/creator/shaders/template/gc.cone.vertex.input.hlsl deleted file mode 100644 index 66221fef1..000000000 --- a/common/src/geometry/creator/shaders/template/gc.cone.vertex.input.hlsl +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef _THIS_EXAMPLE_GC_CONE_VERTEX_INPUT_HLSL_ -#define _THIS_EXAMPLE_GC_CONE_VERTEX_INPUT_HLSL_ - -struct VSInput -{ - [[vk::location(0)]] float3 position : POSITION; - [[vk::location(1)]] float4 color : COLOR; - [[vk::location(2)]] float3 normal : NORMAL; -}; - -#endif // _THIS_EXAMPLE_GC_CONE_VERTEX_INPUT_HLSL_ - -/* - do not remove this text, WAVE is so bad that you can get errors if no proper ending xD -*/ diff --git a/common/src/geometry/creator/shaders/template/gc.ico.vertex.input.hlsl b/common/src/geometry/creator/shaders/template/gc.ico.vertex.input.hlsl deleted file mode 100644 index 6b85486d9..000000000 --- a/common/src/geometry/creator/shaders/template/gc.ico.vertex.input.hlsl +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef _THIS_EXAMPLE_GC_ICO_VERTEX_INPUT_HLSL_ -#define _THIS_EXAMPLE_GC_ICO_VERTEX_INPUT_HLSL_ - -struct VSInput -{ - [[vk::location(0)]] float3 position : POSITION; - [[vk::location(1)]] float3 normal : NORMAL; - [[vk::location(2)]] float2 uv : TEXCOORD; -}; - -#endif // _THIS_EXAMPLE_GC_ICO_VERTEX_INPUT_HLSL_ - -/* - do not remove this text, WAVE is so bad that you can get errors if no proper ending xD -*/ diff --git a/common/src/geometry/creator/shaders/template/gc.vertex.hlsl b/common/src/geometry/creator/shaders/template/gc.vertex.hlsl deleted file mode 100644 index 5a8f26722..000000000 --- a/common/src/geometry/creator/shaders/template/gc.vertex.hlsl +++ /dev/null @@ -1,22 +0,0 @@ -#include "gc.common.hlsl" - -// set 1, binding 0 -[[vk::binding(0, 1)]] -cbuffer CameraData -{ - SBasicViewParameters params; -}; - -PSInput VSMain(VSInput input) -{ - PSInput output; - - output.position = mul(params.MVP, float4(input.position, 1.0)); - output.color = float4(input.normal * 0.5 + 0.5, 1.0); - - return output; -} - -/* - do not remove this text, WAVE is so bad that you can get errors if no proper ending xD -*/ diff --git a/common/src/geometry/creator/shaders/template/grid.common.hlsl b/common/src/geometry/creator/shaders/template/grid.common.hlsl deleted file mode 100644 index bc6516600..000000000 --- a/common/src/geometry/creator/shaders/template/grid.common.hlsl +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef _THIS_EXAMPLE_GRID_COMMON_HLSL_ -#define _THIS_EXAMPLE_GRID_COMMON_HLSL_ - -#ifdef __HLSL_VERSION - struct VSInput - { - [[vk::location(0)]] float3 position : POSITION; - [[vk::location(1)]] float4 color : COLOR; - [[vk::location(2)]] float2 uv : TEXCOORD; - [[vk::location(3)]] float3 normal : NORMAL; - }; - - struct PSInput - { - float4 position : SV_Position; - float2 uv : TEXCOORD0; - }; - - float gridTextureGradBox(float2 p, float2 ddx, float2 ddy) - { - float N = 30.0; // grid ratio - float2 w = max(abs(ddx), abs(ddy)) + 0.01; // filter kernel - - // analytic (box) filtering - float2 a = p + 0.5 * w; - float2 b = p - 0.5 * w; - float2 i = (floor(a) + min(frac(a) * N, 1.0) - floor(b) - min(frac(b) * N, 1.0)) / (N * w); - - // pattern - return (1.0 - i.x) * (1.0 - i.y); - } -#endif // __HLSL_VERSION - -#include "SBasicViewParameters.hlsl" - -#endif // _THIS_EXAMPLE_GRID_COMMON_HLSL_ - -/* - do not remove this text, WAVE is so bad that you can get errors if no proper ending xD -*/ \ No newline at end of file diff --git a/common/src/nbl/examples/CMakeLists.txt b/common/src/nbl/examples/CMakeLists.txt new file mode 100644 index 000000000..a95372eea --- /dev/null +++ b/common/src/nbl/examples/CMakeLists.txt @@ -0,0 +1,4 @@ +# TODO builtin SPIR-V shaders +# add_subdirectory(geometry EXCLUDE_FROM_ALL) + +# TODO: make docs once I get n4ce embed SPIRV tool to build system and then use the tool with Matts new shader \ No newline at end of file diff --git a/common/src/geometry/creator/shaders/grid.vertex.hlsl b/common/src/nbl/examples/geometry/shaders/grid.vertex.hlsl similarity index 72% rename from common/src/geometry/creator/shaders/grid.vertex.hlsl rename to common/src/nbl/examples/geometry/shaders/grid.vertex.hlsl index 167b981d3..389c37bf2 100644 --- a/common/src/geometry/creator/shaders/grid.vertex.hlsl +++ b/common/src/nbl/examples/geometry/shaders/grid.vertex.hlsl @@ -1,11 +1,5 @@ #include "template/grid.common.hlsl" -// set 1, binding 0 -[[vk::binding(0, 1)]] -cbuffer CameraData -{ - SBasicViewParameters params; -}; PSInput VSMain(VSInput input) { diff --git a/common/src/nbl/examples/geometry/shaders/template/grid.common.hlsl b/common/src/nbl/examples/geometry/shaders/template/grid.common.hlsl new file mode 100644 index 000000000..7ec9017e9 --- /dev/null +++ b/common/src/nbl/examples/geometry/shaders/template/grid.common.hlsl @@ -0,0 +1,43 @@ +#ifndef _NBL_EXAMPLES_GRID_COMMON_HLSL_ +#define _NBL_EXAMPLES_GRID_COMMON_HLSL_ + +#include "common/SBasicViewParameters.hlsl" + +#ifdef __HLSL_VERSION +// TODO: why is there even a mesh with HW vertices for this? +struct VSInput +{ + [[vk::location(0)]] float3 position : POSITION; + [[vk::location(1)]] float4 color : COLOR; + [[vk::location(2)]] float2 uv : TEXCOORD; + [[vk::location(3)]] float3 normal : NORMAL; +}; + +struct PSInput +{ + float4 position : SV_Position; + float2 uv : TEXCOORD0; +}; + +[[vk::push_constant]] SBasicViewParameters params; +#endif // __HLSL_VERSION + + +float gridTextureGradBox(float2 p, float2 ddx, float2 ddy) +{ + float N = 30.0; // grid ratio + float2 w = max(abs(ddx), abs(ddy)) + 0.01; // filter kernel + + // analytic (box) filtering + float2 a = p + 0.5 * w; + float2 b = p - 0.5 * w; + float2 i = (floor(a) + min(frac(a) * N, 1.0) - floor(b) - min(frac(b) * N, 1.0)) / (N * w); + + // pattern + return (1.0 - i.x) * (1.0 - i.y); +} + +#endif // _NBL_EXAMPLES_GRID_COMMON_HLSL_ +/* + do not remove this text, WAVE is so bad that you can get errors if no proper ending xD +*/ \ No newline at end of file diff --git a/common/src/nbl/examples/geometry/shaders/unified.hlsl b/common/src/nbl/examples/geometry/shaders/unified.hlsl new file mode 100644 index 000000000..bc6b6e13a --- /dev/null +++ b/common/src/nbl/examples/geometry/shaders/unified.hlsl @@ -0,0 +1,57 @@ +// +#include "nbl/examples/geometry/SPushConstants.hlsl" +using namespace nbl::hlsl; +using namespace nbl::hlsl::examples::geometry_creator_scene; + +// for dat sweet programmable pulling +[[vk::binding(0)]] Buffer utbs[/*SPushConstants::DescriptorCount*/255]; + +// +[[vk::push_constant]] SPushConstants pc; + +// +struct SInterpolants +{ + float32_t4 position : SV_Position; + float32_t3 meta : COLOR0; +}; +#include "nbl/builtin/hlsl/math/linalg/fast_affine.hlsl" + +// +[shader("vertex")] +SInterpolants BasicVS(uint32_t VertexIndex : SV_VertexID) +{ + const float32_t3 position = utbs[pc.positionView][VertexIndex].xyz; + + SInterpolants output; + output.position = math::linalg::promoted_mul(pc.matrices.worldViewProj,position); + output.meta = mul(pc.matrices.normal,utbs[pc.normalView][VertexIndex].xyz); + return output; +} +[shader("pixel")] +float32_t4 BasicFS(SInterpolants input) : SV_Target0 +{ + return float32_t4(normalize(input.meta)*0.5f+promote(0.5f),1.f); +} + +// TODO: do smooth normals on the cone +[shader("vertex")] +SInterpolants ConeVS(uint32_t VertexIndex : SV_VertexID) +{ + const float32_t3 position = utbs[pc.positionView][VertexIndex].xyz; + + SInterpolants output; + output.position = math::linalg::promoted_mul(pc.matrices.worldViewProj,position); + output.meta = mul(inverse(transpose(pc.matrices.normal)),position); + return output; +} +[shader("pixel")] +float32_t4 ConeFS(SInterpolants input) : SV_Target0 +{ + const float32_t2x3 dViewPos_dScreen = float32_t2x3( + ddx(input.meta), + ddy(input.meta) + ); + const float32_t3 normal = cross(dViewPos_dScreen[0],dViewPos_dScreen[1]); + return float32_t4(normalize(normal)*0.5f+promote(0.5f),1.f); +} \ No newline at end of file diff --git a/common/src/nbl/examples/pch.cpp b/common/src/nbl/examples/pch.cpp new file mode 100644 index 000000000..39a146f1d --- /dev/null +++ b/common/src/nbl/examples/pch.cpp @@ -0,0 +1 @@ +#include "nbl/examples/PCH.hpp" \ No newline at end of file diff --git a/media b/media index a98646358..68dbe85b9 160000 --- a/media +++ b/media @@ -1 +1 @@ -Subproject commit a9864635879e5a616ac400eecd8b6451b498fbf1 +Subproject commit 68dbe85b9849c9b094760428a3639f5c8917d85e diff --git a/old_to_refactor/49_ComputeFFT/CMakeLists.txt b/old_to_refactor/49_ComputeFFT/CMakeLists.txt deleted file mode 100644 index b591db9e9..000000000 --- a/old_to_refactor/49_ComputeFFT/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ - -include(common RESULT_VARIABLE RES) -if(NOT RES) - message(FATAL_ERROR "common.cmake not found. Should be in {repo_root}/cmake directory") -endif() - -set(EXAMPLE_SOURCES - ../../src/nbl/ext/FFT/FFT.cpp -) - -nbl_create_executable_project("${EXAMPLE_SOURCES}" "" "" "" "${NBL_EXECUTABLE_PROJECT_CREATION_PCH_TARGET}") \ No newline at end of file diff --git a/old_to_refactor/49_ComputeFFT/config.json.template b/old_to_refactor/49_ComputeFFT/config.json.template deleted file mode 100644 index f961745c1..000000000 --- a/old_to_refactor/49_ComputeFFT/config.json.template +++ /dev/null @@ -1,28 +0,0 @@ -{ - "enableParallelBuild": true, - "threadsPerBuildProcess" : 2, - "isExecuted": false, - "scriptPath": "", - "cmake": { - "configurations": [ "Release", "Debug", "RelWithDebInfo" ], - "buildModes": [], - "requiredOptions": [] - }, - "profiles": [ - { - "backend": "vulkan", - "platform": "windows", - "buildModes": [], - "runConfiguration": "Release", - "gpuArchitectures": [] - } - ], - "dependencies": [], - "data": [ - { - "dependencies": [], - "command": [""], - "outputs": [] - } - ] -} \ No newline at end of file diff --git a/old_to_refactor/49_ComputeFFT/extra_parameters.glsl b/old_to_refactor/49_ComputeFFT/extra_parameters.glsl deleted file mode 100644 index 032f4c363..000000000 --- a/old_to_refactor/49_ComputeFFT/extra_parameters.glsl +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -#include "nbl/builtin/glsl/ext/FFT/parameters_struct.glsl" -struct convolve_parameters_t -{ - nbl_glsl_ext_FFT_Parameters_t fft; - vec2 kernel_half_pixel_size; -}; - -struct image_store_parameters_t -{ - nbl_glsl_ext_FFT_Parameters_t fft; - ivec2 unpad_offset; -}; \ No newline at end of file diff --git a/old_to_refactor/49_ComputeFFT/fft_convolve_ifft.comp b/old_to_refactor/49_ComputeFFT/fft_convolve_ifft.comp deleted file mode 100644 index 18702fe81..000000000 --- a/old_to_refactor/49_ComputeFFT/fft_convolve_ifft.comp +++ /dev/null @@ -1,109 +0,0 @@ -layout(local_size_x=_NBL_GLSL_WORKGROUP_SIZE_, local_size_y=1, local_size_z=1) in; - -layout(set=0, binding=2) uniform sampler2D NormalizedKernel[3]; - -/* TODO: Hardcode the parameters for the frequent FFTs -uvec3 nbl_glsl_ext_FFT_Parameters_t_getDimensions() -{ - return uvec3(1280u,1024u,1u); -} -bool nbl_glsl_ext_FFT_Parameters_t_getIsInverse() -{ - return false; -} -uint nbl_glsl_ext_FFT_Parameters_t_getDirection() -{ - return 0u; -} -uint nbl_glsl_ext_FFT_Parameters_t_getMaxChannel() -{ - return 2u; -} -uint nbl_glsl_ext_FFT_Parameters_t_getLog2FFTSize() -{ - return 11u; -} -uint nbl_glsl_ext_FFT_Parameters_t_getPaddingType() -{ - return 3u; // _NBL_GLSL_EXT_FFT_PAD_MIRROR_; -} -uvec4 nbl_glsl_ext_FFT_Parameters_t_getInputStrides() -{ - return uvec4(1024u,1u,0u,1024u*1280u); -} -uvec4 nbl_glsl_ext_FFT_Parameters_t_getOutputStrides() -{ - return uvec4(1u,1280u,0u,1280u*1024u); -} -#define _NBL_GLSL_EXT_FFT_PARAMETERS_METHODS_DECLARED_ -*/ - -#include "extra_parameters.glsl" -layout(push_constant) uniform PushConstants -{ - convolve_parameters_t params; -} pc; -#define _NBL_GLSL_EXT_FFT_PUSH_CONSTANTS_DEFINED_ - -nbl_glsl_ext_FFT_Parameters_t nbl_glsl_ext_FFT_getParameters() -{ - return pc.params.fft; -} -#define _NBL_GLSL_EXT_FFT_GET_PARAMETERS_DEFINED_ - -#define _NBL_GLSL_EXT_FFT_MAIN_DEFINED_ -#include "nbl/builtin/glsl/ext/FFT/default_compute_fft.comp" - -void convolve(in uint item_per_thread_count, in uint ch) -{ - // TODO: decouple kernel size from image size (can't get the math to work in my head) - for(uint t=0u; t>1u; - const uint shifted = tid-padding; - if (tid>=padding && shifted -nbl_glsl_complex nbl_glsl_ext_FFT_getPaddedData(in ivec3 coordinate, in uint channel) -{ - ivec2 inputImageSize = textureSize(inputImage, 0); - vec2 normalizedCoords = (vec2(coordinate.xy)+vec2(0.5f))/(vec2(inputImageSize)*KERNEL_SCALE); - vec4 texelValue = textureLod(inputImage, normalizedCoords+vec2(0.5-0.5/KERNEL_SCALE), -log2(KERNEL_SCALE)); - return nbl_glsl_complex(texelValue[channel], 0.0f); -} -#define _NBL_GLSL_EXT_FFT_GET_PADDED_DATA_DEFINED_ - - -/* TODO: Hardcode the parameters for the frequent FFTs -#if _NBL_GLSL_EXT_FFT_MAX_DIM_SIZE_>512 -uvec3 nbl_glsl_ext_FFT_Parameters_t_getDimensions() -{ - return uvec3(1280u,720u,1u); -} -bool nbl_glsl_ext_FFT_Parameters_t_getIsInverse() -{ - return false; -} -uint nbl_glsl_ext_FFT_Parameters_t_getDirection() -{ - return 1u; -} -uint nbl_glsl_ext_FFT_Parameters_t_getMaxChannel() -{ - return 2u; -} -uint nbl_glsl_ext_FFT_Parameters_t_getLog2FFTSize() -{ - return 10u; -} -uint nbl_glsl_ext_FFT_Parameters_t_getPaddingType() -{ - return 3u; // _NBL_GLSL_EXT_FFT_PAD_MIRROR_; -} -uvec4 nbl_glsl_ext_FFT_Parameters_t_getInputStrides() -{ - return uvec4(0xdeadbeefu); -} -uvec4 nbl_glsl_ext_FFT_Parameters_t_getOutputStrides() -{ - return uvec4(1024u,1u,0u,1024u*1280u); -} -#define _NBL_GLSL_EXT_FFT_PARAMETERS_METHODS_DECLARED_ -#endif -*/ - -#include "nbl/builtin/glsl/ext/FFT/default_compute_fft.comp" \ No newline at end of file diff --git a/old_to_refactor/49_ComputeFFT/last_fft.comp b/old_to_refactor/49_ComputeFFT/last_fft.comp deleted file mode 100644 index 2183ef63c..000000000 --- a/old_to_refactor/49_ComputeFFT/last_fft.comp +++ /dev/null @@ -1,72 +0,0 @@ -layout(local_size_x=_NBL_GLSL_WORKGROUP_SIZE_, local_size_y=1, local_size_z=1) in; - -// Output Descriptor -layout(set=0, binding=1, rgba16f) uniform image2D outImage; -#define _NBL_GLSL_EXT_FFT_OUTPUT_DESCRIPTOR_DEFINED_ - -/* TODO: Hardcode the parameters for the frequent FFTs -uvec3 nbl_glsl_ext_FFT_Parameters_t_getDimensions() -{ - return uvec3(1280u,1024u,1u); -} -bool nbl_glsl_ext_FFT_Parameters_t_getIsInverse() -{ - return true; -} -uint nbl_glsl_ext_FFT_Parameters_t_getDirection() -{ - return 1u; -} -uint nbl_glsl_ext_FFT_Parameters_t_getMaxChannel() -{ - return 2u; -} -uint nbl_glsl_ext_FFT_Parameters_t_getLog2FFTSize() -{ - return 10u; -} -uint nbl_glsl_ext_FFT_Parameters_t_getPaddingType() -{ - return 3u; // _NBL_GLSL_EXT_FFT_PAD_MIRROR_; -} -uvec4 nbl_glsl_ext_FFT_Parameters_t_getInputStrides() -{ - return uvec4(1u,1280u,0u,1280u*1024u); -} -uvec4 nbl_glsl_ext_FFT_Parameters_t_getOutputStrides() -{ - return uvec4(0xdeadbeefu); -} -#define _NBL_GLSL_EXT_FFT_PARAMETERS_METHODS_DECLARED_ -*/ - -#include "extra_parameters.glsl" -layout(push_constant) uniform PushConstants -{ - image_store_parameters_t params; -} pc; -#define _NBL_GLSL_EXT_FFT_PUSH_CONSTANTS_DEFINED_ - -nbl_glsl_ext_FFT_Parameters_t nbl_glsl_ext_FFT_getParameters() -{ - return pc.params.fft; -} -#define _NBL_GLSL_EXT_FFT_GET_PARAMETERS_DEFINED_ - - -#include -void nbl_glsl_ext_FFT_setData(in uvec3 coordinate, in uint channel, in nbl_glsl_complex complex_value) -{ - const ivec2 coords = ivec2(coordinate.xy)-pc.params.unpad_offset; - - if (all(lessThanEqual(ivec2(0),coords)) && all(greaterThan(imageSize(outImage),coords))) - { - vec4 color_value = imageLoad(outImage, coords); - color_value[channel] = complex_value.x; - imageStore(outImage, coords, color_value); - } -} -#define _NBL_GLSL_EXT_FFT_SET_DATA_DEFINED_ - - -#include "nbl/builtin/glsl/ext/FFT/default_compute_fft.comp" \ No newline at end of file diff --git a/old_to_refactor/49_ComputeFFT/main.cpp b/old_to_refactor/49_ComputeFFT/main.cpp deleted file mode 100644 index ba2b7e33e..000000000 --- a/old_to_refactor/49_ComputeFFT/main.cpp +++ /dev/null @@ -1,753 +0,0 @@ -// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. -// This file is part of the "Nabla Engine". -// For conditions of distribution and use, see copyright notice in nabla.h - -#define _NBL_STATIC_LIB_ -#include -#include -#include - -#include "nbl/ext/FFT/FFT.h" -#include "../common/QToQuitEventReceiver.h" - -using namespace nbl; -using namespace nbl::core; -using namespace nbl::asset; -using namespace nbl::video; - -using FFTClass = ext::FFT::FFT; - -constexpr uint32_t channelCountOverride = 3u; - -inline core::smart_refctd_ptr createShader( - video::IVideoDriver* driver, - const uint32_t maxFFTlen, - const bool useHalfStorage, - const char* includeMainName, - float kernelScale = 1.f) -{ - const char* sourceFmt = -R"===(#version 430 core - -#define _NBL_GLSL_WORKGROUP_SIZE_ %u -#define _NBL_GLSL_EXT_FFT_MAX_DIM_SIZE_ %u -#define _NBL_GLSL_EXT_FFT_HALF_STORAGE_ %u - -#define KERNEL_SCALE %f - -#include "%s" - -)==="; - - const size_t extraSize = 4u+8u+8u+128u; - - constexpr uint32_t DEFAULT_WORK_GROUP_SIZE = FFTClass::DEFAULT_WORK_GROUP_SIZE; - auto shader = core::make_smart_refctd_ptr(strlen(sourceFmt)+extraSize+1u); - snprintf( - reinterpret_cast(shader->getPointer()),shader->getSize(), sourceFmt, - DEFAULT_WORK_GROUP_SIZE, - maxFFTlen, - useHalfStorage ? 1u:0u, - kernelScale, - includeMainName - ); - - auto cpuSpecializedShader = core::make_smart_refctd_ptr( - core::make_smart_refctd_ptr(std::move(shader),ICPUShader::buffer_contains_glsl), - ISpecializedShader::SInfo{nullptr, nullptr, "main", asset::ISpecializedShader::ESS_COMPUTE} - ); - - auto gpuShader = driver->createShader(nbl::core::smart_refctd_ptr(cpuSpecializedShader->getUnspecialized())); - - auto gpuSpecializedShader = driver->createSpecializedShader(gpuShader.get(), cpuSpecializedShader->getSpecializationInfo()); - - return gpuSpecializedShader; -} - - - -inline void updateDescriptorSet_Convolution ( - video::IVideoDriver * driver, - video::IGPUDescriptorSet * set, - core::smart_refctd_ptr inputBufferDescriptor, - core::smart_refctd_ptr outputBufferDescriptor, - const core::smart_refctd_ptr* kernelNormalizedSpectrumImageDescriptors) -{ - constexpr uint32_t descCount = 3u; - video::IGPUDescriptorSet::SDescriptorInfo pInfos[descCount-1u+channelCountOverride]; - video::IGPUDescriptorSet::SWriteDescriptorSet pWrites[descCount]; - - for (auto i = 0; i < descCount; i++) - { - pWrites[i].binding = i; - pWrites[i].dstSet = set; - pWrites[i].arrayElement = 0u; - pWrites[i].info = pInfos+i; - } - - // Input Buffer - pWrites[0].descriptorType = asset::EDT_STORAGE_BUFFER; - pWrites[0].count = 1; - pInfos[0].desc = inputBufferDescriptor; - pInfos[0].buffer.size = inputBufferDescriptor->getSize(); - pInfos[0].buffer.offset = 0u; - - // - pWrites[1].descriptorType = asset::EDT_STORAGE_BUFFER; - pWrites[1].count = 1; - pInfos[1].desc = outputBufferDescriptor; - pInfos[1].buffer.size = outputBufferDescriptor->getSize(); - pInfos[1].buffer.offset = 0u; - - // Kernel Buffer - pWrites[2].descriptorType = asset::EDT_COMBINED_IMAGE_SAMPLER; - pWrites[2].count = channelCountOverride; - for (uint32_t i=0u; iupdateDescriptorSets(descCount, pWrites, 0u, nullptr); -} -inline void updateDescriptorSet_LastFFT ( - video::IVideoDriver * driver, - video::IGPUDescriptorSet * set, - core::smart_refctd_ptr inputBufferDescriptor, - core::smart_refctd_ptr outputImageDescriptor) -{ - video::IGPUDescriptorSet::SDescriptorInfo pInfos[2]; - video::IGPUDescriptorSet::SWriteDescriptorSet pWrites[2]; - - for (auto i = 0; i< 2; i++) - { - pWrites[i].dstSet = set; - pWrites[i].arrayElement = 0u; - pWrites[i].count = 1u; - pWrites[i].info = pInfos+i; - } - - // Input Buffer - pWrites[0].binding = 0; - pWrites[0].descriptorType = asset::EDT_STORAGE_BUFFER; - pWrites[0].count = 1; - pInfos[0].desc = inputBufferDescriptor; - pInfos[0].buffer.size = inputBufferDescriptor->getSize(); - pInfos[0].buffer.offset = 0u; - - // Output Buffer - pWrites[1].binding = 1; - pWrites[1].descriptorType = asset::EDT_STORAGE_IMAGE; - pWrites[1].count = 1; - pInfos[1].desc = outputImageDescriptor; - pInfos[1].image.sampler = nullptr; - pInfos[1].image.imageLayout = static_cast(0u);; - - driver->updateDescriptorSets(2u, pWrites, 0u, nullptr); -} - -using nbl_glsl_ext_FFT_Parameters_t = ext::FFT::FFT::Parameters_t; -struct vec2 -{ - float x,y; -}; -struct ivec2 -{ - int32_t x,y; -}; -#include "extra_parameters.glsl" - - -int main() -{ - nbl::SIrrlichtCreationParameters deviceParams; - deviceParams.Bits = 24; //may have to set to 32bit for some platforms - deviceParams.ZBufferBits = 24; //we'd like 32bit here - deviceParams.DriverType = EDT_OPENGL; //! Only Well functioning driver, software renderer left for sake of 2D image drawing - deviceParams.WindowSize = dimension2d(1280, 720); - deviceParams.Fullscreen = false; - deviceParams.Vsync = true; //! If supported by target platform - deviceParams.Doublebuffer = true; - deviceParams.Stencilbuffer = false; //! This will not even be a choice soon - - auto device = createDeviceEx(deviceParams); - if (!device) - return 1; // could not create selected driver. - - QToQuitEventReceiver receiver; - device->setEventReceiver(&receiver); - - IVideoDriver* driver = device->getVideoDriver(); - - nbl::io::IFileSystem* filesystem = device->getFileSystem(); - IAssetManager* am = device->getAssetManager(); - // Loading SrcImage and Kernel Image from File - - IAssetLoader::SAssetLoadParams lp; - auto srcImageBundle = am->getAsset("../../media/colorexr.exr", lp); - auto kerImageBundle = am->getAsset("../../media/kernels/physical_flare_256.exr", lp); - - // get GPU image views - smart_refctd_ptr srcImageView; - { - auto srcGpuImages = driver->getGPUObjectsFromAssets(srcImageBundle.getContents()); - - IGPUImageView::SCreationParams srcImgViewInfo; - srcImgViewInfo.flags = static_cast(0u); - srcImgViewInfo.image = srcGpuImages->operator[](0u); - srcImgViewInfo.viewType = IGPUImageView::ET_2D; - srcImgViewInfo.format = srcImgViewInfo.image->getCreationParameters().format; - srcImgViewInfo.subresourceRange.aspectMask = static_cast(0u); - srcImgViewInfo.subresourceRange.baseMipLevel = 0; - srcImgViewInfo.subresourceRange.levelCount = 1; - srcImgViewInfo.subresourceRange.baseArrayLayer = 0; - srcImgViewInfo.subresourceRange.layerCount = 1; - srcImageView = driver->createImageView(std::move(srcImgViewInfo)); - } - smart_refctd_ptr kerImageView; - { - auto kerGpuImages = driver->getGPUObjectsFromAssets(kerImageBundle.getContents()); - - IGPUImageView::SCreationParams kerImgViewInfo; - kerImgViewInfo.flags = static_cast(0u); - kerImgViewInfo.image = kerGpuImages->operator[](0u); - kerImgViewInfo.viewType = IGPUImageView::ET_2D; - kerImgViewInfo.format = kerImgViewInfo.image->getCreationParameters().format; - kerImgViewInfo.subresourceRange.aspectMask = static_cast(0u); - kerImgViewInfo.subresourceRange.baseMipLevel = 0; - kerImgViewInfo.subresourceRange.levelCount = kerImgViewInfo.image->getCreationParameters().mipLevels; - kerImgViewInfo.subresourceRange.baseArrayLayer = 0; - kerImgViewInfo.subresourceRange.layerCount = 1; - kerImageView = driver->createImageView(std::move(kerImgViewInfo)); - } - - // agree on formats - const E_FORMAT srcFormat = srcImageView->getCreationParameters().format; - uint32_t srcNumChannels = getFormatChannelCount(srcFormat); - uint32_t kerNumChannels = getFormatChannelCount(kerImageView->getCreationParameters().format); - //! OVERRIDE (we dont need alpha) - srcNumChannels = channelCountOverride; - kerNumChannels = channelCountOverride; - assert(srcNumChannels == kerNumChannels); // Just to make sure, because the other case is not handled in this example - - // Create Out Image - smart_refctd_ptr outImg; - smart_refctd_ptr outImgView; - { - auto dstImgViewInfo = srcImageView->getCreationParameters(); - - auto dstImgInfo = dstImgViewInfo.image->getCreationParameters(); - outImg = driver->createDeviceLocalGPUImageOnDedMem(std::move(dstImgInfo)); - - dstImgViewInfo.image = outImg; - outImgView = driver->createImageView(IGPUImageView::SCreationParams(dstImgViewInfo)); - } - - // input pipeline - auto imageFirstFFTPipelineLayout = [driver]() -> auto - { - IGPUDescriptorSetLayout::SBinding bnd[] = - { - { - 0u, - EDT_COMBINED_IMAGE_SAMPLER, - 1u, - ISpecializedShader::ESS_COMPUTE, - nullptr - }, - { - 1u, - EDT_STORAGE_BUFFER, - 1u, - ISpecializedShader::ESS_COMPUTE, - nullptr - } - }; - - core::SRange pcRange = FFTClass::getDefaultPushConstantRanges(); - core::SRange bindings = {bnd,bnd+sizeof(bnd)/sizeof(IGPUDescriptorSetLayout::SBinding)}; - - return driver->createPipelineLayout( - pcRange.begin(),pcRange.end(), - driver->createDescriptorSetLayout(bindings.begin(),bindings.end()),nullptr,nullptr,nullptr - ); - }(); - auto convolvePipelineLayout = [driver]() -> auto - { - IGPUSampler::SParams params = - { - { - ISampler::ETC_REPEAT, - ISampler::ETC_REPEAT, - ISampler::ETC_REPEAT, - ISampler::ETBC_FLOAT_OPAQUE_BLACK, - ISampler::ETF_LINEAR, // is it needed? - ISampler::ETF_LINEAR, - ISampler::ESMM_NEAREST, - 0u, - 0u, - ISampler::ECO_ALWAYS - } - }; - auto sampler = driver->createSampler(std::move(params)); - smart_refctd_ptr samplers[channelCountOverride]; - std::fill_n(samplers,channelCountOverride,sampler); - - IGPUDescriptorSetLayout::SBinding bnd[] = - { - { - 0u, - EDT_STORAGE_BUFFER, - 1u, - ISpecializedShader::ESS_COMPUTE, - nullptr - }, - { - 1u, - EDT_STORAGE_BUFFER, - 1u, - ISpecializedShader::ESS_COMPUTE, - nullptr - }, - { - 2u, - EDT_COMBINED_IMAGE_SAMPLER, - channelCountOverride, - ISpecializedShader::ESS_COMPUTE, - samplers - } - }; - - const asset::SPushConstantRange pcRange = {ISpecializedShader::ESS_COMPUTE,0u,sizeof(convolve_parameters_t)}; - core::SRange bindings = {bnd,bnd+sizeof(bnd)/sizeof(IGPUDescriptorSetLayout::SBinding)}; - - return driver->createPipelineLayout( - &pcRange,&pcRange+1, - driver->createDescriptorSetLayout(bindings.begin(),bindings.end()),nullptr,nullptr,nullptr - ); - }(); - auto lastFFTPipelineLayout = [driver]() -> auto - { - IGPUDescriptorSetLayout::SBinding bnd[] = - { - { - 0u, - EDT_STORAGE_BUFFER, - 1u, - ISpecializedShader::ESS_COMPUTE, - nullptr - }, - { - 1u, - EDT_STORAGE_IMAGE, - 1u, - ISpecializedShader::ESS_COMPUTE, - nullptr - }, - }; - - const asset::SPushConstantRange pcRange = {ISpecializedShader::ESS_COMPUTE,0u,sizeof(image_store_parameters_t)}; - core::SRange bindings = {bnd, bnd+sizeof(bnd)/sizeof(IGPUDescriptorSetLayout::SBinding)};; - - return driver->createPipelineLayout( - &pcRange,&pcRange+1, - driver->createDescriptorSetLayout(bindings.begin(),bindings.end()),nullptr,nullptr,nullptr - ); - }(); - - const float bloomRelativeScale = 0.25f; - const auto kerDim = kerImageView->getCreationParameters().image->getCreationParameters().extent; - const auto srcDim = srcImageView->getCreationParameters().image->getCreationParameters().extent; - const float bloomScale = core::min(float(srcDim.width)/float(kerDim.width),float(srcDim.height)/float(kerDim.height))*bloomRelativeScale; - if (bloomScale>1.f) - std::cout << "WARNING: Bloom Kernel will Clip and loose sharpness, increase resolution of bloom kernel!" << std::endl; - const auto marginSrcDim = [srcDim,kerDim,bloomScale]() -> auto - { - auto tmp = srcDim; - for (auto i=0u; i<3u; i++) - { - const auto coord = (&kerDim.width)[i]; - if (coord>1u) - (&tmp.width)[i] += core::max(coord*bloomScale,1u)-1u; - } - return tmp; - }(); - constexpr bool useHalfFloats = true; - // Allocate Output Buffer - auto fftOutputBuffer_0 = driver->createDeviceLocalGPUBufferOnDedMem(FFTClass::getOutputBufferSize(useHalfFloats,marginSrcDim,srcNumChannels)); - auto fftOutputBuffer_1 = driver->createDeviceLocalGPUBufferOnDedMem(FFTClass::getOutputBufferSize(useHalfFloats,marginSrcDim,srcNumChannels)); - core::smart_refctd_ptr kernelNormalizedSpectrums[channelCountOverride]; - - auto updateDescriptorSet = [driver](video::IGPUDescriptorSet* set, core::smart_refctd_ptr inputImageDescriptor, asset::ISampler::E_TEXTURE_CLAMP textureWrap, core::smart_refctd_ptr outputBufferDescriptor) -> void - { - IGPUSampler::SParams params = - { - { - textureWrap, - textureWrap, - textureWrap, - ISampler::ETBC_FLOAT_OPAQUE_BLACK, - ISampler::ETF_LINEAR, - ISampler::ETF_LINEAR, - ISampler::ESMM_LINEAR, - 8u, - 0u, - ISampler::ECO_ALWAYS - } - }; - auto sampler = driver->createSampler(std::move(params)); - - constexpr auto kDescriptorCount = 2u; - video::IGPUDescriptorSet::SDescriptorInfo pInfos[kDescriptorCount]; - video::IGPUDescriptorSet::SWriteDescriptorSet pWrites[kDescriptorCount]; - - for (auto i=0; i(0u); - - // Output Buffer - pWrites[1].binding = 1; - pWrites[1].descriptorType = asset::EDT_STORAGE_BUFFER; - pWrites[1].count = 1; - pInfos[1].desc = outputBufferDescriptor; - pInfos[1].buffer.size = outputBufferDescriptor->getSize(); - pInfos[1].buffer.offset = 0u; - - driver->updateDescriptorSets(2u, pWrites, 0u, nullptr); - }; - - // Precompute Kernel FFT - { - const VkExtent3D paddedKerDim = FFTClass::padDimensions(kerDim); - - // create kernel spectrums - auto createKernelSpectrum = [&]() -> auto - { - video::IGPUImage::SCreationParams imageParams; - imageParams.flags = static_cast(0u); - imageParams.type = asset::IImage::ET_2D; - imageParams.format = useHalfFloats ? EF_R16G16_SFLOAT:EF_R32G32_SFLOAT; - imageParams.extent = { paddedKerDim.width,paddedKerDim.height,1u}; - imageParams.mipLevels = 1u; - imageParams.arrayLayers = 1u; - imageParams.samples = asset::IImage::ESCF_1_BIT; - - video::IGPUImageView::SCreationParams viewParams; - viewParams.flags = static_cast(0u); - viewParams.image = driver->createGPUImageOnDedMem(std::move(imageParams),driver->getDeviceLocalGPUMemoryReqs()); - viewParams.viewType = video::IGPUImageView::ET_2D; - viewParams.format = useHalfFloats ? EF_R16G16_SFLOAT:EF_R32G32_SFLOAT; - viewParams.components = {}; - viewParams.subresourceRange = {}; - viewParams.subresourceRange.levelCount = 1u; - viewParams.subresourceRange.layerCount = 1u; - return driver->createImageView(std::move(viewParams)); - }; - for (uint32_t i=0u; i fftPipeline_SSBOInput(core::make_smart_refctd_ptr(driver,0x1u<getDefaultPipeline()); - - // descriptor sets - core::smart_refctd_ptr fftDescriptorSet_Ker_FFT[2] = - { - driver->createDescriptorSet(core::smart_refctd_ptr(imageFirstFFTPipelineLayout->getDescriptorSetLayout(0u))), - driver->createDescriptorSet(core::smart_refctd_ptr(fftPipeline_SSBOInput->getLayout()->getDescriptorSetLayout(0u))) - }; - updateDescriptorSet(fftDescriptorSet_Ker_FFT[0].get(), kerImageView, ISampler::ETC_CLAMP_TO_BORDER, fftOutputBuffer_0); - FFTClass::updateDescriptorSet(driver,fftDescriptorSet_Ker_FFT[1].get(), fftOutputBuffer_0, fftOutputBuffer_1); - - // Normalization of FFT spectrum - struct NormalizationPushConstants - { - ext::FFT::uvec4 stride; - ext::FFT::uvec4 bitreverse_shift; - }; - auto fftPipelineLayout_KernelNormalization = [&]() -> auto - { - IGPUDescriptorSetLayout::SBinding bnd[] = - { - { - 0u, - EDT_STORAGE_BUFFER, - 1u, - ISpecializedShader::ESS_COMPUTE, - nullptr - }, - { - 1u, - EDT_STORAGE_IMAGE, - channelCountOverride, - ISpecializedShader::ESS_COMPUTE, - nullptr - }, - }; - SPushConstantRange pc_rng; - pc_rng.offset = 0u; - pc_rng.size = sizeof(NormalizationPushConstants); - pc_rng.stageFlags = ISpecializedShader::ESS_COMPUTE; - return driver->createPipelineLayout( - &pc_rng,&pc_rng+1u, - driver->createDescriptorSetLayout(bnd,bnd+2),nullptr,nullptr,nullptr - ); - }(); - auto fftDescriptorSet_KernelNormalization = [&]() -> auto - { - auto dset = driver->createDescriptorSet(core::smart_refctd_ptr(fftPipelineLayout_KernelNormalization->getDescriptorSetLayout(0u))); - - video::IGPUDescriptorSet::SDescriptorInfo pInfos[1+channelCountOverride]; - video::IGPUDescriptorSet::SWriteDescriptorSet pWrites[2]; - - for (auto i = 0; i < 2; i++) - { - pWrites[i].dstSet = dset.get(); - pWrites[i].arrayElement = 0u; - pWrites[i].count = 1u; - pWrites[i].info = pInfos + i; - } - - // In Buffer - pWrites[0].binding = 0; - pWrites[0].descriptorType = asset::EDT_STORAGE_BUFFER; - pWrites[0].count = 1; - pInfos[0].desc = fftOutputBuffer_1; - pInfos[0].buffer.size = fftOutputBuffer_1->getSize(); - pInfos[0].buffer.offset = 0u; - - // Out Buffer - pWrites[1].binding = 1; - pWrites[1].descriptorType = asset::EDT_STORAGE_IMAGE; - pWrites[1].count = channelCountOverride; - for (uint32_t i=0u; iupdateDescriptorSets(2u, pWrites, 0u, nullptr); - return dset; - }(); - - // Ker Image First Axis FFT - { - auto fftPipeline_ImageInput = driver->createComputePipeline(nullptr,core::smart_refctd_ptr(imageFirstFFTPipelineLayout),createShader(driver,0x1u<bindComputePipeline(fftPipeline_ImageInput.get()); - driver->bindDescriptorSets(EPBP_COMPUTE, imageFirstFFTPipelineLayout.get(), 0u, 1u, &fftDescriptorSet_Ker_FFT[0].get(), nullptr); - FFTClass::dispatchHelper(driver, imageFirstFFTPipelineLayout.get(), fftPushConstants[0], fftDispatchInfo[0]); - } - - // Ker Image Last Axis FFT - driver->bindComputePipeline(fftPipeline_SSBOInput.get()); - driver->bindDescriptorSets(EPBP_COMPUTE, fftPipeline_SSBOInput->getLayout(), 0u, 1u, &fftDescriptorSet_Ker_FFT[1].get(), nullptr); - FFTClass::dispatchHelper(driver, fftPipeline_SSBOInput->getLayout(), fftPushConstants[1], fftDispatchInfo[1]); - - // Ker Normalization - auto fftPipeline_KernelNormalization = driver->createComputePipeline(nullptr,core::smart_refctd_ptr(fftPipelineLayout_KernelNormalization),createShader(driver,0xdeadbeefu,useHalfFloats,"../normalization.comp")); - driver->bindComputePipeline(fftPipeline_KernelNormalization.get()); - driver->bindDescriptorSets(EPBP_COMPUTE, fftPipelineLayout_KernelNormalization.get(), 0u, 1u, &fftDescriptorSet_KernelNormalization.get(), nullptr); - { - NormalizationPushConstants normalizationPC; - normalizationPC.stride = fftPushConstants[1].output_strides; - normalizationPC.bitreverse_shift.x = 32-core::findMSB(paddedKerDim.width); - normalizationPC.bitreverse_shift.y = 32-core::findMSB(paddedKerDim.height); - normalizationPC.bitreverse_shift.z = 0; - driver->pushConstants(fftPipelineLayout_KernelNormalization.get(),ICPUSpecializedShader::ESS_COMPUTE,0u,sizeof(normalizationPC),&normalizationPC); - } - { - const uint32_t dispatchSizeX = (paddedKerDim.width-1u)/16u+1u; - const uint32_t dispatchSizeY = (paddedKerDim.height-1u)/16u+1u; - driver->dispatch(dispatchSizeX,dispatchSizeY,kerNumChannels); - FFTClass::defaultBarrier(); - } - } - - FFTClass::Parameters_t fftPushConstants[3]; - FFTClass::DispatchInfo_t fftDispatchInfo[3]; - const ISampler::E_TEXTURE_CLAMP fftPadding[2] = {ISampler::ETC_MIRROR,ISampler::ETC_MIRROR}; - const auto passes = FFTClass::buildParameters(false,srcNumChannels,srcDim,fftPushConstants,fftDispatchInfo,fftPadding,marginSrcDim); - { - // override for less work and storage (dont need to store the extra padding of the last axis after iFFT) - fftPushConstants[1].output_strides.x = fftPushConstants[0].input_strides.x; - fftPushConstants[1].output_strides.y = fftPushConstants[0].input_strides.y; - fftPushConstants[1].output_strides.z = fftPushConstants[1].input_strides.z; - fftPushConstants[1].output_strides.w = fftPushConstants[1].input_strides.w; - // iFFT - fftPushConstants[2].input_dimensions = fftPushConstants[1].input_dimensions; - { - fftPushConstants[2].input_dimensions.w = fftPushConstants[0].input_dimensions.w^0x80000000u; - fftPushConstants[2].input_strides = fftPushConstants[1].output_strides; - fftPushConstants[2].output_strides = fftPushConstants[0].input_strides; - } - fftDispatchInfo[2] = fftDispatchInfo[0]; - } - assert(passes==2); - // pipelines - auto fftPipeline_ImageInput = driver->createComputePipeline(nullptr,core::smart_refctd_ptr(imageFirstFFTPipelineLayout),createShader(driver,0x1u<createComputePipeline(nullptr, std::move(convolvePipelineLayout), createShader(driver,0x1u<createComputePipeline(nullptr, std::move(lastFFTPipelineLayout), createShader(driver,0x1u<createDescriptorSet(core::smart_refctd_ptr(imageFirstFFTPipelineLayout->getDescriptorSetLayout(0u))); - updateDescriptorSet(fftDescriptorSet_Src_FirstFFT.get(), srcImageView, ISampler::ETC_MIRROR, fftOutputBuffer_0); - - // Convolution - auto convolveDescriptorSet = driver->createDescriptorSet(core::smart_refctd_ptr(convolvePipeline->getLayout()->getDescriptorSetLayout(0u))); - updateDescriptorSet_Convolution(driver, convolveDescriptorSet.get(), fftOutputBuffer_0, fftOutputBuffer_1, kernelNormalizedSpectrums); - - // Last Axis IFFT - auto lastFFTDescriptorSet = driver->createDescriptorSet(core::smart_refctd_ptr(lastFFTPipeline->getLayout()->getDescriptorSetLayout(0u))); - updateDescriptorSet_LastFFT(driver, lastFFTDescriptorSet.get(), fftOutputBuffer_1, outImgView); - - uint32_t outBufferIx = 0u; - auto lastPresentStamp = std::chrono::high_resolution_clock::now(); - bool savedToFile = false; - - auto downloadStagingArea = driver->getDefaultDownStreamingBuffer(); - - auto blitFBO = driver->addFrameBuffer(); - blitFBO->attach(video::EFAP_COLOR_ATTACHMENT0, std::move(outImgView)); - - while (device->run() && receiver.keepOpen()) - { - driver->beginScene(false, false); - - // Src Image First Axis FFT - driver->bindComputePipeline(fftPipeline_ImageInput.get()); - driver->bindDescriptorSets(EPBP_COMPUTE, imageFirstFFTPipelineLayout.get(), 0u, 1u, &fftDescriptorSet_Src_FirstFFT.get(), nullptr); - FFTClass::dispatchHelper(driver, imageFirstFFTPipelineLayout.get(), fftPushConstants[0], fftDispatchInfo[0]); - - // Src Image Last Axis FFT + Convolution + Convolved Last Axis IFFT Y - driver->bindComputePipeline(convolvePipeline.get()); - driver->bindDescriptorSets(EPBP_COMPUTE, convolvePipeline->getLayout(), 0u, 1u, &convolveDescriptorSet.get(), nullptr); - { - const auto& kernelImgExtent = kernelNormalizedSpectrums[0]->getCreationParameters().image->getCreationParameters().extent; - vec2 kernel_half_pixel_size{0.5f,0.5f}; - kernel_half_pixel_size.x /= kernelImgExtent.width; - kernel_half_pixel_size.y /= kernelImgExtent.height; - driver->pushConstants(convolvePipeline->getLayout(),ISpecializedShader::ESS_COMPUTE,offsetof(convolve_parameters_t,kernel_half_pixel_size),sizeof(convolve_parameters_t::kernel_half_pixel_size),&kernel_half_pixel_size); - } - FFTClass::dispatchHelper(driver, convolvePipeline->getLayout(), fftPushConstants[1], fftDispatchInfo[1]); - - // Last FFT Padding and Copy to GPU Image - driver->bindComputePipeline(lastFFTPipeline.get()); - driver->bindDescriptorSets(EPBP_COMPUTE, lastFFTPipeline->getLayout(), 0u, 1u, &lastFFTDescriptorSet.get(), nullptr); - { - const auto paddedSrcDim = FFTClass::padDimensions(marginSrcDim); - ivec2 unpad_offset = { 0,0 }; - for (auto i=0u; i<2u; i++) - if (fftDispatchInfo[2].workGroupCount[i]==1u) - (&unpad_offset.x)[i] = ((&paddedSrcDim.width)[i]-(&srcDim.width)[i])>>1u; - driver->pushConstants(lastFFTPipeline->getLayout(),ISpecializedShader::ESS_COMPUTE,offsetof(image_store_parameters_t,unpad_offset),sizeof(image_store_parameters_t::unpad_offset),&unpad_offset); - } - FFTClass::dispatchHelper(driver, lastFFTPipeline->getLayout(), fftPushConstants[2], fftDispatchInfo[2]); - - if(!savedToFile) - { - savedToFile = true; - - core::smart_refctd_ptr imageView; - const uint32_t colorBufferBytesize = srcDim.height * srcDim.width * asset::getTexelOrBlockBytesize(srcFormat); - - // create image - ICPUImage::SCreationParams imgParams; - imgParams.flags = static_cast(0u); // no flags - imgParams.type = ICPUImage::ET_2D; - imgParams.format = srcFormat; - imgParams.extent = srcDim; - imgParams.mipLevels = 1u; - imgParams.arrayLayers = 1u; - imgParams.samples = ICPUImage::ESCF_1_BIT; - auto image = ICPUImage::create(std::move(imgParams)); - - constexpr uint64_t timeoutInNanoSeconds = 300000000000u; - const auto waitPoint = std::chrono::high_resolution_clock::now()+std::chrono::nanoseconds(timeoutInNanoSeconds); - - uint32_t address = std::remove_pointer::type::invalid_address; // remember without initializing the address to be allocated to invalid_address you won't get an allocation! - const uint32_t alignment = 4096u; // common page size - auto unallocatedSize = downloadStagingArea->multi_alloc(waitPoint, 1u, &address, &colorBufferBytesize, &alignment); - if (unallocatedSize) - { - os::Printer::log("Could not download the buffer from the GPU!", ELL_ERROR); - } - - // set up regions - auto regions = core::make_refctd_dynamic_array >(1u); - { - auto& region = regions->front(); - - region.bufferOffset = 0u; - region.bufferRowLength = 0u; - region.bufferImageHeight = 0u; - //region.imageSubresource.aspectMask = wait for Vulkan; - region.imageSubresource.mipLevel = 0u; - region.imageSubresource.baseArrayLayer = 0u; - region.imageSubresource.layerCount = 1u; - region.imageOffset = { 0u,0u,0u }; - region.imageExtent = imgParams.extent; - } - - driver->copyImageToBuffer(outImg.get(), downloadStagingArea->getBuffer(), 1, ®ions->front()); - - auto downloadFence = driver->placeFence(true); - - auto* data = reinterpret_cast(downloadStagingArea->getBufferPointer()) + address; - auto cpubufferalias = core::make_smart_refctd_ptr > >(colorBufferBytesize, data, core::adopt_memory); - image->setBufferAndRegions(std::move(cpubufferalias),regions); - - // wait for download fence and then invalidate the CPU cache - { - auto result = downloadFence->waitCPU(timeoutInNanoSeconds,true); - if (result==E_DRIVER_FENCE_RETVAL::EDFR_TIMEOUT_EXPIRED||result==E_DRIVER_FENCE_RETVAL::EDFR_FAIL) - { - os::Printer::log("Could not download the buffer from the GPU, fence not signalled!", ELL_ERROR); - downloadStagingArea->multi_free(1u, &address, &colorBufferBytesize, nullptr); - continue; - } - if (downloadStagingArea->needsManualFlushOrInvalidate()) - driver->invalidateMappedMemoryRanges({{downloadStagingArea->getBuffer()->getBoundMemory(),address,colorBufferBytesize}}); - } - - // create image view - ICPUImageView::SCreationParams imgViewParams; - imgViewParams.flags = static_cast(0u); - imgViewParams.format = image->getCreationParameters().format; - imgViewParams.image = std::move(image); - imgViewParams.viewType = ICPUImageView::ET_2D; - imgViewParams.subresourceRange = {static_cast(0u),0u,1u,0u,1u}; - imageView = ICPUImageView::create(std::move(imgViewParams)); - - IAssetWriter::SAssetWriteParams wp(imageView.get()); - volatile bool success = am->writeAsset("convolved_exr.exr", wp); - assert(success); - } - - driver->blitRenderTargets(blitFBO, nullptr, false, false); - - driver->endScene(); - } - - return 0; -} \ No newline at end of file diff --git a/old_to_refactor/49_ComputeFFT/normalization.comp b/old_to_refactor/49_ComputeFFT/normalization.comp deleted file mode 100644 index b3926090d..000000000 --- a/old_to_refactor/49_ComputeFFT/normalization.comp +++ /dev/null @@ -1,34 +0,0 @@ -layout(local_size_x=16, local_size_y=16, local_size_z=1) in; - -#include - -layout(set=0, binding=0) restrict readonly buffer InBuffer -{ - nbl_glsl_ext_FFT_storage_t in_data[]; -}; - -layout(set=0, binding=1, rg16f) uniform image2D NormalizedKernel[3]; - -layout(push_constant) uniform PushConstants -{ - uvec4 strides; - uvec4 bitreverse_shift; -} pc; - -#include - -void main() -{ - nbl_glsl_complex value = nbl_glsl_ext_FFT_storage_t_get(in_data[nbl_glsl_dot(gl_GlobalInvocationID,pc.strides.xyz)]); - - // imaginary component will be 0, image shall be positive - vec3 avg; - for (uint i=0u; i<3u; i++) - avg[i] = nbl_glsl_ext_FFT_storage_t_get(in_data[pc.strides.z*i]).x; - const float power = (nbl_glsl_scRGBtoXYZ*avg).y; - - const uvec2 coord = bitfieldReverse(gl_GlobalInvocationID.xy)>>pc.bitreverse_shift.xy; - const nbl_glsl_complex shift = nbl_glsl_expImaginary(-nbl_glsl_PI*float(coord.x+coord.y)); - value = nbl_glsl_complex_mul(value,shift)/power; - imageStore(NormalizedKernel[gl_WorkGroupID.z],ivec2(coord),vec4(value,0.0,0.0)); -} \ No newline at end of file diff --git a/60_ClusteredRendering/CMakeLists.txt b/old_to_refactor/60_ClusteredRendering/CMakeLists.txt similarity index 100% rename from 60_ClusteredRendering/CMakeLists.txt rename to old_to_refactor/60_ClusteredRendering/CMakeLists.txt diff --git a/42_FragmentShaderPathTracer/config.json.template b/old_to_refactor/60_ClusteredRendering/config.json.template similarity index 100% rename from 42_FragmentShaderPathTracer/config.json.template rename to old_to_refactor/60_ClusteredRendering/config.json.template diff --git a/60_ClusteredRendering/main.cpp b/old_to_refactor/60_ClusteredRendering/main.cpp similarity index 100% rename from 60_ClusteredRendering/main.cpp rename to old_to_refactor/60_ClusteredRendering/main.cpp diff --git a/60_ClusteredRendering/pipeline.groovy b/old_to_refactor/60_ClusteredRendering/pipeline.groovy similarity index 100% rename from 60_ClusteredRendering/pipeline.groovy rename to old_to_refactor/60_ClusteredRendering/pipeline.groovy