Files
fs2open.github.com/code/lighting/lighting.cpp
T
b26b9cf743 Add Vulkan rendering backend, with HDR10 output and raytraced shadows (#7554)
* 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]>
2026-07-21 16:58:21 +00:00

727 lines
19 KiB
C++

/*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
#include "cmdline/cmdline.h"
#include "debugconsole/console.h"
#include "globalincs/systemvars.h"
#include "graphics/2d.h"
#include "graphics/color.h"
#include "graphics/light.h"
#include "lighting/lighting.h"
#include "lighting/lighting_profiles.h"
#include "math/vecmat.h"
#include "model/modelrender.h"
#include "render/3d.h"
#include "options/Option.h"
SCP_vector<light> Lights;
SCP_vector<light> Static_light;
static int Light_in_shadow = 0; // If true, this means we're in a shadow
#define MIN_LIGHT 0.03f // When light drops below this level, ignore it. Must be non-zero! (1/32)
static int Lighting_off = 0;
// For lighting values, 0.75 is full intensity
#define AMBIENT_LIGHT_DEFAULT 0.15f //0.10f
#define REFLECTIVE_LIGHT_DEFAULT 0.75f //0.90f
static float Ambient_light = AMBIENT_LIGHT_DEFAULT;
static float Reflective_light = REFLECTIVE_LIGHT_DEFAULT;
int Lighting_flag = 1;
int Num_lights = 0;
lighting_mode Lighting_mode = lighting_mode::NORMAL;
DCF(light,"Changes lighting parameters")
{
SCP_string arg_str;
float val_f;
bool val_b;
if (dc_optional_string_either("help", "--help")) {
dc_printf( "Usage: light keyword\nWhere keyword can be in the following forms:\n" );
dc_printf( "light on|off Turns all lighting on/off\n" );
dc_printf( "light default Resets lighting to all default values\n" );
dc_printf( "light ambient X Where X is the ambient light between 0 and 1.0\n" );
dc_printf( "light reflect X Where X is the material reflectiveness between 0 and 1.0\n" );
dc_printf( "light dynamic [bool] Toggles dynamic lighting on/off\n" );
return;
}
if (dc_optional_string_either("status", "--status") || dc_optional_string_either("?", "--?")) {
dc_printf( "Ambient light is set to %.2f\n", Ambient_light );
dc_printf( "Reflective light is set to %.2f\n", Reflective_light );
dc_printf( "Dynamic lighting is: %s\n", (Lighting_flag?"on":"off") );
return;
}
if (dc_optional_string("ambient")) {
dc_stuff_float(&val_f);
if ((val_f < 0.0f) || (val_f > 1.0f)) {
dc_printf(" Error: ambient value must be between 0.0 and 1.0\n");
} else {
Ambient_light = val_f;
}
} else if (dc_optional_string("reflect")) {
dc_stuff_float(&val_f);
if ( (val_f < 0.0f) || (val_f > 1.0f)) {
dc_printf(" Error: reflect value mus be between 0.0 and 1.0\n");
} else {
Reflective_light = val_f;
}
} else if (dc_optional_string("default")) {
Ambient_light = AMBIENT_LIGHT_DEFAULT;
Reflective_light = REFLECTIVE_LIGHT_DEFAULT;
Lighting_flag = 0;
} else if (dc_optional_string("dynamic")) {
dc_stuff_boolean(&val_b);
Lighting_flag = val_b;
} else if(dc_maybe_stuff_boolean(&Lighting_off)) {
Lighting_off = !Lighting_off;
} else {
dc_stuff_string_white(arg_str);
dc_printf("Error: Unknown argument '%s'\n", arg_str.c_str());
}
}
// used by In-Game Options menu
static bool DeferredLightingEnabled = true;
static void parse_deferred_lighting_func()
{
bool enabled;
stuff_boolean(&enabled);
DeferredLightingEnabled = enabled;
}
// coverity[GLOBAL_INIT_ORDER] -- safe; OptionBuilder::finish() uses Meyers singleton
static auto DeferredLightingOption = options::OptionBuilder<bool>("Graphics.DeferredLighting",
std::pair<const char*, int>{"Deferred Lighting", 1782},
std::pair<const char*, int>{"Enables or disables deferred lighting", 1783})
.category(std::make_pair("Graphics", 1825))
.default_func([]() { return DeferredLightingEnabled;})
.level(options::ExpertLevel::Advanced)
.bind_to_once(&DeferredLightingEnabled)
.importance(60)
.parser(parse_deferred_lighting_func)
.finish();
static bool DeferredCockpitLightingEnabled = true;
static void parse_deferredcockpit_lighting_func()
{
bool enabled;
stuff_boolean(&enabled);
DeferredCockpitLightingEnabled = enabled;
}
// coverity[GLOBAL_INIT_ORDER] -- safe; OptionBuilder::finish() uses Meyers singleton
static auto DeferredCockpitLightingOption = options::OptionBuilder<bool>("Graphics.DeferredCockpitLighting",
std::pair<const char*, int>{"Deferred Cockpit Lighting", 1864},
std::pair<const char*, int>{"Enables or disables deferred lighting in cockpits (requires Deferred Lighting to be enabled)", 1865})
.category(std::make_pair("Graphics", 1825))
.default_func([]() { return DeferredCockpitLightingEnabled;})
.level(options::ExpertLevel::Advanced)
.bind_to_once(&DeferredCockpitLightingEnabled)
.importance(60)
.parser(parse_deferredcockpit_lighting_func)
.finish();
bool light_deferred_enabled()
{
if (Using_in_game_options) {
static bool isToggledOn = DeferredLightingOption->getValue();
// This used to get the value of the option object itself,
// however that is not a free operation and changing it requires a restart anyway
// if the restart requirement is lifted care should be taken to cache this value
// and never look it up more than once a frame
// otherwise the performance footprint is measurable enough to worry about.
return isToggledOn;
} else {
return !Cmdline_no_deferred_lighting;
}
}
bool light_deferredcockpit_enabled()
{
if (Using_in_game_options) {
static bool isToggledOn = DeferredCockpitLightingOption->getValue();
// Note, the above comment within light_deferred_enabled()
// about caching the value also applies here.
return isToggledOn;
} else {
return Cmdline_deferred_lighting_cockpit;
}
}
void light_reset()
{
Static_light.clear();
Lights.clear();
Num_lights = 0;
}
extern vec3d Object_position;
/**
* Rotates the light into the current frame of reference
*
* @param l Light to rotate
*/
static void light_rotate(light * l)
{
switch( l->type ) {
case Light_Type::Directional:
// Rotate the light direction into local coodinates
vm_vec_rotate(&l->local_vec, &l->vec, &Light_matrix );
break;
case Light_Type::Point: {
vec3d tempv;
// Rotate the point into local coordinates
vm_vec_sub(&tempv, &l->vec, &Light_base );
vm_vec_rotate(&l->local_vec, &tempv, &Light_matrix );
}
break;
case Light_Type::Tube:{
vec3d tempv;
// Rotate the point into local coordinates
vm_vec_sub(&tempv, &l->vec, &Light_base );
vm_vec_rotate(&l->local_vec, &tempv, &Light_matrix );
// Rotate the point into local coordinates
vm_vec_sub(&tempv, &l->vec2, &Light_base );
vm_vec_rotate(&l->local_vec2, &tempv, &Light_matrix );
}
break;
case Light_Type::Cone:
break;
default:
Int3(); // Invalid light type
}
}
void light_add_directional(const vec3d* dir, int sun_index, bool no_glare, const hdr_color* new_color, const float source_radius)
{
Assert(new_color!= nullptr);
light_add_directional(dir, sun_index, no_glare, new_color->i(), new_color->r(), new_color->g(), new_color->b(), source_radius);
}
namespace ltp=lighting_profiles;
void light_add_directional(const vec3d *dir, int sun_index, bool no_glare, float intensity, float r, float g, float b, const float source_radius)
{
if (Lighting_off) return;
Num_lights++;
light l;
l.type = Light_Type::Directional;
l.flags = no_glare ? (LF_DEFAULT | LF_NO_GLARE) : LF_DEFAULT;
l.sun_index = sun_index;
vm_vec_copy_scale( &l.vec, dir, -1.0f );
l.r = r;
l.g = g;
l.b = b;
//configurable global tuning of light qualities
auto lp = ltp::current();
l.intensity = lp->overall_brightness.handle(lp->directional_light_brightness.handle(intensity));
l.rada = 0.0f;
l.radb = 0.0f;
l.rada_squared = l.rada*l.rada;
l.radb_squared = l.radb*l.radb;
l.instance = Num_lights-1;
l.source_radius = MAX(0.0f,source_radius);
Lights.push_back(l);
Static_light.push_back(l);
}
void light_add_point(const vec3d* pos, float r1, float r2, const hdr_color* new_color, float source_radius, bool no_rt_shadow)
{
Assert(new_color!= nullptr);
light_add_point(pos, r1, r2, new_color->i(), new_color->r(), new_color->g(), new_color->b(), source_radius, no_rt_shadow);
}
void light_add_point(const vec3d *pos, float r1, float r2, float intensity, float r, float g, float b, const float source_radius, bool no_rt_shadow)
{
Assertion( r1 > 0.0f, "Invalid radius r1 specified for light: %f. Radius must be > 0.0f. Examine stack trace to determine culprit.\n", r1 );
Assertion( r2 > 0.0f, "Invalid radius r2 specified for light: %f. Radius must be > 0.0f. Examine stack trace to determine culprit.\n", r2 );
if (Lighting_off) return;
if (!Lighting_flag) return;
light l;
Num_lights++;
l.type = Light_Type::Point;
l.flags = no_rt_shadow ? (LF_DEFAULT | LF_NO_RT_SHADOW) : LF_DEFAULT;
l.sun_index = -1;
l.vec = *pos;
l.r = r;
l.g = g;
l.b = b;
//configurable global tuning of light qualities
auto lp = ltp::current();
l.intensity = lp->overall_brightness.handle(lp->point_light_brightness.handle(intensity));
l.rada = lp->point_light_radius.handle(r1);
l.radb = lp->point_light_radius.handle(r2);
l.rada_squared = l.rada*l.rada;
l.radb_squared = l.radb*l.radb;
l.instance = Num_lights-1;
l.source_radius = MAX(0.0f,source_radius);
Lights.push_back(l);
}
void light_add_tube(const vec3d* p0, const vec3d* p1, float r1, float r2, const hdr_color* new_color, const float source_radius)
{
Assert(new_color!= nullptr);
light_add_tube(p0, p1, r1, r2, new_color->i(), new_color->r(), new_color->g(), new_color->b(), source_radius);
}
void light_add_tube(const vec3d *p0, const vec3d *p1, float r1, float r2, float intensity, float r, float g, float b, const float source_radius)
{
Assertion(r1 > 0.0f, "Invalid radius r1 specified for light: %f. Radius must be > 0.0f. Examine stack trace to determine culprit.\n", r1);
Assertion(r2 > 0.0f, "Invalid radius r2 specified for light: %f. Radius must be > 0.0f. Examine stack trace to determine culprit.\n", r2);
if (Lighting_off) return;
if (!Lighting_flag) return;
light l;
Num_lights++;
l.type = Light_Type::Tube;
l.flags = LF_DEFAULT;
l.sun_index = -1;
l.vec = *p0;
l.vec2 = *p1;
l.r = r;
l.g = g;
l.b = b;
//configurable global tuning of light qualities
auto lp = ltp::current();
l.intensity = lp->overall_brightness.handle(lp->tube_light_brightness.handle(intensity));
l.rada = lp->tube_light_radius.handle(r1);
l.radb = lp->tube_light_radius.handle(r2);
l.rada_squared = l.rada*l.rada;
l.radb_squared = l.radb*l.radb;
l.instance = Num_lights-1;
l.source_radius = MAX(0.0f,source_radius);
l.local_vec = vmd_zero_vector;
l.local_vec2 = vmd_zero_vector;
Lights.push_back(l);
}
void light_rotate_all()
{
if ( Lighting_off ) return;
for (auto& l : Lights)
light_rotate(&l);
}
/**
* Return the # of global light sources
*/
int light_get_global_count()
{
return static_cast<int>(Static_light.size());
}
/**
* Fills direction of global light source N in pos.
*
* @param pos Position
* @param n Light source
*
* Returns false if there is no global light.
*/
bool light_get_global_dir(vec3d *pos, int n)
{
if (!SCP_vector_inbounds(Static_light, n)) {
return false;
}
if (pos) {
*pos = Static_light[n].vec;
vm_vec_scale( pos, -1.0f );
}
return true;
}
bool light_has_glare(int n)
{
if (!SCP_vector_inbounds(Static_light, n)) {
return false;
}
return (Static_light[n].flags & LF_NO_GLARE) == 0;
}
int light_get_sun_index(int n)
{
if (!SCP_vector_inbounds(Static_light, n)) {
return -1;
}
return Static_light[n].sun_index;
}
int light_find_for_sun(int sun_index)
{
for (size_t n = 0; n < Static_light.size(); ++n)
if (Static_light[n].sun_index == sun_index)
return static_cast<int>(n);
return -1;
}
void light_apply_rgb( ubyte *param_r, ubyte *param_g, ubyte *param_b, const vec3d *pos, const vec3d *norm, float static_light_level )
{
int idx;
float rval, gval, bval;
if ( Lighting_off ) {
*param_r = 255;
*param_g = 255;
*param_b = 255;
return;
}
// Factor in ambient light
rval = Ambient_light;
gval = Ambient_light;
bval = Ambient_light;
// Factor in light from sun if there is one
if ( !Light_in_shadow ){
// apply all sun lights
for (idx = 0; idx < (int)Static_light.size(); idx++) {
float ltmp;
// calculate light from surface normal
ltmp = -vm_vec_dot(&Static_light[idx].local_vec, norm )*Static_light[idx].intensity*Reflective_light; // reflective light
if ( ltmp > 0.0f ) {
rval += Static_light[idx].r * ltmp;
gval += Static_light[idx].g * ltmp;
bval += Static_light[idx].b * ltmp;
}
}
}
// At this point, l must be between 0 and 0.75 (0.75-1.0 is for dynamic light only)
CLAMP(rval, 0.0f, 0.75f);
CLAMP(gval, 0.0f, 0.75f);
CLAMP(bval, 0.0f, 0.75f);
rval *= static_light_level;
gval *= static_light_level;
bval *= static_light_level;
vec3d to_light;
float dot, dist;
vec3d temp;
for (const auto& l : Lights) {
dist = -1.0f;
switch(l.type){
// point lights
case Light_Type::Point:
vm_vec_sub( &to_light, &l.local_vec, pos );
break;
// tube lights
case Light_Type::Tube:
if(vm_vec_dist_to_line(pos, &l.local_vec, &l.local_vec2, &temp, &dist) != 0){
continue;
}
vm_vec_sub(&to_light, &temp, pos);
dist *= dist; // since we use radius squared
break;
case Light_Type::Directional:
continue;
case Light_Type::Cone:
continue;
// others. BAD
default:
Error("Unknown light type in light_apply_rgb!\n");
continue;
}
dot = vm_vec_dot(&to_light, norm);
// dot = 1.0f;
if ( dot > 0.0f ) {
// indicating that we already calculated the distance (vm_vec_dist_to_line(...) does this for us)
if(dist < 0.0f){
dist = vm_vec_mag_squared(&to_light);
}
if ( dist < l.rada_squared ) {
float ratio;
ratio = l.intensity*dot;
ratio *= 0.25f;
rval += l.r*ratio;
gval += l.g*ratio;
bval += l.b*ratio;
} else if ( dist < l.radb_squared ) {
float ratio;
// dist from 0 to
float nnum = dist - l.rada_squared;
float dden = l.radb_squared - l.rada_squared;
ratio = (1.0f - nnum / dden)*dot*l.intensity;
ratio *= 0.25f;
rval += l.r*ratio;
gval += l.g*ratio;
bval += l.b*ratio;
}
}
}
float m = rval;
if ( gval > m ) m = gval;
if ( bval > m ) m = bval;
if ( m > 1.0f ) {
float im = 1.0f / m;
rval *= im;
gval *= im;
bval *= im;
}
CLAMP(rval, 0.0f, 1.0f);
CLAMP(gval, 0.0f, 1.0f);
CLAMP(bval, 0.0f, 1.0f);
*param_r = ubyte(fl2i(rval*255.0f));
*param_g = ubyte(fl2i(gval*255.0f));
*param_b = ubyte(fl2i(bval*255.0f));
}
void light_add_cone(const vec3d *pos, const vec3d *dir, float angle, float inner_angle, bool dual_cone, float r1, float r2, const hdr_color* new_color, const float source_radius)
{
Assert(new_color!= nullptr);
light_add_cone(pos, dir, angle, inner_angle, dual_cone, r1, r2, new_color->i(), new_color->r(), new_color->g(), new_color->b(), source_radius);
}
void light_add_cone(const vec3d *pos, const vec3d *dir, float angle, float inner_angle, bool dual_cone, float r1, float r2, float intensity, float r, float g, float b, const float source_radius )
{
Assertion( r1 > 0.0f, "Invalid radius r1 specified for light: %f. Radius must be > 0.0f. Examine stack trace to determine culprit.\n", r1 );
Assertion( r2 > 0.0f, "Invalid radius r2 specified for light: %f. Radius must be > 0.0f. Examine stack trace to determine culprit.\n", r2 );
if ( Lighting_off ) return;
if (!Lighting_flag) return;
light l;
Num_lights++;
l.type = Light_Type::Cone;
l.flags = dual_cone ? (LF_DEFAULT | LF_DUAL_CONE) : LF_DEFAULT;
l.sun_index = -1;
l.vec = *pos;
l.vec2= *dir;
l.cone_angle = angle;
l.cone_inner_angle = inner_angle;
l.r = r;
l.g = g;
l.b = b;
auto lp = ltp::current();
l.intensity = lp->overall_brightness.handle(lp->cone_light_brightness.handle(intensity));
l.rada = lp->cone_light_radius.handle(r1);
l.radb = lp->cone_light_radius.handle(r2);
l.rada_squared = l.rada*l.rada;
l.radb_squared = l.radb*l.radb;
l.instance = Num_lights-1;
l.source_radius = MAX(0.0f,source_radius);
Lights.push_back(l);
}
bool light_compare_by_type(const light &a, const light &b)
{
return a.type < b.type;
}
void scene_lights::addLight(const light *light_ptr)
{
Assert(light_ptr != NULL);
AllLights.push_back(*light_ptr);
if ( light_ptr->type == Light_Type::Directional ) {
StaticLightIndices.push_back(AllLights.size() - 1);
}
}
void scene_lights::setLightFilter(const vec3d *pos, float rad)
{
size_t i = 0;
// clear out current filtered lights
FilteredLights.clear();
for ( auto& l : AllLights ) {
switch ( l.type ) {
case Light_Type::Directional:
++i;
continue;
case Light_Type::Point: {
vec3d to_light;
float dist_squared, max_dist_squared;
vm_vec_sub( &to_light, &l.vec, pos );
dist_squared = vm_vec_mag_squared(&to_light);
max_dist_squared = l.radb+rad;
max_dist_squared *= max_dist_squared;
if ( dist_squared < max_dist_squared ) {
FilteredLights.push_back(i);
}
}
break;
case Light_Type::Tube: {
vec3d nearest;
float dist_squared, max_dist_squared;
vm_vec_dist_squared_to_line(pos,&l.vec,&l.vec2,&nearest,&dist_squared);
max_dist_squared = l.radb+rad;
max_dist_squared *= max_dist_squared;
if ( dist_squared < max_dist_squared ) {
FilteredLights.push_back(i);
}
}
break;
case Light_Type::Cone:
break;
default:
break;
}
++i;
}
}
light_indexing_info scene_lights::bufferLights()
{
size_t i;
light_indexing_info light_info;
light_info.index_start = 0;
light_info.num_lights = 0;
// make sure that there are lights to bind?
if ( FilteredLights.empty() ) {
return light_info;
}
light_info.index_start = BufferedLights.size();
for ( i = 0; i < FilteredLights.size(); ++i ) {
BufferedLights.push_back(FilteredLights[i]);
}
light_info.num_lights = FilteredLights.size();
return light_info;
}
void scene_lights::resetLightState()
{
current_light_index = static_cast<size_t>(-1);
current_num_lights = static_cast<size_t>(-1);
}
bool scene_lights::setLights(const light_indexing_info *info)
{
if ( info->index_start == current_light_index && info->num_lights == current_num_lights ) {
// don't need to set new lights since the ones requested to be set are currently set
return false;
}
current_light_index = info->index_start;
current_num_lights = info->num_lights;
gr_reset_lighting();
for ( size_t i = 0; i < StaticLightIndices.size(); ++i) {
auto light_index = StaticLightIndices[i];
gr_set_light( &AllLights[light_index] );
}
extern bool Deferred_lighting;
if ( Deferred_lighting ) {
gr_set_lighting();
return false;
}
auto index_start = info->index_start;
auto num_lights = info->num_lights;
// check if there are any lights to actually set
if ( num_lights <= 0 ) {
gr_set_lighting();
return false;
}
// we definitely shouldn't be exceeding the number of buffered lights
Assert(index_start + num_lights <= BufferedLights.size());
for ( size_t i = 0; i < num_lights; ++i ) {
auto buffered_light_index = index_start + i;
auto light_index = BufferedLights[buffered_light_index];
gr_set_light(&AllLights[light_index]);
}
gr_set_lighting();
return true;
}