From 9c040b59ac17914d50686fc80c92b34892db68a2 Mon Sep 17 00:00:00 2001 From: cdozdil Date: Wed, 4 Nov 2026 21:16:22 +0300 Subject: [PATCH] Fix Vulkan FG and shader sync --- OptiScaler.ini | 4 +- OptiScaler/framegen/IFGFeature_Vk.cpp | 34 +++++-- OptiScaler/framegen/IFGFeature_Vk.h | 14 ++- OptiScaler/framegen/ffx/FSRFG_Vk.cpp | 97 ++++++++++++++----- OptiScaler/framegen/ffx/FSRFG_Vk.h | 5 +- .../framegen/reprojection/Reprojection_Vk.cpp | 4 + OptiScaler/hudfix/Hudfix_Vk.cpp | 12 ++- OptiScaler/menu/menu_common.cpp | 7 +- OptiScaler/shaders/Shader_Vk.cpp | 29 +++++- OptiScaler/shaders/Shader_Vk.h | 14 ++- OptiScaler/shaders/hud_copy/HudCopy_Vk.cpp | 5 +- OptiScaler/shaders/magnifier/Magnifier_Vk.cpp | 5 +- OptiScaler/shaders/output_scaling/OS_Vk.cpp | 13 +-- OptiScaler/shaders/rcas/RCAS_Vk.cpp | 81 +++++++++------- OptiScaler/shaders/rcas/RCAS_Vk.h | 7 +- 15 files changed, 231 insertions(+), 100 deletions(-) diff --git a/OptiScaler.ini b/OptiScaler.ini index 8182ea4c..540ca05f 100644 --- a/OptiScaler.ini +++ b/OptiScaler.ini @@ -368,8 +368,8 @@ HUDFixExtended=auto HUDFixUITexture=auto ; Vulkan, rebuild the hudless by removing that UI texture from the frame -; FSR-FG only gets the UI this way, DLSSG also takes the UI texture directly -; true or false - Default (auto) is true for FSR-FG, false for DLSSG +; FSR-FG only gets the UI this way. Not used with DLSSG, it takes the UI texture directly +; true or false - Default (auto) is true HUDFixUIUnblend=auto ; Do not use CreateRenderTargetView for resource tracking diff --git a/OptiScaler/framegen/IFGFeature_Vk.cpp b/OptiScaler/framegen/IFGFeature_Vk.cpp index 00a7fc9d..ca25d8fa 100644 --- a/OptiScaler/framegen/IFGFeature_Vk.cpp +++ b/OptiScaler/framegen/IFGFeature_Vk.cpp @@ -487,19 +487,36 @@ bool IFGFeature_Vk::SetResource(VkFGResource* inputResource) return true; } -void IFGFeature_Vk::RemoveUiFromHudless(VkCommandBuffer cmdBuffer, bool premultiplied) +void IFGFeature_Vk::RequestUiUnblend(int fIndex, bool premultiplied) { - auto hudless = GetResource(FG_ResourceType::HudlessColor); - auto ui = GetResource(FG_ResourceType::UIColor); + if (fIndex >= 0 && fIndex < BUFFER_COUNT) + _uiUnblendPending[fIndex].store(premultiplied ? 2 : 1, std::memory_order_release); +} + +void IFGFeature_Vk::UiUnblendSubmitted(int fIndex, uint8_t recorded) +{ + // A newer request of the frame stays + if (recorded != 0) + _uiUnblendPending[fIndex].compare_exchange_strong(recorded, 0, std::memory_order_acq_rel); +} + +uint8_t IFGFeature_Vk::UnblendUi(VkCommandBuffer cmdBuffer, int fIndex) +{ + const auto pending = _uiUnblendPending[fIndex].load(std::memory_order_acquire); + if (pending == 0) + return 0; + + auto hudless = GetResource(FG_ResourceType::HudlessColor, fIndex); + auto ui = GetResource(FG_ResourceType::UIColor, fIndex); if (!hudless || !ui || hudless->view == VK_NULL_HANDLE || ui->view == VK_NULL_HANDLE) - return; + return 0; if (_uiUnblend == nullptr) _uiUnblend = std::make_unique("UiUnblend", _device, _physicalDevice); if (!_uiUnblend->IsInit()) - return; + return 0; auto imageInfo = [](const VkFGResource& resource) -> VkImageInfo { @@ -507,7 +524,10 @@ void IFGFeature_Vk::RemoveUiFromHudless(VkCommandBuffer cmdBuffer, bool premulti resource.format, resource.imageWidth, resource.imageHeight }; }; - _uiUnblend->Dispatch(cmdBuffer, imageInfo(*ui), ui->layout, imageInfo(*hudless), hudless->layout, premultiplied); + return _uiUnblend->Dispatch(cmdBuffer, imageInfo(*ui), ui->layout, imageInfo(*hudless), hudless->layout, + pending == 2) + ? pending + : 0; } VkCommandBuffer IFGFeature_Vk::BeginCommandBuffer(int index) @@ -625,6 +645,8 @@ void IFGFeature_Vk::NewFrame() auto fIndex = GetIndex(); + _uiUnblendPending[fIndex].store(0, std::memory_order_release); + std::unique_lock lock(_resourceMutex[fIndex]); _frameResources[fIndex].clear(); _lastFGFramePresentId = _fgFramePresentId; diff --git a/OptiScaler/framegen/IFGFeature_Vk.h b/OptiScaler/framegen/IFGFeature_Vk.h index 78f87506..5efe2bb5 100644 --- a/OptiScaler/framegen/IFGFeature_Vk.h +++ b/OptiScaler/framegen/IFGFeature_Vk.h @@ -41,6 +41,9 @@ class IFGFeature_Vk : public virtual IFGFeature ImageCopy _flipped[BUFFER_COUNT][ResourceTypeCOUNT] {}; std::unique_ptr _uiUnblend; + + // 0: none, 1: straight alpha, 2: premultiplied alpha + std::atomic _uiUnblendPending[BUFFER_COUNT] {}; std::unique_ptr _depthFlip; std::unique_ptr _mvFlip; @@ -87,6 +90,12 @@ class IFGFeature_Vk : public virtual IFGFeature // Waits until the GPU is done with the previous use of the index, then begins it VkCommandBuffer BeginCommandBuffer(int index); + + // Removes the UI copy from the hudless copy of the frame if it was requested, before the output reads it + // Returns what got recorded. UiUnblendSubmitted clears the request after the submit, a dropped command buffer + // leaves it for another present of the frame + uint8_t UnblendUi(VkCommandBuffer cmdBuffer, int fIndex); + void UiUnblendSubmitted(int fIndex, uint8_t recorded); void WaitForCommandBuffers(); void DestroyCommandBuffers(); @@ -148,8 +157,9 @@ class IFGFeature_Vk : public virtual IFGFeature bool SetResource(VkFGResource* inputResource); - // Removes the current frame's UI copy from its hudless copy, for games blending a UI texture on the frame - void RemoveUiFromHudless(VkCommandBuffer cmdBuffer, bool premultiplied); + // For games blending a UI texture on the frame, the output removes it again in its own command buffer. + // A game's command buffer would keep our compute pipeline and descriptor set bound. + void RequestUiUnblend(int fIndex, bool premultiplied); bool HasResource(FG_ResourceType type, int index = -1) override final; diff --git a/OptiScaler/framegen/ffx/FSRFG_Vk.cpp b/OptiScaler/framegen/ffx/FSRFG_Vk.cpp index c88a29f3..55ff7812 100644 --- a/OptiScaler/framegen/ffx/FSRFG_Vk.cpp +++ b/OptiScaler/framegen/ffx/FSRFG_Vk.cpp @@ -370,7 +370,35 @@ VkResult FSRFG_Vk::QueuePresent(VkQueue queue, const VkPresentInfoKHR* pPresentI LOG_WARN("Game presents from a different queue than the one given to FFX"); } - return _functions.pOutQueuePresentKHR(queue, pPresentInfo); + VkSemaphore prepared = VK_NULL_HANDLE; + + if (IsActive() && !IsPaused()) + { + OwnedLockGuard lock(Mutex, 2); + + // Game stopped sending new frames, menus and such + if ((_fgFramePresentId - _lastFGFramePresentId) > 3 && IsActive() && !_waitingNewFrameData) + { + LOG_DEBUG("Pausing FG"); + Deactivate(); + _waitingNewFrameData = true; + } + else + { + _fgFramePresentId++; + prepared = Dispatch(pPresentInfo); + } + } + + if (prepared == VK_NULL_HANDLE) + return _functions.pOutQueuePresentKHR(queue, pPresentInfo); + + // The prepare waited for the game's semaphores, the present only for the prepare + auto presentInfo = *pPresentInfo; + presentInfo.waitSemaphoreCount = 1; + presentInfo.pWaitSemaphores = &prepared; + + return _functions.pOutQueuePresentKHR(queue, &presentInfo); } void FSRFG_Vk::SetHdrMetadata(VkDevice device, VkSwapchainKHR swapchain, const VkHdrMetadataEXT* pMetadata) @@ -431,6 +459,15 @@ bool FSRFG_Vk::Shutdown() ReleaseSwapchainContext(); DestroyCommandBuffers(); + // The presents waiting for these are done after ReleaseSwapchainContext + for (auto& semaphore : _preparedSemaphore) + { + if (semaphore != VK_NULL_HANDLE) + vkDestroySemaphore(_device, semaphore, nullptr); + + semaphore = VK_NULL_HANDLE; + } + for (auto& copy : _hudlessCopies) DestroyCopy(copy); @@ -739,32 +776,20 @@ void FSRFG_Vk::EvaluateState(FG_Constants& fgConstants) bool FSRFG_Vk::Present() { - OwnedLockGuard lock(Mutex, 2); - - // Game stopped sending new frames, menus and such - if ((_fgFramePresentId - _lastFGFramePresentId) > 3 && IsActive() && !_waitingNewFrameData) - { - LOG_DEBUG("Pausing FG"); - Deactivate(); - _waitingNewFrameData = true; - return false; - } - - _fgFramePresentId++; - - return Dispatch(); + // Done in QueuePresent, the prepare has to wait for the present's semaphores + return false; } -bool FSRFG_Vk::Dispatch() +VkSemaphore FSRFG_Vk::Dispatch(const VkPresentInfoKHR* pPresentInfo) { if (_fgContext == nullptr) - return false; + return VK_NULL_HANDLE; UINT64 willDispatchFrame = 0; auto fIndex = GetDispatchIndex(willDispatchFrame); if (fIndex < 0 || !IsActive() || IsPaused()) - return false; + return VK_NULL_HANDLE; if (State::Instance().fsrfgFramePaceTuningChanged) ConfigureFramePaceTuning(); @@ -775,16 +800,30 @@ bool FSRFG_Vk::Dispatch() if (!depth || !velocity) { LOG_WARN("Depth or Velocity is not ready, skipping"); - return false; + return VK_NULL_HANDLE; } auto& state = State::Instance(); auto config = Config::Instance(); + if (_preparedSemaphore[fIndex] == VK_NULL_HANDLE) + { + VkSemaphoreCreateInfo semaphoreInfo { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO }; + + if (vkCreateSemaphore(_device, &semaphoreInfo, nullptr, &_preparedSemaphore[fIndex]) != VK_SUCCESS) + { + LOG_ERROR("vkCreateSemaphore failed for {}", fIndex); + _preparedSemaphore[fIndex] = VK_NULL_HANDLE; + return VK_NULL_HANDLE; + } + } + auto cmdBuffer = BeginCommandBuffer(fIndex); if (cmdBuffer == VK_NULL_HANDLE) - return false; + return VK_NULL_HANDLE; + + const auto unblended = UnblendUi(cmdBuffer, fIndex); ffxConfigureDescFrameGeneration fgConfig {}; fgConfig.header.type = FFX_API_CONFIGURE_DESC_TYPE_FRAMEGENERATION; @@ -871,7 +910,7 @@ bool FSRFG_Vk::Dispatch() // The begun command buffer is just reset on the next use if (result != FFX_API_RETURN_OK || !_isActive) - return false; + return VK_NULL_HANDLE; ffxDispatchDescFrameGenerationPrepareCameraInfo dfgCameraData {}; dfgCameraData.header.type = FFX_API_DISPATCH_DESC_TYPE_FRAMEGENERATION_PREPARE_CAMERAINFO; @@ -924,20 +963,30 @@ bool FSRFG_Vk::Dispatch() vkEndCommandBuffer(cmdBuffer); - // FFX dispatches the interpolation on the game queue too, which keeps it after the prepare + // The game's copies can be on another queue, its present semaphores order them before the prepare. + // FFX dispatches the interpolation on the game queue too, which keeps it after the prepare. + std::vector waitStages(pPresentInfo->waitSemaphoreCount, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + VkSubmitInfo submitInfo { VK_STRUCTURE_TYPE_SUBMIT_INFO }; + submitInfo.waitSemaphoreCount = pPresentInfo->waitSemaphoreCount; + submitInfo.pWaitSemaphores = pPresentInfo->pWaitSemaphores; + submitInfo.pWaitDstStageMask = waitStages.data(); submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &cmdBuffer; + submitInfo.signalSemaphoreCount = 1; + submitInfo.pSignalSemaphores = &_preparedSemaphore[fIndex]; vkResetFences(_device, 1, &_fence[fIndex]); if (auto submitResult = vkQueueSubmit(_gameQueue, 1, &submitInfo, _fence[fIndex]); submitResult != VK_SUCCESS) { LOG_ERROR("vkQueueSubmit error: {}", magic_enum::enum_name(submitResult)); - return false; + return VK_NULL_HANDLE; } - return result == FFX_API_RETURN_OK; + UiUnblendSubmitted(fIndex, unblended); + + return _preparedSemaphore[fIndex]; } ffxReturnCode_t FSRFG_Vk::DispatchCallback(ffxDispatchDescFrameGeneration* params) diff --git a/OptiScaler/framegen/ffx/FSRFG_Vk.h b/OptiScaler/framegen/ffx/FSRFG_Vk.h index 703c5a6e..bffc7fe5 100644 --- a/OptiScaler/framegen/ffx/FSRFG_Vk.h +++ b/OptiScaler/framegen/ffx/FSRFG_Vk.h @@ -59,6 +59,9 @@ class FSRFG_Vk : public virtual IFGFeature_Vk uint64_t _lastDispatchedFrameId = 0; + // Signaled by the prepare after the game's present semaphores, the present waits for it + VkSemaphore _preparedSemaphore[BUFFER_COUNT] {}; + void CreateContext(); void QueryVersions(); bool IsDriverVersionSelected(); @@ -67,7 +70,7 @@ class FSRFG_Vk : public virtual IFGFeature_Vk ffxReturnCode_t ConfigureEnabled(bool enabled); void ConfigureFramePaceTuning(); - bool Dispatch(); + VkSemaphore Dispatch(const VkPresentInfoKHR* pPresentInfo); ffxReturnCode_t DispatchCallback(ffxDispatchDescFrameGeneration* params); void DispatchHudShaders(ffxDispatchDescFrameGeneration* params); VkImageView PresentView(VkImage image); diff --git a/OptiScaler/framegen/reprojection/Reprojection_Vk.cpp b/OptiScaler/framegen/reprojection/Reprojection_Vk.cpp index 233b7bf4..f0d78b72 100644 --- a/OptiScaler/framegen/reprojection/Reprojection_Vk.cpp +++ b/OptiScaler/framegen/reprojection/Reprojection_Vk.cpp @@ -189,6 +189,8 @@ VkSemaphore Reprojection_Vk::ReprojectPresent(VkQueue queue, const VkPresentInfo if (cmdBuffer == VK_NULL_HANDLE) return VK_NULL_HANDLE; + const auto unblended = UnblendUi(cmdBuffer, fIndex); + auto imageIndex = pPresentInfo->pImageIndices[0]; auto swapchainImage = _swapchainImages[imageIndex]; @@ -266,6 +268,8 @@ VkSemaphore Reprojection_Vk::ReprojectPresent(VkQueue queue, const VkPresentInfo return VK_NULL_HANDLE; } + UiUnblendSubmitted(fIndex, unblended); + _reprojectionActive = !_reproject->IsBypassed(); return _reprojectedSemaphores[imageIndex]; diff --git a/OptiScaler/hudfix/Hudfix_Vk.cpp b/OptiScaler/hudfix/Hudfix_Vk.cpp index f24c4f4e..9bae2a71 100644 --- a/OptiScaler/hudfix/Hudfix_Vk.cpp +++ b/OptiScaler/hudfix/Hudfix_Vk.cpp @@ -584,8 +584,12 @@ static void UseUiTexture(VkCommandBuffer cmdBuffer, const DescriptorImage& ui, c auto config = Config::Instance(); auto fg = state.currentVkFG; + // The render thread can start the next frame meanwhile, all three go to this frame + const auto fIndex = fg->GetIndex(); + auto uiResource = CopiedResource(FG_ResourceType::UIColor, cmdBuffer, ui.image, uiInfo.format, uiInfo.extent, ui.layout); + uiResource.frameIndex = fIndex; if (!fg->SetResource(&uiResource)) return; @@ -593,16 +597,18 @@ static void UseUiTexture(VkCommandBuffer cmdBuffer, const DescriptorImage& ui, c const auto upscaleFrame = _upscaleFrame.load(std::memory_order_acquire); LOG_DEBUG("UI: {:X}, frame: {}", (size_t) ui.image, upscaleFrame); - // FSR-FG has no UI input, the rebuilt hudless is its only way to know about the UI - if (!config->FGHUDFixUIUnblend.value_or(state.activeFgOutput != FGOutput::DLSSG)) + // FSR-FG has no UI input, the rebuilt hudless is its only way to know about the UI. + // DLSSG takes the UI directly and has no command buffer of its own to unblend in. + if (state.activeFgOutput == FGOutput::DLSSG || !config->FGHUDFixUIUnblend.value_or(true)) return; auto hudless = CopiedResource(FG_ResourceType::HudlessColor, cmdBuffer, frame.image, frameInfo.format, frameInfo.extent, frame.layout); + hudless.frameIndex = fIndex; if (fg->SetResource(&hudless)) { - fg->RemoveUiFromHudless(cmdBuffer, config->FGUIPremultipliedAlpha.value_or_default()); + fg->RequestUiUnblend(fIndex, config->FGUIPremultipliedAlpha.value_or_default()); _hudlessFromUiFrame.store(upscaleFrame, std::memory_order_release); } } diff --git a/OptiScaler/menu/menu_common.cpp b/OptiScaler/menu/menu_common.cpp index 0039525d..1fdab8f5 100644 --- a/OptiScaler/menu/menu_common.cpp +++ b/OptiScaler/menu/menu_common.cpp @@ -6219,14 +6219,15 @@ void MenuCommon::RenderFrameGenerationRuntimeSettings(RenderMenuContext& ctx) config->FGHUDFixUITexture = uiTexture; ShowTooltip("Use the UI texture the game blends on the frame in its last compute pass"); - ImGui::BeginDisabled(!uiTexture); + const bool dlssgOutput = state.activeFgOutput == FGOutput::DLSSG; + ImGui::BeginDisabled(!uiTexture || dlssgOutput); ImGui::SameLine(0.0f, 16.0f); - auto uiUnblend = config->FGHUDFixUIUnblend.value_or(state.activeFgOutput != FGOutput::DLSSG); + auto uiUnblend = !dlssgOutput && config->FGHUDFixUIUnblend.value_or(true); if (ImGui::Checkbox("Unblend UI", &uiUnblend)) config->FGHUDFixUIUnblend = uiUnblend; ShowTooltip("Rebuild the HUDless by removing the UI texture from the frame\n" - "FSR-FG gets the UI only this way, DLSSG also takes the UI texture directly"); + "FSR-FG gets the UI only this way, DLSSG takes the UI texture directly"); ImGui::EndDisabled(); diff --git a/OptiScaler/shaders/Shader_Vk.cpp b/OptiScaler/shaders/Shader_Vk.cpp index 522d7634..df6bd3ec 100644 --- a/OptiScaler/shaders/Shader_Vk.cpp +++ b/OptiScaler/shaders/Shader_Vk.cpp @@ -388,11 +388,9 @@ void Shader_Vk::SetImageLayout(VkCommandBuffer cmdBuffer, VkImage image, VkImage VkPipelineStageFlags sourceStage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; VkPipelineStageFlags destinationStage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + // Discarded contents can still be read by earlier commands, the transition waits for them if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED) - { barrier.srcAccessMask = 0; - sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - } else if (oldLayout == VK_IMAGE_LAYOUT_GENERAL) { barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; @@ -413,8 +411,31 @@ void Shader_Vk::SetImageLayout(VkCommandBuffer cmdBuffer, VkImage image, VkImage vkCmdPipelineBarrier(cmdBuffer, sourceStage, destinationStage, 0, 0, nullptr, 0, nullptr, 1, &barrier); } -void Shader_Vk::CreateConstantBuffer(VkDeviceSize bufferSize) +VkDeviceSize Shader_Vk::UniformStride(VkPhysicalDevice physicalDevice, VkDeviceSize size) { + VkPhysicalDeviceProperties properties {}; + vkGetPhysicalDeviceProperties(physicalDevice, &properties); + + const auto alignment = std::max(properties.limits.minUniformBufferOffsetAlignment, 1); + return (size + alignment - 1) / alignment * alignment; +} + +VkDescriptorBufferInfo Shader_Vk::WriteConstants(const void* data, VkDeviceSize size) +{ + const auto offset = _constantStride * _currentSetIndex; + size = std::min(size, _constantStride); + + if (_mappedConstantBuffer != nullptr) + memcpy((uint8_t*) _mappedConstantBuffer + offset, data, size); + + return { _constantBuffer, offset, size }; +} + +void Shader_Vk::CreateConstantBuffer(VkDeviceSize paramsSize) +{ + _constantStride = UniformStride(_physicalDevice, paramsSize); + const auto bufferSize = _constantStride * _maxFramesInFlight; + if (!CreateBufferResource(_device, _physicalDevice, &_constantBuffer, &_constantBufferMemory, bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) diff --git a/OptiScaler/shaders/Shader_Vk.h b/OptiScaler/shaders/Shader_Vk.h index 7141a3f9..e2f9451c 100644 --- a/OptiScaler/shaders/Shader_Vk.h +++ b/OptiScaler/shaders/Shader_Vk.h @@ -37,12 +37,16 @@ class Shader_Vk VkDescriptorPool _descriptorPool = VK_NULL_HANDLE; std::vector _descriptorSets; uint32_t _currentSetIndex = 0; - uint32_t _maxFramesInFlight = 3; + + // Sets and params slots are reused in turn. The game's command buffers using them have no fence, + // like DeferredRelease this relies on presents limiting how far the GPU lags behind. + uint32_t _maxFramesInFlight = 8; // Common Resources VkBuffer _constantBuffer = VK_NULL_HANDLE; VkDeviceMemory _constantBufferMemory = VK_NULL_HANDLE; void* _mappedConstantBuffer = nullptr; + VkDeviceSize _constantStride = 0; // One params slot per set VkSampler _textureSampler = VK_NULL_HANDLE; // Intermediate Image (For shaders that output to a temp texture) @@ -74,7 +78,13 @@ class Shader_Vk void CreateDescriptorSets(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, std::vector& descriptorSets); - void CreateConstantBuffer(VkDeviceSize bufferSize); + static VkDeviceSize UniformStride(VkPhysicalDevice physicalDevice, VkDeviceSize size); + + // Takes the params size, makes a slot for each set + void CreateConstantBuffer(VkDeviceSize paramsSize); + + // Copies the params to the current set's slot + VkDescriptorBufferInfo WriteConstants(const void* data, VkDeviceSize size); void CreateSampler(VkFilter filter = VK_FILTER_LINEAR, VkSamplerAddressMode addressMode = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); diff --git a/OptiScaler/shaders/hud_copy/HudCopy_Vk.cpp b/OptiScaler/shaders/hud_copy/HudCopy_Vk.cpp index f1ba1b77..4948d8da 100644 --- a/OptiScaler/shaders/hud_copy/HudCopy_Vk.cpp +++ b/OptiScaler/shaders/hud_copy/HudCopy_Vk.cpp @@ -102,12 +102,9 @@ bool HudCopy_Vk::DispatchShader(VkCommandBuffer InCmdList, const VkImageInfo& In SetImageLayout(InCmdList, InHudlessInfo.Image, HudlessState, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, InHudlessInfo.SubresourceRange); - if (_mappedConstantBuffer) - memcpy(_mappedConstantBuffer, InParams, InParamsSize); - VkDescriptorSet descriptorSet = _descriptorSets[_currentSetIndex]; - VkDescriptorBufferInfo bufferInfo { _constantBuffer, 0, InParamsSize }; + const auto bufferInfo = WriteConstants(InParams, InParamsSize); VkDescriptorImageInfo hudlessInfo { _textureSampler, InHudlessInfo.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL }; VkDescriptorImageInfo presentInfo { _textureSampler, InPresentInfo.ImageView, diff --git a/OptiScaler/shaders/magnifier/Magnifier_Vk.cpp b/OptiScaler/shaders/magnifier/Magnifier_Vk.cpp index dee7b4b4..2c3b1cc2 100644 --- a/OptiScaler/shaders/magnifier/Magnifier_Vk.cpp +++ b/OptiScaler/shaders/magnifier/Magnifier_Vk.cpp @@ -77,12 +77,9 @@ bool Magnifier_Vk::Dispatch(VkCommandBuffer InCmdList, const VkImageInfo& InReso FilloutStruct((float) OutResourceInfo.Width, (float) OutResourceInfo.Height, constants); - if (_mappedConstantBuffer) - memcpy(_mappedConstantBuffer, &constants, sizeof(InternalMagnifierParams)); - VkDescriptorSet descriptorSet = _descriptorSets[_currentSetIndex]; - VkDescriptorBufferInfo bufferInfo { _constantBuffer, 0, sizeof(InternalMagnifierParams) }; + const auto bufferInfo = WriteConstants(&constants, sizeof(InternalMagnifierParams)); VkDescriptorImageInfo sourceInfo { _textureSampler, InResourceInfo.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL }; VkDescriptorImageInfo destInfo { VK_NULL_HANDLE, OutResourceInfo.ImageView, VK_IMAGE_LAYOUT_GENERAL }; diff --git a/OptiScaler/shaders/output_scaling/OS_Vk.cpp b/OptiScaler/shaders/output_scaling/OS_Vk.cpp index ada2569d..42317f56 100644 --- a/OptiScaler/shaders/output_scaling/OS_Vk.cpp +++ b/OptiScaler/shaders/output_scaling/OS_Vk.cpp @@ -131,20 +131,15 @@ bool OS_Vk::Dispatch(VkCommandBuffer InCmdList, const VkImageInfo& InResourceVie constants.destWidth = State::Instance().currentFeature->DisplayWidth(); constants.destHeight = State::Instance().currentFeature->DisplayHeight(); - if (_mappedConstantBuffer) - { - if (Config::Instance()->OutputScalingDownscaler.value_or_default() == Scaler::FSR1) - memcpy(_mappedConstantBuffer, &fsr1Constants, sizeof(UpscaleShaderConstants)); - else - memcpy(_mappedConstantBuffer, &constants, sizeof(Constants)); - } - // Advance Frame Index _currentSetIndex = (_currentSetIndex + 1) % _maxFramesInFlight; VkDescriptorSet currentSet = _descriptorSets[_currentSetIndex]; + const auto bufferInfo = Config::Instance()->OutputScalingDownscaler.value_or_default() == Scaler::FSR1 + ? WriteConstants(&fsr1Constants, sizeof(UpscaleShaderConstants)) + : WriteConstants(&constants, sizeof(Constants)); + // Build Descriptor Writes - VkDescriptorBufferInfo bufferInfo { _constantBuffer, 0, sizeof(Constants) }; VkDescriptorImageInfo sourceInfo { VK_NULL_HANDLE, InResourceView.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL }; VkDescriptorImageInfo destInfo { VK_NULL_HANDLE, OutResourceView.ImageView, VK_IMAGE_LAYOUT_GENERAL }; diff --git a/OptiScaler/shaders/rcas/RCAS_Vk.cpp b/OptiScaler/shaders/rcas/RCAS_Vk.cpp index ad011ab7..5472a749 100644 --- a/OptiScaler/shaders/rcas/RCAS_Vk.cpp +++ b/OptiScaler/shaders/rcas/RCAS_Vk.cpp @@ -4,6 +4,7 @@ #include "precompile/da_das_sharpen_Shader_Vk.h" #include "precompile/da_rcas_sharpen_Shader_Vk.h" #include +#include RCAS_Vk::RCAS_Vk(std::string InName, VkDevice InDevice, VkPhysicalDevice InPhysicalDevice) : Shader_Vk(InName, InDevice, InPhysicalDevice) @@ -68,10 +69,15 @@ RCAS_Vk::RCAS_Vk(std::string InName, VkDevice InDevice, VkPhysicalDevice InPhysi // Reuse base class definition to safely allocate descriptor sets Shader_Vk::CreateDescriptorSets(_descriptorSetLayoutDA, _descriptorPoolDA, _descriptorSetsDA); - Shader_Vk::CreateBufferResource(_device, _physicalDevice, &_constantBufferDA, &_constantBufferMemoryDA, - sizeof(InternalConstantsDA), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - vkMapMemory(_device, _constantBufferMemoryDA, 0, sizeof(InternalConstantsDA), 0, &_mappedConstantBufferDA); + _constantStrideDA = UniformStride(_physicalDevice, sizeof(InternalConstantsDA)); + const auto bufferSizeDA = _constantStrideDA * _maxFramesInFlight; + + if (Shader_Vk::CreateBufferResource(_device, _physicalDevice, &_constantBufferDA, &_constantBufferMemoryDA, + bufferSizeDA, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) + { + vkMapMemory(_device, _constantBufferMemoryDA, 0, bufferSizeDA, 0, &_mappedConstantBufferDA); + } // 3. Compile Pipelines std::vector shaderCode(rcas_spv, rcas_spv + sizeof(rcas_spv)); @@ -103,30 +109,38 @@ RCAS_Vk::RCAS_Vk(std::string InName, VkDevice InDevice, VkPhysicalDevice InPhysi RCAS_Vk::~RCAS_Vk() { - if (_pipelineDA != VK_NULL_HANDLE) - vkDestroyPipeline(_device, _pipelineDA, nullptr); - if (_pipelineDASDA != VK_NULL_HANDLE) - vkDestroyPipeline(_device, _pipelineDASDA, nullptr); - if (_descriptorPoolDA != VK_NULL_HANDLE) - vkDestroyDescriptorPool(_device, _descriptorPoolDA, nullptr); - if (_descriptorSetLayoutDA != VK_NULL_HANDLE) - vkDestroyDescriptorSetLayout(_device, _descriptorSetLayoutDA, nullptr); - if (_pipelineLayoutDA != VK_NULL_HANDLE) - vkDestroyPipelineLayout(_device, _pipelineLayoutDA, nullptr); - if (_constantBufferDA != VK_NULL_HANDLE) - vkDestroyBuffer(_device, _constantBufferDA, nullptr); - if (_constantBufferMemoryDA != VK_NULL_HANDLE) - vkFreeMemory(_device, _constantBufferMemoryDA, nullptr); + // Command buffers in flight can still reference these, like the base ones + DeferredRelease::Enqueue( + [device = _device, pipelineDA = _pipelineDA, pipelineDASDA = _pipelineDASDA, + descriptorPoolDA = _descriptorPoolDA, descriptorSetLayoutDA = _descriptorSetLayoutDA, + pipelineLayoutDA = _pipelineLayoutDA, constantBufferDA = _constantBufferDA, + constantBufferMemoryDA = _constantBufferMemoryDA]() + { + if (pipelineDA != VK_NULL_HANDLE) + vkDestroyPipeline(device, pipelineDA, nullptr); + if (pipelineDASDA != VK_NULL_HANDLE) + vkDestroyPipeline(device, pipelineDASDA, nullptr); + if (descriptorPoolDA != VK_NULL_HANDLE) + vkDestroyDescriptorPool(device, descriptorPoolDA, nullptr); + if (descriptorSetLayoutDA != VK_NULL_HANDLE) + vkDestroyDescriptorSetLayout(device, descriptorSetLayoutDA, nullptr); + if (pipelineLayoutDA != VK_NULL_HANDLE) + vkDestroyPipelineLayout(device, pipelineLayoutDA, nullptr); + if (constantBufferDA != VK_NULL_HANDLE) + vkDestroyBuffer(device, constantBufferDA, nullptr); + if (constantBufferMemoryDA != VK_NULL_HANDLE) + vkFreeMemory(device, constantBufferMemoryDA, nullptr); + }, + (uint64_t) _device); } -void RCAS_Vk::UpdateDescriptorSet(VkCommandBuffer cmdList, int setIndex, VkImageView inputView, VkImageView motionView, - VkImageView outputView) +void RCAS_Vk::UpdateDescriptorSet(VkDescriptorBufferInfo bufferInfo, int setIndex, VkImageView inputView, + VkImageView motionView, VkImageView outputView) { if (motionView == VK_NULL_HANDLE) motionView = inputView; VkDescriptorSet descriptorSet = _descriptorSets[setIndex]; - VkDescriptorBufferInfo bufferInfo { _constantBuffer, 0, sizeof(InternalConstants) }; VkDescriptorImageInfo sourceInfo { _textureSampler, inputView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL }; VkDescriptorImageInfo motionInfo { _textureSampler, motionView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL }; VkDescriptorImageInfo destInfo { VK_NULL_HANDLE, outputView, VK_IMAGE_LAYOUT_GENERAL }; @@ -145,13 +159,13 @@ void RCAS_Vk::UpdateDescriptorSet(VkCommandBuffer cmdList, int setIndex, VkImage vkUpdateDescriptorSets(_device, static_cast(writes.size()), writes.data(), 0, nullptr); } -void RCAS_Vk::UpdateDescriptorSetDA(VkDescriptorSet descriptorSet, VkBuffer constantBuffer, VkImageView inputView, - VkImageView motionView, VkImageView depthView, VkImageView outputView) +void RCAS_Vk::UpdateDescriptorSetDA(VkDescriptorSet descriptorSet, VkDescriptorBufferInfo bufferInfo, + VkImageView inputView, VkImageView motionView, VkImageView depthView, + VkImageView outputView) { if (motionView == VK_NULL_HANDLE) motionView = inputView; - VkDescriptorBufferInfo bufferInfo { constantBuffer, 0, sizeof(InternalConstantsDA) }; VkDescriptorImageInfo sourceInfo { _textureSampler, inputView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL }; VkDescriptorImageInfo motionInfo { _textureSampler, motionView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL }; VkDescriptorImageInfo depthInfo { _textureSampler, depthView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL }; @@ -182,12 +196,9 @@ bool RCAS_Vk::DispatchRCAS(VkCommandBuffer InCmdList, RcasConstants InConstants, constants.MotionHeight = InMotionVectorsInfo.Height; FillMotionConstants(constants, InConstants); - if (_mappedConstantBuffer) - memcpy(_mappedConstantBuffer, &constants, sizeof(InternalConstants)); - _currentSetIndex = (_currentSetIndex + 1) % _maxFramesInFlight; - UpdateDescriptorSet(InCmdList, _currentSetIndex, InResourceInfo.ImageView, InMotionVectorsInfo.ImageView, - OutResourceInfo.ImageView); + UpdateDescriptorSet(WriteConstants(&constants, sizeof(InternalConstants)), _currentSetIndex, + InResourceInfo.ImageView, InMotionVectorsInfo.ImageView, OutResourceInfo.ImageView); vkCmdBindPipeline(InCmdList, VK_PIPELINE_BIND_POINT_COMPUTE, _pipeline); vkCmdBindDescriptorSets(InCmdList, VK_PIPELINE_BIND_POINT_COMPUTE, _pipelineLayout, 0, 1, @@ -216,11 +227,15 @@ bool RCAS_Vk::DispatchDepthAdaptive(VkCommandBuffer InCmdList, RcasConstants InC constants.DepthHeight = InDepthInfo->Height; FillMotionConstants(constants, InConstants); - if (_mappedConstantBufferDA) - memcpy(_mappedConstantBufferDA, &constants, sizeof(InternalConstantsDA)); - _currentSetIndex = (_currentSetIndex + 1) % _maxFramesInFlight; - UpdateDescriptorSetDA(_descriptorSetsDA[_currentSetIndex], _constantBufferDA, InResourceInfo.ImageView, + + const VkDescriptorBufferInfo bufferInfo { _constantBufferDA, _constantStrideDA * _currentSetIndex, + sizeof(InternalConstantsDA) }; + + if (_mappedConstantBufferDA) + memcpy((uint8_t*) _mappedConstantBufferDA + bufferInfo.offset, &constants, sizeof(InternalConstantsDA)); + + UpdateDescriptorSetDA(_descriptorSetsDA[_currentSetIndex], bufferInfo, InResourceInfo.ImageView, InMotionVectorsInfo.ImageView, InDepthInfo->ImageView, OutResourceInfo.ImageView); vkCmdBindPipeline(InCmdList, VK_PIPELINE_BIND_POINT_COMPUTE, targetPipeline); diff --git a/OptiScaler/shaders/rcas/RCAS_Vk.h b/OptiScaler/shaders/rcas/RCAS_Vk.h index 394d3c57..2f68cb17 100644 --- a/OptiScaler/shaders/rcas/RCAS_Vk.h +++ b/OptiScaler/shaders/rcas/RCAS_Vk.h @@ -9,6 +9,7 @@ class RCAS_Vk : public Shader_Vk, public RCAS_Common VkBuffer _constantBufferDA = VK_NULL_HANDLE; VkDeviceMemory _constantBufferMemoryDA = VK_NULL_HANDLE; void* _mappedConstantBufferDA = nullptr; + VkDeviceSize _constantStrideDA = 0; VkDescriptorPool _descriptorPoolDA = VK_NULL_HANDLE; std::vector _descriptorSetsDA; @@ -19,9 +20,9 @@ class RCAS_Vk : public Shader_Vk, public RCAS_Common VkPipeline _pipelineDA = VK_NULL_HANDLE; VkPipeline _pipelineDASDA = VK_NULL_HANDLE; - void UpdateDescriptorSet(VkCommandBuffer cmdList, int setIndex, VkImageView inputView, VkImageView motionView, - VkImageView outputView); - void UpdateDescriptorSetDA(VkDescriptorSet descriptorSet, VkBuffer constantBuffer, VkImageView inputView, + void UpdateDescriptorSet(VkDescriptorBufferInfo bufferInfo, int setIndex, VkImageView inputView, + VkImageView motionView, VkImageView outputView); + void UpdateDescriptorSetDA(VkDescriptorSet descriptorSet, VkDescriptorBufferInfo bufferInfo, VkImageView inputView, VkImageView motionView, VkImageView depthView, VkImageView outputView); bool DispatchRCAS(VkCommandBuffer InCmdList, RcasConstants InConstants, const VkImageInfo& InResourceInfo,