mirror of
https://github.com/scp-fs2open/fs2open.github.com.git
synced 2026-11-09 04:49:39 -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]>
814 lines
28 KiB
C++
814 lines
28 KiB
C++
#include "VulkanDraw.h"
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
|
|
#include "VulkanState.h"
|
|
#include "VulkanBarrier.h"
|
|
#include "VulkanBuffer.h"
|
|
#include "VulkanPipeline.h"
|
|
#include "VulkanShader.h"
|
|
#include "VulkanTexture.h"
|
|
#include "VulkanRenderer.h"
|
|
#include "VulkanPostProcessing.h"
|
|
#include "VulkanDescriptorManager.h"
|
|
#include "VulkanDeletionQueue.h"
|
|
#include "VulkanMemory.h"
|
|
#include "VulkanConstants.h"
|
|
#include "gr_vulkan.h"
|
|
#include "VulkanVertexFormat.h"
|
|
#include "bmpman/bmpman.h"
|
|
#include "ddsutils/ddsutils.h"
|
|
#include "graphics/grinternal.h"
|
|
#include "graphics/material.h"
|
|
#include "graphics/matrix.h"
|
|
#include "graphics/util/primitives.h"
|
|
#include "graphics/util/uniform_structs.h"
|
|
#include "graphics/shadows.h"
|
|
#include "lighting/lighting.h"
|
|
#include "graphics/util/UniformBuffer.h"
|
|
|
|
#define MODEL_SDR_FLAG_MODE_CPP
|
|
#include "def_files/data/effects/model_shader_flags.h"
|
|
|
|
// PostProcessing_override is defined in globalincs/systemvars.cpp
|
|
|
|
namespace graphics::vulkan {
|
|
|
|
// ========== gr_screen function pointer implementations ==========
|
|
// These free functions are assigned to gr_screen.gf_* in gr_vulkan.cpp.
|
|
|
|
namespace {
|
|
|
|
// Helper to set up GenericData uniform for default material shader
|
|
// Similar to opengl_shader_set_default_material() in gropenglshader.cpp
|
|
void vulkan_set_default_material_uniforms(material* material_info)
|
|
{
|
|
if (!material_info) {
|
|
return;
|
|
}
|
|
|
|
// Get uniform buffer for GenericData
|
|
auto buffer = gr_get_uniform_buffer(uniform_block_type::GenericData, 1, sizeof(genericData_default_material_v_sdr));
|
|
auto* data = buffer.aligner().addTypedElement<genericData_default_material_v_sdr>();
|
|
|
|
// Get base map from material
|
|
int base_map = material_info->get_texture_map(TM_BASE_TYPE);
|
|
bool textured = (base_map >= 0);
|
|
bool alpha = (material_info->get_texture_type() == TCACHE_TYPE_AABITMAP);
|
|
|
|
// Texturing flags
|
|
if (textured) {
|
|
data->noTexturing = 0;
|
|
// Get array index for animated texture arrays
|
|
auto* texSlot = getTextureManager()->getTextureSlot(base_map);
|
|
data->baseMapIndex = texSlot ? static_cast<int>(texSlot->arrayIndex) : 0;
|
|
} else {
|
|
data->noTexturing = 1;
|
|
data->baseMapIndex = 0;
|
|
}
|
|
|
|
// Alpha texture flag
|
|
data->alphaTexture = alpha ? 1 : 0;
|
|
|
|
// HDR / intensity settings
|
|
data->srgb = High_dynamic_range ? 1 : 0;
|
|
data->intensity = material_info->get_color_scale();
|
|
|
|
// Alpha threshold
|
|
data->alphaThreshold = getStateTracker()->getAlphaThreshold();
|
|
|
|
// Color from material
|
|
vec4 clr = material_info->get_color();
|
|
data->color.a1d[0] = clr.xyzw.x;
|
|
data->color.a1d[1] = clr.xyzw.y;
|
|
data->color.a1d[2] = clr.xyzw.z;
|
|
data->color.a1d[3] = clr.xyzw.w;
|
|
|
|
// Clip plane
|
|
const auto& clip_plane = material_info->get_clip_plane();
|
|
if (clip_plane.enabled) {
|
|
data->clipEnabled = 1;
|
|
|
|
data->clipEquation.a1d[0] = clip_plane.normal.xyz.x;
|
|
data->clipEquation.a1d[1] = clip_plane.normal.xyz.y;
|
|
data->clipEquation.a1d[2] = clip_plane.normal.xyz.z;
|
|
// Calculate 'd' value: d = -dot(normal, position)
|
|
data->clipEquation.a1d[3] = -((clip_plane.normal.xyz.x * clip_plane.position.xyz.x) +
|
|
(clip_plane.normal.xyz.y * clip_plane.position.xyz.y) +
|
|
(clip_plane.normal.xyz.z * clip_plane.position.xyz.z));
|
|
|
|
// Model matrix (identity for now, material doesn't provide one)
|
|
vm_matrix4_set_identity(&data->modelMatrix);
|
|
} else {
|
|
data->clipEnabled = 0;
|
|
vm_matrix4_set_identity(&data->modelMatrix);
|
|
data->clipEquation.a1d[0] = 0.0f;
|
|
data->clipEquation.a1d[1] = 0.0f;
|
|
data->clipEquation.a1d[2] = 0.0f;
|
|
data->clipEquation.a1d[3] = 0.0f;
|
|
}
|
|
|
|
buffer.submitData();
|
|
gr_bind_uniform_buffer(uniform_block_type::GenericData, buffer.getBufferOffset(0),
|
|
sizeof(genericData_default_material_v_sdr), buffer.bufferHandle());
|
|
}
|
|
|
|
} // anonymous namespace
|
|
|
|
int vulkan_zbuffer_get()
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
return drawManager->zbufferGet();
|
|
}
|
|
|
|
int vulkan_zbuffer_set(int mode)
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
return drawManager->zbufferSet(mode);
|
|
}
|
|
|
|
void vulkan_zbuffer_clear(int mode)
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->zbufferClear(mode);
|
|
}
|
|
|
|
int vulkan_stencil_set(int mode)
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
return drawManager->stencilSet(mode);
|
|
}
|
|
|
|
void vulkan_stencil_clear()
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->stencilClear();
|
|
}
|
|
|
|
void vulkan_set_fill_mode(int mode)
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
// GR_FILL_MODE_WIRE = 1, GR_FILL_MODE_SOLID = 2
|
|
drawManager->setFillMode(mode);
|
|
}
|
|
|
|
void vulkan_clear()
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->clear();
|
|
}
|
|
|
|
void vulkan_reset_clip()
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->resetClip();
|
|
}
|
|
|
|
void vulkan_set_clear_color(int r, int g, int b)
|
|
{
|
|
graphics::vulkan::VulkanDrawManager::setClearColor(r, g, b);
|
|
}
|
|
|
|
void vulkan_set_clip(int x, int y, int w, int h, int resize_mode)
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->setClip(x, y, w, h, resize_mode);
|
|
}
|
|
|
|
int vulkan_set_cull(int cull)
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
return drawManager->setCull(cull);
|
|
}
|
|
|
|
int vulkan_set_color_buffer(int mode)
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
return drawManager->setColorBuffer(mode);
|
|
}
|
|
|
|
void vulkan_set_texture_addressing(int mode)
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->setTextureAddressing(mode);
|
|
}
|
|
|
|
void vulkan_set_line_width(float width)
|
|
{
|
|
auto* stateTracker = getStateTracker();
|
|
if (width <= 1.0f) {
|
|
stateTracker->setLineWidth(width);
|
|
}
|
|
gr_screen.line_width = width;
|
|
}
|
|
|
|
void vulkan_clear_states()
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->clearStates();
|
|
}
|
|
|
|
void vulkan_scene_texture_begin()
|
|
{
|
|
GR_DEBUG_SCOPE("Begin scene texture");
|
|
|
|
auto* renderer = getRendererInstance();
|
|
|
|
// Switch to HDR scene render pass when post-processing is enabled
|
|
auto* pp = getPostProcessor();
|
|
if (pp && pp->isInitialized() && Gr_post_processing_enabled && !PostProcessing_override) {
|
|
renderer->beginSceneRendering();
|
|
High_dynamic_range = true;
|
|
} else {
|
|
// Fallback: just clear within the current swap chain pass
|
|
auto* stateTracker = getStateTracker();
|
|
auto cmdBuffer = stateTracker->getCommandBuffer();
|
|
|
|
std::array<vk::ClearAttachment, 2> clearAttachments;
|
|
clearAttachments[0].aspectMask = vk::ImageAspectFlagBits::eColor;
|
|
clearAttachments[0].colorAttachment = 0;
|
|
clearAttachments[0].clearValue.color.setFloat32({0.0f, 0.0f, 0.0f, 1.0f});
|
|
|
|
clearAttachments[1].aspectMask = vk::ImageAspectFlagBits::eDepth;
|
|
clearAttachments[1].clearValue.depthStencil = vk::ClearDepthStencilValue(1.0f, 0);
|
|
|
|
vk::ClearRect clearRect;
|
|
clearRect.rect.offset = vk::Offset2D(0, 0);
|
|
clearRect.rect.extent = vk::Extent2D(static_cast<uint32_t>(gr_screen.max_w),
|
|
static_cast<uint32_t>(gr_screen.max_h));
|
|
clearRect.rect = stateTracker->clampToRenderArea(clearRect.rect);
|
|
clearRect.baseArrayLayer = 0;
|
|
clearRect.layerCount = 1;
|
|
|
|
if (clearRect.rect.extent.width > 0 && clearRect.rect.extent.height > 0) {
|
|
cmdBuffer.clearAttachments(clearAttachments, clearRect);
|
|
}
|
|
}
|
|
}
|
|
|
|
void vulkan_scene_texture_end()
|
|
{
|
|
GR_DEBUG_SCOPE("End scene texture");
|
|
|
|
auto* renderer = getRendererInstance();
|
|
|
|
// If we were rendering to the HDR scene target, switch back to swap chain
|
|
if (renderer->isSceneRendering()) {
|
|
renderer->endSceneRendering();
|
|
}
|
|
|
|
High_dynamic_range = false;
|
|
}
|
|
|
|
void vulkan_copy_effect_texture()
|
|
{
|
|
GR_DEBUG_SCOPE("Copy effect texture");
|
|
|
|
auto* renderer = getRendererInstance();
|
|
|
|
// Only copy if we're actively rendering the HDR scene
|
|
if (!renderer->isSceneRendering()) {
|
|
return;
|
|
}
|
|
|
|
renderer->copyEffectTexture();
|
|
}
|
|
|
|
void vulkan_draw_sphere(material* material_def, float /*rad*/)
|
|
{
|
|
// Set up uniform buffers before rendering (like OpenGL does)
|
|
gr_matrix_set_uniforms();
|
|
vulkan_set_default_material_uniforms(material_def);
|
|
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->drawSphere(material_def);
|
|
}
|
|
|
|
void vulkan_render_shield_impact(shield_material* material_info,
|
|
primitive_type prim_type,
|
|
vertex_layout* layout,
|
|
gr_buffer_handle buffer_handle,
|
|
int n_verts)
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
|
|
// Compute impact projection matrices
|
|
float radius = material_info->get_impact_radius();
|
|
vec3d min_v, max_v;
|
|
min_v.xyz.x = min_v.xyz.y = min_v.xyz.z = -radius;
|
|
max_v.xyz.x = max_v.xyz.y = max_v.xyz.z = radius;
|
|
|
|
matrix4 impact_projection;
|
|
vm_matrix4_set_orthographic(&impact_projection, &max_v, &min_v);
|
|
|
|
matrix impact_orient = material_info->get_impact_orient();
|
|
vec3d impact_pos = material_info->get_impact_pos();
|
|
|
|
matrix4 impact_transform;
|
|
vm_matrix4_set_inverse_transform(&impact_transform, &impact_orient, &impact_pos);
|
|
|
|
// Set shield impact uniform data (GenericData UBO)
|
|
auto buffer = gr_get_uniform_buffer(uniform_block_type::GenericData, 1,
|
|
sizeof(graphics::generic_data::shield_impact_data));
|
|
auto* data = buffer.aligner().addTypedElement<graphics::generic_data::shield_impact_data>();
|
|
data->hitNormal = impact_orient.vec.fvec;
|
|
data->shieldProjMatrix = impact_projection;
|
|
data->shieldModelViewMatrix = impact_transform;
|
|
data->shieldMapIndex = 0; // Vulkan binds textures individually, always layer 0
|
|
data->srgb = High_dynamic_range ? 1 : 0;
|
|
data->color = material_info->get_color();
|
|
buffer.submitData();
|
|
gr_bind_uniform_buffer(uniform_block_type::GenericData, buffer.getBufferOffset(0),
|
|
sizeof(graphics::generic_data::shield_impact_data), buffer.bufferHandle());
|
|
|
|
// Set matrix uniforms
|
|
gr_matrix_set_uniforms();
|
|
|
|
// Draw the shield mesh
|
|
drawManager->renderPrimitives(material_info, prim_type, layout, 0, n_verts, buffer_handle, 0);
|
|
}
|
|
|
|
void vulkan_render_model(model_material* material_info,
|
|
indexed_vertex_source* vert_source,
|
|
vertex_buffer* bufferp,
|
|
size_t texi)
|
|
{
|
|
// ModelData UBO (matrices, lights, material params) is already bound by the model
|
|
// rendering pipeline (model_draw_list::render_buffer) before this function is called.
|
|
// Do NOT call vulkan_set_default_material_uniforms here - that would set GenericData
|
|
// uniforms for SDR_TYPE_DEFAULT_MATERIAL, but models use SDR_TYPE_MODEL with ModelData.
|
|
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->renderModel(material_info, vert_source, bufferp, texi);
|
|
}
|
|
|
|
void vulkan_render_shadow_draw(gr_buffer_handle ubo_handle, size_t ubo_offset, size_t ubo_size,
|
|
vertex_buffer* buffer, indexed_vertex_source* vert_src, size_t texi)
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->renderShadowDraw(ubo_handle, ubo_offset, ubo_size, buffer, vert_src, texi);
|
|
}
|
|
|
|
void vulkan_render_primitives(material* material_info,
|
|
primitive_type prim_type,
|
|
vertex_layout* layout,
|
|
int offset,
|
|
int n_verts,
|
|
gr_buffer_handle buffer_handle,
|
|
size_t buffer_offset)
|
|
{
|
|
// Set up uniform buffers before rendering (like OpenGL does)
|
|
gr_matrix_set_uniforms();
|
|
vulkan_set_default_material_uniforms(material_info);
|
|
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->renderPrimitives(material_info, prim_type, layout, offset, n_verts, buffer_handle, buffer_offset);
|
|
}
|
|
|
|
void vulkan_render_primitives_particle(particle_material* material_info,
|
|
primitive_type prim_type,
|
|
vertex_layout* layout,
|
|
int offset,
|
|
int n_verts,
|
|
gr_buffer_handle buffer_handle)
|
|
{
|
|
auto* renderer = getRendererInstance();
|
|
auto* drawManager = getDrawManager();
|
|
auto* pp = getPostProcessor();
|
|
|
|
// In deferred mode, once the G-buffer pass has ended the position texture
|
|
// (view-space XYZ) is in eShaderReadOnlyOptimal and free to sample.
|
|
bool usePosTexture = light_deferred_enabled()
|
|
&& !renderer->isUsingGbufRenderPass()
|
|
&& pp && pp->deferred().isInitialized();
|
|
|
|
if (!usePosTexture) {
|
|
// Non-deferred path: copy hardware depth buffer
|
|
renderer->copySceneDepthForParticles();
|
|
}
|
|
|
|
// Set up matrices
|
|
gr_matrix_set_uniforms();
|
|
|
|
// Set effect_data GenericData UBO (matching OpenGL's opengl_tnl_set_material_particle)
|
|
{
|
|
auto buffer = gr_get_uniform_buffer(uniform_block_type::GenericData, 1,
|
|
sizeof(graphics::generic_data::effect_data));
|
|
auto* data = buffer.aligner().addTypedElement<graphics::generic_data::effect_data>();
|
|
|
|
data->window_width = static_cast<float>(gr_screen.max_w);
|
|
data->window_height = static_cast<float>(gr_screen.max_h);
|
|
data->nearZ = Min_draw_distance;
|
|
data->farZ = Max_draw_distance;
|
|
data->srgb = High_dynamic_range ? 1 : 0;
|
|
data->blend_alpha = material_info->get_blend_mode() != ALPHA_BLEND_ADDITIVE ? 1 : 0;
|
|
// In deferred mode, bind the G-buffer position texture (view-space XYZ)
|
|
// so linear_depth=1 reads .z directly (matches OpenGL behavior).
|
|
// Otherwise use the NDC conversion path with the hardware depth copy.
|
|
data->linear_depth = usePosTexture ? 1 : 0;
|
|
|
|
buffer.submitData();
|
|
gr_bind_uniform_buffer(uniform_block_type::GenericData, buffer.getBufferOffset(0),
|
|
sizeof(graphics::generic_data::effect_data), buffer.bufferHandle());
|
|
}
|
|
|
|
// Set depth texture override
|
|
if (usePosTexture) {
|
|
// Deferred path: bind G-buffer position texture directly
|
|
auto* texMgr = getTextureManager();
|
|
auto nearestSampler = texMgr->getSampler(vk::Filter::eNearest, vk::Filter::eNearest,
|
|
vk::SamplerAddressMode::eClampToEdge, false, 0.0f, false);
|
|
drawManager->setDepthTextureOverride(
|
|
{nearestSampler, pp->deferred().positionView(), vk::ImageLayout::eShaderReadOnlyOptimal});
|
|
} else if (renderer->isSceneDepthCopied() && pp) {
|
|
// Non-deferred path: bind the hardware depth copy
|
|
auto* texMgr = getTextureManager();
|
|
auto nearestSampler = texMgr->getSampler(vk::Filter::eNearest, vk::Filter::eNearest,
|
|
vk::SamplerAddressMode::eClampToEdge, false, 0.0f, false);
|
|
drawManager->setDepthTextureOverride(
|
|
{nearestSampler, pp->getSceneDepthCopyView(), vk::ImageLayout::eShaderReadOnlyOptimal});
|
|
}
|
|
|
|
drawManager->renderPrimitivesParticle(material_info, prim_type, layout, offset, n_verts, buffer_handle);
|
|
|
|
// Clear the override
|
|
drawManager->clearDepthTextureOverride();
|
|
}
|
|
|
|
void vulkan_render_primitives_distortion(distortion_material* material_info,
|
|
primitive_type prim_type,
|
|
vertex_layout* layout,
|
|
int offset,
|
|
int n_verts,
|
|
gr_buffer_handle buffer_handle)
|
|
{
|
|
auto* drawManager = getDrawManager();
|
|
auto* pp = getPostProcessor();
|
|
|
|
// Set up matrices
|
|
gr_matrix_set_uniforms();
|
|
|
|
// Set effect_distort_data GenericData UBO (16 bytes)
|
|
{
|
|
auto buffer = gr_get_uniform_buffer(uniform_block_type::GenericData, 1,
|
|
sizeof(graphics::generic_data::effect_distort_data));
|
|
auto* data = buffer.aligner().addTypedElement<graphics::generic_data::effect_distort_data>();
|
|
|
|
data->window_width = static_cast<float>(gr_screen.max_w);
|
|
data->window_height = static_cast<float>(gr_screen.max_h);
|
|
data->use_offset = material_info->get_thruster_rendering() ? 1.0f : 0.0f;
|
|
|
|
buffer.submitData();
|
|
gr_bind_uniform_buffer(uniform_block_type::GenericData, buffer.getBufferOffset(0),
|
|
sizeof(graphics::generic_data::effect_distort_data), buffer.bufferHandle());
|
|
}
|
|
|
|
// Set scene color override (binding 5) — snapshot of scene color for distortion sampling
|
|
if (pp) drawManager->setSceneColorOverride(pp->getSceneEffectTextureInfo());
|
|
|
|
// Set distortion map override (binding 6) — ping-pong noise texture for thrusters
|
|
if (material_info->get_thruster_rendering() && pp)
|
|
drawManager->setDistMapOverride(pp->getDistortionTextureInfo());
|
|
|
|
drawManager->renderPrimitivesDistortion(material_info, prim_type, layout, offset, n_verts, buffer_handle);
|
|
|
|
// Clear overrides so subsequent draws use fallback textures
|
|
drawManager->clearDistortionOverrides();
|
|
}
|
|
|
|
void vulkan_render_movie(movie_material* material_info,
|
|
primitive_type prim_type,
|
|
vertex_layout* layout,
|
|
int n_verts,
|
|
gr_buffer_handle buffer,
|
|
size_t buffer_offset)
|
|
{
|
|
gr_matrix_set_uniforms();
|
|
vulkan_set_default_material_uniforms(material_info);
|
|
|
|
// Movie shader reads alpha from the MovieData UBO (set 2, binding 4), not from
|
|
// GenericData - matches opengl_tnl_set_material_movie in gropengltnl.cpp.
|
|
auto uniform_buffer = gr_get_uniform_buffer(uniform_block_type::MovieData, 1);
|
|
auto& aligner = uniform_buffer.aligner();
|
|
auto movie_data = aligner.addTypedElement<movie_uniforms>();
|
|
movie_data->alpha = material_info->get_color().xyzw.w;
|
|
uniform_buffer.submitData();
|
|
gr_bind_uniform_buffer(uniform_block_type::MovieData,
|
|
uniform_buffer.getBufferOffset(0),
|
|
sizeof(movie_uniforms),
|
|
uniform_buffer.bufferHandle());
|
|
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->renderMovie(material_info, prim_type, layout, n_verts, buffer, buffer_offset);
|
|
}
|
|
|
|
void vulkan_render_nanovg(nanovg_material* material_info,
|
|
primitive_type prim_type,
|
|
vertex_layout* layout,
|
|
int offset,
|
|
int n_verts,
|
|
gr_buffer_handle buffer_handle)
|
|
{
|
|
// NanoVG shader reads from NanoVGData UBO (set 2 binding 2), not GenericData.
|
|
// The NanoVGRenderer binds NanoVGData before calling gr_render_nanovg().
|
|
|
|
// NanoVG uses its own software scissor (scissorMat/scissorExt in the fragment shader).
|
|
// Disable hardware scissor to match nanovg_gl.h which calls glDisable(GL_SCISSOR_TEST).
|
|
// Without this, NanoVG draws get clipped by gr_set_clip's hardware scissor.
|
|
auto* stateTracker = getStateTracker();
|
|
bool savedScissorEnabled = stateTracker->isScissorEnabled();
|
|
stateTracker->setScissorEnabled(false);
|
|
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->renderNanoVG(material_info, prim_type, layout, offset, n_verts, buffer_handle);
|
|
|
|
// Restore scissor state
|
|
stateTracker->setScissorEnabled(savedScissorEnabled);
|
|
}
|
|
|
|
void vulkan_render_primitives_batched(batched_bitmap_material* material_info,
|
|
primitive_type prim_type,
|
|
vertex_layout* layout,
|
|
int offset,
|
|
int n_verts,
|
|
gr_buffer_handle buffer_handle)
|
|
{
|
|
gr_matrix_set_uniforms();
|
|
|
|
// Set batched_data GenericData UBO (matching OpenGL's opengl_tnl_set_material_batched)
|
|
auto buffer = gr_get_uniform_buffer(uniform_block_type::GenericData, 1,
|
|
sizeof(graphics::generic_data::batched_data));
|
|
auto* data = buffer.aligner().addTypedElement<graphics::generic_data::batched_data>();
|
|
data->intensity = material_info->get_color_scale();
|
|
data->color = material_info->get_color();
|
|
buffer.submitData();
|
|
gr_bind_uniform_buffer(uniform_block_type::GenericData, buffer.getBufferOffset(0),
|
|
sizeof(graphics::generic_data::batched_data), buffer.bufferHandle());
|
|
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->renderPrimitivesBatched(material_info, prim_type, layout, offset, n_verts, buffer_handle);
|
|
}
|
|
|
|
void vulkan_render_rocket_primitives(interface_material* material_info,
|
|
primitive_type prim_type,
|
|
vertex_layout* layout,
|
|
int n_indices,
|
|
gr_buffer_handle vertex_buffer,
|
|
gr_buffer_handle index_buffer)
|
|
{
|
|
// Set up 2D orthographic projection (matches OpenGL's gr_opengl_render_rocket_primitives)
|
|
gr_set_2d_matrix();
|
|
|
|
// Fill GenericData UBO with rocketui_data layout (NOT default material layout).
|
|
// The rocketui shader reads projMatrix, offset, textured, baseMapIndex, and
|
|
// horizontalSwipeOffset from GenericData — a completely different layout than
|
|
// the default material shader's genericData.
|
|
{
|
|
auto buffer = gr_get_uniform_buffer(uniform_block_type::GenericData, 1,
|
|
sizeof(graphics::generic_data::rocketui_data));
|
|
auto* data = buffer.aligner().addTypedElement<graphics::generic_data::rocketui_data>();
|
|
|
|
data->projMatrix = gr_projection_matrix;
|
|
|
|
const vec2d& offset = material_info->get_offset();
|
|
data->offset = offset;
|
|
data->textured = material_info->is_textured() ? 1 : 0;
|
|
data->baseMapIndex = 0; // Vulkan texture array: always layer 0
|
|
data->horizontalSwipeOffset = material_info->get_horizontal_swipe();
|
|
|
|
buffer.submitData();
|
|
gr_bind_uniform_buffer(uniform_block_type::GenericData, buffer.getBufferOffset(0),
|
|
sizeof(graphics::generic_data::rocketui_data), buffer.bufferHandle());
|
|
}
|
|
|
|
// Matrices UBO is still needed for descriptor set completeness
|
|
gr_matrix_set_uniforms();
|
|
|
|
auto* drawManager = getDrawManager();
|
|
drawManager->renderRocketPrimitives(material_info, prim_type, layout, n_indices, vertex_buffer, index_buffer);
|
|
|
|
gr_end_2d_matrix();
|
|
}
|
|
|
|
void vulkan_calculate_irrmap()
|
|
{
|
|
if (ENVMAP < 0 || gr_screen.irrmap_render_target < 0) {
|
|
return;
|
|
}
|
|
|
|
auto* renderer = getRendererInstance();
|
|
auto* stateTracker = getStateTracker();
|
|
auto* texManager = getTextureManager();
|
|
auto* descManager = getDescriptorManager();
|
|
auto* bufferManager = getBufferManager();
|
|
auto* pipelineManager = getPipelineManager();
|
|
if (!renderer || !stateTracker || !texManager || !descManager || !bufferManager || !pipelineManager) {
|
|
return;
|
|
}
|
|
|
|
// Get envmap cubemap view
|
|
auto* envSlot = bm_get_slot(ENVMAP, true);
|
|
if (!envSlot || !envSlot->gr_info) {
|
|
return;
|
|
}
|
|
auto* envTs = static_cast<tcache_slot_vulkan*>(envSlot->gr_info);
|
|
// Both the render-target and static-file cubemap upload paths store the
|
|
// cube-sampling view in imageView, so that's what must be used here regardless
|
|
// of isCubemap.
|
|
vk::ImageView envmapView = envTs->imageView;
|
|
if (!envmapView) {
|
|
return;
|
|
}
|
|
|
|
// Get irrmap render target (cubemap with per-face framebuffers)
|
|
auto* irrSlot = bm_get_slot(gr_screen.irrmap_render_target, true);
|
|
if (!irrSlot || !irrSlot->gr_info) {
|
|
return;
|
|
}
|
|
auto* irrTs = static_cast<tcache_slot_vulkan*>(irrSlot->gr_info);
|
|
if (!irrTs->isCubemap || !irrTs->renderPass) {
|
|
return;
|
|
}
|
|
|
|
vk::CommandBuffer cmd = stateTracker->getCommandBuffer();
|
|
|
|
// End the current swap chain render pass
|
|
cmd.endRenderPass();
|
|
|
|
// Create pipeline for irradiance map generation
|
|
PipelineConfig config;
|
|
config.shaderType = SDR_TYPE_IRRADIANCE_MAP_GEN;
|
|
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 = irrTs->renderPass;
|
|
|
|
vertex_layout emptyLayout;
|
|
vk::Pipeline pipeline = pipelineManager->getPipeline(config, emptyLayout);
|
|
if (!pipeline) {
|
|
nprintf(("vulkan", "vulkan_calculate_irrmap: Failed to get pipeline!\n"));
|
|
return;
|
|
}
|
|
|
|
vk::PipelineLayout pipelineLayout = pipelineManager->getPipelineLayout();
|
|
|
|
// Create a small host-visible UBO for the 6 face indices
|
|
// minUniformBufferOffsetAlignment is typically 256 bytes
|
|
const uint32_t UBO_SLOT_SIZE = 256; // Safe alignment for all GPUs
|
|
const uint32_t UBO_TOTAL_SIZE = 6 * UBO_SLOT_SIZE;
|
|
|
|
vk::Device device = bufferManager->getDevice();
|
|
auto* memManager = getMemoryManager();
|
|
|
|
vk::BufferCreateInfo uboBufInfo;
|
|
uboBufInfo.size = UBO_TOTAL_SIZE;
|
|
uboBufInfo.usage = vk::BufferUsageFlagBits::eUniformBuffer;
|
|
uboBufInfo.sharingMode = vk::SharingMode::eExclusive;
|
|
|
|
vk::Buffer faceUBO;
|
|
VulkanAllocation faceUBOAlloc;
|
|
try {
|
|
faceUBO = device.createBuffer(uboBufInfo);
|
|
} catch (const vk::SystemError& e) {
|
|
nprintf(("vulkan", "vulkan_calculate_irrmap: Failed to create face UBO: %s\n", e.what()));
|
|
return;
|
|
}
|
|
|
|
if (!memManager->allocateBufferMemory(faceUBO, MemoryUsage::CpuToGpu, faceUBOAlloc)) {
|
|
device.destroyBuffer(faceUBO);
|
|
return;
|
|
}
|
|
|
|
// Map and write face indices
|
|
auto* mapped = static_cast<uint8_t*>(memManager->mapMemory(faceUBOAlloc));
|
|
if (!mapped) {
|
|
device.destroyBuffer(faceUBO);
|
|
memManager->freeAllocation(faceUBOAlloc);
|
|
return;
|
|
}
|
|
memset(mapped, 0, UBO_TOTAL_SIZE);
|
|
for (int i = 0; i < 6; i++) {
|
|
*reinterpret_cast<int*>(mapped + (i * UBO_SLOT_SIZE)) = i;
|
|
}
|
|
// Flush before unmap — CpuToGpu memory is not guaranteed coherent, so without
|
|
// this the GPU could sample stale face indices. (No-op on coherent memory.)
|
|
memManager->flushMemory(faceUBOAlloc, 0, UBO_TOTAL_SIZE);
|
|
memManager->unmapMemory(faceUBOAlloc);
|
|
|
|
// This buffer is recreated per call (and queued for deletion at the end).
|
|
// vulkan_calculate_irrmap runs only on env-map (re)generation, not per frame,
|
|
// so the cold allocation isn't worth caching as renderer-lifetime state — and a
|
|
// function-lifetime static VkBuffer would dangle past device destruction.
|
|
|
|
vk::Extent2D irrExtent(irrTs->width, irrTs->height);
|
|
|
|
for (size_t face = 0; face < irrTs->cubeFaceFramebuffers.size(); face++) {
|
|
vk::Framebuffer fb = irrTs->cubeFaceFramebuffers[face];
|
|
if (!fb) {
|
|
continue;
|
|
}
|
|
|
|
// Begin render pass for this face (loadOp=eClear, finalLayout=eShaderReadOnlyOptimal)
|
|
vk::RenderPassBeginInfo rpBegin;
|
|
rpBegin.renderPass = irrTs->renderPass;
|
|
rpBegin.framebuffer = fb;
|
|
rpBegin.renderArea.offset = vk::Offset2D(0, 0);
|
|
rpBegin.renderArea.extent = irrExtent;
|
|
|
|
vk::ClearValue clearValue;
|
|
clearValue.color.setFloat32({0.0f, 0.0f, 0.0f, 1.0f});
|
|
rpBegin.clearValueCount = 1;
|
|
rpBegin.pClearValues = &clearValue;
|
|
|
|
cmd.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
|
|
cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
|
|
|
|
// Set viewport and scissor
|
|
vk::Viewport viewport;
|
|
viewport.x = 0.0f;
|
|
viewport.y = 0.0f;
|
|
viewport.width = static_cast<float>(irrExtent.width);
|
|
viewport.height = static_cast<float>(irrExtent.height);
|
|
viewport.minDepth = 0.0f;
|
|
viewport.maxDepth = 1.0f;
|
|
cmd.setViewport(0, viewport);
|
|
|
|
vk::Rect2D scissor;
|
|
scissor.offset = vk::Offset2D(0, 0);
|
|
scissor.extent = irrExtent;
|
|
cmd.setScissor(0, scissor);
|
|
|
|
DescriptorWriter writer;
|
|
writer.reset(device, descManager->getFallbacks());
|
|
|
|
// Set 0: Global (all fallback)
|
|
vk::DescriptorSet globalSet = descManager->allocateFrameSet(DescriptorSetIndex::Global);
|
|
Assert(globalSet);
|
|
writer.writeSet(globalSet, VulkanDescriptorManager::getSetTemplate(DescriptorSetIndex::Global));
|
|
|
|
// Set 1: Material (envmap cubemap at element 0 of texture array)
|
|
vk::DescriptorSet materialSet = descManager->allocateFrameSet(DescriptorSetIndex::Material);
|
|
Assert(materialSet);
|
|
writer.writeSet(materialSet, VulkanDescriptorManager::getSetTemplate(DescriptorSetIndex::Material));
|
|
{
|
|
std::array<vk::DescriptorImageInfo, VulkanDescriptorManager::MAX_TEXTURE_BINDINGS> texImages;
|
|
texImages.fill(descManager->getFallbacks().texture2D);
|
|
texImages[0].imageView = envmapView;
|
|
writer.setImageArray(MaterialBinding::TextureArray, texImages);
|
|
}
|
|
|
|
// Set 2: PerDraw (face UBO at binding 0)
|
|
vk::DescriptorSet perDrawSet = descManager->allocateFrameSet(DescriptorSetIndex::PerDraw);
|
|
Assert(perDrawSet);
|
|
writer.writeSet(perDrawSet, VulkanDescriptorManager::getSetTemplate(DescriptorSetIndex::PerDraw));
|
|
writer.setBuffer(PerDrawBinding::GenericData, {faceUBO,
|
|
static_cast<vk::DeviceSize>(face) * UBO_SLOT_SIZE, UBO_SLOT_SIZE});
|
|
writer.flush();
|
|
|
|
// Bind all descriptor sets
|
|
cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout,
|
|
0, {globalSet, materialSet, perDrawSet}, {});
|
|
|
|
// Draw fullscreen triangle
|
|
cmd.draw(3, 1, 0, 0);
|
|
cmd.endRenderPass();
|
|
}
|
|
|
|
// Queue UBO for deferred destruction (safe to destroy after frame submission)
|
|
getDeletionQueue()->queueBuffer(faceUBO, faceUBOAlloc);
|
|
|
|
// This path renders each face directly rather than going through
|
|
// bm_set_render_target()/endRenderTarget(), so the mip chain that
|
|
// deferred-f.sdr's implicit-LOD `texture(sIrrmap, ...)` can reach
|
|
// (high-frequency normals/silhouettes push the derivative-based LOD up)
|
|
// would otherwise be left uninitialized above mip 0.
|
|
if (irrTs->mipLevels > 1) {
|
|
ImageBarrier2 barrier;
|
|
barrier.image = irrTs->image;
|
|
barrier.levelCount = 1;
|
|
barrier.layerCount = 6;
|
|
barrier.oldLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
|
|
barrier.newLayout = vk::ImageLayout::eTransferSrcOptimal;
|
|
barrier.srcStage = vk::PipelineStageFlagBits2::eColorAttachmentOutput;
|
|
barrier.srcAccess = vk::AccessFlagBits2::eColorAttachmentWrite;
|
|
barrier.dstStage = vk::PipelineStageFlagBits2::eBlit;
|
|
barrier.dstAccess = vk::AccessFlagBits2::eTransferRead;
|
|
|
|
cmdImageBarrier(cmd, barrier);
|
|
|
|
vulkan_generate_mipmap_chain(cmd, irrTs->image, irrTs->width, irrTs->height, irrTs->mipLevels, 6);
|
|
}
|
|
|
|
// Resume the swap chain pass (irrmap is always called before scene rendering begins)
|
|
renderer->resumeSwapChainPass();
|
|
|
|
nprintf(("vulkan", "vulkan_calculate_irrmap: Generated irradiance cubemap (%ux%u)\n", irrTs->width, irrTs->height));
|
|
}
|
|
|
|
} // namespace graphics::vulkan
|
|
|