Static helper for the game's distance fog. Creates a Fog component on an area's air object with distance mode, radial metric, falloff exponent and optional height layer, and has helpers to set colour, range and opacity.
using System;
using Sandbox.Rendering;
/// <summary>
/// The Sump's distance fog, in one place. Every area (the hub cavern, a flashback arena, a finale
/// layer) has its own <see cref="Fog"/> on its own "air" object under the area's root, so it goes
/// when the area is disabled or destroyed.
///
/// Fog is a camera post-process effect. On an object that is not under a camera or a
/// PostProcessVolume it is a scene-wide default, which is what we want: only one area is enabled at
/// a time, and a disabled Fog simply stops contributing.
///
/// The numbers are the old GradientFog ones: a start/end ramp with an exponent, and the colour's
/// alpha as the most the fog may cover (Fog ignores colour alpha and has MaximumOpacity instead).
/// </summary>
public static class SumpFog
{
/// <summary>
/// Adds fog to an area's air object. Leave <paramref name="height"/> at 0: Fog's height gradient
/// is a separate layer that fogs everything below it whatever the distance, not the ceiling on
/// the distance fog that GradientFog's Height was, so it is only for when that is wanted.
/// </summary>
public static Fog Create( GameObject owner, Color color, float start, float end, float exponent = 1.4f, float height = 0f )
{
var fog = owner.Components.Create<Fog>();
fog.FogEnabled = true;
fog.DistanceEnabled = true;
fog.Mode = FogMode.Distance;
fog.DistanceMetric = FogDistanceMetric.Radial;
fog.FalloffExponent = exponent;
fog.ColorSource = FogColorSource.Constant;
fog.DirectionalColorEnabled = false;
fog.SunLightingEnabled = false;
fog.ColorScale = 1f;
fog.SkyAffect = 1f; // the void past the walls fogs like the walls do
fog.HeightEnabled = height > 0f;
if ( height > 0f )
{
fog.HeightOffset = 0f;
fog.HeightGradientLength = height;
fog.HeightExponent = 1f;
fog.HeightColorSource = FogColorSource.Constant;
}
Set( fog, color, start, end );
return fog;
}
/// <summary>Changes an existing fog's colour and reach. The colour's alpha is its greatest opacity.</summary>
public static void Set( Fog fog, Color color, float start, float end )
{
if ( !fog.IsValid() ) return;
fog.DistanceRange = new Vector2( start, end );
fog.MaxDistance = MathF.Max( start, end ); // sky and void count as fully fogged
Tint( fog, color );
}
/// <summary>Changes only the colour (and, through its alpha, the greatest opacity).</summary>
public static void Tint( Fog fog, Color color )
{
if ( !fog.IsValid() ) return;
fog.Color = color.WithAlpha( 1f );
fog.MaximumOpacity = Math.Clamp( color.a, 0f, 1f );
if ( fog.HeightEnabled ) fog.HeightColor = color;
}
/// <summary>The colour as <see cref="Tint"/> takes it: the fog's colour with its opacity as alpha.</summary>
public static Color ColorOf( Fog fog ) => fog.IsValid() ? fog.Color.WithAlpha( fog.MaximumOpacity ) : default;
}