mirror of
https://github.com/scp-fs2open/fs2open.github.com.git
synced 2026-11-10 04:31:34 -10:00
* Shadow overhaul round 2: PCSS, dynamic cascades, cockpit/instanced shadows Squashed snapshot of lafiel/shadow_overhaul_2's continuation work (d3922aa87..010f9d2d9), which has no separate upstream PR of its own. * Add Vulkan rendering backend Squashed snapshot of the Vulkan backend as vendored into this branch (ce2d1e85f..6ce539463, authored by Mara van der Laan with build/CI fixes by Taylor Richards). This work has its own upstream PR #7553 (notimaginative:vulkan-pr-new) and is not otherwise original to true-hdr. * Add true HDR output, RT shadows, and PCSS shadows for Vulkan Squashed snapshot of true-hdr's own integration work: true HDR framebuffer output, wiring the shadow overhaul into the Vulkan backend (raytraced + cascaded shadow maps), logging refactors, log filter UI, and CI/build fixes. * refactor: update Vulkan logging calls to use `nprintf` for scoped logging * fix: correct shadow cascade count in Vulkan logging calls * fix: fall back to PATH-resolved ccache when CCACHE_PATH is stale CI hardcodes /usr/local/bin/ccache, but macOS runners on Apple Silicon hosts install Homebrew (and ccache) under /opt/homebrew instead, causing all four Mac configs to fail with "No such file or directory". * Fix vulkan texture readback to correctly handle transparent pipelines * Put the pixel swizzles into a util file * OOB safety check * Fix fog handling * Fix MSAA in Vulkan * fix: enable SMAA for vulkan * adapt the post-processing AA shaders to hdr * fix clang-tidy warnings: concatenate nested namespaces, static methods pixel_swizzle.{h,cpp}: collapse `namespace graphics { namespace util {` into `namespace graphics::util {` (modernize-concat-nested-namespaces). VulkanState.h/VulkanDraw.h: getClearColor()/setClearColor() only touch gr_screen and other globals, no instance state, so make them static (readability-convert-member-functions-to-static) and drop the top-level const on getClearColor()'s return type (readability-const-return-type). * fix clang-tidy warning * Extend raytraced shadows to all directional lights RT shadows previously only shadowed the first directional light in the scene, even though multi-sun missions push more than one directional light into the engine. The TLAS raytraced shadows query against is already light-agnostic, so this extends both the deferred lighting pass and the forward MODEL shader to shadow every directional light (capped by a new Max Raytraced Shadow Lights option, configurable via the in-game Options menu or the Lab's Scene rendering options). Cascaded shadow maps are untouched: they're built for a single light only, so the deferred pass still limits itself to one shadowed directional light whenever CSM (not raytracing) is the active method. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_016DA6JHJ3twz2oHGQcZ1Udc * refactor: improve shader flag handling and render target finalization in Vulkan backend - Consolidate shader flag setup logic in VulkanPostProcessingLighting to simplify configuration. - Fix dead field usage in VulkanDraw by ensuring correct image view selection for environment maps. - Add mip chain regeneration in VulkanRenderer::endRenderTarget to ensure correct mip levels for cubemaps. * fix: ensure correct mip chain initialization in cubemap rendering - Add mip chain generation to VulkanDraw for cubemaps with multiple mip levels. - Fix potential issue with uninitialized mip levels above level 0 in deferred-f.sdr sampling paths. * fix: don't crash on startup when environment locale is unavailable std::locale("") pulls in the process's environment locale categories (LC_CTYPE, LC_MONETARY, LC_PAPER, etc.), and throws std::runtime_error if any of them names a locale not installed on the host (e.g. mismatched regional-format overrides). Since SCP_default_locale is constructed during static initialization, before main() and before any of our own exception handling exists, an uncaught throw here aborted the whole process before the game even started. Fall back to the classic "C" locale instead, which is sufficient since this locale is only ever used for ASCII case-folding (SCP_toupper/tolower/isdigit). Co-Authored-By: Claude Sonnet 5 <[email protected]> * `feat: add raytraced shadows for local lights and optimize TLAS management` * Make the Commandline authoritative for -res and -vulkan / -opengl * address BMagnu's comments on the original PR * update prebuilt version hash to 62c89ef6 * refactor: standardize graphics API handling and document Vulkan limitations in qtFRED - Updated `AboutDialogModel.cpp` to use `GraphicsAPI` enum for better clarity. - Ensured qtFRED falls back to OpenGL when Vulkan is requested. - Added detailed documentation in `qtfred/README.md` regarding Vulkan backend limitations and requirements. * chore: include cmdline library in main and mission management modules * docs: add known issue for blank render viewport under Wayland in README.md * fix CI issues * chore: add `GR_DEBUG_SCOPE` markers across Vulkan post-processing and rendering paths for improved debugging * feat: improve Vulkan HDR pipeline with separate encode paths for SDR and HDR10 - Added an HDR10-specific output encode pass in `VulkanRenderer` and `VulkanPostProcessor` that applies PQ/BT.2020 transfer. - Introduced an optimized SDR fallback path with direct blit support for devices that can skip shader draws. - Updated `m_sceneLdrCompressed` to provide [0,1]-clamped proxies for HDR edge detection. - Refactored `copyImageToImage` and added `blitImageToImage` to allow format conversions and optimized transfers. - Replaced `hdr_mode` with explicit HDR10 flags and data structures for clearer state handling. * refactor: encapsulate SMAA processing and refactor VulkanPostProcessor - Moved SMAA-specific logic into `VulkanSMAA` class for better separation of concerns. - Simplified `initSMAA`, `shutdownSMAA`, and `executeSMAA` logic by leveraging `VulkanLDR` and `PostProcessContext` abstractions. - Improved initialization and cleanup code with clearer resource lifecycle management. - Updated debug markers and messages to reference `VulkanSMAA`. - Enhanced flexibility of fullscreen triangle rendering API with additional parameters (`sampleCount`, `bindGlobalSet`). * Update Vulkan porting credits in AboutDialogModel * fix CI issues again * fix: correct Y-flip in viewport setup for Vulkan light volumes - Adjusted viewport height to negative value to account for G-buffer render pass's negative Y-axis convention. - Ensured proper alignment of point and tube light volumes with actual light positions. * feat: add user-adjustable gamma correction to SDR and HDR10 output paths - Added gamma correction to HDR10 path, applying user settings before PQ/BT.2020 encode. - Replaced the SDR blit-only path with an encode pass that applies gamma correction, ensuring consistent behavior across devices. - Refactored VulkanPostProcessor and associated shaders to support gamma slider adjustments for both SDR and HDR output. * fix: ensure proper uniform and cull mode setup for Vulkan sphere rendering - Added uniform buffer setup and default material uniforms in `vulkan_draw_sphere`. - Disabled face culling in material definition for sphere rendering to align behavior with OpenGL. * Ensure memory flushes after UBO updates and add explicit pipeline barrier for MoltenVK compatibility. * fix: add clear pass for SMAA edge detection to prevent persistent artifacts * feat: add Vulkan debug-utils messenger, opt-in sync validation, frame diagnostics Groundwork for the renderer-review fix series (.agents/plans/ vulkan-renderer-review-fixes.md, Phase 0): - Register a VK_EXT_debug_utils messenger (preferred) instead of only the deprecated VK_EXT_debug_report callback, which is kept as a fallback for loaders without debug-utils. The messenger config is also chained into instance creation so vkCreateInstance-time messages are captured. Validation errors/warnings now go to the main log via mprintf. - New -gr_sync_validation cmdline flag (implies -gr_debug): chains VkValidationFeaturesEXT with synchronization validation into instance creation when VK_LAYER_KHRONOS_validation is available. This is the regression net for the synchronization fixes in the following commits. - Frame stats now report descriptor sets/writes allocated per frame and the total pipeline count (descriptor-manager counters; DescriptorWriter::flush moved out-of-line to report into the manager). Co-Authored-By: Claude Fable 5 <[email protected]> * refactor: unify Vulkan render-pass begins, clamp in-pass clears, add per-frame UBO ring Phase 1 of the renderer-review fix series: shared helpers that the correctness fixes build on. - New VulkanRenderer::beginTrackedRenderPass(PassBeginDesc): every render-pass begin on the frame command buffer now records vkCmdBeginRenderPass and updates the state tracker (pass, color attachment count, sample count, render area, viewport) in one place. Converted: setupFrame, beginSceneRendering (both branches), resumeSceneRendering, endSceneRendering, beginRenderTarget (viewport kept for gr_set_viewport), resumeSwapChainPass, plus new resumeScenePassAfterCopy() shared by copyEffectTexture/copySceneDepthForParticles and rebeginSwapChainPassAfterReadback() shared by both readbackFramebuffer exits (~200 lines of duplicated begin/clear/viewport blocks removed). - The state tracker records the active render area; all four vkCmdClearAttachments sites clamp their rects against it and skip empty results. Previously gr_screen-sized clear rects could exceed a smaller off-screen render target's render area, which is invalid API usage. - New PerFrameUboRing utility (VulkanPerFrameUbo.h/.cpp): a persistently mapped uniform buffer with one slot region per frame in flight and a self-flushing alloc(). Used by the next commit to fix the cross-frame UBO races. Deliberate behavior deltas (all safe-direction): the helper always sets colorAttachmentCount/sampleCount (some sites previously inherited stale values), and resumeSwapChainPass/resumeSceneRendering now also reset the standard flipped viewport instead of leaving the previous one. Co-Authored-By: Claude Fable 5 <[email protected]> * fix: eliminate Vulkan cross-frame UBO/buffer races, make gr_sync honest Phase 2 of the renderer-review fix series: with two frames in flight, several host-visible resources were rewritten by the CPU while the previous frame's GPU work could still be reading them. - The post-processing scratch UBO is now a PerFrameUboRing (per-frame-in- flight slot regions, persistently mapped, self-flushing alloc). All the per-pass map/unmap/cursor bookkeeping in bloom/LDR/fog/SMAA is deleted; the cursor resets exactly once per frame via the new VulkanPostProcessor::beginFrame() hook in setupFrame. This also fixes two latent bugs: (a) fog consumed scratch slots mid-scene and bloom's later same-frame cursor reset overwrote them before submission whenever fog+bloom were both active; (b) volumetric_fog_data (288 bytes) overflowed the 256-byte slots - the memcpy spilled into the neighboring slot and the shader's bound range ended before the aspect/fov/noise fields. Slots are now 512 bytes (static_assert at the fog call site) and the per-frame budget is 32 slots. - The dedicated tonemap, output-encode, and MSAA-resolve UBOs (each a single instance rewritten per frame, i.e. racy; the MSAA one also never flushed) are deleted entirely - those passes build their structs on the stack and allocate from the scratch ring. - Static-buffer rewrites orphan instead of racing: getVkBuffer() stamps a last-used frame number, and a full-content updateBufferData() on a Static buffer used within the last MAX_FRAMES_IN_FLIGHT frames defers the old VkBuffer to the deletion queue and writes a fresh one. Offset writes (GPU-heap appends to fresh regions) and PersistentMapping buffers (the engine holds their mapped pointer and syncs via gr_sync) are exempt. - gr_sync_wait now honors its contract: VulkanRenderFrame::waitForFinish takes a timeout and reports expiry without consuming the fence; VulkanRenderer::waitForFrame returns false for fences taken during the still-recording frame (previously it waited on a stale or idle slot and reported success) and resolves the frame->slot mapping correctly. This makes UniformBufferManager's segment-fence throttling actually protective on Vulkan for the first time. Co-Authored-By: Claude Fable 5 <[email protected]> * Refactor framebuffer and target lifecycle: centralized creation/resizing logic, improved resource management across Vulkan post-processing subsystems. * Improve Vulkan cross-frame sync with explicit access masks and validation updates - Unified Vulkan validation flag handling in setup, separating engine debug output from synchronization validation. - Specified access masks and stage flags to address cross-frame WRITE_AFTER_WRITE vulnerabilities, notably in G-buffer, post-processing, and MSAA resolve paths. - Adjusted subpass dependencies and image layout transitions to prevent read-after-write and write-after-write hazards, detected using `-gr_sync_validation`. - Fixed uniform buffer and barrier transitions to ensure proper ordering in render passes across frames. * Refactor Vulkan render-pass dependencies and sync stages for clarity and future testing - Clarified dependency logic for cross-pass and cross-frame synchronization, ensuring explicit stage and access flag comments match observed behavior. - Adjusted subpass dependencies to decouple render-pass compatibility definitions from dependency assumptions. - Highlighted MoltenVK-specific issues and retained workarounds with notes for re-testing on macOS hardware. - Updated synchronization barriers and validation notes to address historical inconsistencies across platforms. * Remove transfer queue support; consolidate all operations into the graphics queue - Removed transfer queue handling, simplifying buffer and queue logic to use the graphics queue for all transfer operations. - Updated buffer sharing modes and removed related code paths and parameters for transfer queue families. - Introduced exclusive buffer access, noting async transfer and queue ownership transfers are future work. - Limited enabled device features to only those actively used by the renderer, reducing unnecessary feature requests (e.g., robustBufferAccess). * Refactor frame advancement and descriptor management in VulkanRenderer - Removed `endFrame()` from `VulkanDescriptorManager`, replacing it with `setCurrentFrame(frameIndex)` for explicit frame synchronization. - Centralized frame index advancement within `VulkanRenderer` to ensure consistency across components. - Invalidated cached descriptor set bindings at render-pass boundaries to handle raw recorder staleness correctly. - Optimized pipeline descriptor rebind logic by removing redundant clears during pipeline changes. * Refactor `PipelineConfig::hash` and Global descriptor set management for improved hashing and memoization efficiency - Replaced inefficient shift-based hashing in `PipelineConfig::hash` with a robust `hashCombine` strategy to minimize bucket collisions. - Introduced `maskBits` helper to streamline bitmask creation for boolean fields. - Implemented memoization for Global (Set 0) descriptor sets, reducing redundant rebuilds across frames and improving performance. - Added dirty state tracking (`m_globalSetDirty`) and invalidation logic for Global set updates following relevant input changes (e.g., TLAS or UBO modifications). * Refactor Vulkan post-processing output logic: extracted shared `encodeToSwapChainPass` method to streamline HDR and SDR output paths. * Optimize Vulkan descriptor set management with per-frame memoization - Added memoization for Material (Set 1) and PerDraw (Set 2) descriptor sets to reuse cached sets across frames if inputs remain unchanged. - Implemented precise input tracking for Material and PerDraw descriptor sets to detect and rebuild only when necessary. - Reduced redundant Vulkan descriptor allocations and writes, improving performance on repeated or batched draw calls. * Fix Vulkan access masks for G-buffer and scene pass transitions - Added `eColorAttachmentRead` to access masks in multiple barriers to ensure proper synchronization for load operations (e.g., `loadOp=eLoad`) across render passes. - Prevented `READ_AFTER_WRITE` synchronization validation issues in deferred and multi-pass rendering scenarios. - Updated comments to clarify the reasoning behind the access mask changes and load dependencies. * Refactor Vulkan resource management and indexed draw logic - Consolidated destruction queue methods in `VulkanDeletionQueue` using a shared `queueHandle` template to reduce redundancy. - Introduced `ModelDrawParams` structure and `computeModelDrawParams` function to unify indexed draw parameters for models and shadows. - Simplified draw logic by eliminating repeated calculation of indexed draw parameters and improving code reuse. * Add `releaseAnimationSlotRef` for ref-count handling of shared animation texture arrays - Introduced `releaseAnimationSlotRef` to manage reference counting for shared animation texture-array slots, preventing premature destruction of shared resources. - Updated `flushTextures` and related methods to integrate `releaseAnimationSlotRef` for shared slot cleanup. - Refactored staging buffer creation into `createStagingBuffer` for 3D texture uploads and shared path consistency. - Enhanced texture upload logic with improved tracking and logging for re-upload cases, aiding preloading gap analysis. - Added instrumentation for on-demand mid-frame texture uploads in `FrameStats`. * Refactor Vulkan resource and texture management, extend debug logging - Updated smart pointer usage for consistency across Vulkan resource managers (`std::make_unique`). - Removed redundant `cubeImageView` member and related cleanup logic; unified sampling view management. - Added per-instance debug log counters (avoiding static state) for Vulkan texture uploads and bindings, improving visibility during initialization and run-time. - Optimized `VulkanRenderer` property/feature getters by caching physical device properties and features during device creation. - Improved memory region flushing logic for out-of-date offsets, aligning with Vulkan Memory Allocator behavior. - Refactored render pass state tracking to reapply dynamic state reliably after mid-frame render passes. - Enhanced validation and error handling for mismatched update texture formats. * fix CI build warning * Fix on-demand YUV texture locking and set alpha uniform for movie rendering in Vulkan - Corrected bitmap lock type from `BMP_TEX_OTHER` to `BMP_AABITMAP` for YUV textures during on-demand loading. - Updated movie rendering to bind alpha from the `MovieData` UBO (set 2, binding 4) for Vulkan, aligning behavior with OpenGL implementation. * revert inadvertent changes introduced by a squash commit * address ci issues * remove wip stuff from code comments that make no sense to people who aren't me * Remove unused LD_LIBRARY_PATH export and fix shader shadow map sampling. * Refactor batched rendering uniform setup in Vulkan - Removed unused fields from `genericData` uniform block, simplifying shader definitions. - Updated Vulkan material uniform handling to align with OpenGL's batched rendering logic. - Introduced `batched_data` struct for streamlined UBO updates, improving maintainability and clarity. * Add `-hdr` command-line option for HDR nits configuration - Introduced `-hdr` parameter to set paper white and peak luminance in nits, overriding in-game HDR settings. - Added input validation with error feedback for incorrect format. * Remove unused `MODEL_SDR_FLAG_SHADOW_MAP` macro from shader flags * clean up unrelated changes * Invalidate Vulkan state tracker bindings after external command buffer modifications - Added `invalidateExternalBindings()` to `VulkanStateTracker` to handle stale pipelines, descriptors, and dynamic states caused by external Vulkan commands (e.g., ImGui renders mid-pass). - Updated ImGui rendering flow to call `invalidateExternalBindings()` post-draw, ensuring consistent pipeline state for subsequent engine renders. - Adjusted image usage flags to account for `eTransferSrc` in texture readbacks. - Fixed barrier `dstAccessMask` and pipeline stage flags to ensure proper synchronization for image transitions. * Add a few more generically useful lines to the log * Simplify Qt deployment logic and improve handling for system-installed Qt on Linux * add cmdline headers to make qtFred compile * use VK_KHR_synchronization2 for sync and barrier purposes * Simplify and clean up Qt deployment logic in CMake for qtfred * update get_bitmap_from_texture to match the new API * Enhance `-hdr` command-line option to force HDR output and support optional nits configuration with improved input validation and overrides. * Improve Vulkan robustness, add device feature checks, and refine memory/logging. - Added depth clamping support gated by device feature checks, with fallback where unsupported. - Improved deferred lighting UBO overflow handling with user-accessible warnings and buffer size adjustments. - Enhanced Vulkan logging for validation, allocation, and debugging: - Automatic logging for descriptor pool exhaustion/fragmentation. - Vertex format and resource destruction checks. - Notifications for generic layout transitions and volumetric texture uploads. - Consolidated shader logic to ensure Vulkan and OpenGL parity. * Remove HDR10 encode shader and consolidate gamma correction logic for SDR and HDR10. Replace `Verify` assertions with `Assert` * Add braces to conditional in object lighting logic for clarity * Refine Vulkan memory allocation checks with `Verification` for improved error handling and messaging. * Refine VulkanBuffer resize logic to preserve contents with CPU-side copy and add safeguards for non-coherent memory scenarios. * Add detailed comments explaining descriptor array capacity constants in VulkanDescriptorManager * Gate shadow support on depth clamp feature availability and clarify its necessity with improved comments. --------- Co-authored-by: BMagnu <[email protected]> Co-authored-by: Mara van der Laan <[email protected]> Co-authored-by: Claude <[email protected]>
877 lines
34 KiB
C++
877 lines
34 KiB
C++
#include "VulkanPostProcessing.h"
|
|
|
|
#include <array>
|
|
|
|
#include "cmdline/cmdline.h"
|
|
#include "gr_vulkan.h"
|
|
#include "VulkanRenderer.h"
|
|
#include "VulkanBuffer.h"
|
|
#include "VulkanPipeline.h"
|
|
#include "VulkanState.h"
|
|
#include "VulkanDescriptorManager.h"
|
|
#include "graphics/util/uniform_structs.h"
|
|
#include "graphics/post_processing.h"
|
|
#include "graphics/grinternal.h"
|
|
#include "graphics/shadows.h"
|
|
#include "graphics/2d.h"
|
|
#include "lighting/lighting_profiles.h"
|
|
#include "lighting/lighting.h"
|
|
#include "math/vecmat.h"
|
|
#include "nebula/neb.h"
|
|
#include "nebula/volumetrics.h"
|
|
#include "mission/missionparse.h"
|
|
|
|
extern float Sun_spot;
|
|
extern int Game_subspace_effect;
|
|
extern SCP_vector<light> Lights;
|
|
extern int Num_lights;
|
|
|
|
|
|
namespace graphics::vulkan {
|
|
|
|
// Global post-processor pointer
|
|
static VulkanPostProcessor* g_postProcessor = nullptr;
|
|
|
|
VulkanPostProcessor* getPostProcessor()
|
|
{
|
|
return g_postProcessor;
|
|
}
|
|
|
|
void setPostProcessor(VulkanPostProcessor* pp)
|
|
{
|
|
g_postProcessor = pp;
|
|
}
|
|
|
|
bool VulkanPostProcessor::init(vk::Device device, vk::PhysicalDevice physDevice,
|
|
VulkanMemoryManager* memMgr, vk::Extent2D extent,
|
|
vk::Format depthFormat, bool hdrActive)
|
|
{
|
|
if (m_initialized) {
|
|
return true;
|
|
}
|
|
|
|
m_ctx.device = device;
|
|
m_ctx.memoryManager = memMgr;
|
|
m_ctx.sceneExtent = extent;
|
|
m_ctx.depthFormat = depthFormat;
|
|
m_ctx.hdrActive = hdrActive;
|
|
// In HDR the tonemapped scene must be able to exceed paper white, so use fp16.
|
|
m_ctx.ldrFormat = hdrActive ? HDR_COLOR_FORMAT : LDR_COLOR_FORMAT;
|
|
|
|
// Verify RGBA16F support for color attachment + sampling
|
|
{
|
|
vk::FormatProperties props = physDevice.getFormatProperties(HDR_COLOR_FORMAT);
|
|
if (!(props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eColorAttachment) ||
|
|
!(props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage)) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: RGBA16F not supported for color attachment + sampling!\n"));
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Create the extent-sized scene targets (color, depth, effect, depth copy)
|
|
if (!createSceneTargets(extent)) {
|
|
shutdown();
|
|
return false;
|
|
}
|
|
|
|
// Create HDR scene render pass
|
|
// Attachment 0: Color (RGBA16F)
|
|
// loadOp=eClear: clear to black each frame
|
|
// finalLayout=eShaderReadOnlyOptimal: ready for post-processing sampling
|
|
// Attachment 1: Depth
|
|
// loadOp=eClear: clear to far plane
|
|
// finalLayout=eDepthStencilAttachmentOptimal
|
|
{
|
|
std::array<vk::AttachmentDescription, 2> attachments;
|
|
|
|
// Color
|
|
attachments[0].format = HDR_COLOR_FORMAT;
|
|
attachments[0].samples = vk::SampleCountFlagBits::e1;
|
|
attachments[0].loadOp = vk::AttachmentLoadOp::eClear;
|
|
attachments[0].storeOp = vk::AttachmentStoreOp::eStore;
|
|
attachments[0].stencilLoadOp = vk::AttachmentLoadOp::eDontCare;
|
|
attachments[0].stencilStoreOp = vk::AttachmentStoreOp::eDontCare;
|
|
attachments[0].initialLayout = vk::ImageLayout::eUndefined;
|
|
attachments[0].finalLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
|
|
|
|
// Depth — storeOp=eStore required for:
|
|
// 1. copy_effect_texture mid-scene interruption (depth must survive render pass end/resume)
|
|
// 2. lightshafts pass (samples scene depth after render pass ends)
|
|
attachments[1].format = depthFormat;
|
|
attachments[1].samples = vk::SampleCountFlagBits::e1;
|
|
attachments[1].loadOp = vk::AttachmentLoadOp::eClear;
|
|
attachments[1].storeOp = vk::AttachmentStoreOp::eStore;
|
|
attachments[1].stencilLoadOp = vk::AttachmentLoadOp::eClear;
|
|
attachments[1].stencilStoreOp = vk::AttachmentStoreOp::eStore;
|
|
attachments[1].initialLayout = vk::ImageLayout::eUndefined;
|
|
attachments[1].finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
|
|
|
|
vk::AttachmentReference colorRef;
|
|
colorRef.attachment = 0;
|
|
colorRef.layout = vk::ImageLayout::eColorAttachmentOptimal;
|
|
|
|
vk::AttachmentReference depthRef;
|
|
depthRef.attachment = 1;
|
|
depthRef.layout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
|
|
|
|
vk::SubpassDescription subpass;
|
|
subpass.pipelineBindPoint = vk::PipelineBindPoint::eGraphics;
|
|
subpass.colorAttachmentCount = 1;
|
|
subpass.pColorAttachments = &colorRef;
|
|
subpass.pDepthStencilAttachment = &depthRef;
|
|
|
|
// Dependency: external → subpass 0.
|
|
// Note: render-pass compatibility (sharing m_sceneFramebuffer between this
|
|
// pass and m_sceneRenderPassLoad, and binding pipelines across both) is
|
|
// defined only by attachment formats/samples and subpass structure --
|
|
// dependencies are NOT part of it. So each pass may carry the dependency it
|
|
// actually needs; they happen to be identical here only because both begin
|
|
// a frame's use of the same shared scene targets.
|
|
vk::SubpassDependency dependency;
|
|
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
|
|
dependency.dstSubpass = 0;
|
|
// srcAccessMask must make the PREVIOUS frame's writes to the (single-
|
|
// instance, shared-across-frames) scene color + depth available before
|
|
// this frame clears/loads them again -- otherwise frame N+1's
|
|
// vkCmdBeginRenderPass races frame N's color storeOp / depth writes
|
|
// (cross-frame WRITE_AFTER_WRITE, flagged by -gr_sync_validation). Also
|
|
// covers the prior frame's post-processing sample (eShaderRead) and
|
|
// copy_effect_texture transfer.
|
|
dependency.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput
|
|
| vk::PipelineStageFlagBits::eEarlyFragmentTests
|
|
| vk::PipelineStageFlagBits::eLateFragmentTests
|
|
| vk::PipelineStageFlagBits::eFragmentShader
|
|
| vk::PipelineStageFlagBits::eTransfer;
|
|
dependency.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput
|
|
| vk::PipelineStageFlagBits::eEarlyFragmentTests;
|
|
dependency.srcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite
|
|
| vk::AccessFlagBits::eDepthStencilAttachmentWrite
|
|
| vk::AccessFlagBits::eShaderRead
|
|
| vk::AccessFlagBits::eTransferRead;
|
|
dependency.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite
|
|
| vk::AccessFlagBits::eDepthStencilAttachmentWrite
|
|
| vk::AccessFlagBits::eDepthStencilAttachmentRead;
|
|
|
|
vk::RenderPassCreateInfo rpInfo;
|
|
rpInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
|
|
rpInfo.pAttachments = attachments.data();
|
|
rpInfo.subpassCount = 1;
|
|
rpInfo.pSubpasses = &subpass;
|
|
rpInfo.dependencyCount = 1;
|
|
rpInfo.pDependencies = &dependency;
|
|
|
|
try {
|
|
m_sceneRenderPass = m_ctx.device.createRenderPass(rpInfo);
|
|
} catch (const vk::SystemError& e) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Failed to create scene render pass: %s\n", e.what()));
|
|
shutdown();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Create scene render pass with loadOp=eLoad (for resuming after copy_effect_texture)
|
|
// Compatible with m_sceneRenderPass (same formats/samples) so shares the same framebuffer
|
|
{
|
|
std::array<vk::AttachmentDescription, 2> attachments;
|
|
|
|
// Color — load existing content, keep final layout for post-processing
|
|
attachments[0].format = HDR_COLOR_FORMAT;
|
|
attachments[0].samples = vk::SampleCountFlagBits::e1;
|
|
attachments[0].loadOp = vk::AttachmentLoadOp::eLoad;
|
|
attachments[0].storeOp = vk::AttachmentStoreOp::eStore;
|
|
attachments[0].stencilLoadOp = vk::AttachmentLoadOp::eDontCare;
|
|
attachments[0].stencilStoreOp = vk::AttachmentStoreOp::eDontCare;
|
|
attachments[0].initialLayout = vk::ImageLayout::eColorAttachmentOptimal;
|
|
attachments[0].finalLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
|
|
|
|
// Depth — load existing content
|
|
attachments[1].format = depthFormat;
|
|
attachments[1].samples = vk::SampleCountFlagBits::e1;
|
|
attachments[1].loadOp = vk::AttachmentLoadOp::eLoad;
|
|
attachments[1].storeOp = vk::AttachmentStoreOp::eStore;
|
|
attachments[1].stencilLoadOp = vk::AttachmentLoadOp::eLoad;
|
|
attachments[1].stencilStoreOp = vk::AttachmentStoreOp::eStore;
|
|
attachments[1].initialLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
|
|
attachments[1].finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
|
|
|
|
vk::AttachmentReference colorRef;
|
|
colorRef.attachment = 0;
|
|
colorRef.layout = vk::ImageLayout::eColorAttachmentOptimal;
|
|
|
|
vk::AttachmentReference depthRef;
|
|
depthRef.attachment = 1;
|
|
depthRef.layout = vk::ImageLayout::eDepthStencilAttachmentOptimal;
|
|
|
|
vk::SubpassDescription subpass;
|
|
subpass.pipelineBindPoint = vk::PipelineBindPoint::eGraphics;
|
|
subpass.colorAttachmentCount = 1;
|
|
subpass.pColorAttachments = &colorRef;
|
|
subpass.pDepthStencilAttachment = &depthRef;
|
|
|
|
// Kept identical to m_sceneRenderPass's dependency because both passes begin
|
|
// a frame's use of the same shared scene targets and need the same
|
|
// cross-frame ordering -- NOT because compatibility requires it (it does
|
|
// not; compatibility ignores dependencies).
|
|
vk::SubpassDependency dependency;
|
|
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
|
|
dependency.dstSubpass = 0;
|
|
// srcAccessMask must make the PREVIOUS frame's writes to the (single-
|
|
// instance, shared-across-frames) scene color + depth available before
|
|
// this frame clears/loads them again -- otherwise frame N+1's
|
|
// vkCmdBeginRenderPass races frame N's color storeOp / depth writes
|
|
// (cross-frame WRITE_AFTER_WRITE, flagged by -gr_sync_validation). Also
|
|
// covers the prior frame's post-processing sample (eShaderRead) and
|
|
// copy_effect_texture transfer.
|
|
dependency.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput
|
|
| vk::PipelineStageFlagBits::eEarlyFragmentTests
|
|
| vk::PipelineStageFlagBits::eLateFragmentTests
|
|
| vk::PipelineStageFlagBits::eFragmentShader
|
|
| vk::PipelineStageFlagBits::eTransfer;
|
|
dependency.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput
|
|
| vk::PipelineStageFlagBits::eEarlyFragmentTests;
|
|
dependency.srcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite
|
|
| vk::AccessFlagBits::eDepthStencilAttachmentWrite
|
|
| vk::AccessFlagBits::eShaderRead
|
|
| vk::AccessFlagBits::eTransferRead;
|
|
dependency.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite
|
|
| vk::AccessFlagBits::eDepthStencilAttachmentWrite
|
|
| vk::AccessFlagBits::eDepthStencilAttachmentRead;
|
|
|
|
vk::RenderPassCreateInfo rpInfo;
|
|
rpInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
|
|
rpInfo.pAttachments = attachments.data();
|
|
rpInfo.subpassCount = 1;
|
|
rpInfo.pSubpasses = &subpass;
|
|
rpInfo.dependencyCount = 1;
|
|
rpInfo.pDependencies = &dependency;
|
|
|
|
try {
|
|
m_sceneRenderPassLoad = m_ctx.device.createRenderPass(rpInfo);
|
|
} catch (const vk::SystemError& e) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Failed to create scene load render pass: %s\n", e.what()));
|
|
shutdown();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Create scene framebuffer
|
|
if (!createSceneFramebuffer()) {
|
|
shutdown();
|
|
return false;
|
|
}
|
|
|
|
// Create linear sampler for post-processing texture reads
|
|
{
|
|
vk::SamplerCreateInfo samplerInfo;
|
|
samplerInfo.magFilter = vk::Filter::eLinear;
|
|
samplerInfo.minFilter = vk::Filter::eLinear;
|
|
samplerInfo.mipmapMode = vk::SamplerMipmapMode::eLinear;
|
|
samplerInfo.addressModeU = vk::SamplerAddressMode::eClampToEdge;
|
|
samplerInfo.addressModeV = vk::SamplerAddressMode::eClampToEdge;
|
|
samplerInfo.addressModeW = vk::SamplerAddressMode::eClampToEdge;
|
|
samplerInfo.mipLodBias = 0.0f;
|
|
samplerInfo.anisotropyEnable = VK_FALSE;
|
|
samplerInfo.compareEnable = VK_FALSE;
|
|
samplerInfo.minLod = 0.0f;
|
|
samplerInfo.maxLod = 0.0f;
|
|
samplerInfo.borderColor = vk::BorderColor::eFloatOpaqueBlack;
|
|
|
|
try {
|
|
m_ctx.linearSampler = m_ctx.device.createSampler(samplerInfo);
|
|
} catch (const vk::SystemError& e) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Failed to create sampler: %s\n", e.what()));
|
|
shutdown();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Create mipmap sampler for bloom textures (supports textureLod)
|
|
{
|
|
vk::SamplerCreateInfo samplerInfo;
|
|
samplerInfo.magFilter = vk::Filter::eLinear;
|
|
samplerInfo.minFilter = vk::Filter::eLinear;
|
|
samplerInfo.mipmapMode = vk::SamplerMipmapMode::eLinear;
|
|
samplerInfo.addressModeU = vk::SamplerAddressMode::eClampToEdge;
|
|
samplerInfo.addressModeV = vk::SamplerAddressMode::eClampToEdge;
|
|
samplerInfo.addressModeW = vk::SamplerAddressMode::eClampToEdge;
|
|
samplerInfo.mipLodBias = 0.0f;
|
|
samplerInfo.anisotropyEnable = VK_FALSE;
|
|
samplerInfo.compareEnable = VK_FALSE;
|
|
samplerInfo.minLod = 0.0f;
|
|
samplerInfo.maxLod = static_cast<float>(VulkanBloom::MAX_MIP_BLUR_LEVELS);
|
|
samplerInfo.borderColor = vk::BorderColor::eFloatOpaqueBlack;
|
|
|
|
try {
|
|
m_ctx.mipmapSampler = m_ctx.device.createSampler(samplerInfo);
|
|
} catch (const vk::SystemError& e) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Failed to create mipmap sampler: %s\n", e.what()));
|
|
shutdown();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Tonemap (blitToSwapChain) and output-encode UBO data comes from the shared
|
|
// per-frame scratch ring below -- no dedicated persistent UBOs. A single-
|
|
// instance buffer would risk being rewritten every frame while a prior
|
|
// in-flight frame's GPU work is still reading it.
|
|
|
|
// Create the shared scratch UBO ring (used by every subsystem's drawFullscreenTriangle)
|
|
if (!m_ctx.initScratchUBO()) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Failed to create scratch UBO!\n"));
|
|
shutdown();
|
|
return false;
|
|
}
|
|
|
|
// Initialize bloom resources (non-fatal if it fails)
|
|
if (!initBloom()) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Bloom initialization failed (non-fatal)\n"));
|
|
}
|
|
|
|
// Initialize LDR targets for tonemapping + FXAA (non-fatal if it fails)
|
|
if (!m_ldr.init(m_ctx, m_sceneColor, m_sceneDepth, m_bloom)) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: LDR target initialization failed (non-fatal)\n"));
|
|
}
|
|
|
|
// Initialize SMAA resources (non-fatal if it fails; requires LDR targets)
|
|
if (m_ldr.isInitialized() && !m_smaa.init(m_ctx, m_ldr)) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: SMAA initialization failed (non-fatal)\n"));
|
|
}
|
|
|
|
// Initialize distortion ping-pong textures (non-fatal if it fails)
|
|
m_distortion.init(m_ctx);
|
|
|
|
// Initialize G-buffer for deferred lighting (non-fatal)
|
|
if (!initGBuffer()) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: G-buffer initialization failed (non-fatal)\n"));
|
|
}
|
|
|
|
// Wire the deferred light accumulation + fog subsystems (resources are lazy).
|
|
m_lighting.init(m_ctx, m_sceneColor, m_deferred, m_shadow);
|
|
m_fog.init(m_ctx, m_sceneColor, m_sceneDepth, m_sceneDepthCopy, m_deferred);
|
|
|
|
// Initialize MSAA resources if MSAA is enabled and G-buffer is ready
|
|
if (m_deferred.isInitialized() && Cmdline_msaa_enabled > 0) {
|
|
if (!initMSAA()) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: MSAA initialization failed (non-fatal, disabling MSAA)\n"));
|
|
Cmdline_msaa_enabled = 0;
|
|
}
|
|
}
|
|
|
|
m_initialized = true;
|
|
nprintf(("vulkan", "VulkanPostProcessor: Initialized (%ux%u, RGBA16F scene color)\n",
|
|
extent.width, extent.height));
|
|
return true;
|
|
}
|
|
|
|
void VulkanPostProcessor::shutdown()
|
|
{
|
|
if (m_ctx.device) {
|
|
m_ctx.device.waitIdle();
|
|
|
|
m_fog.shutdown();
|
|
shutdownShadowPass();
|
|
shadow_cascade_params_shutdown();
|
|
shutdownMSAA();
|
|
m_lighting.shutdown();
|
|
shutdownGBuffer();
|
|
m_smaa.shutdown();
|
|
m_ldr.shutdown();
|
|
shutdownBloom();
|
|
|
|
m_ctx.shutdownScratchUBO();
|
|
|
|
if (m_ctx.mipmapSampler) {
|
|
m_ctx.device.destroySampler(m_ctx.mipmapSampler);
|
|
m_ctx.mipmapSampler = nullptr;
|
|
}
|
|
|
|
if (m_ctx.linearSampler) {
|
|
m_ctx.device.destroySampler(m_ctx.linearSampler);
|
|
m_ctx.linearSampler = nullptr;
|
|
}
|
|
destroySceneTargets();
|
|
|
|
if (m_sceneRenderPassLoad) {
|
|
m_ctx.device.destroyRenderPass(m_sceneRenderPassLoad);
|
|
m_sceneRenderPassLoad = nullptr;
|
|
}
|
|
if (m_sceneRenderPass) {
|
|
m_ctx.device.destroyRenderPass(m_sceneRenderPass);
|
|
m_sceneRenderPass = nullptr;
|
|
}
|
|
|
|
// Destroy distortion textures
|
|
m_distortion.shutdown();
|
|
}
|
|
|
|
m_initialized = false;
|
|
}
|
|
|
|
bool VulkanPostProcessor::createSceneTargets(vk::Extent2D extent)
|
|
{
|
|
// HDR scene color target (RGBA16F)
|
|
// eTransferSrc needed for copy_effect_texture (mid-scene snapshot)
|
|
// eTransferDst needed for deferred_lighting_finish (emissive→color copy)
|
|
if (!createImage(extent.width, extent.height, HDR_COLOR_FORMAT,
|
|
vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eSampled
|
|
| vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst,
|
|
vk::ImageAspectFlagBits::eColor,
|
|
m_sceneColor.image, m_sceneColor.view, m_sceneColor.allocation)) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Failed to create scene color image!\n"));
|
|
return false;
|
|
}
|
|
m_sceneColor.format = HDR_COLOR_FORMAT;
|
|
m_sceneColor.width = extent.width;
|
|
m_sceneColor.height = extent.height;
|
|
|
|
// Scene depth target
|
|
if (!createImage(extent.width, extent.height, m_ctx.depthFormat,
|
|
vk::ImageUsageFlagBits::eDepthStencilAttachment
|
|
| vk::ImageUsageFlagBits::eSampled
|
|
| vk::ImageUsageFlagBits::eTransferSrc,
|
|
vk::ImageAspectFlagBits::eDepth, // View uses depth-only aspect
|
|
m_sceneDepth.image, m_sceneDepth.view, m_sceneDepth.allocation)) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Failed to create scene depth image!\n"));
|
|
return false;
|
|
}
|
|
m_sceneDepth.format = m_ctx.depthFormat;
|
|
m_sceneDepth.width = extent.width;
|
|
m_sceneDepth.height = extent.height;
|
|
|
|
// Effect/composite texture (RGBA16F, snapshot of scene color for distortion/soft particles)
|
|
if (!createImage(extent.width, extent.height, HDR_COLOR_FORMAT,
|
|
vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
|
|
vk::ImageAspectFlagBits::eColor,
|
|
m_sceneEffect.image, m_sceneEffect.view, m_sceneEffect.allocation)) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Failed to create scene effect image!\n"));
|
|
return false;
|
|
}
|
|
m_sceneEffect.format = HDR_COLOR_FORMAT;
|
|
m_sceneEffect.width = extent.width;
|
|
m_sceneEffect.height = extent.height;
|
|
|
|
// Scene depth copy (samplable copy for soft particles)
|
|
// Same depth format, usage: eTransferDst (copy target) + eSampled (fragment shader reads)
|
|
if (!createImage(extent.width, extent.height, m_ctx.depthFormat,
|
|
vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
|
|
vk::ImageAspectFlagBits::eDepth,
|
|
m_sceneDepthCopy.image, m_sceneDepthCopy.view, m_sceneDepthCopy.allocation)) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Failed to create scene depth copy image!\n"));
|
|
return false;
|
|
}
|
|
m_sceneDepthCopy.format = m_ctx.depthFormat;
|
|
m_sceneDepthCopy.width = extent.width;
|
|
m_sceneDepthCopy.height = extent.height;
|
|
|
|
return true;
|
|
}
|
|
|
|
void VulkanPostProcessor::destroySceneTargets()
|
|
{
|
|
if (m_sceneFramebuffer) {
|
|
m_ctx.device.destroyFramebuffer(m_sceneFramebuffer);
|
|
m_sceneFramebuffer = nullptr;
|
|
}
|
|
m_ctx.destroyTarget(m_sceneEffect);
|
|
m_ctx.destroyTarget(m_sceneColor);
|
|
m_ctx.destroyTarget(m_sceneDepth);
|
|
m_ctx.destroyTarget(m_sceneDepthCopy);
|
|
}
|
|
|
|
bool VulkanPostProcessor::createSceneFramebuffer()
|
|
{
|
|
std::array<vk::ImageView, 2> fbAttachments = {m_sceneColor.view, m_sceneDepth.view};
|
|
|
|
vk::FramebufferCreateInfo fbInfo;
|
|
fbInfo.renderPass = m_sceneRenderPass;
|
|
fbInfo.attachmentCount = static_cast<uint32_t>(fbAttachments.size());
|
|
fbInfo.pAttachments = fbAttachments.data();
|
|
fbInfo.width = m_ctx.sceneExtent.width;
|
|
fbInfo.height = m_ctx.sceneExtent.height;
|
|
fbInfo.layers = 1;
|
|
|
|
try {
|
|
m_sceneFramebuffer = m_ctx.device.createFramebuffer(fbInfo);
|
|
} catch (const vk::SystemError& e) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Failed to create scene framebuffer: %s\n", e.what()));
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool VulkanPostProcessor::resize(vk::Extent2D newExtent)
|
|
{
|
|
if (!m_initialized) {
|
|
return false;
|
|
}
|
|
if (newExtent == m_ctx.sceneExtent) {
|
|
return true;
|
|
}
|
|
|
|
// Caller (recreateSwapChain) has already waited for the device to go idle.
|
|
m_ctx.sceneExtent = newExtent;
|
|
|
|
// Scene targets first: every subsystem framebuffer that wires scene
|
|
// color/depth needs the recreated views.
|
|
destroySceneTargets();
|
|
if (!createSceneTargets(newExtent) || !createSceneFramebuffer()) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Failed to recreate scene targets on resize!\n"));
|
|
return false;
|
|
}
|
|
|
|
// Subsystems recreate only their extent-sized targets/framebuffers; their
|
|
// render passes, samplers, and lookup textures are extent-independent.
|
|
// Failures are non-fatal and disable the subsystem, matching init().
|
|
if (m_bloom.isInitialized() && !m_bloom.resize()) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Bloom resize failed, disabling bloom\n"));
|
|
m_bloom.shutdown();
|
|
}
|
|
if (m_ldr.isInitialized() && !m_ldr.resize()) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: LDR resize failed, disabling LDR + SMAA\n"));
|
|
m_smaa.shutdown();
|
|
m_ldr.shutdown();
|
|
}
|
|
if (m_smaa.isInitialized() && !m_smaa.resize()) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: SMAA resize failed, disabling SMAA\n"));
|
|
m_smaa.shutdown();
|
|
}
|
|
if (m_deferred.isInitialized() && !m_deferred.resize()) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: G-buffer resize failed, disabling deferred lighting\n"));
|
|
m_deferred.shutdownMsaa();
|
|
m_deferred.shutdown();
|
|
}
|
|
// The light-accumulation framebuffer attaches the (just recreated) G-buffer
|
|
// composite view — must come after the G-buffer resize.
|
|
if (!m_lighting.onResize()) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Deferred-lighting resize failed, disabling it\n"));
|
|
m_lighting.shutdown();
|
|
}
|
|
// The fog framebuffer attaches the (just recreated) scene color view.
|
|
if (!m_fog.onResize()) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Fog resize failed, disabling fog\n"));
|
|
m_fog.shutdown();
|
|
}
|
|
// Distortion (fixed 32x32) and the shadow map (sized from Shadow_quality)
|
|
// are extent-independent.
|
|
|
|
nprintf(("vulkan", "VulkanPostProcessor: Resized to %ux%u\n", newExtent.width, newExtent.height));
|
|
return true;
|
|
}
|
|
|
|
void VulkanPostProcessor::copyEffectTexture(vk::CommandBuffer cmd) const
|
|
{
|
|
// Called mid-scene, outside a render pass.
|
|
// Scene color is in eShaderReadOnlyOptimal (from the ended scene render pass).
|
|
// Copies scene color → effect texture so distortion/soft particle shaders can sample it.
|
|
copyImageToImage(cmd,
|
|
m_sceneColor.image, vk::ImageLayout::eShaderReadOnlyOptimal, vk::ImageLayout::eColorAttachmentOptimal,
|
|
m_sceneEffect.image, vk::ImageLayout::eUndefined, vk::ImageLayout::eShaderReadOnlyOptimal,
|
|
m_ctx.sceneExtent);
|
|
}
|
|
|
|
void VulkanPostProcessor::copySceneDepth(vk::CommandBuffer cmd) const
|
|
{
|
|
// Called mid-scene, outside a render pass.
|
|
// Copies scene depth → depth copy texture so soft particle shaders can sample it.
|
|
// Scene depth is in eDepthStencilAttachmentOptimal (from the ended scene render pass).
|
|
copyImageToImage(cmd,
|
|
m_sceneDepth.image, vk::ImageLayout::eDepthStencilAttachmentOptimal, vk::ImageLayout::eDepthStencilAttachmentOptimal,
|
|
m_sceneDepthCopy.image, vk::ImageLayout::eUndefined, vk::ImageLayout::eShaderReadOnlyOptimal,
|
|
m_ctx.sceneExtent,
|
|
imageAspectFromFormat(m_ctx.depthFormat));
|
|
}
|
|
|
|
void VulkanPostProcessor::blitToSwapChain(vk::CommandBuffer cmd)
|
|
{
|
|
// C8: unlike PostProcessContext::drawFullscreenTriangle (which begins and ends
|
|
// its OWN render pass), blitToSwapChain draws INTO the caller's already-active
|
|
// composition render pass — it keys the pipeline on
|
|
// stateTracker->getCurrentRenderPass() and goes through the state tracker
|
|
// (bindPipeline/setViewport) rather than raw cmd recording, because the HUD/2D
|
|
// draws that follow it in the same pass must see consistent tracker state. That
|
|
// in-pass, tracker-routed shape is why it can't be folded into the standalone
|
|
// helper.
|
|
//
|
|
// If LDR targets exist, executeTonemap()+executeFXAA() already ran.
|
|
// Blit from the latest post-processing result with passthrough settings.
|
|
// Otherwise, fall back to direct HDR→swap chain tonemapping.
|
|
bool useLdr = m_ldr.isInitialized();
|
|
|
|
auto* pipelineMgr = getPipelineManager();
|
|
auto* descriptorMgr = getDescriptorManager();
|
|
auto* stateTracker = getStateTracker();
|
|
auto* bufferMgr = getBufferManager();
|
|
|
|
if (!pipelineMgr || !descriptorMgr || !stateTracker || !bufferMgr) {
|
|
return;
|
|
}
|
|
|
|
GR_DEBUG_SCOPE("Draw scene texture");
|
|
|
|
// Build pipeline config for tonemapping (fullscreen, no depth, no blending)
|
|
PipelineConfig config;
|
|
config.shaderType = SDR_TYPE_POST_PROCESS_TONEMAPPING;
|
|
config.shaderFlags = useLdr ? SDR_FLAG_TONEMAPPING_LINEAR_OUT : 0;
|
|
config.vertexLayoutHash = 0; // Empty vertex layout
|
|
config.primitiveType = PRIM_TYPE_TRIS;
|
|
config.depthMode = ZBUFFER_TYPE_NONE;
|
|
config.blendMode = ALPHA_BLEND_NONE;
|
|
config.cullEnabled = false;
|
|
config.depthWriteEnabled = false;
|
|
config.renderPass = stateTracker->getCurrentRenderPass();
|
|
|
|
// Get or create the pipeline
|
|
vertex_layout emptyLayout; // No vertex components
|
|
vk::Pipeline pipeline = pipelineMgr->getPipeline(config, emptyLayout);
|
|
if (!pipeline) {
|
|
nprintf(("vulkan", "VulkanPostProcessor: Failed to get tonemapping pipeline!\n"));
|
|
return;
|
|
}
|
|
|
|
vk::PipelineLayout pipelineLayout = pipelineMgr->getPipelineLayout();
|
|
stateTracker->bindPipeline(pipeline, pipelineLayout);
|
|
|
|
// Set viewport (non-flipped for post-processing — textures are already
|
|
// in the correct Vulkan orientation, no Y-flip needed)
|
|
stateTracker->setViewport(0.0f, 0.0f,
|
|
static_cast<float>(m_ctx.sceneExtent.width),
|
|
static_cast<float>(m_ctx.sceneExtent.height));
|
|
|
|
stateTracker->applyDynamicState();
|
|
|
|
DescriptorWriter writer;
|
|
writer.reset(m_ctx.device, descriptorMgr->getFallbacks());
|
|
|
|
// Set 1: Material — source texture at array slot 0
|
|
vk::DescriptorSet materialSet = descriptorMgr->allocateFrameSet(DescriptorSetIndex::Material);
|
|
Assert(materialSet);
|
|
writer.writeSet(materialSet, VulkanDescriptorManager::getSetTemplate(DescriptorSetIndex::Material));
|
|
{
|
|
std::array<vk::DescriptorImageInfo, VulkanDescriptorManager::MAX_TEXTURE_BINDINGS> texArrayInfos;
|
|
texArrayInfos.fill(descriptorMgr->getFallbacks().texture2D);
|
|
texArrayInfos[0].sampler = m_ctx.linearSampler;
|
|
texArrayInfos[0].imageView = m_ldr.postEffectsApplied() ? m_ldr.luminanceView()
|
|
: useLdr ? m_ldr.ldrView()
|
|
: m_sceneColor.view;
|
|
writer.setImageArray(MaterialBinding::TextureArray, texArrayInfos);
|
|
}
|
|
|
|
// Set 2: PerDraw — tonemapping UBO (from the per-frame scratch ring)
|
|
vk::DescriptorSet perDrawSet = descriptorMgr->allocateFrameSet(DescriptorSetIndex::PerDraw);
|
|
Assert(perDrawSet);
|
|
writer.writeSet(perDrawSet, VulkanDescriptorManager::getSetTemplate(DescriptorSetIndex::PerDraw));
|
|
|
|
// LDR path: passthrough (tonemapping already ran). Fallback path: live
|
|
// parameters from the engine lighting profile.
|
|
graphics::generic_data::tonemapping_data tmData;
|
|
memset(&tmData, 0, sizeof(tmData));
|
|
if (useLdr) {
|
|
tmData.exposure = 1.0f;
|
|
tmData.tonemapper = 0; // Linear passthrough
|
|
} else {
|
|
namespace ltp = lighting_profiles;
|
|
auto ppc = ltp::current_piecewise_intermediates();
|
|
tmData.exposure = ltp::current_exposure();
|
|
tmData.tonemapper = static_cast<int>(ltp::current_tonemapper());
|
|
tmData.x0 = ppc.x0;
|
|
tmData.y0 = ppc.y0;
|
|
tmData.x1 = ppc.x1;
|
|
tmData.toe_B = ppc.toe_B;
|
|
tmData.toe_lnA = ppc.toe_lnA;
|
|
tmData.sh_B = ppc.sh_B;
|
|
tmData.sh_lnA = ppc.sh_lnA;
|
|
tmData.sh_offsetX = ppc.sh_offsetX;
|
|
tmData.sh_offsetY = ppc.sh_offsetY;
|
|
}
|
|
{
|
|
vk::DeviceSize slotOffset =
|
|
m_ctx.scratchRing.alloc(descriptorMgr->getCurrentFrame(), &tmData, sizeof(tmData));
|
|
writer.setBuffer(PerDrawBinding::GenericData,
|
|
{m_ctx.scratchRing.buffer(), slotOffset, m_ctx.scratchRing.slotSize()});
|
|
}
|
|
writer.flush();
|
|
stateTracker->bindDescriptorSet(DescriptorSetIndex::Material, materialSet);
|
|
stateTracker->bindDescriptorSet(DescriptorSetIndex::PerDraw, perDrawSet);
|
|
|
|
// Draw fullscreen triangle (3 vertices from gl_VertexIndex, no vertex buffer)
|
|
cmd.draw(3, 1, 0, 0);
|
|
}
|
|
|
|
void VulkanPostProcessor::encodeToSwapChainPass(vk::CommandBuffer cmd, vk::RenderPass renderPass,
|
|
vk::Framebuffer framebuffer, vk::Extent2D extent, vk::ImageView sourceView, vk::Sampler sampler,
|
|
int shaderType, unsigned int shaderFlags, const void* uboData, size_t uboSize)
|
|
{
|
|
auto* pipelineMgr = getPipelineManager();
|
|
auto* descriptorMgr = getDescriptorManager();
|
|
if (!pipelineMgr || !descriptorMgr || !m_ctx.scratchRing.isValid()) {
|
|
return;
|
|
}
|
|
|
|
GR_DEBUG_SCOPE("Draw scene texture");
|
|
|
|
// The UBO comes from the shared per-frame scratch ring; its per-frame budget
|
|
// covers every fullscreen pass of the frame including this final encode.
|
|
PipelineConfig config;
|
|
config.shaderType = static_cast<shader_type>(shaderType);
|
|
config.shaderFlags = shaderFlags; // selects the SDR vs HDR10_OUTPUT gamma-correct variant
|
|
config.vertexLayoutHash = 0;
|
|
config.primitiveType = PRIM_TYPE_TRIS;
|
|
config.depthMode = ZBUFFER_TYPE_NONE;
|
|
config.blendMode = ALPHA_BLEND_NONE;
|
|
config.cullEnabled = false;
|
|
config.depthWriteEnabled = false;
|
|
config.renderPass = renderPass;
|
|
|
|
vertex_layout emptyLayout;
|
|
vk::Pipeline pipeline = pipelineMgr->getPipeline(config, emptyLayout);
|
|
if (!pipeline) {
|
|
mprintf(("VulkanPostProcessor: Failed to get output-encode pipeline (shaderType=%d)!\n", shaderType));
|
|
return;
|
|
}
|
|
vk::PipelineLayout pipelineLayout = pipelineMgr->getPipelineLayout();
|
|
|
|
vk::RenderPassBeginInfo rpBegin;
|
|
rpBegin.renderPass = renderPass;
|
|
rpBegin.framebuffer = framebuffer;
|
|
rpBegin.renderArea.offset = vk::Offset2D(0, 0);
|
|
rpBegin.renderArea.extent = extent;
|
|
|
|
cmd.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
|
|
cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
|
|
|
|
vk::Viewport viewport;
|
|
viewport.x = 0.0f;
|
|
viewport.y = 0.0f;
|
|
viewport.width = static_cast<float>(extent.width);
|
|
viewport.height = static_cast<float>(extent.height);
|
|
viewport.minDepth = 0.0f;
|
|
viewport.maxDepth = 1.0f;
|
|
cmd.setViewport(0, viewport);
|
|
|
|
vk::Rect2D scissor;
|
|
scissor.offset = vk::Offset2D(0, 0);
|
|
scissor.extent = extent;
|
|
cmd.setScissor(0, scissor);
|
|
|
|
DescriptorWriter writer;
|
|
writer.reset(m_ctx.device, descriptorMgr->getFallbacks());
|
|
|
|
vk::DescriptorSet materialSet = descriptorMgr->allocateFrameSet(DescriptorSetIndex::Material);
|
|
Assert(materialSet);
|
|
writer.writeSet(materialSet, VulkanDescriptorManager::getSetTemplate(DescriptorSetIndex::Material));
|
|
{
|
|
std::array<vk::DescriptorImageInfo, VulkanDescriptorManager::MAX_TEXTURE_BINDINGS> texArrayInfos;
|
|
texArrayInfos.fill(descriptorMgr->getFallbacks().texture2D);
|
|
texArrayInfos[0].sampler = sampler;
|
|
texArrayInfos[0].imageView = sourceView;
|
|
writer.setImageArray(MaterialBinding::TextureArray, texArrayInfos);
|
|
}
|
|
|
|
vk::DescriptorSet perDrawSet = descriptorMgr->allocateFrameSet(DescriptorSetIndex::PerDraw);
|
|
Assert(perDrawSet);
|
|
writer.writeSet(perDrawSet, VulkanDescriptorManager::getSetTemplate(DescriptorSetIndex::PerDraw));
|
|
{
|
|
vk::DeviceSize slotOffset =
|
|
m_ctx.scratchRing.alloc(descriptorMgr->getCurrentFrame(), uboData, uboSize);
|
|
writer.setBuffer(PerDrawBinding::GenericData,
|
|
{m_ctx.scratchRing.buffer(), slotOffset, m_ctx.scratchRing.slotSize()});
|
|
}
|
|
writer.flush();
|
|
|
|
cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout,
|
|
static_cast<uint32_t>(DescriptorSetIndex::Material),
|
|
{materialSet, perDrawSet}, {});
|
|
|
|
cmd.draw(3, 1, 0, 0);
|
|
cmd.endRenderPass();
|
|
}
|
|
|
|
void VulkanPostProcessor::encodeOutput(vk::CommandBuffer cmd, vk::RenderPass renderPass,
|
|
vk::Framebuffer framebuffer, vk::Extent2D extent, vk::ImageView sourceView, vk::Sampler sampler,
|
|
float paperwhiteNits, float peakNits, float gamma)
|
|
{
|
|
// HDR10/PQ/BT.2020 encode leg (plus the user gamma slider): the HDR10_OUTPUT
|
|
// variant of the shared gamma-correct shader.
|
|
graphics::generic_data::gamma_encode_data encodeData;
|
|
memset(&encodeData, 0, sizeof(encodeData));
|
|
encodeData.gamma = gamma;
|
|
encodeData.hdr_paperwhite_nits = paperwhiteNits;
|
|
encodeData.hdr_peak_nits = peakNits;
|
|
encodeToSwapChainPass(cmd, renderPass, framebuffer, extent, sourceView, sampler,
|
|
SDR_TYPE_GAMMA_BLIT, SDR_FLAG_GAMMA_HDR10, &encodeData, sizeof(encodeData));
|
|
}
|
|
|
|
void VulkanPostProcessor::encodeOutputSdr(vk::CommandBuffer cmd, vk::RenderPass renderPass,
|
|
vk::Framebuffer framebuffer, vk::Extent2D extent, vk::ImageView sourceView, vk::Sampler sampler,
|
|
float gamma)
|
|
{
|
|
// SDR leg: the composition image already carries the final display-ready
|
|
// sRGB-encoded frame (3D scene + menus/HUD alike); this just applies the user
|
|
// gamma/brightness slider on the way into the swap chain image.
|
|
graphics::generic_data::gamma_encode_data blitData;
|
|
memset(&blitData, 0, sizeof(blitData));
|
|
blitData.gamma = gamma;
|
|
encodeToSwapChainPass(cmd, renderPass, framebuffer, extent, sourceView, sampler,
|
|
SDR_TYPE_GAMMA_BLIT, 0, &blitData, sizeof(blitData));
|
|
}
|
|
|
|
// No-op: In OpenGL, begin/end push/pop an FBO and run the post-processing
|
|
// pipeline. In Vulkan, this is handled by vulkan_scene_texture_begin/end
|
|
// which manage the HDR render pass and post-processing passes. These
|
|
// functions are not actively called by the engine.
|
|
void vulkan_post_process_begin() {}
|
|
void vulkan_post_process_end() {}
|
|
|
|
// No-op: In OpenGL, save/restore swap the depth attachment between
|
|
// Scene_depth_texture and Cockpit_depth_texture to isolate cockpit
|
|
// depth from the main scene. In Vulkan, the render pass loadOp=eClear
|
|
// clears depth at the start of each scene pass, and separate cockpit
|
|
// depth isolation is not yet implemented. Called from ship.cpp during
|
|
// cockpit rendering but degrades gracefully as a no-op (cockpit just
|
|
// shares the scene depth buffer).
|
|
void vulkan_post_process_save_zbuffer() {}
|
|
void vulkan_post_process_restore_zbuffer() {}
|
|
|
|
void vulkan_post_process_set_effect(const char* name, int value, const vec3d* rgb)
|
|
{
|
|
if (!Gr_post_processing_enabled || !graphics::Post_processing_manager) {
|
|
return;
|
|
}
|
|
if (name == nullptr) {
|
|
return;
|
|
}
|
|
|
|
auto& ls_params = graphics::Post_processing_manager->getLightshaftParams();
|
|
if (!stricmp("lightshafts", name)) {
|
|
ls_params.intensity = value / 100.0f;
|
|
ls_params.on = !!value;
|
|
return;
|
|
}
|
|
|
|
auto& postEffects = graphics::Post_processing_manager->getPostEffects();
|
|
for (auto & postEffect : postEffects) {
|
|
if (!stricmp(postEffect.name.c_str(), name)) {
|
|
postEffect.intensity = (value / postEffect.div) + postEffect.add;
|
|
if ((rgb != nullptr) && !(vmd_zero_vector == *rgb)) {
|
|
postEffect.rgb = *rgb;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
void vulkan_post_process_set_defaults()
|
|
{
|
|
if (!graphics::Post_processing_manager) {
|
|
return;
|
|
}
|
|
|
|
auto& postEffects = graphics::Post_processing_manager->getPostEffects();
|
|
for (auto& effect : postEffects) {
|
|
effect.intensity = effect.default_intensity;
|
|
}
|
|
}
|
|
|
|
} // namespace graphics::vulkan
|
|
|