Files
fs2open.github.com/code/lighting/lighting_profiles.cpp
T
Fabian WoltermannandClaude Opus 5.5 7f3e5fae60 Softer shadows in raytracing and RTAO (#7695)
* Add RTAO and unify raytraced/shadow-mapped shadow softness on sun angular size

Raytraced shadow penumbras needed a hand-authored $SunAngularSize: in
stars.tbl, which no shipped content sets -- so in practice nothing ever
got a penumbra, and the shadow-mapped path's $Shadow Smoothness Factor:
had no relation to it at all. Derive a size from the sun bitmap instead
and drive both methods from the same number.

g3_render_rect_screen_aligned_2d() sizes the sun quad so its rad is the
tangent of the half-angle it subtends, making tan(angular radius) equal
to 0.05 * the mission's +Scale: * the emitting disc's fraction of the
bitmap. That fraction is the area of the pixels at or above 90% of the
brightest one, converted to an equivalent radius. Across 90 sun bitmaps
from retail, the MediaVPs, Blue Planet and BtA it lands at a median of
0.261 (retail's chunkier art at 0.487), and the threshold acts as a
constant factor rather than a per-bitmap judgement call -- Spearman rho
0.96 between a 90% and a 50% cutoff.

Taken literally that yields suns 3.9-8.5x Sol's apparent diameter once
+Scale: is folded in (median 1.55, up to 5.0 in retail's own missions),
so the measurement is scaled by 0.25 and clamped to 1.5 degrees, putting
typical content near Sol. Derivation is the default: $SunAngularSize: 0
asks for hard shadows, an explicit value still wins, and missions can
also set +AngularSize: on an individual sun to override both, with FRED
and QtFRED UI (validation and fallback included) to author it. Bitmaps
that can't be read -- and the deliberately blank sun bitmaps mods ship
to get a light source with no visible disc -- fall back to hard shadows
rather than to the widest possible penumbra.

That angular size now sizes the raytraced penumbra cone directly
(traceShadowRayCone() in shadows.sdr), with sample count following the
same Shadow_quality tier that picks the shadow map's resolution (1 ray
at Low, up to 16 at Ultra) rather than being a separate setting. The
shadow-mapped path's tabled smoothness values were tuned by eye against
Sol-sized retail/MediaVPs art, so shadow_smoothness_scale() in
shadows.cpp scales them by the active sun's size relative to Sol,
clamped to what the shadow map can represent (shadow_clamp_smoothness()).
The two methods still disagree about occluder distance -- the raytracer
uses the real one, the shadow map's tabled values stand in for a blocker
distance pinned to the cascade's own extent -- so RT_SHADOW_SUN_SIZE_CALIBRATION
in shadows.sdr is a constant factor that makes a given $SunAngularSize:
read as roughly the same softness either way; it's the number to revisit
if the shadow map ever grows a real blocker search.

Also adds RTAO (raytraced ambient occlusion) sharing the same TLAS as
the shadow rays, with lighting-profile-driven radius/strength, and lab
controls for RT shadow quality (Low/High), the local light cap, RT
shadow samples, RTAO, and an angular-size override for comparing both
shadow methods against the same sun. All are safe to change live: they
only gate which lights are picked as shadow casters or scale existing
uniforms while filling the per-frame light data.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Add shadow contact hardening via PCSS blocker search

The shadow-mapped path's penumbra width was a fixed per-cascade value
(shadow_smoothness_scale()'s ceiling), so every occluder blurred its
shadow by the same amount regardless of how close it actually was to
the receiver -- unlike the raytraced path, which gets that for free
from traceShadowRayCone()'s real occluder distance. Close that gap
with PCSS: search nearby texels for occluders, then scale the filter
radius by how far away they were.

The blocker search (pcssBlockerSearch() in shadows.sdr) needs raw,
uncompared depth reads, which the existing PCF sampler can't do -- it's
bound with a compare mode for the hardware shadow-compare instructions
the filtered sampling itself relies on. So shadow maps now get a second
sampler, shadow_map_raw, bound to the same texture with compare mode
off; on OpenGL that needs a second sampler object and GL 3.3
(shadow_contact_hardening_supported()), Vulkan can always bind it.
Where the raw sampler isn't available, or the new Graphics.ShadowContactHardening
option is off, shadows_start_render() sets Shadow_penumbra_scale[cascade]
to -1 as a sentinel and pcssPenumbraRadius() (shadows.sdr) falls straight
back to the fixed radius, bit-identical to the pre-contact-hardening
behavior and skipping the extra texture reads.

When it is on, shadows_start_render() computes each cascade's penumbra
scale from its own frustum extents and the sun's tanθ; the shader turns
that plus the blocker search's average depth into a per-pixel radius,
clamped to [1 texel, the old fixed ceiling]. A blocker search that finds
nothing doesn't fall back to "no shadow" -- a sparse 8-tap search can
miss a thin occluder, so it instead runs the full filter at the hardest
(1-texel) radius, trading a touch of extra blur for not popping a real
shadow to nothing.

Drops RT_SHADOW_SUN_SIZE_CALIBRATION accordingly: that constant existed
only to fake a blocker-distance-driven penumbra on the shadow-mapped path
by pre-scaling the raytraced cone to match it, and the shadow-mapped path
now has a real blocker search of its own, so the raytraced cone goes back
to its physically correct size.

* Apply review feedback on softer shadows

- Bind the GL raw-depth sampler on unit 11 in the deferred pass and
  unbind it after the pass.
- Enable RTAO only when shadows are on, and remove the RTAO option when
  ray tracing is not supported.
- Use every second Poisson tap in the PCSS blocker search.
- Use TLAS-relative ray origins for RTAO.
- Gate +AngularSize: at version 27.0.
- Measure an .eff sun from its first frame, and skip the measurement
  when shadows are off.
- Guard the GL 3.3 sampler check for GLES builds.
- Restore the lab session overrides when the lab closes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* apply review suggestions

* Fix review findings and build the ray-tracing structure once per frame

Build the ray-tracing TLAS one time in each frame, in
vulkan_scene_texture_begin(), where no render pass is open. Remove the
TLAS build from the shadow pass and the second build in
vulkan_deferred_lighting_finish(). Remove gr_build_shadow_tlas.

Move the RTAO inputs and the deferred ray inputs (ray origin, cull mask,
bias) into globalDeferredData. Write them in each frame with
shadows_fill_deferred_global_data(). RTAO now works with shadows off and
in frames with no sun.

Other fixes from the review:
- Add the sampler2DArray precision to the OpenGL ES shader blocks.
- Declare shadowCascadeParams one time, in shadow_cascade_params.sdr.
- Use one ray function for traceShadowRay() and traceShadowRayCone().
- Restore the shadow method and the raytraced light limits when the lab
  closes.
- Limit the sun angular size to 90 degrees in stars.tbl and in missions.
- Make the OpenGL sampler part of the texture unit binding, and name the
  raw shadow map unit SHADOW_MAP_RAW_TEXTURE_UNIT.
- Measure the sun disc when the sun bitmap loads, not in the draw path.
- Use starfield_copy_entry_to_instance() in stars_set_data().
- Share the sun quad radius as SUN_QUAD_RADIUS.
- Correct the sun size tooltips and comments: the size affects both
  shadow methods.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
2026-11-12 21:05:22 +01:00

530 lines
15 KiB
C++

// clang-format on
#include "lighting/lighting_profiles.h"
#include "globalincs/adjustment.h"
#include "globalincs/pstypes.h"
#include "globalincs/safe_strings.h"
#include "globalincs/vmallocator.h"
#include "cmdline/cmdline.h"
#include "def_files/def_files.h"
#include "graphics/2d.h"
#include "io/timer.h"
#include "lighting/lighting.h"
#include "osapi/dialogs.h"
#include "parse/parsehi.h"
#include "parse/parselo.h"
namespace lighting_profiles {
typedef int profile_index;
//*************************************************
// profile management
//*************************************************
//TIMESTAMP switch_start;
//TIMESTAMP switch_end;
profile _current;
SCP_unordered_map<SCP_string, profile> Profiles;
SCP_string default_profile_name;
SCP_string non_mission_profile_name;
const SCP_string &default_name()
{
return default_profile_name;
}
const SCP_string& non_mission_name()
{
return non_mission_profile_name;
}
const profile* current()
{
return &_current;
}
SCP_vector<SCP_string> list_profiles()
{
SCP_vector<SCP_string> r;
for (auto& p : Profiles) {
r.push_back(p.second.name);
}
return r;
}
void switch_to(const SCP_string& name)
{
if (Profiles.find(name) == Profiles.end()) {
Warning(LOCATION, "Attempted to switch to unknown lighting profile '%s';", name.c_str());
return;
}
_current = Profiles[name];
}
void switch_to_non_mission()
{
switch_to(non_mission_profile_name);
}
void update_current_profile()
{
// processes any change-overs and transitions
}
//*************************************************
// General interface
//*************************************************
TonemapperAlgorithm current_tonemapper()
{
// HDR10 output has no use for the SDR tone curves -- the shader's HdrScene
// case is the only one that produces valid extended-range output for it.
// Enforce that here, at the single point everything (Vulkan, OpenGL, the
// Lab UI) reads the active tonemapper from, rather than mutating the
// stored profile value.
if (Gr_hdr_output_active) {
return TonemapperAlgorithm::HdrScene;
}
return _current.tonemapper;
}
const piecewise_power_curve_values& current_piecewise_values()
{
return _current.ppc_values;
}
float current_exposure()
{
return _current.exposure;
}
float current_rtao_radius()
{
return _current.rtao_radius;
}
float current_rtao_strength()
{
return _current.rtao_strength;
}
piecewise_power_curve_intermediates current_piecewise_intermediates()
{
return calc_intermediates(_current.ppc_values);
}
piecewise_power_curve_intermediates calc_intermediates(piecewise_power_curve_values input)
{
piecewise_power_curve_intermediates ppci;
// Some safety clamping based on John Hable's implementation: https://github.com/johnhable/fw-public
CLAMP(input.toe_length, 0.0f, 1.0f);
CLAMP(input.toe_strength, 0.0f, 1.0f);
CLAMP(input.shoulder_angle, 0.0f, 1.0f);
CLAMP(input.shoulder_length, 0.0f, 1.0f);
input.shoulder_strength = fmax(0.0f, input.shoulder_strength);
ppci.x0 = input.toe_length * 0.5f; // L,F,P
ppci.y0 = (1.0f - input.toe_strength) * ppci.x0; // L
float remainingY = 1.0f - ppci.y0;
float initialW = ppci.x0 + remainingY;
float y1_offset = (1.0f - input.shoulder_length) * remainingY;
ppci.x1 = ppci.x0 + y1_offset; // F,P
float y1 = ppci.y0 + y1_offset;
float extraW = exp2f(input.shoulder_length) - 1.0f;
float W = initialW + extraW;
float overshootX = (W * 2.0f) * input.shoulder_strength + (ppci.x0 - ppci.y0);
float overshootY = 0.5f * input.shoulder_angle;
ppci.toe_B = ppci.x0 / ppci.y0; // T
ppci.toe_lnA = log(ppci.y0) - ppci.toe_B * log(ppci.x0); // T
float sh_x0 = (1.0f + overshootX) - ppci.x1;
float sh_y0 = (1.0f + overshootY) - y1;
ppci.sh_B = sh_x0 / sh_y0; // S
ppci.sh_lnA = log(sh_y0) - ppci.sh_B * log(sh_x0); // S
ppci.sh_offsetX = 1.0f + overshootX; // F,P,S
ppci.sh_offsetY = 1.0f + overshootY; // F,P,S
return ppci;
}
TonemapperAlgorithm name_to_tonemapper(SCP_string name)
{
SCP_tolower(name);
TonemapperAlgorithm r = TonemapperAlgorithm::Invalid;
if (name == "uncharted" || name == "uncharted 2") {
r = TonemapperAlgorithm::Uncharted;
}
if (name == "linear") {
r = TonemapperAlgorithm::Linear;
}
if (name == "aces") {
r = TonemapperAlgorithm::Aces;
}
if (name == "aces approximate") {
r = TonemapperAlgorithm::Aces_Approx;
}
if (name == "cineon") {
r = TonemapperAlgorithm::Cineon;
}
if (name == "reinhard jodie") {
r = TonemapperAlgorithm::Reinhard_Jodie;
}
if (name == "reinhard extended") {
r = TonemapperAlgorithm::Reinhard_Extended;
}
if (name == "ppc" || name == "piecewise power curve") {
r = TonemapperAlgorithm::PPC;
}
if (name == "ppc rgb" || name == "piecewise power curve (rgb)") {
r = TonemapperAlgorithm::PPC_RGB;
}
return r;
}
SCP_string tonemapper_to_name(TonemapperAlgorithm tnm)
{
switch (tnm) {
case TonemapperAlgorithm::Aces:
return "ACES";
case TonemapperAlgorithm::Aces_Approx:
return "ACES Approximate";
case TonemapperAlgorithm::Cineon:
return "Cineon";
case TonemapperAlgorithm::Invalid:
return "invalid";
case TonemapperAlgorithm::Linear:
return "Linear";
case TonemapperAlgorithm::PPC:
return "Piecewise Power Curve";
case TonemapperAlgorithm::PPC_RGB:
return "Piecewise Power Curve (RGB)";
case TonemapperAlgorithm::Reinhard_Extended:
return "Reinhard Extended";
case TonemapperAlgorithm::Reinhard_Jodie:
return "Reinhard Jodie";
case TonemapperAlgorithm::Uncharted:
return "Uncharted 2";
case TonemapperAlgorithm::HdrScene:
return "HDR (Display-referred)";
default:
return "<unknown algorithm>";
}
}
//*************************************************
// Lab access
//*************************************************
void lab_set_exposure(float exIn)
{
_current.exposure = exIn;
}
void lab_set_rtao_radius(float radius)
{
_current.rtao_radius = radius;
}
void lab_set_rtao_strength(float strength)
{
_current.rtao_strength = strength;
}
void lab_set_tonemapper(TonemapperAlgorithm tnin)
{
_current.tonemapper = tnin;
}
void lab_set_ppc(const piecewise_power_curve_values &ppcin)
{
_current.ppc_values = ppcin;
}
const piecewise_power_curve_values &lab_get_ppc()
{
return _current.ppc_values;
}
float lab_get_light()
{
float r;
_current.overall_brightness.read_multiplier(&r);
return r;
}
float lab_get_ambient()
{
float r;
_current.ambient_light_brightness.read_multiplier(&r);
return r;
}
float lab_get_emissive()
{
float r;
_current.ambient_light_brightness.read_adjust(&r);
return r;
}
void lab_set_light(float in)
{
_current.overall_brightness.set_multiplier(in);
}
void lab_set_ambient(float in)
{
_current.ambient_light_brightness.set_multiplier(in);
}
void lab_set_emissive(float in)
{
_current.ambient_light_brightness.set_adjust(MAX(0.0f, in));
}
//*************************************************
// Parsing
//*************************************************
void parse_profile_section(const char* filename);
void parse_file(const char* filename);
void parse_default_section(const char* filename);
void parse_all();
void load_profiles()
{
default_profile_name = "Default Profile";
non_mission_profile_name = default_profile_name;
parse_all();
if (Profiles.find(non_mission_profile_name) == Profiles.end()) {
mprintf(("Unknown non-mission lighting profile '%s'; using '%s' instead.\n",
non_mission_profile_name.c_str(),
default_profile_name.c_str()));
non_mission_profile_name = default_profile_name;
}
switch_to(default_profile_name);
}
// The logic for grabbing all the parseable files
void parse_all()
{
Profiles[default_profile_name] = profile();
Profiles[default_profile_name].reset();
//.reset() resets name to "" which makes sense in all cases but this one
Profiles[default_profile_name].name = default_profile_name;
_current.reset();
if (cf_exists_full("lighting_profiles.tbl", CF_TYPE_TABLES)) {
mprintf(("TABLES: Starting parse of lighting profiles.tbl\n"));
parse_file("lighting_profiles.tbl");
}
mprintf(("TBM => Starting parse of lighting profiles ...\n"));
parse_modular_table("*-ltp.tbm", parse_file);
}
// Handle an individual file.
void parse_file(const char* filename)
{
try {
if (filename == nullptr) {
// All defaults currently handled by profile.reset()
return;
}
read_file_text(filename, CF_TYPE_TABLES);
reset_parse();
int index = optional_string_one_of(4, "#DEFAULT PROFILE", "#PROFILES", "#END DEFAULT PROFILE", "#END PROFILES");
while (index >= 0) {
switch (index) {
case 0: //#DEFAULT PROFILE
parse_default_section(filename);
break;
case 1: //#PROFILES
parse_profile_section(filename);
break;
}
index = optional_string_one_of(4, "#DEFAULT PROFILE", "#PROFILES", "#END DEFAULT PROFILE", "#END PROFILES");
}
} catch (const parse::ParseException& e) {
mprintf(("TABLES: Unable to parse '%s'! Error message = %s.\n",
(filename) ? filename : "<default lighting_profiles.tbl>",
e.what()));
return;
}
}
void parse_default_section(const char* filename)
{
SCP_string profile_name = default_profile_name;
SCP_string endtag = "#END DEFAULT PROFILE";
if (Profiles.find(profile_name) == Profiles.end()) {
Profiles[profile_name] = profile();
}
profile* p = &Profiles.at(profile_name);
p->parse(filename, profile_name, endtag);
}
void parse_profile_section(const char* filename)
{
SCP_string buffer;
while (optional_string("$Profile:")) {
stuff_string(buffer, F_NAME);
if (Profiles.find(buffer) == Profiles.end()) {
Profiles[buffer] = profile();
Profiles[buffer].reset();
}
profile* p = &Profiles.at(buffer);
SCP_string endtag = "#END PROFILES";
p->parse(filename, buffer, endtag);
}
}
void profile::parse(const char* filename, const SCP_string& profile_name, const SCP_string& end_tag)
{
name = profile_name;
bool parsed;
SCP_string buffer;
while (0 > optional_string_either(end_tag.c_str(), "$Profile:", false)) {
parsed = false;
if (optional_string("$Tonemapper:")) {
stuff_string(buffer, F_NAME);
TonemapperAlgorithm tn = name_to_tonemapper(buffer);
tonemapper = tn;
parsed = true;
}
if (optional_string("$Non-mission lighting profile:")) {
stuff_string(non_mission_profile_name, F_NAME);
parsed = true;
}
parsed |= parse_optional_float_into("$PPC Toe Strength:", &ppc_values.toe_strength);
parsed |= parse_optional_float_into("$PPC Toe Length:", &ppc_values.toe_length);
parsed |= parse_optional_float_into("$PPC Shoulder Length:", &ppc_values.shoulder_length);
parsed |= parse_optional_float_into("$PPC Shoulder Strength:", &ppc_values.shoulder_strength);
parsed |= parse_optional_float_into("$PPC Shoulder Angle:", &ppc_values.shoulder_angle);
parsed |= parse_optional_float_into("$Exposure:", &exposure);
if (parse_optional_float_into("$RTAO Radius:", &rtao_radius)) {
parsed = true;
if (rtao_radius < 0.0f) {
error_display(0, "$RTAO Radius: must be >= 0 (got %f); using 0.", rtao_radius);
rtao_radius = 0.0f;
}
}
if (parse_optional_float_into("$RTAO Strength:", &rtao_strength)) {
parsed = true;
if (rtao_strength < 0.0f) {
error_display(0, "$RTAO Strength: must be >= 0 (got %f); using 0.", rtao_strength);
rtao_strength = 0.0f;
}
}
parsed |= adjustment::parse(filename, "$Missile light brightness:", profile_name, &missile_light_brightness);
parsed |= adjustment::parse(filename, "$Missile light radius:", profile_name, &missile_light_radius);
parsed |= adjustment::parse(filename, "$Laser light brightness:", profile_name, &laser_light_brightness);
parsed |= adjustment::parse(filename, "$Laser light radius:", profile_name, &laser_light_radius);
parsed |= adjustment::parse(filename, "$Beam light brightness:", profile_name, &beam_light_brightness);
parsed |= adjustment::parse(filename, "$Beam light radius:", profile_name, &beam_light_radius);
parsed |= adjustment::parse(filename, "$Tube light brightness:", profile_name, &tube_light_brightness);
parsed |= adjustment::parse(filename, "$Tube light radius:", profile_name, &tube_light_radius);
parsed |= adjustment::parse(filename, "$Point light brightness:", profile_name, &point_light_brightness);
parsed |= adjustment::parse(filename, "$Point light radius:", profile_name, &point_light_radius);
parsed |=
adjustment::parse(filename, "$Directional light brightness:", profile_name, &directional_light_brightness);
parsed |= adjustment::parse(filename, "$Cone light radius:", profile_name, &cone_light_radius);
parsed |= adjustment::parse(filename, "$Cone light brightness:", profile_name, &cone_light_brightness);
if (adjustment::parse(filename, "$Ambient light brightness:", profile_name, &ambient_light_brightness)) {
parsed = true;
ambient_light_brightness.stack_multiplier(Cmdline_ambient_power);
ambient_light_brightness.stack_multiplier(Cmdline_light_power);
ambient_light_brightness.stack_minimum(Cmdline_emissive_power);
}
if (adjustment::parse(filename, "$Overall brightness:", profile_name, &overall_brightness)) {
parsed = true;
overall_brightness.stack_multiplier(Cmdline_light_power);
}
parsed |= parse_optional_float_into("$Exposure:", &exposure);
parsed |= adjustment::parse(filename,
"$Cockpit light radius modifier:",
profile_name,
&cockpit_light_radius_modifier);
parsed |= adjustment::parse(filename,
"$Cockpit light intensity modifier:",
profile_name,
&cockpit_light_intensity_modifier);
if (!parsed) {
stuff_string(buffer, F_RAW);
Warning(LOCATION, "Unhandled line in lighting profile\n\t%s", buffer.c_str());
}
}
}
void profile::reset()
{
name = "";
tonemapper = TonemapperAlgorithm::Uncharted;
ppc_values.toe_strength = 0.5f;
ppc_values.toe_length = 0.5f;
ppc_values.shoulder_strength = 0.0f;
ppc_values.shoulder_length = 0.5f;
ppc_values.shoulder_angle = 0.1f;
exposure = 4.0f;
rtao_radius = 20.0f;
rtao_strength = 1.0f;
missile_light_brightness.reset();
missile_light_radius.reset();
missile_light_radius.base = 20.0f;
laser_light_brightness.reset();
laser_light_radius.reset();
laser_light_radius.base = 100.0f;
beam_light_brightness.reset();
beam_light_radius.reset();
beam_light_radius.base = 37.5f;
tube_light_brightness.reset();
tube_light_radius.reset();
point_light_brightness.reset();
point_light_radius.reset();
point_light_radius.set_multiplier(1.25f);
cone_light_brightness.reset();
cone_light_radius.reset();
cone_light_radius.set_multiplier(1.25f);
directional_light_brightness.reset();
overall_brightness.reset();
// Default Multiplier to maintain legacy visual compatibility
overall_brightness.set_multiplier(3.5f);
overall_brightness.set_minimum(0.0f);
overall_brightness.stack_multiplier(Cmdline_light_power);
ambient_light_brightness.reset();
// Inverse of the overall brightness boost
ambient_light_brightness.set_multiplier(0.286f);
ambient_light_brightness.stack_multiplier(Cmdline_ambient_power);
ambient_light_brightness.set_adjust(MAX(0.0f, Cmdline_emissive_power));
cockpit_light_radius_modifier.reset();
cockpit_light_radius_modifier.set_multiplier(1.0f);
cockpit_light_intensity_modifier.reset();
cockpit_light_intensity_modifier.set_multiplier(1.0f);
}
profile& profile::operator=(const profile& rhs) = default;
} // namespace lighting_profiles