388 lines
15 KiB
C#
388 lines
15 KiB
C#
using System;
|
|
using Godot;
|
|
using RustToDust.Core;
|
|
|
|
namespace RustToDust.Client;
|
|
|
|
/// <summary>
|
|
/// Single authority for Forward+ Vulkan atmospheric skybox, Sky IBL, 4-split PSSM sun light,
|
|
/// two-tier volumetric valley fog + aerial perspective, SSR, SSAO, AgX tonemapping,
|
|
/// normalized additive HDR bloom, and post-tonemap film grain (<see cref="CanvasLayer"/> Layer 5).
|
|
/// </summary>
|
|
public partial class AtmosphereSystem : Node
|
|
{
|
|
private WorldEnvironment _worldEnv = null!;
|
|
private Godot.Environment _env = null!;
|
|
private Sky _sky = null!;
|
|
private ShaderMaterial _skyMat = null!;
|
|
private DirectionalLight3D _sun = null!;
|
|
private FogVolume _valleyFog = null!;
|
|
private FogMaterial _valleyFogMat = null!;
|
|
private CanvasLayer _filmGrainLayer = null!;
|
|
private ColorRect _filmGrainRect = null!;
|
|
private ShaderMaterial _filmGrainMat = null!;
|
|
private Texture3Drd? _flowTexRd;
|
|
private ImageTexture3D? _dummyFlowTex;
|
|
private VolumetricCompositorEffect? _volumetricEffect;
|
|
private Compositor? _compositor;
|
|
private VolumetricEmitterPool _emitterPool = new();
|
|
private bool _initialized;
|
|
|
|
public WorldEnvironment WorldEnvironment => _worldEnv;
|
|
public Godot.Environment Environment => _env;
|
|
public DirectionalLight3D Sun => _sun;
|
|
public FogVolume ValleyFogVolume => _valleyFog;
|
|
public CanvasLayer FilmGrainLayer => _filmGrainLayer;
|
|
public AtmosphereLutBaker.BakedAtmosphere? CurrentBaked { get; private set; }
|
|
public VolumetricCompositorEffect? VolumetricEffect => _volumetricEffect;
|
|
public VolumetricEmitterPool EmitterPool => _emitterPool;
|
|
|
|
public override void _Ready()
|
|
{
|
|
EnsureInitialized();
|
|
}
|
|
|
|
public void EnsureInitialized()
|
|
{
|
|
if (_initialized)
|
|
{
|
|
return;
|
|
}
|
|
_initialized = true;
|
|
|
|
Shader skyShader = GD.Load<Shader>("res://sky_atmosphere.gdshader")
|
|
?? throw new InvalidOperationException("Failed to load res://sky_atmosphere.gdshader");
|
|
_skyMat = new ShaderMaterial { Shader = skyShader };
|
|
|
|
_sky = new Sky
|
|
{
|
|
SkyMaterial = _skyMat,
|
|
ProcessMode = Sky.ProcessModeEnum.Quality,
|
|
RadianceSize = Sky.RadianceSizeEnum.Size128
|
|
};
|
|
|
|
_env = new Godot.Environment
|
|
{
|
|
BackgroundMode = Godot.Environment.BGMode.Sky,
|
|
Sky = _sky,
|
|
AmbientLightSource = Godot.Environment.AmbientSource.Disabled,
|
|
AmbientLightEnergy = 0.0f,
|
|
|
|
// Option 1 (Low-Gamma): SDFGI multi-bounce + occlusion with zero flat ambient
|
|
SdfgiEnabled = true,
|
|
SdfgiUseOcclusion = true,
|
|
SdfgiReadSkyLight = true,
|
|
SdfgiBounceFeedback = 0.60f,
|
|
SdfgiCascades = 3,
|
|
SdfgiMinCellSize = 0.8f,
|
|
SdfgiYScale = Godot.Environment.SdfgiyScale.Scale75Percent,
|
|
SdfgiEnergy = 0.85f,
|
|
|
|
// AgX tonemapping preserves orange/amber combat hues while rolling off HDR emitters smoothly
|
|
TonemapMode = Godot.Environment.ToneMapper.Agx,
|
|
TonemapAgxWhite = 6.0f,
|
|
TonemapAgxContrast = 1.50f,
|
|
TonemapExposure = 0.84f,
|
|
|
|
// Normalized additive bloom strictly above GlowHdrThreshold=1.0 (zero diffuse screen smear)
|
|
GlowEnabled = true,
|
|
GlowNormalized = true,
|
|
GlowBlendMode = Godot.Environment.GlowBlendModeEnum.Additive,
|
|
GlowHdrThreshold = 1.0f,
|
|
GlowHdrScale = 1.8f,
|
|
GlowHdrLuminanceCap = 12.0f,
|
|
GlowBloom = 0.0f,
|
|
GlowIntensity = 0.40f,
|
|
GlowStrength = 0.72f,
|
|
|
|
// Screen-space reflections for visors, optics, bare steel, and Sion window_glass
|
|
SsrEnabled = true,
|
|
SsrMaxSteps = 32,
|
|
SsrFadeIn = 0.15f,
|
|
SsrFadeOut = 2.0f,
|
|
SsrDepthTolerance = 0.22f,
|
|
|
|
// Screen-space ambient occlusion for mech foot & building contact grounding
|
|
SsaoEnabled = true,
|
|
SsaoRadius = 1.15f,
|
|
SsaoIntensity = 1.85f,
|
|
SsaoPower = 1.5f,
|
|
SsaoDetail = 0.45f,
|
|
SsaoHorizon = 0.06f,
|
|
SsaoSharpness = 0.98f,
|
|
SsaoLightAffect = 0.12f,
|
|
SsaoAOChannelAffect = 0.5f,
|
|
|
|
// Tier 1: Froxel volumetric fog (0..380/460m)
|
|
VolumetricFogEnabled = true,
|
|
VolumetricFogTemporalReprojectionEnabled = true,
|
|
VolumetricFogTemporalReprojectionAmount = 0.88f,
|
|
VolumetricFogAmbientInject = 0.0f,
|
|
VolumetricFogSkyAffect = 0.10f,
|
|
|
|
// Tier 2: Far aerial perspective (340/400m .. horizon peaks)
|
|
FogEnabled = true,
|
|
FogMode = Godot.Environment.FogModeEnum.Depth,
|
|
FogSkyAffect = 0.0f
|
|
};
|
|
|
|
_env.SetGlowLevel(0, 0.0f);
|
|
_env.SetGlowLevel(1, 0.25f);
|
|
_env.SetGlowLevel(2, 0.55f);
|
|
_env.SetGlowLevel(3, 0.85f);
|
|
_env.SetGlowLevel(4, 0.65f);
|
|
_env.SetGlowLevel(5, 0.35f);
|
|
_env.SetGlowLevel(6, 0.15f);
|
|
|
|
_worldEnv = new WorldEnvironment
|
|
{
|
|
Name = "WorldEnv",
|
|
Environment = _env
|
|
};
|
|
|
|
Vector3 defaultInvExtent = new(
|
|
1f / (VolumetricCompositorEffect.FlowDimX * VolumetricCompositorEffect.FlowVoxelSizeMeters),
|
|
1f / (VolumetricCompositorEffect.FlowDimY * VolumetricCompositorEffect.FlowVoxelSizeMeters),
|
|
1f / (VolumetricCompositorEffect.FlowDimZ * VolumetricCompositorEffect.FlowVoxelSizeMeters));
|
|
RegisterGlobalParamIfMissing("rtd_flow_origin", RenderingServer.GlobalShaderParameterType.Vec3, Vector3.Zero);
|
|
RegisterGlobalParamIfMissing("rtd_flow_inv_extent", RenderingServer.GlobalShaderParameterType.Vec3, defaultInvExtent);
|
|
|
|
if (RenderingServer.GetRenderingDevice() is not null)
|
|
{
|
|
RenderingServer.GISetUseHalfResolution(true);
|
|
RenderingServer.EnvironmentSetSdfgiRayCount(RenderingServer.EnvironmentSdfgiRayCount.Count4);
|
|
RenderingServer.EnvironmentSetSdfgiFramesToConverge(RenderingServer.EnvironmentSdfgiFramesToConverge.In10Frames);
|
|
RenderingServer.EnvironmentSetSdfgiFramesToUpdateLight(RenderingServer.EnvironmentSdfgiFramesToUpdateLight.In8Frames);
|
|
_flowTexRd = new Texture3Drd();
|
|
RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _flowTexRd);
|
|
_volumetricEffect = new VolumetricCompositorEffect(_flowTexRd, _emitterPool);
|
|
_compositor = new Compositor
|
|
{
|
|
CompositorEffects = new Godot.Collections.Array<CompositorEffect> { _volumetricEffect }
|
|
};
|
|
_worldEnv.Compositor = _compositor;
|
|
}
|
|
else
|
|
{
|
|
var dummyImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah);
|
|
dummyImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f));
|
|
_dummyFlowTex = new ImageTexture3D();
|
|
_dummyFlowTex.Create(Image.Format.Rgbah, 1, 1, 1, false, new Godot.Collections.Array<Image> { dummyImg });
|
|
RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _dummyFlowTex);
|
|
}
|
|
|
|
AddChild(_worldEnv);
|
|
|
|
_sun = new DirectionalLight3D
|
|
{
|
|
Name = "SunLight",
|
|
ShadowEnabled = true,
|
|
DirectionalShadowMode = DirectionalLight3D.ShadowMode.Parallel4Splits,
|
|
DirectionalShadowMaxDistance = 320f,
|
|
DirectionalShadowSplit1 = 0.08f,
|
|
DirectionalShadowSplit2 = 0.25f,
|
|
DirectionalShadowSplit3 = 0.56f,
|
|
DirectionalShadowBlendSplits = true,
|
|
DirectionalShadowFadeStart = 0.85f,
|
|
DirectionalShadowPancakeSize = 20f,
|
|
ShadowBlur = 1.25f,
|
|
ShadowBias = 0.06f,
|
|
ShadowNormalBias = 1.6f,
|
|
LightAngularDistance = 0.53f
|
|
};
|
|
AddChild(_sun);
|
|
|
|
_valleyFogMat = new FogMaterial
|
|
{
|
|
Density = 0.0038f,
|
|
HeightFalloff = 1.65f,
|
|
EdgeFade = 0.12f
|
|
};
|
|
_valleyFog = new FogVolume
|
|
{
|
|
Name = "ValleyMistVolume",
|
|
Shape = RenderingServer.FogVolumeShape.Box,
|
|
Material = _valleyFogMat
|
|
};
|
|
AddChild(_valleyFog);
|
|
|
|
Shader grainShader = GD.Load<Shader>("res://film_grain.gdshader")
|
|
?? throw new InvalidOperationException("Failed to load res://film_grain.gdshader");
|
|
_filmGrainMat = new ShaderMaterial { Shader = grainShader };
|
|
_filmGrainMat.SetShaderParameter("grain_strength", 0.018f);
|
|
_filmGrainMat.SetShaderParameter("post_gamma", 1.32f);
|
|
|
|
_filmGrainLayer = new CanvasLayer
|
|
{
|
|
Name = "FilmGrainLayer",
|
|
Layer = 5
|
|
};
|
|
_filmGrainRect = new ColorRect
|
|
{
|
|
Name = "FilmGrainRect",
|
|
MouseFilter = Control.MouseFilterEnum.Ignore,
|
|
Material = _filmGrainMat,
|
|
Color = Colors.White,
|
|
AnchorLeft = 0f,
|
|
AnchorTop = 0f,
|
|
AnchorRight = 1f,
|
|
AnchorBottom = 1f,
|
|
OffsetLeft = 0f,
|
|
OffsetTop = 0f,
|
|
OffsetRight = 0f,
|
|
OffsetBottom = 0f
|
|
};
|
|
_filmGrainLayer.AddChild(_filmGrainRect);
|
|
AddChild(_filmGrainLayer);
|
|
}
|
|
|
|
public void ApplyMap(ArenaMapKind mapKind)
|
|
{
|
|
EnsureInitialized();
|
|
|
|
AtmosphereLutBaker.BakedAtmosphere baked = AtmosphereLutBaker.GetOrBake(mapKind);
|
|
AtmosphereLutBaker.AtmospherePreset preset = baked.Preset;
|
|
CurrentBaked = baked;
|
|
|
|
_skyMat.SetShaderParameter("skyview_lut", baked.SkyViewTexture);
|
|
_skyMat.SetShaderParameter("sun_dir", baked.SunDirection);
|
|
_skyMat.SetShaderParameter("sun_transmittance", baked.SunTransmittance);
|
|
_skyMat.SetShaderParameter("horizon_elev", baked.HorizonElevationRad);
|
|
_skyMat.SetShaderParameter("sun_disc_intensity", preset.SunDiscIntensity);
|
|
_skyMat.SetShaderParameter("mie_aureole_strength", preset.MieAureoleStrength);
|
|
_skyMat.SetShaderParameter("sky_exposure", 1.0f);
|
|
|
|
_sun.RotationDegrees = new Vector3(preset.SunPitchDeg, preset.SunYawDeg, 0f);
|
|
_sun.LightColor = baked.SunLightColor;
|
|
_sun.LightEnergy = baked.SunLightEnergy;
|
|
_sun.DirectionalShadowMaxDistance = preset.ShadowMaxDistance;
|
|
|
|
_env.AmbientLightEnergy = preset.AmbientLightEnergy;
|
|
|
|
Color haze = baked.HazeColor;
|
|
_env.VolumetricFogLength = preset.FogMaxLengthMeters;
|
|
_env.VolumetricFogDensity = preset.VolumetricFogDensity;
|
|
_env.VolumetricFogDetailSpread = preset.VolumetricFogDetailSpread;
|
|
_env.VolumetricFogAnisotropy = preset.VolumetricFogAnisotropy;
|
|
_env.VolumetricFogEmissionEnergy = 0f;
|
|
_env.VolumetricFogAlbedo = haze;
|
|
_env.VolumetricFogEmission = Colors.Black;
|
|
|
|
_valleyFog.Size = preset.ValleyVolumeSize;
|
|
_valleyFog.Position = preset.ValleyVolumePosition;
|
|
_valleyFogMat.Density = preset.ValleyVolumeDensity;
|
|
_valleyFogMat.HeightFalloff = preset.ValleyVolumeHeightFalloff;
|
|
_valleyFogMat.EdgeFade = preset.ValleyVolumeEdgeFade;
|
|
_valleyFogMat.Albedo = haze;
|
|
_valleyFogMat.Emission = Colors.Black;
|
|
|
|
_env.FogLightColor = haze;
|
|
_env.FogDepthBegin = preset.DepthFogBegin;
|
|
_env.FogDepthEnd = preset.DepthFogEnd;
|
|
_env.FogDepthCurve = preset.DepthFogCurve;
|
|
_env.FogDensity = preset.DepthFogDensity;
|
|
_env.FogAerialPerspective = preset.DepthFogAerialPerspective;
|
|
_env.FogSunScatter = preset.DepthFogSunScatter;
|
|
|
|
if (_volumetricEffect is not null)
|
|
{
|
|
Color ambCol = new(
|
|
MathF.Max(0.10f, haze.R * 0.55f),
|
|
MathF.Max(0.12f, haze.G * 0.55f),
|
|
MathF.Max(0.14f, haze.B * 0.58f));
|
|
_volumetricEffect.SetAtmosphere(
|
|
baked.SunDirection,
|
|
baked.SunLightEnergy,
|
|
baked.SunLightColor,
|
|
ambCol,
|
|
extinctionScale: mapKind == ArenaMapKind.Sion ? 0.95f : 0.85f);
|
|
}
|
|
}
|
|
|
|
public void BindEmitterPool(VolumetricEmitterPool pool)
|
|
{
|
|
_emitterPool = pool ?? throw new ArgumentNullException(nameof(pool));
|
|
_volumetricEffect?.SetEmitterPool(pool);
|
|
}
|
|
|
|
public void ApplyGraphicsSettings(GraphicsSettings settings)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(settings);
|
|
EnsureInitialized();
|
|
|
|
_volumetricEffect?.ApplyGraphicsSettings(settings);
|
|
|
|
SdfgiSettingsConfig sdfgi = GraphicsSettings.GetSdfgiConfig(settings.SdfgiQuality);
|
|
_env.SdfgiEnabled = sdfgi.Enabled;
|
|
if (sdfgi.Enabled)
|
|
{
|
|
_env.SdfgiMinCellSize = sdfgi.MinCellSize;
|
|
_env.SdfgiCascades = sdfgi.Cascades;
|
|
}
|
|
|
|
if (RenderingServer.GetRenderingDevice() is not null)
|
|
{
|
|
RenderingServer.GISetUseHalfResolution(sdfgi.HalfResolution);
|
|
RenderingServer.EnvironmentSetSdfgiRayCount(
|
|
sdfgi.RayCount >= 8
|
|
? RenderingServer.EnvironmentSdfgiRayCount.Count8
|
|
: RenderingServer.EnvironmentSdfgiRayCount.Count4);
|
|
}
|
|
}
|
|
|
|
public override void _ExitTree()
|
|
{
|
|
if (_worldEnv is not null && GodotObject.IsInstanceValid(_worldEnv))
|
|
{
|
|
_worldEnv.Compositor = null;
|
|
}
|
|
if (_flowTexRd is not null)
|
|
{
|
|
_flowTexRd.TextureRdRid = new Rid();
|
|
}
|
|
if (AreFlowGlobalsRegistered && RenderingServer.Singleton is not null)
|
|
{
|
|
_dummyFlowTex ??= CreateDummyFlowTexture();
|
|
RenderingServer.GlobalShaderParameterSet("rtd_flow_field", _dummyFlowTex);
|
|
}
|
|
if (_volumetricEffect is not null)
|
|
{
|
|
_volumetricEffect.Enabled = false;
|
|
if (RenderingServer.GetRenderingDevice() is not null)
|
|
{
|
|
RenderingServer.CallOnRenderThread(Callable.From(_volumetricEffect.DisposeRdResources));
|
|
RenderingServer.ForceSync();
|
|
}
|
|
}
|
|
}
|
|
|
|
private static ImageTexture3D CreateDummyFlowTexture()
|
|
{
|
|
var dummyImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah);
|
|
dummyImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f));
|
|
var tex = new ImageTexture3D();
|
|
tex.Create(Image.Format.Rgbah, 1, 1, 1, false, new Godot.Collections.Array<Image> { dummyImg });
|
|
return tex;
|
|
}
|
|
|
|
private static readonly System.Collections.Generic.HashSet<string> RegisteredGlobals = new();
|
|
public static bool AreFlowGlobalsRegistered =>
|
|
RegisteredGlobals.Contains("rtd_flow_field") &&
|
|
RegisteredGlobals.Contains("rtd_flow_origin") &&
|
|
RegisteredGlobals.Contains("rtd_flow_inv_extent");
|
|
|
|
private static void RegisterGlobalParamIfMissing(
|
|
StringName name,
|
|
RenderingServer.GlobalShaderParameterType type,
|
|
Variant defaultValue)
|
|
{
|
|
string key = name.ToString();
|
|
if (RegisteredGlobals.Contains(key))
|
|
{
|
|
RenderingServer.GlobalShaderParameterSet(name, defaultValue);
|
|
return;
|
|
}
|
|
RegisteredGlobals.Add(key);
|
|
RenderingServer.GlobalShaderParameterAdd(name, type, defaultValue);
|
|
}
|
|
}
|