diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs index e91369c..c185907 100644 --- a/client/ArenaRenderer.cs +++ b/client/ArenaRenderer.cs @@ -70,7 +70,7 @@ public partial class ArenaRenderer : Node3D } private const int MaxVfxBeams = 512; - private const int MaxVfxSpheres = 512; + private const int MaxVfxSpheres = 64; private const int MaxVfxRings = 128; private VehicleAssetCache _assetCache = null!; @@ -80,6 +80,8 @@ public partial class ArenaRenderer : Node3D private PomDecalPool _pomDecals = null!; private DebrisSystem _debris = null!; private ParticlePool _particles = null!; + private readonly VolumetricEmitterPool _volumetrics = new(); + private GpuSparksSystem _gpuSparks = null!; private MeshInstance3D _safeRingMesh = null!; private ImmediateMesh _safeRingImm = null!; @@ -89,8 +91,9 @@ public partial class ArenaRenderer : Node3D private MultiMesh _dropPillarMm = null!; private MultiMeshInstance3D _dropPillarMmi = null!; - // Pooled weapon VFX MultiMeshes (beams/tracers, explosive detonation cores, shockwave rings) + // Pooled weapon VFX MultiMeshes (analytic volumetric capsule beams, optional spheres, shockwave rings) private ShaderMaterial _vfxMat = null!; + private ShaderMaterial _vfxBeamMat = null!; private MultiMesh _vfxBeamMm = null!; private MultiMeshInstance3D _vfxBeamMmi = null!; private MultiMesh _vfxSphereMm = null!; @@ -99,8 +102,9 @@ public partial class ArenaRenderer : Node3D private MultiMeshInstance3D _vfxRingMmi = null!; private readonly List _transientVfx = new(128); private readonly ClientOrdnanceMirror _ordnanceMirror = new(); - private readonly List<(Transform3D Xf, Color Col)> _mirrorSpheres = new(64); + private readonly List<(Transform3D Xf, Color Col)> _mirrorSpheres = new(32); private readonly List<(Transform3D Xf, Color Col)> _mirrorRings = new(128); + private readonly List _mirrorBeams = new(64); private int _activeBeamCount; // Continuous emitter rate limiters (keyed by (IsContender, EntityId)) @@ -126,6 +130,8 @@ public partial class ArenaRenderer : Node3D public VehicleAssetCache AssetCache => _assetCache; public DebrisSystem Debris => _debris; public ParticlePool Particles => _particles; + public VolumetricEmitterPool Volumetrics => _volumetrics; + public GpuSparksSystem GpuSparks => _gpuSparks; internal MultiMeshPartPool PartPool => _partPool; internal PomDecalPool PomDecals => _pomDecals; internal ClientOrdnanceMirror OrdnanceMirror => _ordnanceMirror; @@ -167,12 +173,15 @@ public partial class ArenaRenderer : Node3D _pomDecals = new PomDecalPool { Name = "PomDecals" }; _debris = new DebrisSystem { Name = "Debris" }; _particles = new ParticlePool { Name = "ParticlePool" }; + _gpuSparks = new GpuSparksSystem { Name = "GpuSparks" }; + _particles.BindTargets(_volumetrics, _gpuSparks); AddChild(_staticGroup); AddChild(_actorsGroup); AddChild(_partPool); AddChild(_pomDecals); AddChild(_debris); AddChild(_particles); + AddChild(_gpuSparks); _coverMat = new StandardMaterial3D { AlbedoColor = CoverRust, Roughness = 0.88f, Metallic = 0.25f }; _bermMat = new StandardMaterial3D { AlbedoColor = BermDark, Roughness = 0.94f, Metallic = 0.1f }; @@ -229,9 +238,14 @@ public partial class ArenaRenderer : Node3D }; _vfxMat = new ShaderMaterial { Shader = vfxShader }; + Shader beamShader = GD.Load("res://volumetric_capsule_beam.gdshader") + ?? throw new InvalidOperationException("Failed to load res://volumetric_capsule_beam.gdshader"); + _vfxBeamMat = new ShaderMaterial { Shader = beamShader }; + _vfxBeamMm = new MultiMesh { TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseColors = true, UseCustomData = true, Mesh = new BoxMesh { Size = Vector3.One }, InstanceCount = MaxVfxBeams, @@ -241,7 +255,7 @@ public partial class ArenaRenderer : Node3D { Name = "VfxBeams", Multimesh = _vfxBeamMm, - MaterialOverride = _vfxMat, + MaterialOverride = _vfxBeamMat, CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)), PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, @@ -357,17 +371,19 @@ public partial class ArenaRenderer : Node3D SyncOrbitalPods(session, alpha, hasCam, camPos); _mirrorSpheres.Clear(); _mirrorRings.Clear(); + _mirrorBeams.Clear(); _ordnanceMirror.StepAndSubmit( dt, session, _assetCache, _partPool, _particles, + _volumetrics, state.Terrain, hasCam, camPos, (xf, col) => _mirrorRings.Add((xf, col)), - (xf, col) => _mirrorSpheres.Add((xf, col))); + beam => _mirrorBeams.Add(beam)); _debris.Step(dt, state.Terrain); _debris.SubmitToPool(_partPool); _partPool.EndFrame(); @@ -397,6 +413,7 @@ public partial class ArenaRenderer : Node3D _assetCache, _debris, _particles, + _volumetrics, hasCam, camPos, spec => AddTransient(new TransientVfx @@ -424,6 +441,7 @@ public partial class ArenaRenderer : Node3D ConsumeDropPodEvents(session, events, camPos, hasCam); UpdateExplosiveRingsAndCores(events, stepDt); _particles.AdvanceAndCommit(stepDt); + _volumetrics.Step(stepDt); } private VehicleVisualInstance? ResolveEntityVisual(bool isContender, int id) => @@ -513,10 +531,13 @@ public partial class ArenaRenderer : Node3D _pomDecals.ClearAll(); _debris.ClearAll(); _particles.ClearAll(); + _volumetrics.ClearAll(); + _gpuSparks.ClearAll(); _transientVfx.Clear(); _ordnanceMirror.Clear(); _mirrorSpheres.Clear(); _mirrorRings.Clear(); + _mirrorBeams.Clear(); _tireDustNextTime.Clear(); _thermalVentNextTime.Clear(); _damageSmokeNextTime.Clear(); @@ -1256,7 +1277,7 @@ public partial class ArenaRenderer : Node3D lifetime: petalLife); } - // Touchdown retro shockwave ring + brief detonation core + // Touchdown retro shockwave ring (fireball & radial dust handled by VolumetricEmitterPool + GpuSparksSystem) Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up; Vector3 right = upRef.Cross(normal).Normalized(); Vector3 fwd = normal.Cross(right).Normalized(); @@ -1274,19 +1295,6 @@ public partial class ArenaRenderer : Node3D Age = 0f, Lifetime = isContender ? 0.42f : 0.30f }); - AddTransient(new TransientVfx - { - Shape = VfxShape.Sphere, - Position = pos + normal * 0.65f, - Velocity = normal * 1.8f, - BaseRotation = Basis.Identity, - StartScale = Vector3.One * (isContender ? 1.2f : 0.7f), - EndScale = Vector3.One * (isContender ? 4.4f : 2.6f), - ColorStart = new Color(3.8f, 2.2f, 0.65f, 0.90f), - ColorEnd = new Color(0.85f, 0.25f, 0.06f, 0.0f), - Age = 0f, - Lifetime = isContender ? 0.28f : 0.20f - }); } } @@ -1299,90 +1307,69 @@ public partial class ArenaRenderer : Node3D var t = tracers[i]; Vector3 start = new(t.StartX, t.StartY, t.StartZ); Vector3 end = new(t.EndX, t.EndY, t.EndZ); - Vector3 delta = end - start; - float dist = delta.Length(); - if (dist < 0.1f) + if (start.DistanceSquaredTo(end) < 0.01f) { continue; } - Vector3 dir = delta / dist; - Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; - Basis lookBasis = Basis.LookingAt(dir, up); - Vector3 mid = (start + end) * 0.5f; - switch (t.WeaponClass) { case WeaponVisualClass.KineticLight: { bool isPd = string.Equals(t.WeaponId, "pd_flak", StringComparison.Ordinal); Color col = isPd - ? new Color(2.8f, 1.35f, 0.35f, 0.94f) - : new Color(2.6f, 2.35f, 1.15f, 0.92f); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(isPd ? 0.09f : 0.06f, isPd ? 0.09f : 0.06f, dist), col); + ? new Color(3.2f, 1.55f, 0.42f, 0.94f) + : new Color(3.0f, 2.55f, 1.25f, 0.92f); + SubmitCapsuleBeam(ref beamIdx, start, end, isPd ? 0.075f : 0.055f, col, coreSharpness: 3.0f, coreRadiusFrac: 0.36f, tailFade: 1.0f); break; } case WeaponVisualClass.Autocannon: - { - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.20f, 0.20f, dist), new Color(2.5f, 0.85f, 0.14f, 0.72f)); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.08f, 0.08f, dist), new Color(3.6f, 2.7f, 1.3f, 0.98f)); + SubmitCapsuleBeam(ref beamIdx, start, end, 0.14f, new Color(3.4f, 1.35f, 0.28f, 0.96f), coreSharpness: 2.8f, coreRadiusFrac: 0.36f, tailFade: 1.0f); break; - } case WeaponVisualClass.Explosive: { bool isRecoilless = string.Equals(t.WeaponId, "recoilless", StringComparison.Ordinal); - float w = isRecoilless ? 0.22f : 0.12f; - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(w, w, dist), new Color(3.2f, 1.25f, 0.25f, 0.96f)); + SubmitCapsuleBeam(ref beamIdx, start, end, isRecoilless ? 0.17f : 0.10f, new Color(3.6f, 1.45f, 0.32f, 0.96f), coreSharpness: 2.6f, coreRadiusFrac: 0.34f, tailFade: 1.0f); break; } case WeaponVisualClass.ThermalBeam: { bool isLance = string.Equals(t.WeaponId, "gilded_lance", StringComparison.Ordinal); - float outerW = isLance ? 0.34f : 0.20f; - float coreW = isLance ? 0.13f : 0.08f; - Color outerCol = isLance - ? new Color(2.8f, 1.95f, 0.45f, 0.62f) - : new Color(0.45f, 2.35f, 2.95f, 0.65f); - Color coreCol = isLance - ? new Color(1.6f, 3.6f, 3.8f, 0.98f) - : new Color(2.4f, 3.4f, 3.8f, 0.98f); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(outerW, outerW, dist), outerCol); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(coreW, coreW, dist), coreCol); + float outerR = isLance ? 0.24f : 0.15f; + Color beamCol = isLance + ? new Color(3.4f, 2.35f, 0.55f, 0.96f) + : new Color(0.55f, 2.80f, 3.60f, 0.96f); + SubmitCapsuleBeam(ref beamIdx, start, end, outerR, beamCol, coreSharpness: 3.2f, coreRadiusFrac: 0.38f, tailFade: 0.0f, pulsePhase: 12f); break; } case WeaponVisualClass.GaussRail: - { - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.30f, 0.30f, dist), new Color(0.25f, 1.85f, 3.4f, 0.68f)); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.10f, 0.10f, dist), new Color(2.2f, 3.6f, 4.0f, 0.98f)); + SubmitCapsuleBeam(ref beamIdx, start, end, 0.22f, new Color(0.42f, 2.45f, 3.80f, 0.98f), coreSharpness: 3.6f, coreRadiusFrac: 0.34f, tailFade: 0.0f, pulsePhase: 18f); break; - } case WeaponVisualClass.PlasmaPpc: - { - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.36f, 0.36f, dist), new Color(0.18f, 2.25f, 2.65f, 0.65f)); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.14f, 0.14f, dist), new Color(1.2f, 3.5f, 3.8f, 0.98f)); + SubmitCapsuleBeam(ref beamIdx, start, end, 0.25f, new Color(0.28f, 2.85f, 3.40f, 0.96f), coreSharpness: 2.6f, coreRadiusFrac: 0.40f, tailFade: 0.0f, pulsePhase: 14f); break; - } case WeaponVisualClass.RocketSalvo: - { - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.22f, 0.22f, dist), new Color(3.2f, 1.45f, 0.30f, 0.92f)); + SubmitCapsuleBeam(ref beamIdx, start, end, 0.16f, new Color(3.6f, 1.65f, 0.38f, 0.94f), coreSharpness: 2.6f, coreRadiusFrac: 0.36f, tailFade: 1.0f); break; - } case WeaponVisualClass.SwarmSmart: - { - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.16f, 0.16f, dist), new Color(1.4f, 2.8f, 0.45f, 0.85f)); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.07f, 0.07f, dist), new Color(2.0f, 0.95f, 3.2f, 0.96f)); + SubmitCapsuleBeam(ref beamIdx, start, end, 0.12f, new Color(1.65f, 3.20f, 0.58f, 0.95f), coreSharpness: 2.8f, coreRadiusFrac: 0.36f, tailFade: 1.0f); break; - } } } + for (int i = 0; i < _mirrorBeams.Count; i++) + { + var b = _mirrorBeams[i]; + SubmitCapsuleBeam(ref beamIdx, b.Start, b.End, b.Radius, b.HdrTint, b.CoreSharpness, b.CoreRadiusFrac, b.TailFade); + } + _activeBeamCount = beamIdx; _vfxBeamMm.VisibleInstanceCount = beamIdx; _vfxBeamMmi.Visible = beamIdx > 0; @@ -1421,7 +1408,6 @@ public partial class ArenaRenderer : Node3D normal = normal.Normalized(); bool isRecoilless = string.Equals(ev.WeaponId, "recoilless", StringComparison.Ordinal); - float detSize = isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 3.2f : 1.9f; float ringSize = isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 6.2f : 3.4f; Color coreStart = wClass switch { @@ -1435,19 +1421,6 @@ public partial class ArenaRenderer : Node3D WeaponVisualClass.SwarmSmart => new Color(0.55f, 0.25f, 0.85f, 0f), _ => new Color(0.85f, 0.28f, 0.08f, 0f) }; - AddTransient(new TransientVfx - { - Shape = VfxShape.Sphere, - Position = pos + normal * 0.25f, - Velocity = normal * 1.4f, - BaseRotation = Basis.Identity, - StartScale = Vector3.One * 0.5f, - EndScale = Vector3.One * detSize, - ColorStart = coreStart, - ColorEnd = coreEnd, - Age = 0f, - Lifetime = isRecoilless ? 0.28f : 0.22f - }); Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up; Vector3 right = upRef.Cross(normal).Normalized(); @@ -1689,14 +1662,34 @@ public partial class ArenaRenderer : Node3D return fallbackPos + new Vector3(0f, halfHeight * 0.7f, 0f); } - private void EmitBeam(ref int beamIdx, Basis lookBasis, Vector3 mid, Vector3 scale, Color color) + private void SubmitCapsuleBeam( + ref int beamIdx, + Vector3 start, + Vector3 end, + float outerRadius, + Color hdrTint, + float coreSharpness, + float coreRadiusFrac, + float tailFade, + float pulsePhase = 0f) { if (beamIdx >= MaxVfxBeams) { return; } + + Vector3 delta = end - start; + float len = delta.Length(); + Vector3 dir = len > 0.01f ? delta / len : Vector3.Forward; + Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; + Basis lookBasis = Basis.LookingAt(dir, up); + Vector3 mid = (start + end) * 0.5f; + float r = MathF.Max(0.01f, outerRadius); + Vector3 scale = new(2f * r, 2f * r, len + 2f * r); + _vfxBeamMm.SetInstanceTransform(beamIdx, new Transform3D(lookBasis * Basis.FromScale(scale), mid)); - _vfxBeamMm.SetInstanceCustomData(beamIdx, color); + _vfxBeamMm.SetInstanceColor(beamIdx, hdrTint); + _vfxBeamMm.SetInstanceCustomData(beamIdx, new Color(coreSharpness, coreRadiusFrac, tailFade, pulsePhase)); beamIdx++; } diff --git a/client/AtmosphereSystem.cs b/client/AtmosphereSystem.cs index 80b953d..53e0ce6 100644 --- a/client/AtmosphereSystem.cs +++ b/client/AtmosphereSystem.cs @@ -21,6 +21,11 @@ public partial class AtmosphereSystem : Node 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; @@ -29,6 +34,8 @@ public partial class AtmosphereSystem : Node 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() { @@ -122,6 +129,34 @@ public partial class AtmosphereSystem : Node 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) + { + _flowTexRd = new Texture3Drd(); + RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _flowTexRd); + _volumetricEffect = new VolumetricCompositorEffect(_flowTexRd, _emitterPool); + _compositor = new Compositor + { + CompositorEffects = new Godot.Collections.Array { _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 { dummyImg }); + RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _dummyFlowTex); + } + AddChild(_worldEnv); _sun = new DirectionalLight3D @@ -233,5 +268,81 @@ public partial class AtmosphereSystem : Node _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.58f : 0.52f); + } + } + + public void BindEmitterPool(VolumetricEmitterPool pool) + { + _emitterPool = pool ?? throw new ArgumentNullException(nameof(pool)); + _volumetricEffect?.SetEmitterPool(pool); + } + + 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 { dummyImg }); + return tex; + } + + private static readonly System.Collections.Generic.HashSet 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); } } diff --git a/client/ClientOrdnanceMirror.cs b/client/ClientOrdnanceMirror.cs index 57304c9..1330924 100644 --- a/client/ClientOrdnanceMirror.cs +++ b/client/ClientOrdnanceMirror.cs @@ -27,6 +27,15 @@ public sealed class ClientOrdnanceMirror Color ColorEnd, float Lifetime); + public readonly record struct ActiveBeamSpec( + Vector3 Start, + Vector3 End, + float Radius, + Color HdrTint, + float CoreSharpness, + float CoreRadiusFrac, + float TailFade); + private struct MirroredSlot { public bool Active; @@ -39,6 +48,7 @@ public sealed class ClientOrdnanceMirror public Color Color; public float ManufacturerRoleIndex; public Vector3 Pos; + public Vector3 TailPos; public Vector3 Vel; public Vector3 AnchorPos; public int TargetEntityId; @@ -82,6 +92,7 @@ public sealed class ClientOrdnanceMirror VehicleAssetCache cache, DebrisSystem debris, ParticlePool particles, + VolumetricEmitterPool volumetrics, bool hasCam, Vector3 camPos, Action emitTransient) @@ -186,16 +197,10 @@ public sealed class ClientOrdnanceMirror RemoveById(ev.OrdnanceId); float splashR = def is not null && def.SplashRadius > 0.5f ? def.SplashRadius : 4.2f; particles.EmitOrdnanceBurst(pos, col, sparkCount: 6, radiusScale: Math.Clamp(splashR / 4.5f, 0.7f, 1.6f), camPos, hasCam); - emitTransient(new TransientVfxSpec( - IsSphere: true, - Position: pos + Vector3.Up * 0.2f, - Velocity: Vector3.Up * 1.2f, - Rotation: Basis.Identity, - StartScale: Vector3.One * 0.55f, - EndScale: Vector3.One * Math.Clamp(splashR * 0.75f, 1.8f, 4.8f), - ColorStart: new Color(col.R * 3.2f, col.G * 3.2f, col.B * 3.2f, 0.92f), - ColorEnd: new Color(col.R * 0.8f, col.G * 0.3f, col.B * 0.2f, 0f), - Lifetime: 0.26f)); + if (!hasCam || pos.DistanceSquaredTo(camPos) <= 280f * 280f) + { + volumetrics.EmitOrdnanceDetonation(pos, col, splashR); + } emitTransient(new TransientVfxSpec( IsSphere: false, Position: pos + Vector3.Up * 0.16f, @@ -227,11 +232,12 @@ public sealed class ClientOrdnanceMirror VehicleAssetCache cache, MultiMeshPartPool partPool, ParticlePool particles, + VolumetricEmitterPool volumetrics, TerrainField terrain, bool hasCam, Vector3 camPos, Action submitActiveRing, - Action submitActiveSphere) + Action submitActiveBeam) { if (_activeCount == 0) { @@ -273,6 +279,8 @@ public sealed class ClientOrdnanceMirror } AdvanceSlotKinematics(ref s, def, state, terrain, stepDt); + float tailLerp = 1f - MathF.Exp(-stepDt * 18f); + s.TailPos = s.TailPos.Lerp(s.Pos, tailLerp); } if (hasCam && s.Pos.DistanceSquaredTo(camPos) > 340f * 340f) @@ -293,9 +301,6 @@ public sealed class ClientOrdnanceMirror Transform3D ringXf = new(Basis.FromScale(new Vector3(radius * 2f * pulse, 0.35f, radius * 2f * pulse)), poolPos); submitActiveRing(ringXf, new Color(s.Color.R * 2.6f, s.Color.G * 2.6f, s.Color.B * 2.6f, 0.78f)); - Transform3D discXf = new(Basis.FromScale(new Vector3(radius * 1.4f * pulse, 0.14f, radius * 1.4f * pulse)), poolPos - new Vector3(0f, 0.04f, 0f)); - submitActiveSphere(discXf, new Color(s.Color.R * 2.1f, s.Color.G * 2.1f, s.Color.B * 2.1f, 0.42f)); - if (stepDt > 0f) { s.EmberTimer += stepDt; @@ -303,6 +308,10 @@ public sealed class ClientOrdnanceMirror { s.EmberTimer = 0f; particles.EmitThermalPoolEmber(poolPos, radius, s.Color, camPos, hasCam); + if (!hasCam || poolPos.DistanceSquaredTo(camPos) <= 220f * 220f) + { + volumetrics.EmitThermalPoolPlume(poolPos, radius, s.Color); + } } } continue; @@ -349,10 +358,13 @@ public sealed class ClientOrdnanceMirror if (stepDt > 0f) { s.TrailTimer += stepDt; - if (s.TrailTimer >= 0.055f) + if (s.TrailTimer >= 0.075f) { s.TrailTimer = 0f; - particles.EmitOrdnanceTrail(s.Pos, s.Vel, s.Color, isRocket: def?.Motion != OrdnanceMotion.LoiterOrbit, camPos, hasCam); + if (!hasCam || s.Pos.DistanceSquaredTo(camPos) <= 240f * 240f) + { + volumetrics.EmitOrdnanceTrailCapsule(s.TailPos, s.Pos, s.Vel, s.Color, isRocket: def?.Motion != OrdnanceMotion.LoiterOrbit); + } } } continue; @@ -382,19 +394,30 @@ public sealed class ClientOrdnanceMirror def?.Motion is OrdnanceMotion.RocketBoosted or OrdnanceMotion.HomingMissile; partPool.Submit(projMesh, in projXf, new Color(0f, isRocket ? 0.65f : 0.25f, s.ManufacturerRoleIndex, 1f), wantsShadow: false); - if (isRocket) - { - Transform3D thrusterXf = new(Basis.FromScale(Vector3.One * 0.42f), s.Pos - dir * 0.22f); - submitActiveSphere(thrusterXf, new Color(s.Color.R * 3.2f, s.Color.G * 3.2f, s.Color.B * 3.2f, 0.90f)); - } + // Connected [TailPos, Pos] volumetric capsule streak + Vector3 tailStart = s.Pos.DistanceSquaredTo(s.TailPos) > 0.04f ? s.TailPos : s.Pos - dir * 1.4f; + Color beamCol = isRocket + ? new Color(s.Color.R * 3.4f, s.Color.G * 2.4f, s.Color.B * 1.4f, 0.94f) + : new Color(s.Color.R * 3.0f, s.Color.G * 3.0f, s.Color.B * 3.0f, 0.92f); + submitActiveBeam(new ActiveBeamSpec( + Start: tailStart, + End: s.Pos - dir * 0.16f, + Radius: isRocket ? 0.24f : 0.15f, + HdrTint: beamCol, + CoreSharpness: 2.8f, + CoreRadiusFrac: 0.36f, + TailFade: 1.0f)); if (stepDt > 0f) { s.TrailTimer += stepDt; - if (s.TrailTimer >= (isRocket ? 0.035f : 0.055f)) + if (s.TrailTimer >= (isRocket ? 0.055f : 0.075f)) { s.TrailTimer = 0f; - particles.EmitOrdnanceTrail(s.Pos - dir * 0.18f, s.Vel, s.Color, isRocket, camPos, hasCam); + if (!hasCam || s.Pos.DistanceSquaredTo(camPos) <= 240f * 240f) + { + volumetrics.EmitOrdnanceTrailCapsule(s.TailPos, s.Pos - dir * 0.18f, s.Vel, s.Color, isRocket); + } } } } @@ -565,6 +588,7 @@ public sealed class ClientOrdnanceMirror Color = col, ManufacturerRoleIndex = mfgRole, Pos = pos, + TailPos = pos, Vel = vel, AnchorPos = pos, TargetEntityId = ev.TargetEntityId, diff --git a/client/GpuSparksSystem.cs b/client/GpuSparksSystem.cs new file mode 100644 index 0000000..525b55f --- /dev/null +++ b/client/GpuSparksSystem.cs @@ -0,0 +1,212 @@ +using System; +using Godot; + +namespace RustToDust.Client; + +/// +/// Flow-coupled GPU particle system (, 8,192 capacity) driven by +/// the global rtd_flow_field for tiny kite-stretched HDR sparks, +/// buoyant embers, flow-entrained dust motes, and 0.08s muzzle starbursts. +/// +public partial class GpuSparksSystem : Node3D +{ + public const int Capacity = 8192; + + public const int TypeVelocitySpark = 0; + public const int TypeBuoyantEmber = 1; + public const int TypeDustMote = 2; + public const int TypeMuzzleStarburst = 3; + + private const uint EmitFlagsAll = (uint)( + GpuParticles3D.EmitFlags.Position | + GpuParticles3D.EmitFlags.Velocity | + GpuParticles3D.EmitFlags.Color | + GpuParticles3D.EmitFlags.Custom); + + private GpuParticles3D _particles = null!; + private ShaderMaterial _processMat = null!; + private ShaderMaterial _drawMat = null!; + private bool _initialized; + private uint _rng = 0x9E3779B9u; + + public int TotalEmittedCount { get; private set; } + public GpuParticles3D ParticlesNode => _particles; + + public override void _Ready() + { + EnsureInitialized(); + } + + public void EnsureInitialized() + { + if (_initialized) + { + return; + } + _initialized = true; + + Shader processShader = GD.Load("res://gpu_sparks_process.gdshader") + ?? throw new InvalidOperationException("Failed to load res://gpu_sparks_process.gdshader"); + Shader drawShader = GD.Load("res://gpu_sparks_draw.gdshader") + ?? throw new InvalidOperationException("Failed to load res://gpu_sparks_draw.gdshader"); + + _processMat = new ShaderMaterial { Shader = processShader }; + _drawMat = new ShaderMaterial { Shader = drawShader }; + + var quad = new QuadMesh + { + Size = Vector2.One, + Material = _drawMat + }; + + _particles = new GpuParticles3D + { + Name = "GpuSparks3D", + Amount = Capacity, + LocalCoords = false, + Emitting = true, + AmountRatio = 0.0f, // Keep GPU process active with zero automatic spawns + Lifetime = 2.5f, + FixedFps = 0, + Explosiveness = 0.0f, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + VisibilityAabb = new Aabb(new Vector3(-1800f, -200f, -1800f), new Vector3(3600f, 2200f, 3600f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + ProcessMaterial = _processMat, + DrawPass1 = quad + }; + AddChild(_particles); + } + + public void ClearAll() + { + EnsureInitialized(); + TotalEmittedCount = 0; + _particles.Restart(); + _particles.Emitting = true; + _particles.AmountRatio = 0.0f; + } + + public void Prewarm(Vector3 nearPos) + { + EnsureInitialized(); + EmitRaw(nearPos + new Vector3(0f, -20f, 0f), Vector3.Up * 0.1f, new Color(1f, 1f, 1f, 0.01f), 0.02f, 0.05f, TypeVelocitySpark, 1.0f); + TotalEmittedCount = 0; + } + + public void EmitMuzzleStarburst(Vector3 pos, Color hdrColor, float sizeM, float lifetimeSec) + { + EnsureInitialized(); + EmitRaw(pos, Vector3.Zero, hdrColor, Math.Clamp(sizeM, 0.25f, 0.90f), Math.Clamp(lifetimeSec, 0.05f, 0.14f), TypeMuzzleStarburst, 0f); + } + + public void EmitSparkBurst(Vector3 pos, Vector3 normal, int count, Color hdrColor, float speed, float widthM = 0.042f) + { + EnsureInitialized(); + Vector3 n = normal.LengthSquared() > 1e-4f ? normal.Normalized() : Vector3.Up; + for (int i = 0; i < count; i++) + { + Vector3 rand = new(NextSigned(), MathF.Abs(NextSigned()) + 0.30f, NextSigned()); + Vector3 dir = (n * 0.72f + rand).Normalized(); + float spd = speed * (0.55f + 0.80f * NextFloat()); + float life = 0.22f + 0.26f * NextFloat(); + EmitRaw(pos, dir * spd, hdrColor, widthM, life, TypeVelocitySpark, 0.85f); + } + } + + public void EmitEmberBurst(Vector3 pos, int count, Color hdrColor, float spreadSpeed, float widthM = 0.055f) + { + EnsureInitialized(); + for (int i = 0; i < count; i++) + { + Vector3 vel = new(NextSigned() * spreadSpeed, 2.5f + NextFloat() * 5.0f, NextSigned() * spreadSpeed); + float life = 0.85f + NextFloat() * 1.15f; + EmitRaw(pos + new Vector3(NextSigned() * 0.6f, NextFloat() * 0.6f, NextSigned() * 0.6f), vel, hdrColor, widthM, life, TypeBuoyantEmber, 1.6f); + } + } + + public void EmitDustMotes(Vector3 pos, Vector3 normal, int count, Color dustColor, float speed, float widthM = 0.065f) + { + EnsureInitialized(); + Vector3 n = normal.LengthSquared() > 1e-4f ? normal.Normalized() : Vector3.Up; + for (int i = 0; i < count; i++) + { + float ang = NextFloat() * MathF.Tau; + float spd = speed * (0.55f + 0.70f * NextFloat()); + Vector3 vel = new Vector3(MathF.Cos(ang) * spd, 0.8f + NextFloat() * 1.4f, MathF.Sin(ang) * spd) + n * (0.4f * spd); + float life = 0.45f + NextFloat() * 0.45f; + EmitRaw(pos + new Vector3(NextSigned() * 0.35f, 0.08f, NextSigned() * 0.35f), vel, dustColor, widthM, life, TypeDustMote, 3.6f); + } + } + + public void EmitThermalPoolEmber(Vector3 pos, float radius, Color accentCol) + { + EnsureInitialized(); + float ang = NextFloat() * MathF.Tau; + float r = MathF.Sqrt(NextFloat()) * MathF.Max(0.5f, radius * 0.85f); + Vector3 p = pos + new Vector3(MathF.Cos(ang) * r, 0.18f, MathF.Sin(ang) * r); + Vector3 vel = new(NextSigned() * 0.7f, 2.0f + NextFloat() * 1.8f, NextSigned() * 0.7f); + Color hdr = new(accentCol.R * 3.8f, accentCol.G * 3.8f, accentCol.B * 3.8f, 0.95f); + EmitRaw(p, vel, hdr, 0.055f, 0.65f + NextFloat() * 0.45f, TypeBuoyantEmber, 1.4f); + } + + public void EmitPodRetroSparksAndDust(Vector3 podBasePos, float agl, Color groundTint, bool isContender) + { + EnsureInitialized(); + float scale = isContender ? 1.2f : 0.85f; + Color sparkHdr = new(4.2f, 2.4f, 0.75f, 0.98f); + for (int i = 0; i < 2; i++) + { + Vector3 vel = new(NextSigned() * 6.5f, -(11f + NextFloat() * 7f), NextSigned() * 6.5f); + EmitRaw(podBasePos + new Vector3(NextSigned() * 0.6f, 0.1f, NextSigned() * 0.6f), vel, sparkHdr, 0.048f * scale, 0.24f + NextFloat() * 0.14f, TypeVelocitySpark, 1.2f); + } + + if (agl < 60f) + { + float washT = Math.Clamp(1f - agl / 60f, 0.2f, 1f); + Vector3 groundPos = podBasePos - new Vector3(0f, MathF.Max(0f, agl), 0f) + new Vector3(0f, 0.22f, 0f); + Color dustCol = new(groundTint.R * 1.1f, groundTint.G * 1.1f, groundTint.B * 1.1f, 0.75f * washT); + int moteCount = isContender ? 4 : 2; + for (int d = 0; d < moteCount; d++) + { + float ang = NextFloat() * MathF.Tau; + float spd = (7.5f + NextFloat() * 8.5f) * washT * scale; + Vector3 vel = new(MathF.Cos(ang) * spd, 1.0f + NextFloat() * 1.4f, MathF.Sin(ang) * spd); + EmitRaw(groundPos + new Vector3(MathF.Cos(ang) * 0.9f, 0f, MathF.Sin(ang) * 0.9f), vel, dustCol, 0.07f * scale, 0.55f + NextFloat() * 0.25f, TypeDustMote, 3.4f); + } + } + } + + public void EmitPodTouchdownSparksAndDust(Vector3 pos, Vector3 normal, Color groundTint, bool isContender) + { + EnsureInitialized(); + float scale = isContender ? 1.3f : 0.95f; + EmitSparkBurst(pos + normal * 0.45f, normal, isContender ? 16 : 8, new Color(4.5f, 2.5f, 0.75f, 0.98f), 18f * scale, 0.048f); + EmitEmberBurst(pos + normal * 0.45f, isContender ? 10 : 5, new Color(3.6f, 1.6f, 0.45f, 0.95f), 6.5f * scale, 0.055f); + EmitDustMotes(pos + normal * 0.25f, normal, isContender ? 14 : 8, groundTint with { A = 0.80f }, 10f * scale, 0.075f); + } + + private void EmitRaw(Vector3 pos, Vector3 vel, Color hdrColor, float widthM, float lifetimeSec, int type, float drag) + { + float packedTypeAndDrag = type + Math.Clamp(drag, 0f, 19.9f) * 0.05f; + _particles.EmitParticle( + new Transform3D(Basis.Identity, pos), + vel, + hdrColor, + new Color(widthM, 0f, lifetimeSec, packedTypeAndDrag), + EmitFlagsAll); + TotalEmittedCount++; + } + + private float NextFloat() + { + uint x = _rng; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + _rng = x; + return (x & 0x00FFFFFFu) / 16777216f; + } + + private float NextSigned() => NextFloat() * 2f - 1f; +} diff --git a/client/Main.cs b/client/Main.cs index 9d76e57..818d352 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -149,6 +149,7 @@ public partial class Main : Node3D _arena = new ArenaRenderer { Name = "Arena" }; AddChild(_arena); _arena.AssetCache.PreloadAll(); + _atmosphere.BindEmitterPool(_arena.Volumetrics); _audio = new ArenaAudioSystem { Name = "ArenaAudio" }; AddChild(_audio); @@ -298,6 +299,11 @@ public partial class Main : Node3D { _perfTargetFrames = perfFrames; ArenaSession.PerfEnabled = true; + RenderingServer.ViewportSetMeasureRenderTime(GetViewport().GetViewportRid(), true); + if (_atmosphere.VolumetricEffect is not null) + { + _atmosphere.VolumetricEffect.ProfilingEnabled = true; + } } else if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_AUTO_EXIT_FRAMES"), out int autoExitFrames) && autoExitFrames > 0) { @@ -878,6 +884,7 @@ public partial class Main : Node3D Vector3 startVec = new(localStart.X, localStart.Y, localStart.Z); Vector3 startFwd = new(MathF.Sin(localStart.Yaw), 0f, MathF.Cos(localStart.Yaw)); _arena.Particles.PrewarmFlashLights(startVec, startFwd); + _arena.GpuSparks.Prewarm(startVec); _arena.PomDecals.PrewarmShader(startVec); _hud.Sync(_session); } @@ -1482,7 +1489,14 @@ public partial class Main : Node3D GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}"); int ticks = Math.Max(1, _perfPhysicsTicks); GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / ticks:F2} ai={ArenaSession.PerfAiMs / ticks:F2} drive={ArenaSession.PerfDriveMs / ticks:F2} world={ArenaSession.PerfWorldMs / ticks:F2} sync={ArenaSession.PerfBodySyncMs / ticks:F2} detect={ArenaSession.PerfDetectMs / ticks:F2} weapons={ArenaSession.PerfWeaponsMs / ticks:F2}"); - GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} particlesActive={_arena.Particles.ActiveParticleCount} flashLightsPeak={_arena.Particles.PeakFlashLightCount} tracers={_session?.ViewState.Tracers.Count ?? 0}"); + GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} gpuSparksEmitted={_arena.GpuSparks.TotalEmittedCount} volEmitters={_arena.Volumetrics.ActiveEmitterCount} volImpulses={_arena.Volumetrics.ActiveImpulseCount} flashLightsPeak={_arena.Particles.PeakFlashLightCount} tracers={_session?.ViewState.Tracers.Count ?? 0}"); + if (_atmosphere.VolumetricEffect is { } volFx) + { + Rid vpRid = GetViewport().GetViewportRid(); + double vpGpuMs = RenderingServer.ViewportGetMeasuredRenderTimeGpu(vpRid); + double vpCpuMs = RenderingServer.ViewportGetMeasuredRenderTimeCpu(vpRid); + GD.Print($"Cut10bGpuMs: total={volFx.LastTotalGpuMs:F3} flow={volFx.LastFlowGpuMs:F3} cull={volFx.LastCullGpuMs:F3} march={volFx.LastMarchGpuMs:F3} comp={volFx.LastCompGpuMs:F3} viewportGpuMs={vpGpuMs:F2} viewportCpuMs={vpCpuMs:F2}"); + } if (_session is not null) { var net = _session.ConnectionStatus; diff --git a/client/ParticlePool.cs b/client/ParticlePool.cs index 3e61689..023cacb 100644 --- a/client/ParticlePool.cs +++ b/client/ParticlePool.cs @@ -6,40 +6,16 @@ using RustToDust.Core; namespace RustToDust.Client; /// -/// Single-draw-call GPU billboard particle pool ( backed by -/// particle_billboard.gdshader) plus the strictly capped [2] -/// dynamic combat flash pool for Forward+ Vulkan. +/// Owns ONLY the strictly capped [2] dynamic combat flash pool +/// plus idempotent deduplication and dispatch into +/// (smoke/fire/shockwaves) and +/// ( sparks/embers/dust/muzzle bursts). +/// Zero CPU particle buffers or billboard MultiMeshes. /// public partial class ParticlePool : Node3D { - public const int MaxParticles = 512; public const int MaxFlashLights = 2; - public const float ModeDustSmoke = 0f; - public const float ModeMuzzleStarburst = 1f; - public const float ModeSparkStreak = 2f; - public const float ModeSteamFire = 3f; - - private struct ParticleSlot - { - public bool Active; - public float Mode; - public Vector3 Position; - public Vector3 Velocity; - public float Gravity; - public float Drag; - public float StartSize; - public float EndSize; - public float AspectY; - public float Rotation; - public float AngularVel; - public float Emissive; - public Color ColorStart; - public Color ColorEnd; - public float Age; - public float Lifetime; - } - private struct FlashLightSlot { public OmniLight3D Light; @@ -52,7 +28,6 @@ public partial class ParticlePool : Node3D public Color Color; } - private readonly ParticleSlot[] _particles = new ParticleSlot[MaxParticles]; private readonly FlashLightSlot[] _flashLights = new FlashLightSlot[MaxFlashLights]; // Bounded rolling dedupe buffers (zero polling cursor on MatchState) @@ -61,15 +36,11 @@ public partial class ParticlePool : Node3D private readonly long[] _recentHitIds = new long[64]; private int _recentHitCursor; - private MultiMesh _multiMesh = null!; - private MultiMeshInstance3D _instanceNode = null!; - private ShaderMaterial _material = null!; - private int _writeCursor; + private VolumetricEmitterPool? _volumetrics; + private GpuSparksSystem? _gpuSparks; private int _warmupFramesRemaining; private bool _initialized; - private uint _rng = 0x7A3B91E5u; - public int ActiveParticleCount { get; private set; } public int FlashLightPoolSize => MaxFlashLights; public int ActiveFlashLightCount @@ -87,6 +58,12 @@ public partial class ParticlePool : Node3D public int PeakFlashLightCount { get; private set; } + public void BindTargets(VolumetricEmitterPool volumetrics, GpuSparksSystem gpuSparks) + { + _volumetrics = volumetrics; + _gpuSparks = gpuSparks; + } + public override void _Ready() { EnsureInitialized(); @@ -100,32 +77,6 @@ public partial class ParticlePool : Node3D } _initialized = true; - Shader shader = GD.Load("res://particle_billboard.gdshader") - ?? throw new InvalidOperationException("Failed to load res://particle_billboard.gdshader"); - _material = new ShaderMaterial { Shader = shader }; - - _multiMesh = new MultiMesh - { - TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, - UseColors = true, - UseCustomData = true, - Mesh = new QuadMesh { Size = Vector2.One }, - InstanceCount = MaxParticles, - VisibleInstanceCount = 0 - }; - - _instanceNode = new MultiMeshInstance3D - { - Name = "ParticleBillboardBatch", - Multimesh = _multiMesh, - MaterialOverride = _material, - CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, - CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 500f, 3200f)), - PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, - Visible = false - }; - AddChild(_instanceNode); - for (int i = 0; i < MaxFlashLights; i++) { var light = new OmniLight3D @@ -144,7 +95,7 @@ public partial class ParticlePool : Node3D } /// - /// Pre-warms the pooled nodes on startup for 1 rendered frame + /// Pre-warms the pooled nodes on startup for 2 rendered frames /// with near-zero energy so Forward+ compiles lit shader variants before combat begins. /// public void PrewarmFlashLights(Vector3 nearPos, Vector3 forwardHoriz) @@ -168,31 +119,18 @@ public partial class ParticlePool : Node3D slot.Light.LightEnergy = 0.001f; slot.Light.Visible = true; } - - // Also pre-warm the particle billboard shader on frame 0 with 1 micro-quad - _multiMesh.SetInstanceTransform(0, new Transform3D(Basis.FromScale(new Vector3(0.01f, 0.01f, 1f)), nearPos)); - _multiMesh.SetInstanceColor(0, new Color(1f, 1f, 1f, 0.01f)); - _multiMesh.SetInstanceCustomData(0, new Color(ModeDustSmoke, 0f, 0f, 0f)); - _multiMesh.VisibleInstanceCount = 1; - _instanceNode.Visible = true; } public void ClearAll() { EnsureInitialized(); - Array.Clear(_particles, 0, _particles.Length); Array.Clear(_recentShotIds, 0, _recentShotIds.Length); Array.Clear(_recentHitIds, 0, _recentHitIds.Length); _recentShotCursor = 0; _recentHitCursor = 0; - _writeCursor = 0; _warmupFramesRemaining = 0; - ActiveParticleCount = 0; PeakFlashLightCount = 0; - _multiMesh.VisibleInstanceCount = 0; - _instanceNode.Visible = false; - for (int i = 0; i < _flashLights.Length; i++) { _flashLights[i].Active = false; @@ -293,35 +231,9 @@ public partial class ParticlePool : Node3D float massScale = Math.Clamp(pulse.MassKg / 2600f, 0.72f, 1.55f); float loadScale = Math.Clamp(pulse.LoadG, 0.5f, 1.8f); - int count = pulse.MassKg >= 3600f ? 3 : 2; - - Color dustStart = new(groundTint.R, groundTint.G, groundTint.B, 0.50f); - Color dustEnd = new(groundTint.R * 0.92f, groundTint.G * 0.92f, groundTint.B * 0.92f, 0.0f); - - for (int i = 0; i < count; i++) - { - float ang = (i / (float)count) * MathF.Tau + NextFloat() * 0.8f; - float speed = (2.2f + NextFloat() * 2.6f) * massScale * MathF.Sqrt(loadScale); - Vector3 vel = new(MathF.Cos(ang) * speed, 0.85f + NextFloat() * 1.1f, MathF.Sin(ang) * speed); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = footPos + new Vector3(MathF.Cos(ang) * 0.25f, 0f, MathF.Sin(ang) * 0.25f), - Velocity = vel, - Gravity = 0.25f, - Drag = 2.8f, - StartSize = 0.55f * massScale, - EndSize = MathF.Min(2.2f, 1.55f * massScale), - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.4f, - Emissive = 0f, - ColorStart = dustStart, - ColorEnd = dustEnd, - Lifetime = 0.35f + NextFloat() * 0.18f - }); - } + int count = pulse.MassKg >= 3600f ? 6 : 4; + _gpuSparks?.EmitDustMotes(footPos, Vector3.Up, count, groundTint with { A = 0.72f }, 3.4f * massScale * MathF.Sqrt(loadScale), 0.06f * massScale); + _volumetrics?.EmitFootstepOrTirePuff(footPos, groundTint, massScale); } public void EmitTireDust(Vector3 worldPos, Vector3 vehicleVel, Color groundTint, float intensity, Vector3 camPos, bool hasCam) @@ -333,27 +245,8 @@ public partial class ParticlePool : Node3D } float scale = Math.Clamp(intensity, 0.5f, 1.5f); - Color dustStart = new(groundTint.R, groundTint.G, groundTint.B, 0.42f); - Color dustEnd = new(groundTint.R * 0.95f, groundTint.G * 0.95f, groundTint.B * 0.95f, 0.0f); - - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = worldPos + new Vector3(NextSigned() * 0.3f, 0.18f, NextSigned() * 0.3f), - Velocity = -vehicleVel * 0.15f + new Vector3(NextSigned() * 1.1f, 0.9f + NextFloat() * 0.8f, NextSigned() * 1.1f), - Gravity = 0.15f, - Drag = 2.4f, - StartSize = 0.50f * scale, - EndSize = MathF.Min(2.1f, 1.65f * scale), - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.2f, - Emissive = 0f, - ColorStart = dustStart, - ColorEnd = dustEnd, - Lifetime = 0.36f + NextFloat() * 0.16f - }); + _gpuSparks?.EmitDustMotes(worldPos, Vector3.Up, 3, groundTint with { A = 0.65f }, 2.6f * scale, 0.055f * scale); + _volumetrics?.EmitFootstepOrTirePuff(worldPos, groundTint, scale * 0.9f); } public void EmitThermalVent(Vector3 worldPos, float thermalRatio, Vector3 camPos, bool hasCam) @@ -364,46 +257,10 @@ public partial class ParticlePool : Node3D return; } - float heatT = Math.Clamp((thermalRatio - 0.85f) / 0.25f, 0f, 1f); - SpawnParticle(new ParticleSlot + _volumetrics?.EmitThermalVentPlume(worldPos, thermalRatio); + if (thermalRatio >= 0.94f) { - Active = true, - Mode = ModeSteamFire, - Position = worldPos + new Vector3(NextSigned() * 0.25f, 0.15f, NextSigned() * 0.25f), - Velocity = new Vector3(NextSigned() * 0.9f, 2.2f + NextFloat() * 1.5f, NextSigned() * 0.9f), - Gravity = -0.35f, - Drag = 1.6f, - StartSize = 0.40f, - EndSize = 1.25f + heatT * 0.35f, - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.8f, - Emissive = 0.35f + heatT * 0.85f, - ColorStart = new Color(0.95f, 0.88f - heatT * 0.32f, 0.78f - heatT * 0.50f, 0.62f), - ColorEnd = new Color(0.65f, 0.58f, 0.54f, 0.0f), - Lifetime = 0.36f + NextFloat() * 0.16f - }); - - if (heatT > 0.35f) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSparkStreak, - Position = worldPos, - Velocity = new Vector3(NextSigned() * 3.5f, 2.5f + NextFloat() * 3.5f, NextSigned() * 3.5f), - Gravity = 9.0f, - Drag = 0.6f, - StartSize = 0.24f, - EndSize = 0.10f, - AspectY = 1.3f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = 0f, - Emissive = 2.6f, - ColorStart = new Color(1.0f, 0.62f, 0.16f, 0.95f), - ColorEnd = new Color(0.9f, 0.24f, 0.06f, 0.0f), - Lifetime = 0.22f + NextFloat() * 0.12f - }); + _gpuSparks?.EmitSparkBurst(worldPos, Vector3.Up, 3, new Color(4.0f, 2.2f, 0.55f, 0.96f), 6.5f, 0.038f); } } @@ -415,46 +272,96 @@ public partial class ParticlePool : Node3D return; } - float dmgT = Math.Clamp((0.35f - coreHpRatio) / 0.35f, 0f, 1f); - SpawnParticle(new ParticleSlot + _volumetrics?.EmitDamageSmokePlume(worldPos, coreHpRatio); + if (coreHpRatio < 0.24f) { - Active = true, - Mode = ModeDustSmoke, - Position = worldPos + new Vector3(NextSigned() * 0.35f, 0.35f, NextSigned() * 0.35f), - Velocity = new Vector3(NextSigned() * 0.8f, 2.4f + NextFloat() * 1.4f, NextSigned() * 0.8f), - Gravity = -0.35f, - Drag = 1.2f, - StartSize = 0.58f, - EndSize = MathF.Min(2.2f, 1.65f + dmgT * 0.55f), - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.1f, - Emissive = 0f, - ColorStart = new Color(0.18f, 0.16f, 0.15f, 0.70f), - ColorEnd = new Color(0.10f, 0.10f, 0.10f, 0.0f), - Lifetime = 0.55f + NextFloat() * 0.25f - }); + _gpuSparks?.EmitEmberBurst(worldPos, 2, new Color(3.8f, 1.8f, 0.45f, 0.92f), 2.2f, 0.045f); + } + } - if (dmgT > 0.3f && NextFloat() < 0.65f) + public void EmitOrdnanceBurst(Vector3 pos, Color accentCol, int sparkCount, float radiusScale, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && pos.DistanceSquaredTo(camPos) > 220f * 220f) { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = worldPos + new Vector3(NextSigned() * 0.22f, 0.25f, NextSigned() * 0.22f), - Velocity = new Vector3(NextSigned() * 0.6f, 2.1f + NextFloat() * 1.1f, NextSigned() * 0.6f), - Gravity = -0.4f, - Drag = 1.8f, - StartSize = 0.45f, - EndSize = 0.95f, - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 2.0f, - Emissive = 2.2f, - ColorStart = new Color(1.0f, 0.56f, 0.14f, 0.92f), - ColorEnd = new Color(0.65f, 0.16f, 0.04f, 0.0f), - Lifetime = 0.26f + NextFloat() * 0.12f - }); + return; + } + + Color hdr = new(accentCol.R * 4.2f, accentCol.G * 4.2f, accentCol.B * 4.2f, 0.98f); + _gpuSparks?.EmitSparkBurst(pos, Vector3.Up, Math.Clamp(sparkCount * 3, 6, 24), hdr, 14f * radiusScale, 0.044f); + _gpuSparks?.EmitEmberBurst(pos, Math.Clamp(sparkCount, 3, 12), hdr * 0.85f, 4.5f * radiusScale, 0.052f); + } + + public void EmitThermalPoolEmber(Vector3 pos, float radius, Color accentCol, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && pos.DistanceSquaredTo(camPos) > 150f * 150f) + { + return; + } + + _gpuSparks?.EmitThermalPoolEmber(pos, radius, accentCol); + } + + public void EmitPodReentryStreak(Vector3 podPos, Vector3 podVel, float heatGlow, bool isContender, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && podPos.DistanceSquaredTo(camPos) > 650f * 650f) + { + return; + } + + _volumetrics?.EmitPodReentryPlume(podPos, podVel, heatGlow, isContender); + _gpuSparks?.EmitEmberBurst(podPos, isContender ? 3 : 2, new Color(4.0f, 2.2f, 0.65f, 0.95f), 2.5f, 0.048f); + } + + public void EmitPodRetroBurn( + Vector3 podBasePos, + float agl, + Color groundTint, + bool isContender, + bool isLocal, + Vector3 camPos, + bool hasCam) + { + EnsureInitialized(); + float distSq = hasCam ? podBasePos.DistanceSquaredTo(camPos) : 0f; + if (hasCam && distSq > 480f * 480f) + { + return; + } + + _volumetrics?.EmitPodRetroPlume(podBasePos, agl, groundTint, isContender); + _gpuSparks?.EmitPodRetroSparksAndDust(podBasePos, agl, groundTint, isContender); + + if (isLocal || !hasCam || distSq <= 95f * 95f) + { + SpawnFlashLight(podBasePos - new Vector3(0f, 0.6f, 0f), new Color(1.0f, 0.60f, 0.18f), 3.8f, 14f, 0.09f, priority: isLocal ? 8 : 3); + } + } + + public void EmitPodTouchdownBurst( + Vector3 pos, + Vector3 normal, + Color groundTint, + bool isContender, + bool isLocal, + Vector3 camPos, + bool hasCam) + { + EnsureInitialized(); + float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f; + if (!isLocal && hasCam && distSq > 360f * 360f) + { + return; + } + + _volumetrics?.EmitPodTouchdownPlume(pos, normal, groundTint, isContender); + _gpuSparks?.EmitPodTouchdownSparksAndDust(pos, normal, groundTint, isContender); + + if (isLocal || !hasCam || distSq <= 140f * 140f) + { + SpawnFlashLight(pos + normal * 1.2f, new Color(1.0f, 0.58f, 0.16f), 5.8f, 18f, 0.18f, priority: isLocal ? 10 : 6); } } @@ -469,49 +376,6 @@ public partial class ParticlePool : Node3D EnsureInitialized(); float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; - // 1. Advance particles and pack active billboards into MultiMesh - int visibleCount = 0; - for (int i = 0; i < MaxParticles; i++) - { - ref ParticleSlot p = ref _particles[i]; - if (!p.Active) - { - continue; - } - - if (stepDt > 0f) - { - p.Age += stepDt; - if (p.Age >= p.Lifetime) - { - p.Active = false; - continue; - } - if (p.Drag > 0f) - { - p.Velocity *= MathF.Exp(-p.Drag * stepDt); - } - p.Velocity.Y -= p.Gravity * stepDt; - p.Position += p.Velocity * stepDt; - p.Rotation += p.AngularVel * stepDt; - } - - float ageNorm = Math.Clamp(p.Age / MathF.Max(0.01f, p.Lifetime), 0f, 1f); - float size = Mathf.Lerp(p.StartSize, p.EndSize, ageNorm); - Color col = p.ColorStart.Lerp(p.ColorEnd, ageNorm); - - var scale = new Vector3(size, size * p.AspectY, 1f); - _multiMesh.SetInstanceTransform(visibleCount, new Transform3D(Basis.FromScale(scale), p.Position)); - _multiMesh.SetInstanceColor(visibleCount, col); - _multiMesh.SetInstanceCustomData(visibleCount, new Color(p.Mode, ageNorm, p.Emissive, p.Rotation)); - visibleCount++; - } - - ActiveParticleCount = visibleCount; - _multiMesh.VisibleInstanceCount = visibleCount; - _instanceNode.Visible = visibleCount > 0; - - // 2. Advance pooled OmniLight3D[2] dynamic flashes int activeLights = 0; for (int i = 0; i < _flashLights.Length; i++) { @@ -586,7 +450,7 @@ public partial class ParticlePool : Node3D Vector3 start = new(shot.StartX, shot.StartY, shot.StartZ); Vector3 end = new(shot.EndX, shot.EndY, shot.EndZ); - if (hasCam && start.DistanceSquaredTo(camPos) > 120f * 120f) + if (hasCam && start.DistanceSquaredTo(camPos) > 140f * 140f) { return; } @@ -595,268 +459,80 @@ public partial class ParticlePool : Node3D bool isRecoilless = string.Equals(shot.WeaponId, "recoilless", StringComparison.Ordinal); bool isLance = string.Equals(shot.WeaponId, "gilded_lance", StringComparison.Ordinal); bool isPd = string.Equals(shot.WeaponId, "pd_flak", StringComparison.Ordinal); + Vector3 aimDir = (end - start).LengthSquared() > 1e-4f ? (end - start).Normalized() : Vector3.Forward; switch (wClass) { case WeaponVisualClass.KineticLight: - { - float flashSize = isPd ? 0.62f : 0.44f; - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = flashSize, - EndSize = flashSize * 0.45f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.2f, - ColorStart = new Color(1.0f, 0.85f, 0.42f, 0.95f), - ColorEnd = new Color(0.95f, 0.55f, 0.16f, 0.0f), - Lifetime = 0.065f - }); + _gpuSparks?.EmitMuzzleStarburst(start, new Color(3.8f, 2.8f, 1.1f, 0.96f), isPd ? 0.42f : 0.30f, 0.07f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 3, new Color(4.0f, 2.8f, 0.9f, 0.95f), 11f, 0.035f); break; - } case WeaponVisualClass.Autocannon: - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = 1.05f, - EndSize = 0.45f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.8f, - ColorStart = new Color(1.0f, 0.72f, 0.25f, 0.98f), - ColorEnd = new Color(0.95f, 0.40f, 0.10f, 0.0f), - Lifetime = 0.08f - }); - for (int p = 0; p < 2; p++) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = start + new Vector3(NextSigned() * 0.2f, NextFloat() * 0.15f, NextSigned() * 0.2f), - Velocity = new Vector3(NextSigned() * 0.9f, 1.1f + NextFloat() * 0.8f, NextSigned() * 0.9f), - Gravity = -0.15f, - Drag = 2.2f, - StartSize = 0.35f, - EndSize = 1.15f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.4f, - Emissive = 0f, - ColorStart = new Color(0.55f, 0.50f, 0.44f, 0.46f), - ColorEnd = new Color(0.42f, 0.40f, 0.38f, 0.0f), - Lifetime = 0.32f - }); - } + _gpuSparks?.EmitMuzzleStarburst(start, new Color(4.4f, 2.6f, 0.75f, 0.98f), 0.56f, 0.08f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 5, new Color(4.2f, 2.5f, 0.7f, 0.96f), 13f, 0.04f); + _volumetrics?.EmitMuzzleBreechPuff(start, end, sampleGroundTint(start.X, start.Z), wClass, isRecoilless: false); if (!hasCam || start.DistanceSquaredTo(camPos) <= 45f * 45f) { SpawnFlashLight(start, new Color(1.0f, 0.68f, 0.24f), 2.8f, 10.5f, 0.10f, priority: 3); } break; - } case WeaponVisualClass.Explosive: - { - float flashSize = isRecoilless ? 1.55f : 0.85f; - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = flashSize, - EndSize = flashSize * 0.48f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 3.2f, - ColorStart = new Color(1.0f, 0.68f, 0.22f, 0.98f), - ColorEnd = new Color(0.95f, 0.32f, 0.08f, 0.0f), - Lifetime = 0.095f - }); - - int puffs = isRecoilless ? 4 : 2; - Color gTint = sampleGroundTint(start.X, start.Z); - Color smokeCol = new( - Mathf.Lerp(0.56f, gTint.R, 0.35f), - Mathf.Lerp(0.52f, gTint.G, 0.35f), - Mathf.Lerp(0.46f, gTint.B, 0.35f), - 0.58f); - for (int p = 1; p <= puffs; p++) - { - float frac = p / (float)(puffs + 1); - Vector3 smokePos = start.Lerp(end, frac); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = smokePos, - Velocity = new Vector3(NextSigned() * 0.6f, 1.3f + NextFloat() * 0.6f, NextSigned() * 0.6f), - Gravity = -0.2f, - Drag = 1.8f, - StartSize = isRecoilless ? 0.48f : 0.30f, - EndSize = isRecoilless ? 1.65f : 0.95f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.2f, - Emissive = 0f, - ColorStart = smokeCol, - ColorEnd = smokeCol with { A = 0f }, - Lifetime = isRecoilless ? 0.48f : 0.32f - }); - } - + _gpuSparks?.EmitMuzzleStarburst(start, new Color(4.8f, 2.6f, 0.70f, 0.98f), isRecoilless ? 0.78f : 0.48f, 0.09f); + _gpuSparks?.EmitSparkBurst(start, aimDir, isRecoilless ? 8 : 4, new Color(4.5f, 2.4f, 0.65f, 0.98f), 15f, 0.042f); + _volumetrics?.EmitMuzzleBreechPuff(start, end, sampleGroundTint(start.X, start.Z), wClass, isRecoilless); if (!hasCam || start.DistanceSquaredTo(camPos) <= 65f * 65f) { SpawnFlashLight(start, new Color(1.0f, 0.58f, 0.18f), isRecoilless ? 4.2f : 2.6f, isRecoilless ? 14f : 10f, 0.13f, priority: 5); } break; - } case WeaponVisualClass.ThermalBeam: { - Color beamCol = isLance - ? new Color(1.0f, 0.78f, 0.28f, 0.96f) - : new Color(0.32f, 0.90f, 1.0f, 0.96f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = isLance ? 1.25f : 0.85f, - EndSize = 0.42f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 3.4f, - ColorStart = beamCol, - ColorEnd = beamCol with { A = 0f }, - Lifetime = 0.09f - }); + Color beamCol = isLance ? new Color(4.5f, 3.2f, 0.95f, 0.96f) : new Color(0.95f, 3.6f, 4.5f, 0.96f); + _gpuSparks?.EmitMuzzleStarburst(start, beamCol, isLance ? 0.68f : 0.48f, 0.09f); if (!hasCam || start.DistanceSquaredTo(camPos) <= 45f * 45f) { - SpawnFlashLight(start, beamCol with { A = 1f }, isLance ? 3.5f : 2.6f, 11f, 0.12f, priority: 4); + Color lCol = isLance ? new Color(1.0f, 0.78f, 0.28f) : new Color(0.32f, 0.90f, 1.0f); + SpawnFlashLight(start, lCol, isLance ? 3.5f : 2.6f, 11f, 0.12f, priority: 4); } break; } case WeaponVisualClass.GaussRail: { - Color gaussCol = new(0.22f, 0.78f, 1.0f, 0.98f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = 1.45f, - EndSize = 0.50f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 3.8f, - ColorStart = new Color(0.75f, 0.96f, 1.0f, 1.0f), - ColorEnd = gaussCol with { A = 0f }, - Lifetime = 0.095f - }); - SpawnSparkBurst(start, (end - start).Normalized(), 4, gaussCol, 14f); + Color gaussHdr = new(0.85f, 3.5f, 4.8f, 0.98f); + _gpuSparks?.EmitMuzzleStarburst(start, gaussHdr, 0.72f, 0.09f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 10, gaussHdr, 19f, 0.04f); if (!hasCam || start.DistanceSquaredTo(camPos) <= 65f * 65f) { - SpawnFlashLight(start, gaussCol with { A = 1f }, 4.2f, 14f, 0.11f, priority: 5); + SpawnFlashLight(start, new Color(0.22f, 0.78f, 1.0f), 4.2f, 14f, 0.11f, priority: 5); } break; } case WeaponVisualClass.PlasmaPpc: { - Color plasmaCol = new(0.16f, 0.88f, 0.95f, 0.96f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = start, - Velocity = (end - start).Normalized() * 3.5f, - StartSize = 0.85f, - EndSize = 2.0f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 3.2f, - ColorStart = plasmaCol, - ColorEnd = new Color(0.08f, 0.45f, 0.65f, 0f), - Lifetime = 0.24f - }); + Color plasmaHdr = new(0.65f, 3.4f, 4.2f, 0.96f); + _gpuSparks?.EmitMuzzleStarburst(start, plasmaHdr, 0.65f, 0.09f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 6, plasmaHdr, 12f, 0.042f); if (!hasCam || start.DistanceSquaredTo(camPos) <= 55f * 55f) { - SpawnFlashLight(start, plasmaCol with { A = 1f }, 3.4f, 12f, 0.12f, priority: 4); + SpawnFlashLight(start, new Color(0.16f, 0.88f, 0.95f), 3.4f, 12f, 0.12f, priority: 4); } break; } case WeaponVisualClass.RocketSalvo: - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = 1.15f, - EndSize = 0.55f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 3.0f, - ColorStart = new Color(1.0f, 0.72f, 0.24f, 0.96f), - ColorEnd = new Color(0.95f, 0.35f, 0.08f, 0f), - Lifetime = 0.10f - }); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = start, - Velocity = new Vector3(NextSigned() * 1.2f, 1.4f, NextSigned() * 1.2f), - Gravity = -0.15f, - Drag = 1.8f, - StartSize = 0.55f, - EndSize = 1.85f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.3f, - Emissive = 0f, - ColorStart = new Color(0.62f, 0.58f, 0.52f, 0.55f), - ColorEnd = new Color(0.45f, 0.42f, 0.38f, 0f), - Lifetime = 0.42f - }); + _gpuSparks?.EmitMuzzleStarburst(start, new Color(4.4f, 2.6f, 0.75f, 0.96f), 0.62f, 0.095f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 6, new Color(4.2f, 2.4f, 0.65f, 0.96f), 13f, 0.042f); + _volumetrics?.EmitMuzzleBreechPuff(start, end, sampleGroundTint(start.X, start.Z), wClass, isRecoilless: false); break; - } case WeaponVisualClass.SwarmSmart: - { - Color swarmCol = new(0.56f, 0.96f, 0.28f, 0.96f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = 0.78f, - EndSize = 0.36f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.6f, - ColorStart = swarmCol, - ColorEnd = new Color(0.55f, 0.28f, 0.88f, 0f), - Lifetime = 0.085f - }); + _gpuSparks?.EmitMuzzleStarburst(start, new Color(2.2f, 4.0f, 1.0f, 0.96f), 0.48f, 0.085f); break; - } } } @@ -880,7 +556,7 @@ public partial class ParticlePool : Node3D } Vector3 pos = new(hit.HitX, hit.HitY, hit.HitZ); - if (hasCam && pos.DistanceSquaredTo(camPos) > 125f * 125f) + if (hasCam && pos.DistanceSquaredTo(camPos) > 180f * 180f) { return; } @@ -895,23 +571,8 @@ public partial class ParticlePool : Node3D if (hit.IsAirburst || (wClass == WeaponVisualClass.KineticLight && string.Equals(hit.WeaponId, "pd_flak", StringComparison.Ordinal))) { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos, - Velocity = Vector3.Zero, - StartSize = 0.50f, - EndSize = 2.15f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.5f, - Emissive = 1.6f, - ColorStart = new Color(1.0f, 0.55f, 0.16f, 0.90f), - ColorEnd = new Color(0.24f, 0.16f, 0.12f, 0.0f), - Lifetime = 0.35f - }); - SpawnSparkBurst(pos, normal, 3, new Color(1.0f, 0.68f, 0.24f, 0.98f), 10f); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: true); + _gpuSparks?.EmitSparkBurst(pos, normal, 10, new Color(4.5f, 2.6f, 0.75f, 0.98f), 14f, 0.042f); return; } @@ -920,45 +581,26 @@ public partial class ParticlePool : Node3D case WeaponVisualClass.KineticLight: if (isTerrain) { - EmitImpactDustPlume(pos, normal, groundTint, count: 2, size: 1.0f); + _gpuSparks?.EmitDustMotes(pos, normal, 5, groundTint with { A = 0.72f }, 4.5f, 0.055f); } else { - SpawnSparkBurst(pos, normal, 3, new Color(1.0f, 0.88f, 0.45f, 0.96f), 8.5f); + _gpuSparks?.EmitSparkBurst(pos, normal, 7, new Color(4.4f, 3.2f, 1.2f, 0.96f), 11f, 0.036f); } break; case WeaponVisualClass.Autocannon: - EmitImpactDustPlume(pos, normal, groundTint, count: 2, size: 1.45f); - SpawnSparkBurst(pos, normal, 3, new Color(1.0f, 0.72f, 0.26f, 0.98f), 11.5f); + _gpuSparks?.EmitSparkBurst(pos, normal, 9, new Color(4.4f, 2.6f, 0.75f, 0.98f), 13.5f, 0.04f); + _gpuSparks?.EmitDustMotes(pos, normal, 6, groundTint with { A = 0.75f }, 5.5f, 0.06f); + _volumetrics?.EmitFootstepOrTirePuff(pos, groundTint, 1.0f); break; case WeaponVisualClass.Explosive: { bool isRecoilless = string.Equals(hit.WeaponId, "recoilless", StringComparison.Ordinal); - EmitImpactDustPlume(pos, normal, groundTint, count: isRecoilless ? 4 : 2, size: isRecoilless ? 1.85f : 1.35f); - for (int f = 0; f < (isRecoilless ? 3 : 2); f++) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos + normal * 0.25f + new Vector3(NextSigned() * 0.5f, NextFloat() * 0.4f, NextSigned() * 0.5f), - Velocity = normal * (1.8f + NextFloat() * 1.8f) + new Vector3(NextSigned(), 1.2f, NextSigned()), - Gravity = -0.3f, - Drag = 1.6f, - StartSize = isRecoilless ? 0.95f : 0.65f, - EndSize = isRecoilless ? 3.1f : 2.0f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.4f, - Emissive = 2.6f, - ColorStart = new Color(1.0f, 0.64f, 0.18f, 0.95f), - ColorEnd = new Color(0.28f, 0.16f, 0.12f, 0.0f), - Lifetime = isRecoilless ? 0.38f : 0.35f - }); - } - SpawnSparkBurst(pos, normal, isRecoilless ? 5 : 3, new Color(1.0f, 0.64f, 0.20f, 0.98f), 14f); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, isRecoilless ? 16 : 10, new Color(4.8f, 2.5f, 0.7f, 0.98f), 17f, 0.044f); + _gpuSparks?.EmitDustMotes(pos, normal, isRecoilless ? 10 : 6, groundTint with { A = 0.78f }, 7.5f, 0.068f); if (!hasCam || pos.DistanceSquaredTo(camPos) <= 75f * 75f) { SpawnFlashLight(pos + normal * 0.45f, new Color(1.0f, 0.55f, 0.16f), isRecoilless ? 4.8f : 3.2f, isRecoilless ? 14.5f : 11f, 0.14f, priority: 7); @@ -967,27 +609,14 @@ public partial class ParticlePool : Node3D } case WeaponVisualClass.ThermalBeam: - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos, - Velocity = normal * 1.4f, - StartSize = 0.60f, - EndSize = 1.75f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.8f, - ColorStart = new Color(0.45f, 0.94f, 1.0f, 0.94f), - ColorEnd = new Color(0.95f, 0.52f, 0.16f, 0.0f), - Lifetime = 0.35f - }); - SpawnSparkBurst(pos, normal, 4, new Color(0.55f, 0.92f, 1.0f, 0.98f), 12f); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, 10, new Color(1.6f, 3.8f, 4.6f, 0.98f), 13f, 0.04f); break; case WeaponVisualClass.GaussRail: - EmitImpactDustPlume(pos, normal, groundTint, count: 3, size: 1.65f); - SpawnSparkBurst(pos, normal, 6, new Color(0.30f, 0.84f, 1.0f, 0.98f), 17f); + _gpuSparks?.EmitSparkBurst(pos, normal, 16, new Color(1.0f, 3.6f, 4.8f, 0.98f), 20f, 0.042f); + _gpuSparks?.EmitDustMotes(pos, normal, 8, groundTint with { A = 0.76f }, 6.5f, 0.06f); + _volumetrics?.EmitFootstepOrTirePuff(pos, groundTint, 1.2f); if (!hasCam || pos.DistanceSquaredTo(camPos) <= 65f * 65f) { SpawnFlashLight(pos + normal * 0.35f, new Color(0.28f, 0.82f, 1.0f), 4.0f, 13f, 0.12f, priority: 6); @@ -995,44 +624,15 @@ public partial class ParticlePool : Node3D break; case WeaponVisualClass.PlasmaPpc: - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos + normal * 0.2f, - Velocity = normal * 1.6f, - StartSize = 0.90f, - EndSize = 2.6f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 3.2f, - ColorStart = new Color(0.20f, 0.88f, 1.0f, 0.95f), - ColorEnd = new Color(0.12f, 0.38f, 0.52f, 0f), - Lifetime = 0.42f - }); - SpawnSparkBurst(pos, normal, 5, new Color(0.32f, 0.94f, 1.0f, 0.98f), 12.5f); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, 14, new Color(0.95f, 3.8f, 4.6f, 0.98f), 15f, 0.044f); + _gpuSparks?.EmitEmberBurst(pos, 6, new Color(0.75f, 3.2f, 4.0f, 0.92f), 4.5f, 0.05f); break; case WeaponVisualClass.RocketSalvo: - EmitImpactDustPlume(pos, normal, groundTint, count: 4, size: 1.75f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos + normal * 0.25f, - Velocity = normal * 2.2f, - Gravity = -0.25f, - Drag = 1.6f, - StartSize = 0.95f, - EndSize = 2.95f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.8f, - ColorStart = new Color(1.0f, 0.62f, 0.18f, 0.96f), - ColorEnd = new Color(0.28f, 0.16f, 0.12f, 0f), - Lifetime = 0.38f - }); - SpawnSparkBurst(pos, normal, 5, new Color(1.0f, 0.68f, 0.22f, 0.98f), 14.5f); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, 14, new Color(4.6f, 2.6f, 0.75f, 0.98f), 16f, 0.044f); + _gpuSparks?.EmitDustMotes(pos, normal, 8, groundTint with { A = 0.78f }, 7.0f, 0.068f); if (!hasCam || pos.DistanceSquaredTo(camPos) <= 75f * 75f) { SpawnFlashLight(pos + normal * 0.45f, new Color(1.0f, 0.56f, 0.16f), 4.5f, 14f, 0.14f, priority: 7); @@ -1040,131 +640,12 @@ public partial class ParticlePool : Node3D break; case WeaponVisualClass.SwarmSmart: - EmitImpactDustPlume(pos, normal, groundTint, count: 2, size: 1.25f); - SpawnSparkBurst(pos, normal, 4, new Color(0.56f, 0.96f, 0.32f, 0.98f), 12f); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, 10, new Color(2.2f, 4.2f, 1.0f, 0.98f), 13f, 0.04f); break; } } - public void EmitOrdnanceTrail(Vector3 pos, Vector3 vel, Color accentCol, bool isRocket, Vector3 camPos, bool hasCam) - { - EnsureInitialized(); - if (hasCam && pos.DistanceSquaredTo(camPos) > 220f * 220f) - { - return; - } - - Vector3 backVel = vel.LengthSquared() > 1f ? -vel.Normalized() * 4.5f : Vector3.Up * 1.2f; - if (isRocket) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = pos, - Velocity = backVel * 0.4f, - StartSize = 0.58f, - EndSize = 0.20f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.8f, - ColorStart = new Color(1.0f, 0.72f, 0.24f, 0.92f), - ColorEnd = accentCol with { A = 0f }, - Lifetime = 0.12f - }); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = pos, - Velocity = backVel * 0.25f + new Vector3(NextSigned() * 0.6f, 0.7f, NextSigned() * 0.6f), - Gravity = -0.15f, - Drag = 1.8f, - StartSize = 0.32f, - EndSize = 1.25f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.4f, - Emissive = 0f, - ColorStart = new Color(0.58f, 0.54f, 0.48f, 0.46f), - ColorEnd = new Color(0.40f, 0.38f, 0.36f, 0f), - Lifetime = 0.42f - }); - } - else - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSparkStreak, - Position = pos, - Velocity = backVel * 0.25f, - StartSize = 0.24f, - EndSize = 0.08f, - AspectY = 1.4f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.4f, - ColorStart = accentCol with { A = 0.90f }, - ColorEnd = accentCol with { A = 0f }, - Lifetime = 0.16f - }); - } - } - - public void EmitOrdnanceBurst(Vector3 pos, Color accentCol, int sparkCount, float radiusScale, Vector3 camPos, bool hasCam) - { - EnsureInitialized(); - if (hasCam && pos.DistanceSquaredTo(camPos) > 220f * 220f) - { - return; - } - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos, - Velocity = Vector3.Up * 1.5f, - StartSize = 0.65f * radiusScale, - EndSize = 2.2f * radiusScale, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.8f, - ColorStart = accentCol with { A = 0.94f }, - ColorEnd = new Color(0.24f, 0.16f, 0.14f, 0f), - Lifetime = 0.34f - }); - SpawnSparkBurst(pos, Vector3.Up, Math.Clamp(sparkCount, 1, 8), accentCol with { A = 0.98f }, 12f * radiusScale); - } - - public void EmitThermalPoolEmber(Vector3 pos, float radius, Color accentCol, Vector3 camPos, bool hasCam) - { - EnsureInitialized(); - if (hasCam && pos.DistanceSquaredTo(camPos) > 150f * 150f) - { - return; - } - float ang = NextFloat() * MathF.Tau; - float r = MathF.Sqrt(NextFloat()) * MathF.Max(0.5f, radius * 0.85f); - Vector3 p = pos + new Vector3(MathF.Cos(ang) * r, 0.18f, MathF.Sin(ang) * r); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = p, - Velocity = new Vector3(NextSigned() * 0.5f, 1.8f + NextFloat() * 1.4f, NextSigned() * 0.5f), - Gravity = -0.3f, - Drag = 1.2f, - StartSize = 0.36f, - EndSize = 0.92f, - AspectY = 1.25f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.9f, - ColorStart = accentCol with { A = 0.88f }, - ColorEnd = accentCol with { A = 0f }, - Lifetime = 0.45f - }); - } - private void EmitChassisExplosion( Vector3 pos, float massKg, @@ -1172,311 +653,22 @@ public partial class ParticlePool : Node3D bool hasCam, Func sampleGroundTint) { - if (hasCam && pos.DistanceSquaredTo(camPos) > 160f * 160f) + if (hasCam && pos.DistanceSquaredTo(camPos) > 280f * 280f) { return; } - float sizeScale = Math.Clamp(massKg / 2800f, 0.85f, 1.55f); Color gTint = sampleGroundTint(pos.X, pos.Z); + _volumetrics?.EmitChassisExplosion(pos, massKg, gTint); + _gpuSparks?.EmitSparkBurst(pos, Vector3.Up, 32, new Color(5.0f, 2.8f, 0.75f, 0.98f), 22f, 0.046f); + _gpuSparks?.EmitEmberBurst(pos, 16, new Color(4.0f, 1.8f, 0.45f, 0.95f), 7.0f, 0.055f); - for (int i = 0; i < 4; i++) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos + new Vector3(NextSigned() * 0.8f, NextFloat() * 0.9f, NextSigned() * 0.8f), - Velocity = new Vector3(NextSigned() * 2.4f, 2.2f + NextFloat() * 2.8f, NextSigned() * 2.4f), - Gravity = -0.35f, - Drag = 1.4f, - StartSize = 1.1f * sizeScale, - EndSize = MathF.Min(3.8f, 2.7f * sizeScale), - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.5f, - Emissive = 3.0f, - ColorStart = new Color(1.0f, 0.62f, 0.16f, 0.98f), - ColorEnd = new Color(0.22f, 0.12f, 0.08f, 0.0f), - Lifetime = 0.42f + NextFloat() * 0.18f - }); - } - - for (int i = 0; i < 5; i++) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = pos + new Vector3(NextSigned() * 1.1f, NextFloat() * 0.8f, NextSigned() * 1.1f), - Velocity = new Vector3(NextSigned() * 2.8f, 3.0f + NextFloat() * 2.8f, NextSigned() * 2.8f), - Gravity = -0.35f, - Drag = 1.1f, - StartSize = 1.0f * sizeScale, - EndSize = MathF.Min(2.2f, 1.55f * sizeScale), - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.1f, - Emissive = 0f, - ColorStart = new Color(0.20f * 0.6f + gTint.R * 0.2f, 0.18f * 0.6f + gTint.G * 0.2f, 0.16f * 0.6f + gTint.B * 0.2f, 0.80f), - ColorEnd = new Color(0.10f, 0.10f, 0.10f, 0.0f), - Lifetime = 0.72f + NextFloat() * 0.30f - }); - } - - SpawnSparkBurst(pos, Vector3.Up, 6, new Color(1.0f, 0.68f, 0.22f, 0.98f), 17f); if (!hasCam || pos.DistanceSquaredTo(camPos) <= 95f * 95f) { SpawnFlashLight(pos + new Vector3(0f, 1.2f, 0f), new Color(1.0f, 0.56f, 0.14f), 6.2f, 16f, 0.18f, priority: 10); } } - public void EmitPodReentryStreak(Vector3 podPos, Vector3 podVel, float heatGlow, bool isContender, Vector3 camPos, bool hasCam) - { - EnsureInitialized(); - if (hasCam && podPos.DistanceSquaredTo(camPos) > 650f * 650f) - { - return; - } - - float scale = isContender ? 1.25f : 0.85f; - Vector3 upTrail = (-podVel.Normalized()) * (3.5f + NextFloat() * 3.0f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = podPos + new Vector3(NextSigned() * 0.55f, 0.6f, NextSigned() * 0.55f), - Velocity = upTrail + new Vector3(NextSigned() * 1.1f, 1.8f, NextSigned() * 1.1f), - Gravity = -1.5f, - Drag = 2.2f, - StartSize = 0.85f * scale, - EndSize = 0.28f * scale, - AspectY = 2.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 2.5f, - Emissive = 2.4f + heatGlow * 1.4f, - ColorStart = new Color(1.0f, 0.64f, 0.20f, 0.88f), - ColorEnd = new Color(0.75f, 0.22f, 0.06f, 0.0f), - Lifetime = 0.20f + NextFloat() * 0.10f - }); - } - - public void EmitPodRetroBurn( - Vector3 podBasePos, - float agl, - Color groundTint, - bool isContender, - bool isLocal, - Vector3 camPos, - bool hasCam) - { - EnsureInitialized(); - float distSq = hasCam ? podBasePos.DistanceSquaredTo(camPos) : 0f; - if (hasCam && distSq > 480f * 480f) - { - return; - } - - float scale = isContender ? 1.20f : 0.85f; - // Downward fiery retro plume - for (int i = 0; i < 2; i++) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = podBasePos + new Vector3(NextSigned() * 0.65f, 0.05f, NextSigned() * 0.65f), - Velocity = new Vector3(NextSigned() * 2.2f, -(14f + NextFloat() * 9f), NextSigned() * 2.2f), - Gravity = -2.0f, - Drag = 2.4f, - StartSize = 0.72f * scale, - EndSize = 1.65f * scale, - AspectY = 1.45f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 3.0f, - Emissive = 3.1f, - ColorStart = new Color(1.0f, 0.72f, 0.26f, 0.94f), - ColorEnd = new Color(0.85f, 0.24f, 0.05f, 0.0f), - Lifetime = 0.16f + NextFloat() * 0.08f - }); - } - - // Hot retro ember spark - if (NextFloat() < 0.7f) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSparkStreak, - Position = podBasePos + new Vector3(NextSigned() * 0.7f, 0.1f, NextSigned() * 0.7f), - Velocity = new Vector3(NextSigned() * 6.5f, -(9f + NextFloat() * 6f), NextSigned() * 6.5f), - Gravity = 6.0f, - Drag = 1.2f, - StartSize = 0.26f, - EndSize = 0.10f, - AspectY = 1.6f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = 0f, - Emissive = 3.2f, - ColorStart = new Color(1.0f, 0.78f, 0.30f, 0.96f), - ColorEnd = new Color(0.95f, 0.28f, 0.06f, 0.0f), - Lifetime = 0.18f + NextFloat() * 0.08f - }); - } - - // Ground dust wash when < 55m AGL - if (agl < 55f && (!hasCam || distSq <= 240f * 240f)) - { - float washT = Math.Clamp(1f - agl / 55f, 0.15f, 1f); - Vector3 groundPos = podBasePos - new Vector3(0f, MathF.Max(0f, agl), 0f) + new Vector3(0f, 0.25f, 0f); - Color dustStart = new(groundTint.R, groundTint.G, groundTint.B, 0.56f * washT); - Color dustEnd = new(groundTint.R * 0.9f, groundTint.G * 0.9f, groundTint.B * 0.9f, 0.0f); - int dustCount = isContender ? 2 : 1; - for (int d = 0; d < dustCount; d++) - { - float ang = NextFloat() * MathF.Tau; - float spd = (6.5f + NextFloat() * 7.0f) * washT * scale; - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = groundPos + new Vector3(MathF.Cos(ang) * 0.9f, 0f, MathF.Sin(ang) * 0.9f), - Velocity = new Vector3(MathF.Cos(ang) * spd, 1.2f + NextFloat() * 1.4f, MathF.Sin(ang) * spd), - Gravity = 0.35f, - Drag = 2.6f, - StartSize = 0.85f * scale, - EndSize = 2.35f * scale, - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.8f, - Emissive = 0f, - ColorStart = dustStart, - ColorEnd = dustEnd, - Lifetime = 0.42f + NextFloat() * 0.18f - }); - } - } - - if (isLocal || !hasCam || distSq <= 95f * 95f) - { - SpawnFlashLight(podBasePos - new Vector3(0f, 0.6f, 0f), new Color(1.0f, 0.60f, 0.18f), 3.8f, 14f, 0.09f, priority: isLocal ? 8 : 3); - } - } - - public void EmitPodTouchdownBurst( - Vector3 pos, - Vector3 normal, - Color groundTint, - bool isContender, - bool isLocal, - Vector3 camPos, - bool hasCam) - { - EnsureInitialized(); - float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f; - if (!isLocal && hasCam && distSq > 360f * 360f) - { - return; - } - - float scale = isContender ? 1.35f : 0.95f; - int dustCount = isContender ? 7 : 4; - Color dustStart = new(groundTint.R, groundTint.G, groundTint.B, 0.68f); - Color dustEnd = new(groundTint.R * 0.88f, groundTint.G * 0.88f, groundTint.B * 0.88f, 0.0f); - for (int i = 0; i < dustCount; i++) - { - float ang = (i / (float)dustCount) * MathF.Tau + NextFloat() * 0.4f; - float spd = (7.5f + NextFloat() * 6.5f) * scale; - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = pos + normal * 0.35f + new Vector3(MathF.Cos(ang) * 1.1f, 0f, MathF.Sin(ang) * 1.1f), - Velocity = new Vector3(MathF.Cos(ang) * spd, 1.8f + NextFloat() * 2.2f, MathF.Sin(ang) * spd), - Gravity = 0.45f, - Drag = 2.2f, - StartSize = 0.95f * scale, - EndSize = 2.55f * scale, - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.6f, - Emissive = 0f, - ColorStart = dustStart, - ColorEnd = dustEnd, - Lifetime = 0.55f + NextFloat() * 0.25f - }); - } - - SpawnSparkBurst(pos + normal * 0.5f, normal, isContender ? 8 : 4, new Color(1.0f, 0.68f, 0.20f, 0.98f), 16f * scale); - - if (isLocal || !hasCam || distSq <= 140f * 140f) - { - SpawnFlashLight(pos + normal * 1.2f, new Color(1.0f, 0.58f, 0.16f), 5.8f, 18f, 0.18f, priority: isLocal ? 10 : 6); - } - } - - private void EmitImpactDustPlume(Vector3 pos, Vector3 normal, Color groundTint, int count, float size) - { - Color c0 = new(groundTint.R, groundTint.G, groundTint.B, 0.60f); - Color c1 = new(groundTint.R * 0.88f, groundTint.G * 0.88f, groundTint.B * 0.88f, 0.0f); - float endSize = MathF.Min(2.2f, size * 1.15f); - for (int i = 0; i < count; i++) - { - Vector3 vel = normal * (1.8f + NextFloat() * 2.4f) + new Vector3(NextSigned() * 1.6f, 0.8f + NextFloat() * 1.2f, NextSigned() * 1.6f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = pos + normal * 0.12f, - Velocity = vel, - Gravity = 0.45f, - Drag = 2.0f, - StartSize = size * 0.40f, - EndSize = endSize, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.4f, - Emissive = 0f, - ColorStart = c0, - ColorEnd = c1, - Lifetime = 0.35f + NextFloat() * 0.16f - }); - } - } - - private void SpawnSparkBurst(Vector3 pos, Vector3 normal, int count, Color color, float speed) - { - for (int i = 0; i < count; i++) - { - Vector3 rand = new(NextSigned(), MathF.Abs(NextSigned()) + 0.35f, NextSigned()); - Vector3 dir = (normal * 0.75f + rand).Normalized(); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSparkStreak, - Position = pos, - Velocity = dir * (speed * (0.6f + 0.75f * NextFloat())), - Gravity = 11.0f, - Drag = 0.8f, - StartSize = 0.26f, - EndSize = 0.10f, - AspectY = 1.45f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 6f, - Emissive = 2.8f, - ColorStart = color, - ColorEnd = color with { A = 0f }, - Lifetime = 0.16f + 0.10f * NextFloat() - }); - } - } - - private void SpawnParticle(in ParticleSlot slot) - { - _particles[_writeCursor] = slot; - _writeCursor = (_writeCursor + 1) % MaxParticles; - } - private void SpawnFlashLight(Vector3 pos, Color color, float energy, float range, float duration, int priority) { int targetIdx = -1; @@ -1530,16 +722,4 @@ public partial class ParticlePool : Node3D PeakFlashLightCount = active; } } - - private float NextFloat() - { - uint x = _rng; - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - _rng = x; - return (x & 0x00FFFFFFu) / 16777216f; - } - - private float NextSigned() => NextFloat() * 2f - 1f; } diff --git a/client/VolumetricCompositorEffect.cs b/client/VolumetricCompositorEffect.cs new file mode 100644 index 0000000..ad9b6ae --- /dev/null +++ b/client/VolumetricCompositorEffect.cs @@ -0,0 +1,681 @@ +using System; +using System.Runtime.InteropServices; +using Godot; + +namespace RustToDust.Client; + +/// +/// 4-pass Forward+ Vulkan compute pipeline (PostOpaque) owning: +/// Pass 0: flow_field_step.glsl (camera-snapped 3m 64x24x64 RGBA16F ping-pong -> ) +/// Pass 1: volumetric_tile_cull.glsl (16x16 half-res tiles + 1-warp 32-element Bitonic sort) +/// Pass 2: volumetric_raymarch.glsl (sorted sweep-line + Aetheria curl/triNoise + shock cavity + 2 shadow taps) +/// Pass 3: volumetric_composite.glsl (2x2 bilateral depth upsample pre-tonemap) +/// +public sealed partial class VolumetricCompositorEffect : CompositorEffect +{ + public const int FlowDimX = 64; + public const int FlowDimY = 24; + public const int FlowDimZ = 64; + public const float FlowVoxelSizeMeters = 3.0f; + public const int TileSizeHalfRes = 16; + public const int TileStrideBytes = 112; + public const int FrameUboBytes = 256; + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct VolumetricFrameUbo + { + public Vector4 InvProj0, InvProj1, InvProj2, InvProj3; + public Vector4 CamPosTime; + public Vector4 CamRightAspect; + public Vector4 CamUpTanHalfFov; + public Vector4 CamFwdNearFar; + public Vector4 SunDirIntensity; + public Vector4 SunColorExt; + public Vector4 AmbientColorFog; + public Vector4 ViewportInfo; + public uint HalfW, HalfH, TilesX, FrameIndex; + public Vector4 FlowOriginVoxel; + public Vector4 FlowInvExtentDt; + public int DeltaX, DeltaY, DeltaZ, ImpulseCount; + } + + private readonly Texture3Drd _flowTexRd; + private VolumetricEmitterPool _emitterPool; + + // Atmosphere parameters updated from game thread via volatile/lock + private readonly object _atmoLock = new(); + private Vector3 _sunDir = new Vector3(0.45f, 0.55f, 0.70f).Normalized(); + private float _sunEnergy = 1.25f; + private Color _sunColor = Colors.White; + private Color _ambientColor = new(0.28f, 0.34f, 0.42f); + private float _globalExtinctionScale = 0.28f; + + // Render-thread RD state + private RenderingDevice? _rd; + private bool _rdInitialized; + private bool _rdFailed; + + private Rid _flowShaderRid, _flowPipeRid; + private Rid _cullShaderRid, _cullPipeRid; + private Rid _marchShaderRid, _marchPipeRid; + private Rid _compShaderRid, _compPipeRid; + + private readonly Rid[] _flowTexRids = new Rid[2]; + private int _flowReadIdx; + private Vector3I _prevFlowVoxelOrigin; + private bool _hasPrevFlowOrigin; + + private Rid _nearestSamplerRid; + private Rid _linearSamplerRid; + private Rid _frameUboRid; + private Rid _emitterSsboRid; + private Rid _impulseSsboRid; + private Rid _tileSsboRid; + private int _tileSsboCapacityTiles; + + private Rid _halfVolRid; + private Vector2I _halfVolSize; + private uint _frameCounter; + + // Pre-allocated CPU staging buffers (zero per-frame allocations) + private readonly byte[] _uboBytes = new byte[FrameUboBytes]; + private readonly byte[] _emitterUploadBytes = new byte[VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes]; + private readonly byte[] _impulseUploadBytes = new byte[VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes]; + + // Lightweight RD timestamp telemetry (populated when ProfilingEnabled == true) + public bool ProfilingEnabled { get; set; } + public double LastFlowGpuMs { get; private set; } + public double LastCullGpuMs { get; private set; } + public double LastMarchGpuMs { get; private set; } + public double LastCompGpuMs { get; private set; } + public double LastTotalGpuMs => LastFlowGpuMs + LastCullGpuMs + LastMarchGpuMs + LastCompGpuMs; + + public VolumetricCompositorEffect() : this(new Texture3Drd(), new VolumetricEmitterPool()) + { + } + + public VolumetricCompositorEffect(Texture3Drd flowTexRd, VolumetricEmitterPool emitterPool) + { + _flowTexRd = flowTexRd; + _emitterPool = emitterPool; + EffectCallbackType = EffectCallbackTypeEnum.PostOpaque; + AccessResolvedColor = true; + AccessResolvedDepth = true; + Enabled = true; + } + + public void SetEmitterPool(VolumetricEmitterPool pool) + { + _emitterPool = pool ?? throw new ArgumentNullException(nameof(pool)); + } + + public void SetAtmosphere(Vector3 sunDir, float sunEnergy, Color sunColor, Color ambientColor, float extinctionScale = 0.28f) + { + lock (_atmoLock) + { + _sunDir = sunDir.LengthSquared() > 1e-5f ? sunDir.Normalized() : Vector3.Up; + _sunEnergy = MathF.Max(0.05f, sunEnergy); + _sunColor = sunColor; + _ambientColor = ambientColor; + _globalExtinctionScale = Math.Clamp(extinctionScale, 0.05f, 2.0f); + } + } + + public override void _RenderCallback(int effectCallbackType, RenderData renderData) + { + if (effectCallbackType != (int)EffectCallbackTypeEnum.PostOpaque || _rdFailed) + { + return; + } + + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null) + { + return; + } + + if (!_rdInitialized && !TryInitializeRd(rd)) + { + _rdFailed = true; + return; + } + + if (renderData.GetRenderSceneBuffers() is not RenderSceneBuffersRD sceneBuffers) + { + return; + } + + RenderSceneData sceneData = renderData.GetRenderSceneData(); + if (sceneData is null) + { + return; + } + + Vector2I fullSize = sceneBuffers.GetInternalSize(); + if (fullSize.X < 2 || fullSize.Y < 2) + { + return; + } + + Vector2I halfSize = new(Math.Max(1, (fullSize.X + 1) / 2), Math.Max(1, (fullSize.Y + 1) / 2)); + int tilesX = Math.Max(1, (halfSize.X + TileSizeHalfRes - 1) / TileSizeHalfRes); + int tilesY = Math.Max(1, (halfSize.Y + TileSizeHalfRes - 1) / TileSizeHalfRes); + int totalTiles = tilesX * tilesY; + + EnsureHalfResAndTileBuffers(rd, halfSize, totalTiles); + + uint viewCount = Math.Max(1u, sceneData.GetViewCount()); + const uint view = 0u; + + Transform3D camXf = sceneData.GetCamTransform(); + Projection rawProj = sceneData.GetViewProjection(view); + + // Validate reverse-Z projection convention [1..0] + Vector4 testNear = rawProj * new Vector4(0f, 0f, -0.05f, 1f); + Projection revProj = (testNear.W != 0f && (testNear.Z / testNear.W) < 0f) + ? Projection.CreateDepthCorrection(flipY: false) * rawProj + : rawProj; + Projection invProj = revProj.Inverse(); + + Vector4 nearView = invProj * new Vector4(0f, 0f, 1f, 1f); + Vector4 farView = invProj * new Vector4(0f, 0f, 0f, 1f); + float zNear = MathF.Max(0.01f, MathF.Abs(nearView.W) > 1e-6f ? -nearView.Z / nearView.W : 0.05f); + float zFar = MathF.Abs(farView.W) > 1e-6f && (-farView.Z / farView.W) > zNear + 1f + ? -farView.Z / farView.W + : 4800f; + + float tanHalfFovY = 1f / MathF.Max(1e-4f, MathF.Abs(rawProj.Y.Y)); + float aspect = MathF.Abs(rawProj.Y.Y) / MathF.Max(1e-4f, MathF.Abs(rawProj.X.X)); + + Vector3 camPos = camXf.Origin; + Vector3 camRight = camXf.Basis.X.Normalized(); + Vector3 camUp = camXf.Basis.Y.Normalized(); + Vector3 camFwd = (-camXf.Basis.Z).Normalized(); + + _emitterPool.CopyRenderSnapshot( + _emitterUploadBytes, + _impulseUploadBytes, + out int emitterCount, + out int impulseCount, + out float elapsedTime, + out float dt); + + Vector3I newVoxelOrigin = new( + (int)MathF.Floor((camPos.X - 96f) / FlowVoxelSizeMeters), + (int)MathF.Floor((camPos.Y - 24f) / FlowVoxelSizeMeters), + (int)MathF.Floor((camPos.Z - 96f) / FlowVoxelSizeMeters)); + Vector3I flowDelta = _hasPrevFlowOrigin ? (newVoxelOrigin - _prevFlowVoxelOrigin) : Vector3I.Zero; + _prevFlowVoxelOrigin = newVoxelOrigin; + _hasPrevFlowOrigin = true; + + Vector3 flowOriginWorld = new( + newVoxelOrigin.X * FlowVoxelSizeMeters, + newVoxelOrigin.Y * FlowVoxelSizeMeters, + newVoxelOrigin.Z * FlowVoxelSizeMeters); + Vector3 flowInvExtent = new( + 1f / (FlowDimX * FlowVoxelSizeMeters), + 1f / (FlowDimY * FlowVoxelSizeMeters), + 1f / (FlowDimZ * FlowVoxelSizeMeters)); + + Vector3 sunDir; + float sunEnergy; + Color sunCol, ambCol; + float extScale; + lock (_atmoLock) + { + sunDir = _sunDir; + sunEnergy = _sunEnergy; + sunCol = _sunColor; + ambCol = _ambientColor; + extScale = _globalExtinctionScale; + } + + _frameCounter++; + var ubo = new VolumetricFrameUbo + { + InvProj0 = invProj.X, + InvProj1 = invProj.Y, + InvProj2 = invProj.Z, + InvProj3 = invProj.W, + CamPosTime = new Vector4(camPos.X, camPos.Y, camPos.Z, elapsedTime), + CamRightAspect = new Vector4(camRight.X, camRight.Y, camRight.Z, aspect), + CamUpTanHalfFov = new Vector4(camUp.X, camUp.Y, camUp.Z, tanHalfFovY), + CamFwdNearFar = new Vector4(camFwd.X, camFwd.Y, camFwd.Z, 0f), + SunDirIntensity = new Vector4(sunDir.X, sunDir.Y, sunDir.Z, sunEnergy), + SunColorExt = new Vector4(sunCol.R, sunCol.G, sunCol.B, extScale), + AmbientColorFog = new Vector4(ambCol.R, ambCol.G, ambCol.B, zNear), + ViewportInfo = new Vector4(fullSize.X, fullSize.Y, zFar, emitterCount), + HalfW = (uint)halfSize.X, + HalfH = (uint)halfSize.Y, + TilesX = (uint)tilesX, + FrameIndex = _frameCounter, + FlowOriginVoxel = new Vector4(flowOriginWorld.X, flowOriginWorld.Y, flowOriginWorld.Z, FlowVoxelSizeMeters), + FlowInvExtentDt = new Vector4(flowInvExtent.X, flowInvExtent.Y, flowInvExtent.Z, dt), + DeltaX = flowDelta.X, + DeltaY = flowDelta.Y, + DeltaZ = flowDelta.Z, + ImpulseCount = impulseCount + }; + + MemoryMarshal.Write(_uboBytes, in ubo); + rd.BufferUpdate(_frameUboRid, 0, FrameUboBytes, _uboBytes); + + if (emitterCount > 0) + { + uint emBytes = (uint)(emitterCount * VolumetricEmitterPool.EmitterStrideBytes); + rd.BufferUpdate(_emitterSsboRid, 0, emBytes, _emitterUploadBytes); + } + if (impulseCount > 0) + { + uint impBytes = (uint)(impulseCount * VolumetricEmitterPool.ImpulseStrideBytes); + rd.BufferUpdate(_impulseSsboRid, 0, impBytes, _impulseUploadBytes); + } + + int writeIdx = 1 - _flowReadIdx; + Rid prevFlowRid = _flowTexRids[_flowReadIdx]; + Rid nextFlowRid = _flowTexRids[writeIdx]; + + bool captureThisFrame = ProfilingEnabled && (_frameCounter & 7u) == 0u && _frameCounter >= 32u && rd.GetCapturedTimestampsCount() < 180; + if (ProfilingEnabled && (_frameCounter & 7u) == 1u && _frameCounter >= 32u) + { + SamplePreviousFrameTimestamps(rd); + } + if (captureThisFrame) + { + rd.CaptureTimestamp("Cut10b_FlowStart"); + } + + // Compute pass list (Pass 0 always; Passes 1-3 whenever active emitters exist) + long computeList = rd.ComputeListBegin(); + + // Pass 0: flow_field_step (64x24x64 / 8x4x8 = 8x6x8 groups) + Rid flowSet = GetPass0UniformSet(prevFlowRid, nextFlowRid); + rd.ComputeListBindComputePipeline(computeList, _flowPipeRid); + rd.ComputeListBindUniformSet(computeList, flowSet, 0); + rd.ComputeListDispatch(computeList, 8, 6, 8); + + if (emitterCount > 0) + { + for (uint v = 0; v < viewCount; v++) + { + Rid colorLayer = sceneBuffers.GetColorLayer(v, false); + Rid depthLayer = sceneBuffers.GetDepthLayer(v, false); + if (!colorLayer.IsValid || !depthLayer.IsValid) + { + continue; + } + + // Pass 1: volumetric_tile_cull + rd.ComputeListAddBarrier(computeList); + if (captureThisFrame && v == 0) + { + rd.ComputeListEnd(); + rd.CaptureTimestamp("Cut10b_CullStart"); + computeList = rd.ComputeListBegin(); + } + + Rid cullSet = GetPass1UniformSet(depthLayer); + rd.ComputeListBindComputePipeline(computeList, _cullPipeRid); + rd.ComputeListBindUniformSet(computeList, cullSet, 0); + rd.ComputeListDispatch(computeList, (uint)tilesX, (uint)tilesY, 1); + + // Pass 2: volumetric_raymarch (reading freshly updated nextFlowRid!) + rd.ComputeListAddBarrier(computeList); + if (captureThisFrame && v == 0) + { + rd.ComputeListEnd(); + rd.CaptureTimestamp("Cut10b_MarchStart"); + computeList = rd.ComputeListBegin(); + } + + Rid marchSet = GetPass2UniformSet(depthLayer, nextFlowRid); + rd.ComputeListBindComputePipeline(computeList, _marchPipeRid); + rd.ComputeListBindUniformSet(computeList, marchSet, 0); + rd.ComputeListDispatch(computeList, (uint)tilesX, (uint)tilesY, 1); + + // Pass 3: volumetric_composite (2x2 bilateral depth upsample -> colorLayer) + rd.ComputeListAddBarrier(computeList); + if (captureThisFrame && v == 0) + { + rd.ComputeListEnd(); + rd.CaptureTimestamp("Cut10b_CompStart"); + computeList = rd.ComputeListBegin(); + } + + Rid compSet = GetPass3UniformSet(depthLayer, colorLayer); + rd.ComputeListBindComputePipeline(computeList, _compPipeRid); + rd.ComputeListBindUniformSet(computeList, compSet, 0); + uint compGroupsX = (uint)((fullSize.X + 15) / 16); + uint compGroupsY = (uint)((fullSize.Y + 15) / 16); + rd.ComputeListDispatch(computeList, compGroupsX, compGroupsY, 1); + } + } + + rd.ComputeListEnd(); + + if (captureThisFrame) + { + rd.CaptureTimestamp("Cut10b_End"); + } + + // Advance ping-pong & update global Texture3Drd + flow origin for GPUParticles3D + _flowReadIdx = writeIdx; + _flowTexRd.TextureRdRid = nextFlowRid; + RenderingServer.GlobalShaderParameterSet("rtd_flow_origin", flowOriginWorld); + RenderingServer.GlobalShaderParameterSet("rtd_flow_inv_extent", flowInvExtent); + } + + private void SamplePreviousFrameTimestamps(RenderingDevice rd) + { + uint count = rd.GetCapturedTimestampsCount(); + if (count == 0) + { + return; + } + + ulong tFlow = 0, tCull = 0, tMarch = 0, tComp = 0, tEnd = 0; + for (uint i = 0; i < count; i++) + { + string name = rd.GetCapturedTimestampName(i); + switch (name) + { + case "Cut10b_FlowStart": tFlow = rd.GetCapturedTimestampGpuTime(i); break; + case "Cut10b_CullStart": tCull = rd.GetCapturedTimestampGpuTime(i); break; + case "Cut10b_MarchStart": tMarch = rd.GetCapturedTimestampGpuTime(i); break; + case "Cut10b_CompStart": tComp = rd.GetCapturedTimestampGpuTime(i); break; + case "Cut10b_End": tEnd = rd.GetCapturedTimestampGpuTime(i); break; + } + } + + if (tFlow > 0 && tEnd >= tFlow) + { + // Godot RD timestamps are in nanoseconds -> convert to ms (Wait: docs say microseconds or nanoseconds; let's check magnitude!) + // Godot 4 RenderingDevice.GetCapturedTimestampGpuTime returns nanoseconds in Vulkan (Wait: XML says microseconds, let's check both or measure delta!). + // Wait: in Godot 4 Vulkan `get_captured_timestamp_gpu_time` actually returns nanoseconds in 4.2+ or microseconds? Let's check in live Vulkan run! + if (tCull > tFlow && tMarch > tCull && tComp > tMarch && tEnd >= tComp) + { + LastFlowGpuMs = (tCull - tFlow) / 1_000_000.0; + LastCullGpuMs = (tMarch - tCull) / 1_000_000.0; + LastMarchGpuMs = (tComp - tMarch) / 1_000_000.0; + LastCompGpuMs = (tEnd - tComp) / 1_000_000.0; + } + else if (tEnd >= tFlow) + { + LastFlowGpuMs = (tEnd - tFlow) / 1_000_000.0; + LastCullGpuMs = 0.0; + LastMarchGpuMs = 0.0; + LastCompGpuMs = 0.0; + } + } + } + + private bool TryInitializeRd(RenderingDevice rd) + { + _rd = rd; + + if (!TryCompileCompute(rd, "res://flow_field_step.glsl", "flow_field_step", out _flowShaderRid, out _flowPipeRid) || + !TryCompileCompute(rd, "res://volumetric_tile_cull.glsl", "volumetric_tile_cull", out _cullShaderRid, out _cullPipeRid) || + !TryCompileCompute(rd, "res://volumetric_raymarch.glsl", "volumetric_raymarch", out _marchShaderRid, out _marchPipeRid) || + !TryCompileCompute(rd, "res://volumetric_composite.glsl", "volumetric_composite", out _compShaderRid, out _compPipeRid)) + { + return false; + } + + var nearestState = new RDSamplerState + { + MinFilter = RenderingDevice.SamplerFilter.Nearest, + MagFilter = RenderingDevice.SamplerFilter.Nearest, + RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge + }; + _nearestSamplerRid = rd.SamplerCreate(nearestState); + + var linearState = new RDSamplerState + { + MinFilter = RenderingDevice.SamplerFilter.Linear, + MagFilter = RenderingDevice.SamplerFilter.Linear, + RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge + }; + _linearSamplerRid = rd.SamplerCreate(linearState); + + var flowFmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type3D, + Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat, + Width = FlowDimX, + Height = FlowDimY, + Depth = FlowDimZ, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit + }; + byte[] zero3d = new byte[FlowDimX * FlowDimY * FlowDimZ * 8]; + var initArr = new Godot.Collections.Array { zero3d }; + _flowTexRids[0] = rd.TextureCreate(flowFmt, new RDTextureView(), initArr); + _flowTexRids[1] = rd.TextureCreate(flowFmt, new RDTextureView(), initArr); + _flowReadIdx = 0; + _flowTexRd.TextureRdRid = _flowTexRids[0]; + + _frameUboRid = rd.UniformBufferCreate(FrameUboBytes, new byte[FrameUboBytes]); + _emitterSsboRid = rd.StorageBufferCreate( + (uint)(VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes), + new byte[VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes]); + _impulseSsboRid = rd.StorageBufferCreate( + (uint)(VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes), + new byte[VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes]); + + _rdInitialized = true; + return true; + } + + private static bool TryCompileCompute( + RenderingDevice rd, + string resPath, + string debugName, + out Rid shaderRid, + out Rid pipeRid) + { + shaderRid = new Rid(); + pipeRid = new Rid(); + + string source = FileAccess.GetFileAsString(resPath); + if (string.IsNullOrWhiteSpace(source)) + { + GD.PrintErr($"VolumetricCompositorEffect: missing compute shader '{resPath}'"); + return false; + } + + using var rdSrc = new RDShaderSource + { + Language = RenderingDevice.ShaderLanguage.Glsl, + SourceCompute = source + }; + using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true); + string err = spirv.CompileErrorCompute; + if (!string.IsNullOrEmpty(err)) + { + GD.PrintErr($"VolumetricCompositorEffect: SPIR-V compile error in '{resPath}': {err}"); + return false; + } + + shaderRid = rd.ShaderCreateFromSpirV(spirv, debugName); + if (!shaderRid.IsValid) + { + GD.PrintErr($"VolumetricCompositorEffect: ShaderCreateFromSpirV failed for '{resPath}'"); + return false; + } + pipeRid = rd.ComputePipelineCreate(shaderRid); + if (!pipeRid.IsValid) + { + GD.PrintErr($"VolumetricCompositorEffect: ComputePipelineCreate failed for '{resPath}'"); + return false; + } + return true; + } + + private void EnsureHalfResAndTileBuffers(RenderingDevice rd, Vector2I halfSize, int totalTiles) + { + if (!_halfVolRid.IsValid || _halfVolSize != halfSize) + { + if (_halfVolRid.IsValid) + { + rd.FreeRid(_halfVolRid); + } + var fmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat, + Width = (uint)halfSize.X, + Height = (uint)halfSize.Y, + Depth = 1, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit + }; + _halfVolRid = rd.TextureCreate(fmt, new RDTextureView()); + _halfVolSize = halfSize; + } + + if (!_tileSsboRid.IsValid || _tileSsboCapacityTiles < totalTiles) + { + if (_tileSsboRid.IsValid) + { + rd.FreeRid(_tileSsboRid); + } + _tileSsboCapacityTiles = Math.Max(totalTiles, 2048); + uint sizeBytes = (uint)(_tileSsboCapacityTiles * TileStrideBytes); + _tileSsboRid = rd.StorageBufferCreate(sizeBytes, new byte[sizeBytes]); + } + } + + private Rid GetPass0UniformSet(Rid prevFlowRid, Rid nextFlowRid) + { + var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 }; + u0.AddId(_frameUboRid); + var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 }; + u1.AddId(_impulseSsboRid); + var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 2 }; + u2.AddId(_linearSamplerRid); + u2.AddId(prevFlowRid); + var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 3 }; + u3.AddId(nextFlowRid); + return UniformSetCacheRD.GetCache(_flowShaderRid, 0, new Godot.Collections.Array { u0, u1, u2, u3 }); + } + + private Rid GetPass1UniformSet(Rid depthLayer) + { + var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 }; + u0.AddId(_frameUboRid); + var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 }; + u1.AddId(_emitterSsboRid); + var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 2 }; + u2.AddId(_tileSsboRid); + var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 3 }; + u3.AddId(_nearestSamplerRid); + u3.AddId(depthLayer); + return UniformSetCacheRD.GetCache(_cullShaderRid, 0, new Godot.Collections.Array { u0, u1, u2, u3 }); + } + + private Rid GetPass2UniformSet(Rid depthLayer, Rid flowTexRid) + { + var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 }; + u0.AddId(_frameUboRid); + var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 }; + u1.AddId(_emitterSsboRid); + var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 2 }; + u2.AddId(_tileSsboRid); + var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 3 }; + u3.AddId(_nearestSamplerRid); + u3.AddId(depthLayer); + var u4 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 4 }; + u4.AddId(_linearSamplerRid); + u4.AddId(flowTexRid); + var u5 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 5 }; + u5.AddId(_halfVolRid); + return UniformSetCacheRD.GetCache(_marchShaderRid, 0, new Godot.Collections.Array { u0, u1, u2, u3, u4, u5 }); + } + + private Rid GetPass3UniformSet(Rid depthLayer, Rid colorLayer) + { + var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 }; + u0.AddId(_frameUboRid); + var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 1 }; + u1.AddId(_nearestSamplerRid); + u1.AddId(depthLayer); + var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 2 }; + u2.AddId(_nearestSamplerRid); + u2.AddId(_halfVolRid); + var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 3 }; + u3.AddId(colorLayer); + return UniformSetCacheRD.GetCache(_compShaderRid, 0, new Godot.Collections.Array { u0, u1, u2, u3 }); + } + + public void DisposeRdResources() + { + if (!_rdInitialized || _rd is null) + { + return; + } + _rdInitialized = false; + Enabled = false; + + if (_flowTexRd is not null) + { + _flowTexRd.TextureRdRid = new Rid(); + } + + FreeIfValid(_rd, ref _flowTexRids[0]); + FreeIfValid(_rd, ref _flowTexRids[1]); + FreeIfValid(_rd, ref _halfVolRid); + FreeIfValid(_rd, ref _frameUboRid); + FreeIfValid(_rd, ref _emitterSsboRid); + FreeIfValid(_rd, ref _impulseSsboRid); + FreeIfValid(_rd, ref _tileSsboRid); + FreeIfValid(_rd, ref _nearestSamplerRid); + FreeIfValid(_rd, ref _linearSamplerRid); + + // Free shaders (automatically cleans up dependent pipelines in Godot RD) + _flowPipeRid = new Rid(); + _cullPipeRid = new Rid(); + _marchPipeRid = new Rid(); + _compPipeRid = new Rid(); + FreeIfValid(_rd, ref _flowShaderRid); + FreeIfValid(_rd, ref _cullShaderRid); + FreeIfValid(_rd, ref _marchShaderRid); + FreeIfValid(_rd, ref _compShaderRid); + + _rd = null; + } + + public override void _Notification(int what) + { + if (what != NotificationPredelete) + { + return; + } + + // Only release if still alive and not already cleaned up in AtmosphereSystem._ExitTree + if (_flowTexRd is not null) + { + _flowTexRd.TextureRdRid = new Rid(); + } + if (_rdInitialized && RenderingServer.GetRenderingDevice() is not null) + { + DisposeRdResources(); + } + } + + private static void FreeIfValid(RenderingDevice rd, ref Rid rid) + { + if (rid.IsValid) + { + rd.FreeRid(rid); + rid = new Rid(); + } + } +} diff --git a/client/VolumetricEmitterPool.cs b/client/VolumetricEmitterPool.cs new file mode 100644 index 0000000..d1a5ed9 --- /dev/null +++ b/client/VolumetricEmitterPool.cs @@ -0,0 +1,1026 @@ +using System; +using System.Runtime.InteropServices; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// CPU authority for all volumetric smoke, fire, retro-plume, plasma, and thermal-pool emitters +/// (<= 128) plus 3D flow-field impulses (<= 64) consumed by . +/// Packs std430-aligned snapshots under a short lock for zero-allocation GPU upload. +/// +public sealed class VolumetricEmitterPool +{ + public const int MaxEmitters = 128; + public const int MaxFlowImpulses = 64; + public const int EmitterStrideBytes = 64; + public const int ImpulseStrideBytes = 48; + + public const uint EmitterSmoke = 0u; + public const uint EmitterFireball = 1u; + public const uint EmitterRetroPlume = 2u; + public const uint EmitterPlasmaBurst = 3u; + public const uint EmitterThermalPool = 4u; + + public const uint FlowShockShell = 0u; + public const uint FlowRetroDownwash = 1u; + public const uint FlowThermalUpdraft = 2u; + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + public struct GpuVolumetricEmitter + { + public float Ax, Ay, Az, RadiusA; + public float Bx, By, Bz, Temp; + public float DensityMult, RadiusB, FlowSpeed, PackedFlags; + public float R, G, B, Softness; + } + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + public struct GpuFlowImpulse + { + public float PosX, PosY, PosZ, Radius; + public float DirX, DirY, DirZ, Strength; + public float ShellThickness, ShockPressure, TypeBitsFloat, FalloffExp; + } + + private struct EmitterSlot + { + public bool Active; + public uint Type; + public int Priority; + public byte Seed; + public Vector3 StartPos; + public Vector3 EndPos; + public Vector3 VelStart; + public Vector3 VelEnd; + public float Drag; + public float Buoyancy; + public float RadiusA0; + public float RadiusA1; + public float RadiusB0; + public float RadiusB1; + public float Density0; + public float Density1; + public float Temp0; + public float Temp1; + public float FlowSpeed; + public float Softness; + public Color Tint0; + public Color Tint1; + public float Age; + public float Lifetime; + } + + private struct ImpulseSlot + { + public bool Active; + public uint Type; + public int Priority; + public Vector3 Pos; + public Vector3 Dir; + public float Radius0; + public float Radius1; + public float Strength0; + public float Strength1; + public float ShellThickness; + public float ShockPressure0; + public float ShockPressure1; + public float FalloffExp; + public float Age; + public float Lifetime; + } + + private readonly EmitterSlot[] _emitters = new EmitterSlot[MaxEmitters]; + private readonly ImpulseSlot[] _impulses = new ImpulseSlot[MaxFlowImpulses]; + + private readonly object _sync = new(); + private readonly byte[] _emitterBytes = new byte[MaxEmitters * EmitterStrideBytes]; + private readonly byte[] _impulseBytes = new byte[MaxFlowImpulses * ImpulseStrideBytes]; + private int _packedEmitterCount; + private int _packedImpulseCount; + private float _elapsedTime; + private float _lastStepDt = 1f / 60f; + private uint _rng = 0x51F29D4Bu; + private byte _seedSeq; + + public int ActiveEmitterCount { get; private set; } + public int ActiveImpulseCount { get; private set; } + + public void ClearAll() + { + Array.Clear(_emitters, 0, _emitters.Length); + Array.Clear(_impulses, 0, _impulses.Length); + ActiveEmitterCount = 0; + ActiveImpulseCount = 0; + lock (_sync) + { + _packedEmitterCount = 0; + _packedImpulseCount = 0; + Array.Clear(_emitterBytes, 0, _emitterBytes.Length); + Array.Clear(_impulseBytes, 0, _impulseBytes.Length); + } + } + + public void Step(float dt) + { + float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; + _elapsedTime += stepDt; + + Span gpuEmitters = stackalloc GpuVolumetricEmitter[MaxEmitters]; + int emCount = 0; + for (int i = 0; i < MaxEmitters; i++) + { + ref EmitterSlot s = ref _emitters[i]; + if (!s.Active) + { + continue; + } + if (stepDt > 0f) + { + s.Age += stepDt; + if (s.Age >= s.Lifetime) + { + s.Active = false; + continue; + } + if (s.Drag > 0f) + { + float damp = MathF.Exp(-s.Drag * stepDt); + s.VelStart *= damp; + s.VelEnd *= damp; + } + s.VelStart.Y += s.Buoyancy * stepDt; + s.VelEnd.Y += s.Buoyancy * stepDt; + s.StartPos += s.VelStart * stepDt; + s.EndPos += s.VelEnd * stepDt; + } + + float t = Math.Clamp(s.Age / MathF.Max(0.01f, s.Lifetime), 0f, 1f); + float density = Mathf.Lerp(s.Density0, s.Density1, t); + // Smooth fade-out tail in last 25% of lifetime + if (t > 0.75f) + { + density *= 1f - (t - 0.75f) / 0.25f; + } + if (density <= 0.002f) + { + continue; + } + + float rA = MathF.Max(0.25f, Mathf.Lerp(s.RadiusA0, s.RadiusA1, t)); + float rB = MathF.Max(0.25f, Mathf.Lerp(s.RadiusB0, s.RadiusB1, t)); + float temp = MathF.Max(0f, Mathf.Lerp(s.Temp0, s.Temp1, t)); + Color tint = s.Tint0.Lerp(s.Tint1, t); + + uint ageByte = (uint)Math.Clamp((int)(t * 255f), 0, 255); + uint packedFlags = (s.Type & 0xFu) | (ageByte << 4) | ((uint)s.Seed << 12); + + gpuEmitters[emCount++] = new GpuVolumetricEmitter + { + Ax = s.StartPos.X, + Ay = s.StartPos.Y, + Az = s.StartPos.Z, + RadiusA = rA, + Bx = s.EndPos.X, + By = s.EndPos.Y, + Bz = s.EndPos.Z, + Temp = temp, + DensityMult = density, + RadiusB = rB, + FlowSpeed = s.FlowSpeed, + PackedFlags = BitConverter.UInt32BitsToSingle(packedFlags), + R = MathF.Max(0f, tint.R), + G = MathF.Max(0f, tint.G), + B = MathF.Max(0f, tint.B), + Softness = s.Softness + }; + } + + Span gpuImpulses = stackalloc GpuFlowImpulse[MaxFlowImpulses]; + int impCount = 0; + for (int i = 0; i < MaxFlowImpulses; i++) + { + ref ImpulseSlot s = ref _impulses[i]; + if (!s.Active) + { + continue; + } + if (stepDt > 0f) + { + s.Age += stepDt; + if (s.Age >= s.Lifetime) + { + s.Active = false; + continue; + } + } + + float t = Math.Clamp(s.Age / MathF.Max(0.01f, s.Lifetime), 0f, 1f); + float radius = MathF.Max(0.5f, Mathf.Lerp(s.Radius0, s.Radius1, t)); + float strength = Mathf.Lerp(s.Strength0, s.Strength1, t); + float pressure = MathF.Max(0f, Mathf.Lerp(s.ShockPressure0, s.ShockPressure1, t)); + + gpuImpulses[impCount++] = new GpuFlowImpulse + { + PosX = s.Pos.X, + PosY = s.Pos.Y, + PosZ = s.Pos.Z, + Radius = radius, + DirX = s.Dir.X, + DirY = s.Dir.Y, + DirZ = s.Dir.Z, + Strength = strength, + ShellThickness = s.ShellThickness, + ShockPressure = pressure, + TypeBitsFloat = BitConverter.UInt32BitsToSingle(s.Type), + FalloffExp = s.FalloffExp + }; + } + + ActiveEmitterCount = emCount; + ActiveImpulseCount = impCount; + + lock (_sync) + { + _packedEmitterCount = emCount; + _packedImpulseCount = impCount; + if (stepDt > 0f) + { + _lastStepDt = stepDt; + } + if (emCount > 0) + { + MemoryMarshal.AsBytes(gpuEmitters.Slice(0, emCount)).CopyTo(_emitterBytes); + } + if (impCount > 0) + { + MemoryMarshal.AsBytes(gpuImpulses.Slice(0, impCount)).CopyTo(_impulseBytes); + } + } + } + + public void CopyRenderSnapshot( + byte[] dstEmitters, + byte[] dstImpulses, + out int emitterCount, + out int impulseCount, + out float elapsedTime, + out float dt) + { + lock (_sync) + { + emitterCount = _packedEmitterCount; + impulseCount = _packedImpulseCount; + elapsedTime = _elapsedTime; + dt = _lastStepDt; + if (emitterCount > 0) + { + Buffer.BlockCopy(_emitterBytes, 0, dstEmitters, 0, emitterCount * EmitterStrideBytes); + } + if (impulseCount > 0) + { + Buffer.BlockCopy(_impulseBytes, 0, dstImpulses, 0, impulseCount * ImpulseStrideBytes); + } + } + } + + public void SpawnEmitter( + uint type, + Vector3 startPos, + Vector3 endPos, + Vector3 velStart, + Vector3 velEnd, + float radiusA0, + float radiusA1, + float radiusB0, + float radiusB1, + float density0, + float density1, + float temp0, + float temp1, + Color tint0, + Color tint1, + float lifetime, + float flowSpeed = 0.55f, + float softness = 0.36f, + float drag = 1.2f, + float buoyancy = 0.45f, + int priority = 5) + { + int slot = FindOrEvictEmitterSlot(priority); + if (slot < 0) + { + return; + } + _emitters[slot] = new EmitterSlot + { + Active = true, + Type = type, + Priority = priority, + Seed = _seedSeq++, + StartPos = startPos, + EndPos = endPos, + VelStart = velStart, + VelEnd = velEnd, + Drag = drag, + Buoyancy = buoyancy, + RadiusA0 = radiusA0, + RadiusA1 = radiusA1, + RadiusB0 = radiusB0, + RadiusB1 = radiusB1, + Density0 = density0, + Density1 = density1, + Temp0 = temp0, + Temp1 = temp1, + FlowSpeed = flowSpeed, + Softness = softness, + Tint0 = tint0, + Tint1 = tint1, + Age = 0f, + Lifetime = MathF.Max(0.05f, lifetime) + }; + ActiveEmitterCount = CountActiveEmitters(); + } + + public void SpawnFlowImpulse( + uint type, + Vector3 pos, + Vector3 dir, + float radius0, + float radius1, + float strength0, + float strength1, + float shellThickness, + float shockPressure0, + float shockPressure1, + float lifetime, + float falloffExp = 1.6f, + int priority = 5) + { + int slot = FindOrEvictImpulseSlot(priority); + if (slot < 0) + { + return; + } + _impulses[slot] = new ImpulseSlot + { + Active = true, + Type = type, + Priority = priority, + Pos = pos, + Dir = dir.LengthSquared() > 1e-5f ? dir.Normalized() : Vector3.Up, + Radius0 = radius0, + Radius1 = radius1, + Strength0 = strength0, + Strength1 = strength1, + ShellThickness = shellThickness, + ShockPressure0 = shockPressure0, + ShockPressure1 = shockPressure1, + FalloffExp = falloffExp, + Age = 0f, + Lifetime = MathF.Max(0.04f, lifetime) + }; + ActiveImpulseCount = CountActiveImpulses(); + } + + public void EmitChassisExplosion(Vector3 pos, float massKg, Color groundTint) + { + Color gLin = groundTint.SrgbToLinear(); + float scale = Math.Clamp(massKg / 2800f, 0.85f, 1.55f); + // Primary fireball -> rising billowing soot capsule (3.5s) + SpawnEmitter( + EmitterFireball, + startPos: pos + new Vector3(0f, 0.4f, 0f), + endPos: pos + new Vector3(NextSigned() * 0.4f, 2.2f * scale, NextSigned() * 0.4f), + velStart: new Vector3(NextSigned() * 0.6f, 1.4f, NextSigned() * 0.6f), + velEnd: new Vector3(NextSigned() * 0.9f, 3.8f * scale, NextSigned() * 0.9f), + radiusA0: 1.8f * scale, + radiusA1: 5.2f * scale, + radiusB0: 2.2f * scale, + radiusB1: 6.4f * scale, + density0: 1.55f, + density1: 0.55f, + temp0: 1.50f, + temp1: 0.08f, + tint0: new Color(0.14f, 0.11f, 0.09f), + tint1: new Color(0.06f, 0.055f, 0.055f), + lifetime: 3.4f, + flowSpeed: 0.85f, + softness: 0.42f, + drag: 0.95f, + buoyancy: 0.90f, + priority: 10); + + // Low ground dust skirt pushed outward by blast + SpawnEmitter( + EmitterSmoke, + startPos: pos - new Vector3(1.5f, 0.1f, 0f), + endPos: pos + new Vector3(1.5f, 0.2f, 0f), + velStart: Vector3.Up * 0.5f, + velEnd: Vector3.Up * 1.1f, + radiusA0: 2.4f * scale, + radiusA1: 6.8f * scale, + radiusB0: 2.4f * scale, + radiusB1: 6.8f * scale, + density0: 0.80f, + density1: 0.10f, + temp0: 0.30f, + temp1: 0f, + tint0: gLin * 0.85f, + tint1: gLin * 0.50f, + lifetime: 2.2f, + flowSpeed: 0.65f, + softness: 0.48f, + drag: 1.4f, + buoyancy: 0.25f, + priority: 9); + + // Expanding radial ShockShell (~90 m/s) + buoyant ThermalUpdraft column + SpawnFlowImpulse( + FlowShockShell, + pos, + Vector3.Up, + radius0: 1.6f * scale, + radius1: 24.0f * scale, + strength0: 90f, + strength1: 14f, + shellThickness: 3.4f, + shockPressure0: 1.4f, + shockPressure1: 0.0f, + lifetime: 0.40f, + priority: 10); + + SpawnFlowImpulse( + FlowThermalUpdraft, + pos, + Vector3.Up, + radius0: 5.5f * scale, + radius1: 8.5f * scale, + strength0: 13.5f, + strength1: 3.5f, + shellThickness: 0f, + shockPressure0: 0f, + shockPressure1: 0f, + lifetime: 3.2f, + priority: 9); + } + + public void EmitExplosiveHit(Vector3 pos, Vector3 normal, Color groundTint, WeaponVisualClass wClass, bool isRecoilless, bool isAirburst) + { + bool isPlasma = wClass == WeaponVisualClass.PlasmaPpc; + bool isSwarm = wClass == WeaponVisualClass.SwarmSmart; + bool isThermal = wClass == WeaponVisualClass.ThermalBeam; + float scale = isRecoilless || wClass == WeaponVisualClass.RocketSalvo + ? 1.35f + : (isAirburst ? 1.15f : (isThermal ? 0.58f : 0.90f)); + + uint type = (isPlasma || isSwarm || isThermal) ? EmitterPlasmaBurst : EmitterFireball; + Color gLin = groundTint.SrgbToLinear(); + Color tint0 = isPlasma + ? new Color(0.10f, 0.52f, 0.72f) + : isSwarm + ? new Color(0.24f, 0.62f, 0.14f) + : isThermal + ? new Color(0.12f, 0.22f, 0.28f) + : gLin * 0.48f + new Color(0.06f, 0.045f, 0.04f); + Color tint1 = new(0.06f, 0.055f, 0.05f); + + float temp0 = (isPlasma || isThermal) ? 0.95f : (isAirburst || isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 1.25f : 0.85f); + float life = (isRecoilless || wClass == WeaponVisualClass.RocketSalvo) ? 1.45f : (isThermal ? 0.45f : 0.85f); + + SpawnEmitter( + type, + startPos: pos + normal * 0.25f, + endPos: pos + normal * (1.2f * scale) + Vector3.Up * (0.9f * scale), + velStart: normal * 1.4f, + velEnd: normal * 2.4f + Vector3.Up * 1.8f, + radiusA0: 0.9f * scale, + radiusA1: 2.8f * scale, + radiusB0: 1.1f * scale, + radiusB1: 3.4f * scale, + density0: 1.15f, + density1: 0.16f, + temp0: temp0, + temp1: -0.35f, + tint0: tint0, + tint1: tint1, + lifetime: life, + flowSpeed: 0.75f, + softness: 0.42f, + drag: 1.4f, + buoyancy: 0.65f, + priority: isRecoilless ? 8 : 6); + + if (isRecoilless || wClass is WeaponVisualClass.RocketSalvo or WeaponVisualClass.PlasmaPpc or WeaponVisualClass.Explosive) + { + SpawnFlowImpulse( + FlowShockShell, + pos, + normal, + radius0: 0.8f, + radius1: 11.0f * scale, + strength0: 54f * scale, + strength1: 8f, + shellThickness: 2.4f, + shockPressure0: 1.05f, + shockPressure1: 0.0f, + lifetime: 0.26f, + priority: 7); + } + } + + public void EmitMuzzleBreechPuff(Vector3 start, Vector3 end, Color groundTint, WeaponVisualClass wClass, bool isRecoilless) + { + Vector3 dir = (end - start).LengthSquared() > 1e-4f ? (end - start).Normalized() : Vector3.Forward; + float scale = isRecoilless ? 1.25f : 0.85f; + Color gLin = groundTint.SrgbToLinear(); + Color smokeTint = new( + Mathf.Lerp(0.24f, gLin.R, 0.35f), + Mathf.Lerp(0.22f, gLin.G, 0.35f), + Mathf.Lerp(0.20f, gLin.B, 0.35f)); + + SpawnEmitter( + EmitterSmoke, + startPos: start + dir * 0.2f, + endPos: start + dir * (2.6f * scale), + velStart: dir * 2.8f + Vector3.Up * 0.8f, + velEnd: dir * 4.2f + Vector3.Up * 1.4f, + radiusA0: 0.48f * scale, + radiusA1: 1.55f * scale, + radiusB0: 0.75f * scale, + radiusB1: 2.15f * scale, + density0: 0.85f, + density1: 0.10f, + temp0: isRecoilless ? 0.45f : 0.25f, + temp1: 0f, + tint0: smokeTint, + tint1: smokeTint * 0.75f, + lifetime: isRecoilless ? 0.82f : 0.50f, + flowSpeed: 0.6f, + softness: 0.44f, + drag: 2.2f, + buoyancy: 0.55f, + priority: 6); + + if (isRecoilless || wClass == WeaponVisualClass.RocketSalvo) + { + // Backblast / recoil puff & impulse + SpawnFlowImpulse( + FlowShockShell, + start, + dir, + radius0: 0.6f, + radius1: 6.5f * scale, + strength0: 28f, + strength1: 4f, + shellThickness: 1.8f, + shockPressure0: 0.55f, + shockPressure1: 0f, + lifetime: 0.18f, + priority: 5); + } + } + + public void EmitOrdnanceDetonation(Vector3 pos, Color accentCol, float splashRadius) + { + float scale = Math.Clamp(splashRadius / 4.2f, 0.75f, 1.85f); + SpawnEmitter( + EmitterFireball, + startPos: pos, + endPos: pos + Vector3.Up * (1.8f * scale), + velStart: Vector3.Up * 1.4f, + velEnd: Vector3.Up * 3.2f, + radiusA0: 1.2f * scale, + radiusA1: 3.8f * scale, + radiusB0: 1.4f * scale, + radiusB1: 4.5f * scale, + density0: 1.35f, + density1: 0.25f, + temp0: 1.25f, + temp1: 0.05f, + tint0: accentCol * 0.6f + new Color(0.22f, 0.18f, 0.15f), + tint1: new Color(0.14f, 0.13f, 0.12f), + lifetime: 2.1f, + flowSpeed: 0.8f, + softness: 0.40f, + drag: 1.1f, + buoyancy: 0.85f, + priority: 9); + + SpawnFlowImpulse( + FlowShockShell, + pos, + Vector3.Up, + radius0: 1.0f, + radius1: Math.Clamp(splashRadius * 3.2f, 9f, 24f), + strength0: 76f, + strength1: 12f, + shellThickness: 2.8f, + shockPressure0: 1.25f, + shockPressure1: 0f, + lifetime: 0.34f, + priority: 9); + + SpawnFlowImpulse( + FlowThermalUpdraft, + pos, + Vector3.Up, + radius0: 3.5f * scale, + radius1: 6.0f * scale, + strength0: 9.5f, + strength1: 2.5f, + shellThickness: 0f, + shockPressure0: 0f, + shockPressure1: 0f, + lifetime: 2.2f, + priority: 7); + } + + public void EmitOrdnanceTrailCapsule(Vector3 tailPos, Vector3 pos, Vector3 vel, Color accentCol, bool isRocket) + { + if (ActiveEmitterCount >= 112) + { + return; + } + Vector3 back = vel.LengthSquared() > 1f ? -vel.Normalized() : Vector3.Up; + Vector3 segStart = pos; + Vector3 segEnd = pos.DistanceSquaredTo(tailPos) > 0.25f ? tailPos : pos + back * 2.2f; + SpawnEmitter( + isRocket ? EmitterFireball : EmitterSmoke, + startPos: segStart, + endPos: segEnd, + velStart: back * 1.4f + Vector3.Up * 0.5f, + velEnd: back * 0.8f + Vector3.Up * 1.1f, + radiusA0: isRocket ? 0.55f : 0.38f, + radiusA1: isRocket ? 1.85f : 1.15f, + radiusB0: isRocket ? 0.72f : 0.48f, + radiusB1: isRocket ? 2.25f : 1.35f, + density0: isRocket ? 0.92f : 0.58f, + density1: 0.06f, + temp0: isRocket ? 0.75f : 0.10f, + temp1: 0f, + tint0: isRocket ? new Color(0.62f, 0.56f, 0.50f) : accentCol * 0.65f, + tint1: new Color(0.32f, 0.30f, 0.28f), + lifetime: isRocket ? 0.95f : 0.55f, + flowSpeed: 0.65f, + softness: 0.46f, + drag: 1.6f, + buoyancy: 0.45f, + priority: 4); + } + + public void EmitThermalPoolPlume(Vector3 pos, float radius, Color accentCol) + { + if (ActiveEmitterCount >= 116) + { + return; + } + float r = Math.Clamp(radius * 0.55f, 1.4f, 4.5f); + SpawnEmitter( + EmitterThermalPool, + startPos: pos + new Vector3(NextSigned() * r * 0.45f, 0.2f, NextSigned() * r * 0.45f), + endPos: pos + new Vector3(NextSigned() * r * 0.35f, 2.8f, NextSigned() * r * 0.35f), + velStart: Vector3.Up * 1.1f, + velEnd: Vector3.Up * 2.2f, + radiusA0: r * 0.55f, + radiusA1: r * 0.85f, + radiusB0: r * 0.40f, + radiusB1: r * 0.95f, + density0: 0.78f, + density1: 0.10f, + temp0: 0.85f, + temp1: 0.15f, + tint0: accentCol, + tint1: accentCol * 0.55f, + lifetime: 0.75f, + flowSpeed: 0.75f, + softness: 0.45f, + drag: 1.0f, + buoyancy: 0.85f, + priority: 5); + + SpawnFlowImpulse( + FlowThermalUpdraft, + pos, + Vector3.Up, + radius0: radius, + radius1: radius * 1.15f, + strength0: 7.5f, + strength1: 7.5f, + shellThickness: 0f, + shockPressure0: 0f, + shockPressure1: 0f, + lifetime: 0.45f, + priority: 4); + } + + public void EmitPodReentryPlume(Vector3 podPos, Vector3 podVel, float heatGlow, bool isContender) + { + float scale = isContender ? 1.25f : 0.85f; + Vector3 upTrail = podVel.LengthSquared() > 1f ? -podVel.Normalized() : Vector3.Up; + SpawnEmitter( + EmitterRetroPlume, + startPos: podPos + upTrail * 0.8f, + endPos: podPos + upTrail * (4.5f * scale), + velStart: upTrail * 2.5f, + velEnd: upTrail * 4.0f, + radiusA0: 0.75f * scale, + radiusA1: 1.85f * scale, + radiusB0: 1.15f * scale, + radiusB1: 2.65f * scale, + density0: 0.90f, + density1: 0.08f, + temp0: 0.72f + heatGlow * 0.45f, + temp1: 0.04f, + tint0: new Color(0.55f, 0.42f, 0.34f), + tint1: new Color(0.28f, 0.26f, 0.25f), + lifetime: 0.42f, + flowSpeed: 0.90f, + softness: 0.42f, + drag: 1.6f, + buoyancy: 0.4f, + priority: isContender ? 7 : 4); + } + + public void EmitPodRetroPlume(Vector3 podBasePos, float agl, Color groundTint, bool isContender) + { + float scale = isContender ? 1.25f : 0.88f; + float jetLen = MathF.Min(12f * scale, MathF.Max(3.5f, agl * 0.6f)); + SpawnEmitter( + EmitterRetroPlume, + startPos: podBasePos, + endPos: podBasePos - new Vector3(0f, jetLen, 0f), + velStart: new Vector3(0f, -8f, 0f), + velEnd: new Vector3(NextSigned() * 2.5f, -4f, NextSigned() * 2.5f), + radiusA0: 0.85f * scale, + radiusA1: 1.6f * scale, + radiusB0: 1.65f * scale, + radiusB1: 3.4f * scale, + density0: 1.25f, + density1: 0.15f, + temp0: 1.20f, + temp1: 0.12f, + tint0: new Color(0.60f, 0.48f, 0.38f), + tint1: groundTint * 0.72f, + lifetime: 0.26f, + flowSpeed: 1.1f, + softness: 0.40f, + drag: 1.8f, + buoyancy: 0.2f, + priority: isContender ? 9 : 6); + + if (agl < 65f) + { + float washT = Math.Clamp(1f - agl / 65f, 0.20f, 1f); + Vector3 groundPos = podBasePos - new Vector3(0f, MathF.Max(0f, agl), 0f) + new Vector3(0f, 0.6f, 0f); + SpawnEmitter( + EmitterSmoke, + startPos: groundPos + new Vector3(-1.8f * scale, 0f, 0f), + endPos: groundPos + new Vector3(1.8f * scale, 0.4f, 0f), + velStart: new Vector3(-3.5f * washT, 1.1f, NextSigned() * 2.2f), + velEnd: new Vector3(3.5f * washT, 1.3f, NextSigned() * 2.2f), + radiusA0: 1.6f * scale, + radiusA1: 4.8f * scale * washT + 1.4f, + radiusB0: 1.6f * scale, + radiusB1: 4.8f * scale * washT + 1.4f, + density0: 0.82f * washT, + density1: 0.08f, + temp0: 0.10f, + temp1: 0f, + tint0: groundTint, + tint1: groundTint * 0.78f, + lifetime: 0.72f, + flowSpeed: 0.85f, + softness: 0.48f, + drag: 1.6f, + buoyancy: 0.35f, + priority: isContender ? 8 : 5); + + SpawnFlowImpulse( + FlowRetroDownwash, + groundPos, + Vector3.Down, + radius0: 14.0f * scale, + radius1: 18.0f * scale, + strength0: 42f * washT, + strength1: 30f * washT, + shellThickness: 0f, + shockPressure0: 0.65f * washT, + shockPressure1: 0.35f * washT, + lifetime: 0.14f, + priority: isContender ? 9 : 6); + } + } + + public void EmitPodTouchdownPlume(Vector3 pos, Vector3 normal, Color groundTint, bool isContender) + { + float scale = isContender ? 1.40f : 0.95f; + SpawnEmitter( + EmitterFireball, + startPos: pos + normal * 0.6f, + endPos: pos + normal * (2.6f * scale), + velStart: normal * 1.8f, + velEnd: normal * 3.4f, + radiusA0: 1.6f * scale, + radiusA1: 5.5f * scale, + radiusB0: 1.9f * scale, + radiusB1: 6.2f * scale, + density0: 1.18f, + density1: 0.18f, + temp0: 0.95f, + temp1: 0.0f, + tint0: groundTint * 0.82f, + tint1: groundTint * 0.55f, + lifetime: isContender ? 1.85f : 1.15f, + flowSpeed: 0.85f, + softness: 0.46f, + drag: 1.3f, + buoyancy: 0.65f, + priority: isContender ? 10 : 7); + + SpawnFlowImpulse( + FlowShockShell, + pos + normal * 0.4f, + normal, + radius0: 1.8f, + radius1: 22.0f * scale, + strength0: 68f * scale, + strength1: 12f, + shellThickness: 3.2f, + shockPressure0: 1.1f, + shockPressure1: 0f, + lifetime: 0.35f, + priority: 10); + } + + public void EmitThermalVentPlume(Vector3 pos, float thermalRatio) + { + if (ActiveEmitterCount >= 112) + { + return; + } + float heatT = Math.Clamp((thermalRatio - 0.85f) / 0.25f, 0f, 1f); + SpawnEmitter( + EmitterSmoke, + startPos: pos, + endPos: pos + new Vector3(0f, 1.4f, 0f), + velStart: new Vector3(NextSigned() * 0.6f, 2.2f, NextSigned() * 0.6f), + velEnd: new Vector3(NextSigned() * 0.8f, 3.0f, NextSigned() * 0.8f), + radiusA0: 0.45f, + radiusA1: 1.45f + heatT * 0.4f, + radiusB0: 0.55f, + radiusB1: 1.65f + heatT * 0.5f, + density0: 0.72f, + density1: 0.06f, + temp0: 0.25f + heatT * 0.45f, + temp1: 0f, + tint0: new Color(0.82f, 0.72f - heatT * 0.22f, 0.62f - heatT * 0.35f), + tint1: new Color(0.45f, 0.42f, 0.40f), + lifetime: 0.65f, + flowSpeed: 0.6f, + softness: 0.45f, + drag: 1.5f, + buoyancy: 0.75f, + priority: 4); + } + + public void EmitDamageSmokePlume(Vector3 pos, float coreHpRatio) + { + if (ActiveEmitterCount >= 112) + { + return; + } + float dmgT = Math.Clamp((0.35f - coreHpRatio) / 0.35f, 0f, 1f); + SpawnEmitter( + dmgT > 0.35f ? EmitterFireball : EmitterSmoke, + startPos: pos, + endPos: pos + new Vector3(0f, 1.8f, 0f), + velStart: new Vector3(NextSigned() * 0.5f, 2.1f, NextSigned() * 0.5f), + velEnd: new Vector3(NextSigned() * 0.8f, 3.2f, NextSigned() * 0.8f), + radiusA0: 0.62f, + radiusA1: 1.95f + dmgT * 0.65f, + radiusB0: 0.75f, + radiusB1: 2.35f + dmgT * 0.75f, + density0: 0.95f, + density1: 0.12f, + temp0: dmgT > 0.30f ? 0.55f + dmgT * 0.40f : 0.08f, + temp1: 0f, + tint0: new Color(0.18f, 0.16f, 0.15f), + tint1: new Color(0.10f, 0.10f, 0.10f), + lifetime: 0.95f, + flowSpeed: 0.7f, + softness: 0.42f, + drag: 1.1f, + buoyancy: 0.85f, + priority: 5); + } + + public void EmitFootstepOrTirePuff(Vector3 pos, Color groundTint, float scale) + { + // Strictly gated under 104 active emitters so combat explosions never drop slots + if (ActiveEmitterCount >= 104) + { + return; + } + Color gLin = groundTint.SrgbToLinear(); + SpawnEmitter( + EmitterSmoke, + startPos: pos, + endPos: pos + new Vector3(NextSigned() * 0.4f, 0.45f, NextSigned() * 0.4f), + velStart: new Vector3(NextSigned() * 1.1f, 0.9f, NextSigned() * 1.1f), + velEnd: new Vector3(NextSigned() * 1.4f, 1.4f, NextSigned() * 1.4f), + radiusA0: 0.48f * scale, + radiusA1: 1.55f * scale, + radiusB0: 0.58f * scale, + radiusB1: 1.75f * scale, + density0: 0.52f, + density1: 0.05f, + temp0: 0f, + temp1: 0f, + tint0: gLin * 1.1f, + tint1: gLin * 0.75f, + lifetime: 0.52f, + flowSpeed: 0.45f, + softness: 0.50f, + drag: 2.0f, + buoyancy: 0.35f, + priority: 1); + } + + private int FindOrEvictEmitterSlot(int priority) + { + int oldestIdx = -1; + int lowestPri = int.MaxValue; + float oldestAge = -1f; + for (int i = 0; i < MaxEmitters; i++) + { + if (!_emitters[i].Active) + { + return i; + } + if (_emitters[i].Priority < lowestPri || + (_emitters[i].Priority == lowestPri && _emitters[i].Age > oldestAge)) + { + lowestPri = _emitters[i].Priority; + oldestAge = _emitters[i].Age; + oldestIdx = i; + } + } + return lowestPri <= priority ? oldestIdx : -1; + } + + private int FindOrEvictImpulseSlot(int priority) + { + int oldestIdx = -1; + int lowestPri = int.MaxValue; + float oldestAge = -1f; + for (int i = 0; i < MaxFlowImpulses; i++) + { + if (!_impulses[i].Active) + { + return i; + } + if (_impulses[i].Priority < lowestPri || + (_impulses[i].Priority == lowestPri && _impulses[i].Age > oldestAge)) + { + lowestPri = _impulses[i].Priority; + oldestAge = _impulses[i].Age; + oldestIdx = i; + } + } + return lowestPri <= priority ? oldestIdx : -1; + } + + private int CountActiveEmitters() + { + int count = 0; + for (int i = 0; i < MaxEmitters; i++) + { + if (_emitters[i].Active) count++; + } + return count; + } + + private int CountActiveImpulses() + { + int count = 0; + for (int i = 0; i < MaxFlowImpulses; i++) + { + if (_impulses[i].Active) count++; + } + return count; + } + + private float NextFloat() + { + uint x = _rng; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + _rng = x; + return (x & 0x00FFFFFFu) / 16777216f; + } + + private float NextSigned() => NextFloat() * 2f - 1f; +} diff --git a/client/flow_field_step.glsl b/client/flow_field_step.glsl new file mode 100644 index 0000000..e95aedf --- /dev/null +++ b/client/flow_field_step.glsl @@ -0,0 +1,129 @@ +#version 450 + +layout(local_size_x = 8, local_size_y = 4, local_size_z = 8) in; + +struct FlowImpulse { + vec4 posRadius; + vec4 dirStrength; + vec4 shellParams; +}; + +layout(set = 0, binding = 0, std140) uniform VolumetricFrame { + mat4 invProj; + vec4 camPosTime; + vec4 camRightAspect; + vec4 camUpTanHalfFov; + vec4 camFwdNearFar; + vec4 sunDirIntensity; + vec4 sunColorExt; + vec4 ambientColorFog; + vec4 viewportInfo; + uvec4 tileGridParams; + vec4 flowOriginVoxel; + vec4 flowInvExtentDt; + ivec4 flowDeltaImpulse; +} u_frame; + +layout(set = 0, binding = 1, std430) readonly buffer FlowImpulseBuffer { + FlowImpulse impulses[]; +} u_impulses; + +layout(set = 0, binding = 2) uniform sampler3D u_prevFlow; +layout(set = 0, binding = 3, rgba16f) uniform writeonly image3D u_nextFlow; + +shared FlowImpulse sImp[64]; + +void main() { + uint tid = gl_LocalInvocationIndex; + uint impulseCount = min(uint(max(0, u_frame.flowDeltaImpulse.w)), 64u); + if (tid < impulseCount) { + sImp[tid] = u_impulses.impulses[tid]; + } + memoryBarrierShared(); + barrier(); + + ivec3 g = ivec3(gl_GlobalInvocationID.xyz); + const ivec3 gridDim = ivec3(64, 24, 64); + if (any(greaterThanEqual(g, gridDim))) { + return; + } + + float voxelSize = u_frame.flowOriginVoxel.w; + float dt = clamp(u_frame.flowInvExtentDt.w, 0.0, 0.05); + float elapsed = u_frame.camPosTime.w; + + // Gentle planetary wind that shifts subtly with time so idle smoke plumes breathe + vec3 ambientWind = vec3( + 1.25 + 0.35 * sin(elapsed * 0.23), + 0.18, + 0.55 + 0.25 * cos(elapsed * 0.19) + ); + + ivec3 prevIdx = g + u_frame.flowDeltaImpulse.xyz; + bool inPrev = all(greaterThanEqual(prevIdx, ivec3(0))) && all(lessThan(prevIdx, gridDim)); + vec3 prevVel = inPrev ? texelFetch(u_prevFlow, prevIdx, 0).rgb : ambientWind; + + vec3 srcUv = (vec3(prevIdx) + vec3(0.5) - (prevVel * dt) / voxelSize) / vec3(gridDim); + vec4 advected = (inPrev && all(greaterThanEqual(srcUv, vec3(0.0))) && all(lessThanEqual(srcUv, vec3(1.0)))) + ? textureLod(u_prevFlow, srcUv, 0.0) + : vec4(ambientWind, 0.0); + + vec3 vel = mix(ambientWind, advected.rgb, exp(-dt * 1.45)); + float shockP = advected.a * exp(-dt * 4.5); + + vec3 worldP = u_frame.flowOriginVoxel.xyz + (vec3(g) + vec3(0.5)) * voxelSize; + + for (uint i = 0u; i < impulseCount; i++) { + FlowImpulse imp = sImp[i]; + uint typeBits = floatBitsToUint(imp.shellParams.z); + float radius = max(0.5, imp.posRadius.w); + float strength = imp.dirStrength.w; + + if (typeBits == 0u) { + // ShockShell: expanding radial blast shell + vec3 delta = worldP - imp.posRadius.xyz; + float dist = length(delta); + float thick = max(1.5, imp.shellParams.x); + float dShell = (dist - radius) / thick; + if (abs(dShell) < 3.0) { + float shell = exp(-dShell * dShell); + vec3 rDir = dist > 0.05 ? delta / dist : vec3(0.0, 1.0, 0.0); + vel += rDir * (strength * shell); + shockP = max(shockP, imp.shellParams.y * shell); + } + } else if (typeBits == 1u) { + // RetroDownwash: radial ground deflection from pod retro thruster + vec3 d = worldP - imp.posRadius.xyz; + float rXZ = length(d.xz); + float rNorm = rXZ / radius; + float hNorm = abs(d.y) / max(3.0, radius * 0.55); + if (rNorm < 1.35 && hNorm < 1.35) { + float rFall = exp(-rNorm * rNorm * 1.6) * smoothstep(1.35, 0.08, rNorm); + float hFall = exp(-hNorm * hNorm * 1.4); + vec2 rXZDir = rXZ > 0.1 ? d.xz / rXZ : vec2(1.0, 0.0); + vec3 outDir = normalize(vec3(rXZDir.x, 0.28, rXZDir.y)); + float w = rFall * hFall; + vel += outDir * (strength * w); + shockP = max(shockP, imp.shellParams.y * w); + } + } else { + // ThermalUpdraft: buoyant rising column above fireballs & thermal pools + vec3 d = worldP - imp.posRadius.xyz; + float rXZ = length(d.xz); + float rNorm = rXZ / radius; + if (rNorm < 1.3 && d.y > -2.5 && d.y < radius * 2.8) { + float hFall = smoothstep(-2.5, 1.5, d.y) * smoothstep(radius * 2.8, 0.0, max(0.0, d.y)); + float colFall = exp(-rNorm * rNorm * 1.5) * hFall; + vel += vec3(0.0, strength * colFall, 0.0); + } + } + } + + float vLen = length(vel); + if (vLen > 120.0) { + vel *= 120.0 / vLen; + } + shockP = clamp(shockP, 0.0, 2.0); + + imageStore(u_nextFlow, g, vec4(vel, shockP)); +} diff --git a/client/gpu_sparks_draw.gdshader b/client/gpu_sparks_draw.gdshader new file mode 100644 index 0000000..0daea79 --- /dev/null +++ b/client/gpu_sparks_draw.gdshader @@ -0,0 +1,124 @@ +shader_type spatial; +render_mode unshaded, cull_disabled, blend_mix, depth_draw_never; + +varying vec4 v_color; +varying vec2 v_uvCentered; +varying vec2 v_kite; +varying float v_ageNorm; +varying float v_type; + +void vertex() { + vec3 worldPos = MODEL_MATRIX[3].xyz; + vec3 velWorld = MODEL_MATRIX[0].xyz; + + float widthM = max(0.015, INSTANCE_CUSTOM.x); + float ageNorm = clamp(INSTANCE_CUSTOM.y / max(0.01, INSTANCE_CUSTOM.z), 0.0, 1.0); + float pType = floor(INSTANCE_CUSTOM.w + 0.001); + + v_color = COLOR; + v_ageNorm = ageNorm; + v_type = pType; + v_uvCentered = UV * 2.0 - vec2(1.0); + + // Kite-stretch trick: rotate quad coordinates 45 degrees so pointed ears align directly along velocity: + // (-1,-1) -> u=-1,v=0 (tail tip); (+1,+1) -> u=+1,v=0 (nose tip); (+1,-1)/( -1,+1) -> v=±1 (side ears) + float uKite = 0.5 * (v_uvCentered.x + v_uvCentered.y); + float vKite = 0.5 * (v_uvCentered.x - v_uvCentered.y); + v_kite = vec2(uKite, vKite); + + vec3 camRight = INV_VIEW_MATRIX[0].xyz; + vec3 camUp = INV_VIEW_MATRIX[1].xyz; + vec3 toCamVec = CAMERA_POSITION_WORLD - worldPos; + float toCamLen2 = dot(toCamVec, toCamVec); + vec3 toCam = toCamLen2 > 1e-6 ? toCamVec * inversesqrt(toCamLen2) : INV_VIEW_MATRIX[2].xyz; + + vec3 axisWorld; + vec3 perpWorld; + float halfWidth; + float halfLen; + + if (pType > 2.5) { + // Type 3: Stationary 4-point HDR muzzle starburst + float pulse = sin(ageNorm * 3.14159265); + float sz = widthM * (0.65 + 0.45 * pulse); + vec3 displacedWorld = worldPos + camRight * (v_uvCentered.x * sz) + camUp * (v_uvCentered.y * sz); + MODELVIEW_MATRIX = VIEW_MATRIX; + VERTEX = displacedWorld; + } else { + float speed = length(velWorld); + vec3 vProj = velWorld - toCam * dot(velWorld, toCam); + float vProjLen2 = dot(vProj, vProj); + axisWorld = vProjLen2 > 1e-4 ? vProj * inversesqrt(vProjLen2) : camRight; + vec3 rawPerp = cross(toCam, axisWorld); + float rawPerpLen2 = dot(rawPerp, rawPerp); + perpWorld = rawPerpLen2 > 1e-6 ? rawPerp * inversesqrt(rawPerpLen2) : camUp; + + if (pType > 1.5) { + // Type 2: Tiny flow-blown grit / dust mote + float minGritPx = sqrt(toCamLen2) * 0.0011; + halfWidth = max(clamp(widthM * (0.85 + 0.35 * ageNorm), 0.025, 0.07), minGritPx); + halfLen = halfWidth + clamp(speed * 0.012, 0.01, 0.16); + } else { + // Type 0 (VelocitySpark) & Type 1 (BuoyantEmber): strictly tiny width + velocity-stretched kite ears + float minSparkPx = sqrt(toCamLen2) * 0.0018; + halfWidth = max(clamp(widthM * mix(1.0, 0.45, ageNorm), 0.015, 0.042), minSparkPx); + halfLen = max(halfWidth * 2.4, clamp(halfWidth * 1.6 + speed * 0.028, 0.08, 0.48)); + } + + vec3 displacedWorld = worldPos + axisWorld * (uKite * halfLen) + perpWorld * (vKite * halfWidth); + MODELVIEW_MATRIX = VIEW_MATRIX; + VERTEX = displacedWorld; + } +} + +void fragment() { + float fade = (1.0 - v_ageNorm * v_ageNorm) * clamp(v_color.a, 0.0, 1.0); + if (fade < 0.01) { + discard; + } + + if (v_type > 2.5) { + // 4-point HDR muzzle starburst + float r = length(v_uvCentered); + if (r > 1.0) { + discard; + } + float cx = exp(-abs(v_uvCentered.y) * 9.5) * smoothstep(1.0, 0.05, abs(v_uvCentered.x)); + float cy = exp(-abs(v_uvCentered.x) * 9.5) * smoothstep(1.0, 0.05, abs(v_uvCentered.y)); + float core = smoothstep(0.55, 0.0, r); + float mask = max(core, max(cx, cy) * 0.90); + float alpha = clamp(mask * fade, 0.0, 1.0); + if (alpha < 0.01) { + discard; + } + ALBEDO = max(v_color.rgb, vec3(0.0)) * (1.0 + core * 0.9); + ALPHA = alpha; + } else if (v_type > 1.5) { + // Tiny flow-entrained grit speck + float r = length(v_kite); + if (r > 0.92) { + discard; + } + float alpha = smoothstep(0.92, 0.18, r) * fade * 0.78; + if (alpha < 0.01) { + discard; + } + ALBEDO = max(v_color.rgb, vec3(0.0)); + ALPHA = alpha; + } else { + // Kite-stretched HDR spark / ember: razor diamond falloff with hot core + float rKite = length(vec2(v_kite.x, v_kite.y * 1.15)); + if (rKite > 1.0) { + discard; + } + float core = pow(clamp(1.0 - rKite, 0.0, 1.0), 1.55); + float hotCenter = smoothstep(0.45, 0.0, rKite); + float alpha = clamp(core * fade, 0.0, 1.0); + if (alpha < 0.01) { + discard; + } + vec3 baseRgb = max(v_color.rgb, vec3(0.0)); + ALBEDO = mix(baseRgb, baseRgb * 1.65 + vec3(1.2), hotCenter * 0.45); + ALPHA = alpha; + } +} diff --git a/client/gpu_sparks_process.gdshader b/client/gpu_sparks_process.gdshader new file mode 100644 index 0000000..8d4c413 --- /dev/null +++ b/client/gpu_sparks_process.gdshader @@ -0,0 +1,67 @@ +shader_type particles; +render_mode disable_velocity; + +global uniform sampler3D rtd_flow_field; +global uniform vec3 rtd_flow_origin; +global uniform vec3 rtd_flow_inv_extent; + +void start() { + ACTIVE = false; +} + +void process() { + float age = CUSTOM.y + DELTA; + float maxLife = max(0.01, CUSTOM.z); + if (age >= maxLife) { + ACTIVE = false; + } else { + CUSTOM.y = age; + float pType = floor(CUSTOM.w + 0.001); + float drag = fract(CUSTOM.w) * 20.0; + + if (pType > 2.5) { + // Type 3: MuzzleStarburst (stationary HDR flash) + VELOCITY = vec3(0.0); + TRANSFORM[0].xyz = vec3(1.0, 0.0, 0.0); + TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0); + TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0); + } else { + vec3 worldPos = TRANSFORM[3].xyz; + vec3 flowUv = (worldPos - rtd_flow_origin) * rtd_flow_inv_extent; + vec4 flowSample = vec4(0.0); + if (all(greaterThanEqual(flowUv, vec3(0.0))) && all(lessThanEqual(flowUv, vec3(1.0)))) { + flowSample = textureLod(rtd_flow_field, flowUv, 0.0); + } + + vec3 flowVel = flowSample.rgb; + float shockP = flowSample.a; + + if (pType < 0.5) { + // Type 0: VelocitySpark (ballistic + flow drag + shock kick) + VELOCITY += (flowVel - VELOCITY) * min(1.0, drag * DELTA); + VELOCITY.y -= 11.0 * DELTA; + if (shockP > 0.25) { + VELOCITY += flowVel * (shockP * 0.45 * DELTA); + } + } else if (pType < 1.5) { + // Type 1: BuoyantEmber (upward buoyancy + thermal swirl) + VELOCITY += (flowVel - VELOCITY) * min(1.0, drag * DELTA); + VELOCITY.y += 2.2 * DELTA; + if (shockP > 0.25) { + VELOCITY += flowVel * (shockP * 0.65 * DELTA); + } + } else { + // Type 2: DustMote (heavily flow-entrained ground grit) + float dustDrag = max(drag, 3.2); + VELOCITY += (flowVel - VELOCITY) * min(1.0, dustDrag * DELTA); + VELOCITY.y -= 1.2 * DELTA; + } + + TRANSFORM[3].xyz += VELOCITY * DELTA; + // Pass world VELOCITY to gpu_sparks_draw.gdshader cleanly via MODEL_MATRIX[0] + TRANSFORM[0].xyz = VELOCITY; + TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0); + TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0); + } + } +} diff --git a/client/particle_billboard.gdshader b/client/particle_billboard.gdshader deleted file mode 100644 index eb44cea..0000000 --- a/client/particle_billboard.gdshader +++ /dev/null @@ -1,108 +0,0 @@ -shader_type spatial; -render_mode unshaded, cull_disabled, blend_mix, depth_draw_never; - -// Forward+ Vulkan single-draw-call billboard particle shader for MultiMeshInstance3D. -// Zero texture binds; packs shape mode, normalized age, HDR emissive, and 2D rotation into INSTANCE_CUSTOM, -// and sRGB RGB tint (converted to linear in vertex()) + alpha fade into COLOR. -// -// INSTANCE_CUSTOM layout: -// x = mode (0.0 = soft wisp dust/smoke, 1.0 = 4-point HDR muzzle starburst, 2.0 = spark/ember streak, 3.0 = steam/fireball puff) -// y = age_norm (0.0..1.0) -// z = emissive (0.0..4.0+ HDR multiplier) -// w = rot_rad (2D billboard roll angle in radians) - -varying vec4 v_color; -varying vec4 v_custom; - -float hash21(vec2 p) { - p = fract(p * vec2(127.1, 311.7)); - p += dot(p, p + 34.43); - return fract(p.x * p.y); -} - -float soft_noise(vec2 p) { - return 0.5 + 0.25 * sin(p.x * 2.7 + p.y * 1.9) + 0.25 * cos(p.y * 2.3 - p.x * 1.7); -} - -vec3 srgb_to_linear(vec3 c) { - vec3 lo = c / 12.92; - vec3 hi = pow((c + vec3(0.055)) / 1.055, vec3(2.4)); - return mix(lo, hi, step(vec3(0.04045), c)); -} - -void vertex() { - v_color = vec4(srgb_to_linear(max(COLOR.rgb, vec3(0.0))), COLOR.a); - v_custom = INSTANCE_CUSTOM; - - float rot = INSTANCE_CUSTOM.w; - float c = cos(rot); - float s = sin(rot); - VERTEX.xy = vec2(VERTEX.x * c - VERTEX.y * s, VERTEX.x * s + VERTEX.y * c); - - vec3 world_pos = MODEL_MATRIX[3].xyz; - float sx = length(MODEL_MATRIX[0].xyz); - float sy = length(MODEL_MATRIX[1].xyz); - - MODELVIEW_MATRIX = VIEW_MATRIX * mat4( - vec4(INV_VIEW_MATRIX[0].xyz * sx, 0.0), - vec4(INV_VIEW_MATRIX[1].xyz * sy, 0.0), - vec4(INV_VIEW_MATRIX[2].xyz, 0.0), - vec4(world_pos, 1.0) - ); -} - -void fragment() { - vec2 centered = UV * 2.0 - vec2(1.0); - float r = length(centered); - if (r > 1.0) { - discard; - } - - float mode = floor(v_custom.x + 0.5); - float age_norm = clamp(v_custom.y, 0.0, 1.0); - float emissive = max(v_custom.z, 0.0); - - float shape_alpha = 0.0; - float core_mask = 0.0; - - if (mode < 0.5) { - // Mode 0: Soft wisp dust / smoke plume - float wisp = soft_noise(centered * 2.4 + vec2(v_custom.w * 1.7, age_norm * 1.5)); - float radial = smoothstep(1.0, 0.14, r + (wisp - 0.5) * 0.34); - shape_alpha = radial * (0.72 + 0.28 * wisp); - core_mask = smoothstep(0.65, 0.0, r) * 0.4; - } else if (mode < 1.5) { - // Mode 1: Crisp 4-point HDR muzzle starburst - float ax = abs(centered.x); - float ay = abs(centered.y); - float cross_x = exp(-ay * 10.5) * smoothstep(1.0, 0.08, ax); - float cross_y = exp(-ax * 10.5) * smoothstep(1.0, 0.08, ay); - float core = smoothstep(0.58, 0.0, r); - float flash = max(core, max(cross_x, cross_y) * 0.92); - shape_alpha = clamp(flash, 0.0, 1.0); - core_mask = clamp(core * 1.35 + (cross_x + cross_y) * 0.55, 0.0, 1.5); - } else if (mode < 2.5) { - // Mode 2: Elongated spark / hot shrapnel streak - vec2 stretched = vec2(centered.x * 1.0, centered.y * 2.6); - float sr = length(stretched); - float streak = smoothstep(1.0, 0.05, sr); - shape_alpha = streak * streak; - core_mask = smoothstep(0.75, 0.0, sr); - } else { - // Mode 3: Steam / fireball / thermal puff - float billow = soft_noise(centered * 3.1 - vec2(age_norm * 1.9, v_custom.w)); - float radial = smoothstep(1.0, 0.08, r + (billow - 0.5) * 0.26); - float hot_core = smoothstep(0.62, 0.0, r); - shape_alpha = radial; - core_mask = hot_core * (1.0 - age_norm * 0.55); - } - - float alpha = clamp(shape_alpha * v_color.a, 0.0, 1.0); - if (alpha < 0.005) { - discard; - } - - vec3 rgb = max(v_color.rgb, vec3(0.0)) * (1.0 + emissive * core_mask); - ALBEDO = rgb; - ALPHA = alpha; -} diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index f7de3e2..133683c 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -1231,11 +1231,34 @@ public partial class Smoke : Node $"Expected zero StandardMaterial3D duplicates, got {VehicleVisualInstance.PerfMaterialDupCount}"); } - // 12. Cut 5d-2: Unified SimEvent -> ParticlePool idempotency + OmniLight3D[4] cap + CameraJuice zero-idle-jitter + Hud X-flash & vignette + // 12. Cut 5d-2 + Cut 10b: Unified SimEvent -> GpuSparksSystem + VolumetricEmitterPool idempotency + OmniLight3D[2] cap + global rtd_flow_field + CameraJuice + Hud X-flash { var particles = _main.Arena.Particles; + var volumetrics = _main.Arena.Volumetrics; + var gpuSparks = _main.Arena.GpuSparks; particles.ClearAll(); - int beforeCount = particles.ActiveParticleCount; + volumetrics.ClearAll(); + gpuSparks.ClearAll(); + + // Verify Cut 10b structural subtraction & GPUParticles3D / global shader param wiring + Check(!FileAccess.FileExists("res://particle_billboard.gdshader"), + "Expected obsolete particle_billboard.gdshader to be deleted"); + int particleMmiCount = 0; + foreach (Node ch in particles.GetChildren()) + { + if (ch is MultiMeshInstance3D) particleMmiCount++; + } + Check(particleMmiCount == 0, + $"Expected zero MultiMeshInstance3D nodes inside collapsed ParticlePool, found {particleMmiCount}"); + Check(gpuSparks.ParticlesNode.Amount == GpuSparksSystem.Capacity && gpuSparks.ParticlesNode.AmountRatio == 0.0f, + $"Expected GpuSparksSystem Amount={GpuSparksSystem.Capacity} AmountRatio=0.0f, got {gpuSparks.ParticlesNode.Amount} ratio={gpuSparks.ParticlesNode.AmountRatio}"); + + Check(AtmosphereSystem.AreFlowGlobalsRegistered, + "Expected global rtd_flow_* shader parameters registered in AtmosphereSystem"); + + int beforeSparks = gpuSparks.TotalEmittedCount; + int beforeVol = volumetrics.ActiveEmitterCount; + int beforeImp = volumetrics.ActiveImpulseCount; int tracerId = _main.Session.ViewState.AllocateTracerId(); var localC = _main.Session.LocalContender; @@ -1260,15 +1283,17 @@ public partial class Smoke : Node var simBatch = new List { shotEvent }; var emptyFootsteps = new List(); _main.Arena.ConsumeEvents(_main.Session, simBatch, emptyFootsteps, 0f, _main.SampleCurrentMapGroundTint); - int afterFirst = particles.ActiveParticleCount; - Check(afterFirst == beforeCount + 5, - $"Expected recoilless ShotFiredEvent #{tracerId} to spawn 1 muzzle starburst + 4 smoke puffs (+5 particles), got +{afterFirst - beforeCount}"); + int afterSparks = gpuSparks.TotalEmittedCount; + int afterVol = volumetrics.ActiveEmitterCount; + int afterImp = volumetrics.ActiveImpulseCount; + Check(afterSparks >= beforeSparks + 1 && afterVol >= beforeVol + 1 && afterImp >= beforeImp + 1, + $"Expected recoilless ShotFiredEvent #{tracerId} to emit GPU muzzle flash/sparks (+{afterSparks - beforeSparks}), volumetric breech puff (+{afterVol - beforeVol}), and flow impulse (+{afterImp - beforeImp})"); // Re-consume with dt=0: idempotent TracerId dedupe must NOT double-emit _main.Arena.ConsumeEvents(_main.Session, simBatch, emptyFootsteps, 0f, _main.SampleCurrentMapGroundTint); _main.Arena.ConsumeEvents(_main.Session, simBatch, emptyFootsteps, 0f, _main.SampleCurrentMapGroundTint); - Check(particles.ActiveParticleCount == afterFirst, - $"Expected duplicate ShotFiredEvent #{tracerId} across dt=0 frames to spawn once, got {afterFirst} -> {particles.ActiveParticleCount}"); + Check(gpuSparks.TotalEmittedCount == afterSparks && volumetrics.ActiveEmitterCount == afterVol && volumetrics.ActiveImpulseCount == afterImp, + $"Expected duplicate ShotFiredEvent #{tracerId} across dt=0 frames to spawn once, got sparks {afterSparks}->{gpuSparks.TotalEmittedCount}, vol {afterVol}->{volumetrics.ActiveEmitterCount}"); // OmniLight3D[2] pool strictly capped at <= 2 active lights even under 12 simultaneous flashes particles.ClearAll(); @@ -1286,8 +1311,10 @@ public partial class Smoke : Node Check(particles.FlashLightPoolSize == 2 && particles.ActiveFlashLightCount <= 2 && particles.PeakFlashLightCount <= 2, $"Expected OmniLight3D pool capped at <= 2, got active={particles.ActiveFlashLightCount} peak={particles.PeakFlashLightCount}"); - // Far walker footstep pulse (>70m static LOD, <=110m) still emits terrain-tinted dust in ParticlePool + // Far walker footstep pulse (>70m static LOD, <=110m) emits GPU dust motes + optional volumetric puff particles.ClearAll(); + volumetrics.ClearAll(); + gpuSparks.ClearAll(); var farStep = new FootstepPulse( IsContender: true, EntityId: 99, @@ -1297,9 +1324,11 @@ public partial class Smoke : Node LoadG: 1.25f, WorldPos: new System.Numerics.Vector3(pPos.X + 85f, pPos.Y, pPos.Z)); _main.Arena.ConsumeEvents(_main.Session, Array.Empty(), new[] { farStep }, 0f, _main.SampleCurrentMapGroundTint); - Check(particles.ActiveParticleCount >= 3, - $"Expected far walker (85m > 70m static LOD) footstep to emit dust puffs, got {particles.ActiveParticleCount}"); + Check(gpuSparks.TotalEmittedCount >= 4 && volumetrics.ActiveEmitterCount >= 1, + $"Expected far walker (85m > 70m static LOD) footstep to emit GPU dust motes ({gpuSparks.TotalEmittedCount}) + volumetric puff ({volumetrics.ActiveEmitterCount})"); particles.ClearAll(); + volumetrics.ClearAll(); + gpuSparks.ClearAll(); // CameraJuiceState zero-idle-jitter & ComputeCenterScreenAim invariance under trauma var juice = _main.CameraJuice; @@ -1593,10 +1622,14 @@ public partial class Smoke : Node Check(audio.CountActiveUiVoicesForClip("mech_quick_bolt") == 1, $"Expected first ContenderLoadoutEvent (1 -> 2) after ResetForSession to play mech_quick_bolt, got {audio.CountActiveUiVoicesForClip("mech_quick_bolt")}"); - // Finding 3: Out-of-PVS deaths spawn zero phantom particles, lights, or audio + // Finding 3: Out-of-PVS deaths spawn zero phantom volumetric emitters, GPU sparks, lights, or audio audio.ResetForSession(_main.Session); var particles3 = _main.Arena.Particles; + var volumetrics3 = _main.Arena.Volumetrics; + var gpuSparks3 = _main.Arena.GpuSparks; particles3.ClearAll(); + volumetrics3.ClearAll(); + gpuSparks3.ClearAll(); var hiddenSession = new HiddenRemoteDeathsSession(_main.Session); var spec0 = _main.Session.ViewState.Spectators.Spectators[0]; var hiddenDeaths = new ISimEvent[] @@ -1607,9 +1640,11 @@ public partial class Smoke : Node particles3.ConsumeEvents(hiddenSession, hiddenDeaths, listener, hasCam: true, _main.SampleCurrentMapGroundTint); particles3.AdvanceAndCommit(0f); audio.ConsumeSimEvents(hiddenSession, hiddenDeaths, listener); - Check(particles3.ActiveParticleCount == 0 && particles3.ActiveFlashLightCount == 0 && audio.ActiveOneShotVoiceCount == 0, - $"Expected out-of-PVS deaths to spawn 0 VFX/SFX, got particles={particles3.ActiveParticleCount} lights={particles3.ActiveFlashLightCount} voices={audio.ActiveOneShotVoiceCount}"); + Check(gpuSparks3.TotalEmittedCount == 0 && volumetrics3.ActiveEmitterCount == 0 && particles3.ActiveFlashLightCount == 0 && audio.ActiveOneShotVoiceCount == 0, + $"Expected out-of-PVS deaths to spawn 0 VFX/SFX, got sparks={gpuSparks3.TotalEmittedCount} vol={volumetrics3.ActiveEmitterCount} lights={particles3.ActiveFlashLightCount} voices={audio.ActiveOneShotVoiceCount}"); particles3.ClearAll(); + volumetrics3.ClearAll(); + gpuSparks3.ClearAll(); GD.Print($"SMOKE INFO: Audio verified (haven={audio.Bank.HavenClipCount}, proc={audio.Bank.ProceduralClipCount}, dummy={audio.IsDummyAudio}, kestrelPitch={kestrelPitch:F3}, bastionPitch={bastionPitch:F3})"); } diff --git a/client/volumetric_capsule_beam.gdshader b/client/volumetric_capsule_beam.gdshader new file mode 100644 index 0000000..0f3330e --- /dev/null +++ b/client/volumetric_capsule_beam.gdshader @@ -0,0 +1,155 @@ +shader_type spatial; +render_mode unshaded, cull_front, blend_mix, depth_draw_never, depth_test_disabled; + +uniform sampler2D depth_tex : hint_depth_texture, filter_nearest; + +varying flat vec4 v_color; +varying flat vec4 v_custom; +varying flat vec3 v_ro; +varying flat float v_radius; +varying flat float v_halfLen; +varying vec3 v_fragCap; + +void vertex() { + v_color = COLOR; + v_custom = INSTANCE_CUSTOM; + + vec3 eX = normalize(MODEL_MATRIX[0].xyz); + vec3 eY = normalize(MODEL_MATRIX[1].xyz); + vec3 eZ = normalize(MODEL_MATRIX[2].xyz); + v_radius = max(0.005, 0.5 * length(MODEL_MATRIX[0].xyz)); + v_halfLen = max(0.0, 0.5 * length(MODEL_MATRIX[2].xyz) - v_radius); + + vec3 mid = MODEL_MATRIX[3].xyz; + mat3 invR = transpose(mat3(eX, eY, eZ)); + v_ro = invR * (CAMERA_POSITION_WORLD - mid); + + vec3 worldVert = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz; + v_fragCap = invR * (worldVert - mid); +} + +bool hitSphere(vec3 oc, vec3 rd, float r2, out float t0, out float t1) { + float b = dot(oc, rd); + float c = dot(oc, oc) - r2; + float disc = b * b - c; + if (disc <= 0.0) { + return false; + } + float sq = sqrt(disc); + t0 = -b - sq; + t1 = -b + sq; + return true; +} + +bool hitLocalCapsule(vec3 ro, vec3 rd, float h, float r, out float outEnter, out float outExit) { + float r2 = r * r; + if (h < 0.005) { + return hitSphere(ro, rd, r2, outEnter, outExit); + } + + outEnter = 1e9; + outExit = -1e9; + bool hit = false; + + float s0, s1; + if (hitSphere(ro - vec3(0.0, 0.0, -h), rd, r2, s0, s1)) { + outEnter = min(outEnter, s0); + outExit = max(outExit, s1); + hit = true; + } + if (hitSphere(ro - vec3(0.0, 0.0, h), rd, r2, s0, s1)) { + outEnter = min(outEnter, s0); + outExit = max(outExit, s1); + hit = true; + } + + // Infinite Z-axis cylinder x^2 + y^2 <= r^2 clipped to z in [-h, +h] + float a = dot(rd.xy, rd.xy); + float b = dot(ro.xy, rd.xy); + float c = dot(ro.xy, ro.xy) - r2; + float disc = b * b - a * c; + if (disc >= 0.0 && a > 1e-6) { + float sq = sqrt(disc); + float ct0 = (-b - sq) / a; + float ct1 = (-b + sq) / a; + if (abs(rd.z) > 1e-6) { + float tz0 = (-h - ro.z) / rd.z; + float tz1 = (h - ro.z) / rd.z; + ct0 = max(ct0, min(tz0, tz1)); + ct1 = min(ct1, max(tz0, tz1)); + if (ct1 > ct0) { + outEnter = min(outEnter, ct0); + outExit = max(outExit, ct1); + hit = true; + } + } else if (abs(ro.z) <= h) { + outEnter = min(outEnter, ct0); + outExit = max(outExit, ct1); + hit = true; + } + } + + return hit && (outExit > outEnter); +} + +void fragment() { + vec3 rd = normalize(v_fragCap - v_ro); + + float tEnter, tExit; + if (!hitLocalCapsule(v_ro, rd, v_halfLen, v_radius, tEnter, tExit)) { + discard; + } + tEnter = max(0.0, tEnter); + if (tExit <= tEnter) { + discard; + } + + float rawDepth = texture(depth_tex, SCREEN_UV).r; + float tScene = 1e6; + if (rawDepth > 0.0) { + vec4 viewPos = INV_PROJECTION_MATRIX * vec4(SCREEN_UV * 2.0 - 1.0, rawDepth, 1.0); + tScene = length(viewPos.xyz / viewPos.w); + } + + float tClipExit = min(tExit, tScene); + if (tClipExit <= tEnter) { + discard; + } + float depthFade = clamp((tScene - tEnter) / max(0.06, v_radius * 0.45), 0.0, 1.0); + + // Closest approach between clamped ray segment [tEnter, tClipExit] and capsule axis z in [-h, +h] + float xy2 = dot(rd.xy, rd.xy); + float tCyl = xy2 > 1e-6 ? -dot(v_ro.xy, rd.xy) / xy2 : 0.5 * (tEnter + tClipExit); + float tBest = clamp(tCyl, tEnter, tClipExit); + float s = v_ro.z + tBest * rd.z; + if (abs(s) > v_halfLen) { + s = clamp(s, -v_halfLen, v_halfLen); + tBest = clamp(-dot(v_ro - vec3(0.0, 0.0, s), rd), tEnter, tClipExit); + s = clamp(v_ro.z + tBest * rd.z, -v_halfLen, v_halfLen); + } + + vec3 pRay = v_ro + rd * tBest; + float dMin = length(pRay - vec3(0.0, 0.0, s)); + float rFrac = clamp(dMin / v_radius, 0.0, 1.0); + float chord = sqrt(max(0.0, 1.0 - rFrac * rFrac)); + + float coreSharpness = max(1.0, v_custom.x); + float coreFrac = clamp(v_custom.y, 0.08, 0.85); + float core = pow(clamp(1.0 - smoothstep(0.0, coreFrac, rFrac), 0.0, 1.0), coreSharpness); + float sheath = pow(chord, 1.75); + + // Basis.LookingAt puts -Z forward: start (tail) is at +v_halfLen, end (head) is at -v_halfLen + float tailT = v_halfLen > 0.01 ? clamp(0.5 - 0.5 * (s / v_halfLen), 0.0, 1.0) : 1.0; + float axial = mix(1.0, smoothstep(0.0, 0.78, tailT), v_custom.z * step(0.01, v_halfLen)); + float pulse = v_custom.w > 0.0 ? (0.88 + 0.12 * sin(s * 2.4 + TIME * v_custom.w)) : 1.0; + + vec3 hotCore = vec3(3.8, 3.8, 4.0); + vec3 rgb = mix(max(v_color.rgb, vec3(0.0)), hotCore, core * 0.82) * (0.45 + 0.55 * chord) * pulse; + float alpha = clamp(max(core, sheath * 0.85) * axial * depthFade * v_color.a, 0.0, 1.0); + if (alpha < 0.005) { + discard; + } + + ALBEDO = rgb; + ALPHA = alpha; +} diff --git a/client/volumetric_composite.glsl b/client/volumetric_composite.glsl new file mode 100644 index 0000000..8364dc3 --- /dev/null +++ b/client/volumetric_composite.glsl @@ -0,0 +1,92 @@ +#version 450 + +layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in; + +layout(set = 0, binding = 0, std140) uniform VolumetricFrame { + mat4 invProj; + vec4 camPosTime; + vec4 camRightAspect; + vec4 camUpTanHalfFov; + vec4 camFwdNearFar; + vec4 sunDirIntensity; + vec4 sunColorExt; + vec4 ambientColorFog; + vec4 viewportInfo; + uvec4 tileGridParams; + vec4 flowOriginVoxel; + vec4 flowInvExtentDt; + ivec4 flowDeltaImpulse; +} u_frame; + +layout(set = 0, binding = 1) uniform sampler2D u_depthTex; +layout(set = 0, binding = 2) uniform sampler2D u_halfVolTex; +layout(set = 0, binding = 3, rgba16f) uniform image2D u_colorImg; + +float linearizeReverseZ(float rawDepth) { + if (rawDepth <= 0.0) { + return u_frame.viewportInfo.z; + } + float zN = u_frame.ambientColorFog.w; + float zF = u_frame.viewportInfo.z; + return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN)); +} + +float halfQuadMaxDepth(ivec2 hpx, ivec2 fullRes) { + ivec2 basePx = hpx * 2; + float dMax = 0.0; + for (int dy = 0; dy < 2; dy++) { + for (int dx = 0; dx < 2; dx++) { + ivec2 sp = min(basePx + ivec2(dx, dy), fullRes - ivec2(1)); + dMax = max(dMax, linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r)); + } + } + return dMax; +} + +void main() { + ivec2 fullRes = ivec2(u_frame.viewportInfo.xy); + ivec2 px = ivec2(gl_GlobalInvocationID.xy); + if (any(greaterThanEqual(px, fullRes))) { + return; + } + + ivec2 halfRes = ivec2(u_frame.tileGridParams.xy); + float dFull = linearizeReverseZ(texelFetch(u_depthTex, px, 0).r); + + // 2x2 depth-aware bilateral upsample from half-res volumetric buffer + vec2 hCoord = (vec2(px) + vec2(0.5)) * 0.5 - vec2(0.5); + ivec2 h0 = clamp(ivec2(floor(hCoord)), ivec2(0), halfRes - ivec2(1)); + vec2 f = clamp(hCoord - vec2(h0), vec2(0.0), vec2(1.0)); + + float depthScale = max(0.45, 0.055 * dFull); + vec4 volSum = vec4(0.0); + float wSum = 0.0; + + ivec2 offsets[4] = ivec2[4](ivec2(0, 0), ivec2(1, 0), ivec2(0, 1), ivec2(1, 1)); + float spatialW[4] = float[4]( + (1.0 - f.x) * (1.0 - f.y), + f.x * (1.0 - f.y), + (1.0 - f.x) * f.y, + f.x * f.y + ); + + for (int i = 0; i < 4; i++) { + ivec2 hp = min(h0 + offsets[i], halfRes - ivec2(1)); + vec4 vSample = texelFetch(u_halfVolTex, hp, 0); + float dHalf = halfQuadMaxDepth(hp, fullRes); + float wDepth = exp(-abs(dFull - dHalf) / depthScale); + float w = max(1e-5, spatialW[i] * wDepth); + volSum += vSample * w; + wSum += w; + } + + vec4 vol = volSum / max(1e-5, wSum); + // Skip write when completely transparent + if (vol.a > 0.999 && dot(vol.rgb, vol.rgb) < 1e-7) { + return; + } + + vec4 scene = imageLoad(u_colorImg, px); + scene.rgb = scene.rgb * clamp(vol.a, 0.0, 1.0) + max(vol.rgb, vec3(0.0)); + imageStore(u_colorImg, px, scene); +} diff --git a/client/volumetric_raymarch.glsl b/client/volumetric_raymarch.glsl new file mode 100644 index 0000000..a713034 --- /dev/null +++ b/client/volumetric_raymarch.glsl @@ -0,0 +1,471 @@ +#version 450 + +layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in; + +#define MAX_TILE_EMITTERS 24u + +struct VolumetricEmitter { + vec4 posRadius; + vec4 endRadiusTemp; + vec4 params; + vec4 tintSoftness; +}; + +struct TileData { + uint count; + float minDepth; + float maxDepth; + uint _pad; + uint packedKeys[MAX_TILE_EMITTERS]; +}; + +layout(set = 0, binding = 0, std140) uniform VolumetricFrame { + mat4 invProj; + vec4 camPosTime; + vec4 camRightAspect; + vec4 camUpTanHalfFov; + vec4 camFwdNearFar; + vec4 sunDirIntensity; + vec4 sunColorExt; + vec4 ambientColorFog; + vec4 viewportInfo; + uvec4 tileGridParams; + vec4 flowOriginVoxel; + vec4 flowInvExtentDt; + ivec4 flowDeltaImpulse; +} u_frame; + +layout(set = 0, binding = 1, std430) readonly buffer EmitterBuffer { + VolumetricEmitter emitters[]; +} u_emitters; + +layout(set = 0, binding = 2, std430) readonly buffer TileBuffer { + TileData tiles[]; +} u_tiles; + +layout(set = 0, binding = 3) uniform sampler2D u_depthTex; +layout(set = 0, binding = 4) uniform sampler3D u_flowField; +layout(set = 0, binding = 5, rgba16f) uniform writeonly image2D u_halfVol; + +shared uint sTileCount; +shared VolumetricEmitter sEmitters[MAX_TILE_EMITTERS]; + +float linearizeReverseZ(float rawDepth) { + if (rawDepth <= 0.0) { + return u_frame.viewportInfo.z; + } + float zN = u_frame.ambientColorFog.w; + float zF = u_frame.viewportInfo.z; + return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN)); +} + +vec3 computeRayDirWorld(vec2 fullUv, out float invCosView) { + vec2 ndcXY = fullUv * 2.0 - 1.0; + float tanY = u_frame.camUpTanHalfFov.w; + float aspect = u_frame.camRightAspect.w; + vec3 viewVec = vec3(ndcXY.x * aspect * tanY, (1.0 - 2.0 * fullUv.y) * tanY, -1.0); + invCosView = length(viewVec); + return normalize(u_frame.camRightAspect.xyz * viewVec.x + + u_frame.camUpTanHalfFov.xyz * viewVec.y + + u_frame.camFwdNearFar.xyz); +} + +// --- Aetheria Volumetric.cginc math (ported cleanly with NaN-safe normalize) --- +float tri(float x) { + return abs(fract(x) - 0.5); +} + +vec3 tri3(vec3 p) { + return vec3( + tri(p.z + tri(p.y)), + tri(p.z + tri(p.x)), + tri(p.y + tri(p.x)) + ); +} + +vec3 safeNorm(vec3 v) { + float l2 = dot(v, v); + return l2 > 1e-8 ? v * inversesqrt(l2) : vec3(0.0, 1.0, 0.0); +} + +vec3 Tri3D(vec3 P, vec3 PGolden) { + vec3 t1 = safeNorm(tri3(P)); + vec3 t2 = safeNorm(tri3(PGolden)); + return cross(t1, t2); +} + +float triNoise3d(vec3 p, float flowTime) { + float z = 1.4; + float rz = 0.001; + vec3 bp = p; + for (int i = 0; i < 2; i++) { + vec3 dg = tri3(bp * 2.0); + p += dg + flowTime; + bp *= 1.8; + z *= 1.5; + p *= 1.2; + rz += tri(p.z + tri(p.x + tri(p.y))) / z; + bp += 0.14; + } + return rz; +} + +vec3 aetheriaFlow(vec3 pos, float flowScale, float scrollSpeed, float time) { + vec3 field = pos / max(0.5, flowScale); + float s1 = time * scrollSpeed; + float s2 = time * scrollSpeed * 1.61803398875; + vec3 fl = Tri3D(field - vec3(0.0, s1, 0.0), field * 1.61803398875 - vec3(0.0, s2, 0.0)); + fl.y *= 0.5; + return fl; +} + +bool intersectSphere(vec3 oc, vec3 rd, float r2, out float t0, out float t1) { + float b = dot(oc, rd); + float c = dot(oc, oc) - r2; + float disc = b * b - c; + if (disc <= 0.0) { + return false; + } + float sq = sqrt(disc); + t0 = -b - sq; + t1 = -b + sq; + return true; +} + +bool intersectCapsule(vec3 ro, vec3 rd, vec3 A, vec3 B, float R, out float outNear, out float outFar) { + float r2 = R * R; + vec3 ba = B - A; + float baba = dot(ba, ba); + if (baba < 0.0025) { + return intersectSphere(ro - A, rd, r2, outNear, outFar); + } + + outNear = 1e9; + outFar = -1e9; + bool hit = false; + + float s0, s1; + if (intersectSphere(ro - A, rd, r2, s0, s1)) { + outNear = min(outNear, s0); + outFar = max(outFar, s1); + hit = true; + } + if (intersectSphere(ro - B, rd, r2, s0, s1)) { + outNear = min(outNear, s0); + outFar = max(outFar, s1); + hit = true; + } + + vec3 oa = ro - A; + float bard = dot(ba, rd); + float baoa = dot(ba, oa); + float rdoa = dot(rd, oa); + float oaoa = dot(oa, oa); + float a = baba - bard * bard; + float b = baba * rdoa - baoa * bard; + float c = baba * oaoa - baoa * baoa - r2 * baba; + float h = b * b - a * c; + if (h >= 0.0 && a > 1e-6) { + float sq = sqrt(h); + float ct0 = (-b - sq) / a; + float ct1 = (-b + sq) / a; + if (abs(bard) > 1e-6) { + float tEnd0 = -baoa / bard; + float tEnd1 = (baba - baoa) / bard; + float tCapMin = min(tEnd0, tEnd1); + float tCapMax = max(tEnd0, tEnd1); + ct0 = max(ct0, tCapMin); + ct1 = min(ct1, tCapMax); + if (ct1 > ct0) { + outNear = min(outNear, ct0); + outFar = max(outFar, ct1); + hit = true; + } + } else if (baoa >= 0.0 && baoa <= baba) { + outNear = min(outNear, ct0); + outFar = max(outFar, ct1); + hit = true; + } + } + return hit && (outFar > outNear); +} + +vec3 blackbodyRamp(float temp) { + // Tuned for AgX (TonemapAgxWhite=6.0) + GlowHdrThreshold=1.0: preserves rich orange-amber fire without clipping to white + vec3 c0 = vec3(0.40, 0.03, 0.002); + vec3 c1 = vec3(1.45, 0.20, 0.012); + vec3 c2 = vec3(2.85, 0.68, 0.055); + vec3 c3 = vec3(4.20, 1.65, 0.24); + vec3 c4 = vec3(5.60, 3.10, 0.85); + if (temp < 0.35) return mix(c0, c1, smoothstep(0.12, 0.35, temp)); + if (temp < 0.70) return mix(c1, c2, (temp - 0.35) / 0.35); + if (temp < 1.05) return mix(c2, c3, (temp - 0.70) / 0.35); + return mix(c3, c4, clamp((temp - 1.05) / 0.45, 0.0, 1.0)); +} + +float hgPhase(float cosTheta, float g) { + float g2 = g * g; + float denom = max(0.05, 1.0 + g2 - 2.0 * g * cosTheta); + return (1.0 - g2) / (12.5663706 * pow(denom, 1.5)); +} + +void main() { + uint tid = gl_LocalInvocationIndex; + ivec2 tileCoord = ivec2(gl_WorkGroupID.xy); + uint tilesX = u_frame.tileGridParams.z; + uint tileIdx = uint(tileCoord.y) * tilesX + uint(tileCoord.x); + + if (tid == 0u) { + sTileCount = min(u_tiles.tiles[tileIdx].count, MAX_TILE_EMITTERS); + } + memoryBarrierShared(); + barrier(); + + ivec2 halfRes = ivec2(u_frame.tileGridParams.xy); + ivec2 px = ivec2(gl_GlobalInvocationID.xy); + + // Empty-tile fast exit (uniform across workgroup) + if (sTileCount == 0u) { + if (all(lessThan(px, halfRes))) { + imageStore(u_halfVol, px, vec4(0.0, 0.0, 0.0, 1.0)); + } + return; + } + + if (tid < sTileCount) { + uint eIdx = u_tiles.tiles[tileIdx].packedKeys[tid] & 0x7Fu; + sEmitters[tid] = u_emitters.emitters[eIdx]; + } + memoryBarrierShared(); + barrier(); + + if (any(greaterThanEqual(px, halfRes))) { + return; + } + + ivec2 fullRes = ivec2(u_frame.viewportInfo.xy); + ivec2 basePx = px * 2; + float dMax = 0.0; + for (int dy = 0; dy < 2; dy++) { + for (int dx = 0; dx < 2; dx++) { + ivec2 sp = min(basePx + ivec2(dx, dy), fullRes - ivec2(1)); + float linD = linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r); + dMax = max(dMax, linD); + } + } + + vec2 fullUv = (vec2(px) * 2.0 + vec2(1.0)) / vec2(fullRes); + float invCosView; + vec3 rd = computeRayDirWorld(fullUv, invCosView); + vec3 ro = u_frame.camPosTime.xyz; + float tSceneMax = dMax * invCosView; + + // Exact per-pixel capsule bounds & hit bitmask + uint pBounds[MAX_TILE_EMITTERS]; + uint pendingMask = 0u; + float tEndMax = 0.0; + + for (uint k = 0u; k < sTileCount; k++) { + VolumetricEmitter em = sEmitters[k]; + float rBound = max(em.posRadius.w, em.params.y) * 1.85; + float t0, t1; + if (intersectCapsule(ro, rd, em.posRadius.xyz, em.endRadiusTemp.xyz, rBound, t0, t1)) { + t0 = max(0.0, t0); + t1 = min(tSceneMax, t1); + if (t1 > t0) { + pendingMask |= (1u << k); + // Conservative 0.5m pad before fp16 pack so distant emitters never clip + pBounds[k] = packHalf2x16(vec2(max(0.0, t0 - 0.5), t1 + 0.5)); + tEndMax = max(tEndMax, t1); + } + } + } + + if (pendingMask == 0u) { + imageStore(u_halfVol, px, vec4(0.0, 0.0, 0.0, 1.0)); + return; + } + + // Interleaved Gradient Noise temporal jitter + float frameF = float(u_frame.tileGridParams.w & 63u); + float ign = fract(52.9829189 * fract(dot(vec2(px) + 5.588238 * frameF, vec2(0.06711056, 0.00583715)))); + + float elapsed = u_frame.camPosTime.w; + vec3 sunDir = u_frame.sunDirIntensity.xyz; + float phase = hgPhase(dot(rd, sunDir), 0.56); + vec3 sunRad = u_frame.sunColorExt.rgb * u_frame.sunDirIntensity.w; + vec3 ambRad = u_frame.ambientColorFog.rgb; + float extScale = u_frame.sunColorExt.w; + + vec3 L = vec3(0.0); + float T = 1.0; + uint activeMask = 0u; + float t = 0.0; + int steps = 0; + const int MaxSteps = 22; + + while ((pendingMask != 0u || activeMask != 0u) && t < tEndMax && T >= 0.01 && steps < MaxSteps) { + // Empty-space jump whenever no emitter is currently active + if (activeMask == 0u) { + float minNext = tEndMax; + uint m = pendingMask; + while (m != 0u) { + int bit = findLSB(m); + m &= m - 1u; + float nT = unpackHalf2x16(pBounds[bit]).x; + minNext = min(minNext, nT); + } + float dsLeap = max(0.36, 0.26 + 0.011 * minNext); + t = max(t, minNext) + ign * dsLeap; + if (t >= tEndMax) { + break; + } + } + + float ds = max(0.36, 0.26 + 0.011 * t); + + // Admit emitters whose entry bound has arrived + uint pm = pendingMask; + while (pm != 0u) { + int bit = findLSB(pm); + pm &= pm - 1u; + vec2 b = unpackHalf2x16(pBounds[bit]); + if (b.x <= t + 0.5 * ds) { + pendingMask &= ~(1u << uint(bit)); + if (b.y >= t - 0.5 * ds) { + activeMask |= (1u << uint(bit)); + } + } + } + + // Retire emitters already exited + uint amCheck = activeMask; + while (amCheck != 0u) { + int bit = findLSB(amCheck); + amCheck &= amCheck - 1u; + vec2 b = unpackHalf2x16(pBounds[bit]); + if (t - 0.5 * ds > b.y) { + activeMask &= ~(1u << uint(bit)); + } + } + + if (activeMask == 0u) { + continue; + } + + vec3 worldPos = ro + rd * t; + vec3 flowUv = (worldPos - u_frame.flowOriginVoxel.xyz) * u_frame.flowInvExtentDt.xyz; + vec4 flowSample = (all(greaterThanEqual(flowUv, vec3(0.0))) && all(lessThanEqual(flowUv, vec3(1.0)))) + ? textureLod(u_flowField, flowUv, 0.0) + : vec4(0.0); + float shock = clamp(flowSample.a, 0.0, 1.5); + + float rhoSum = 0.0; + vec3 albedoSum = vec3(0.0); + vec3 emissionSum = vec3(0.0); + + uint am = activeMask; + while (am != 0u) { + int k = findLSB(am); + am &= am - 1u; + VolumetricEmitter em = sEmitters[k]; + + uint flags = floatBitsToUint(em.params.w); + uint emType = flags & 0xFu; + float ageNorm = float((flags >> 4u) & 0xFFu) / 255.0; + float seed = float((flags >> 12u) & 0xFFu) * 0.371; + + float rA = em.posRadius.w; + float rB = em.params.y; + float radAvg = max(0.35, 0.5 * (rA + rB)); + + // Bound flow + curl displacement strictly inside rBound (1.85 * rad) so zero spherical/tile clipping occurs + vec3 flowOffset = flowSample.rgb * (0.16 + 0.12 * ageNorm); + float fOffLen = length(flowOffset); + if (fOffLen > 0.42 * radAvg) { + flowOffset *= (0.42 * radAvg) / fOffLen; + } + vec3 advectedPos = worldPos - flowOffset; + + vec3 curl = aetheriaFlow(advectedPos + vec3(seed * 13.7), max(1.8, radAvg * 1.45), abs(em.params.z), elapsed); + vec3 evalPos = advectedPos + curl * (0.34 * radAvg); + + vec3 A = em.posRadius.xyz; + vec3 B = em.endRadiusTemp.xyz; + vec3 ab = B - A; + float ab2 = dot(ab, ab); + float segT = ab2 > 1e-5 ? clamp(dot(evalPos - A, ab) / ab2, 0.0, 1.0) : 0.0; + vec3 closest = A + ab * segT; + float rad = mix(rA, rB, segT); + float distNorm = length(evalPos - closest) / max(0.15, rad); + + if (distNorm < 1.05) { + float softness = clamp(em.tintSoftness.a, 0.18, 0.75); + float baseFall = 1.0 - smoothstep(1.0 - softness, 1.04, distNorm); + // Sample triNoise3d at Nyquist-safe wavelength (>= 2.0m billows) to eliminate stipple aliasing + float billow = clamp(triNoise3d(evalPos / max(1.55, rad * 1.15) + vec3(seed), elapsed * 0.30) * 1.68, 0.0, 1.0); + float eroded = smoothstep(0.08 + 0.34 * distNorm, 0.82, billow * 0.65 + baseFall * 0.72); + float rho_k = baseFall * eroded * em.params.x; + + // Shock-front cavity carving + adiabatic compression rim + rho_k *= clamp(1.0 - shock * 0.45, 0.30, 1.0) * (1.0 + 0.40 * smoothstep(0.2, 0.9, shock)); + + if (rho_k > 1e-4) { + rhoSum += rho_k; + albedoSum += em.tintSoftness.rgb * rho_k; + + float localTemp = max(em.endRadiusTemp.w * (1.0 - 0.62 * distNorm) * (0.62 + 0.58 * billow), shock * 0.24); + if (localTemp > 0.16) { + vec3 bb = blackbodyRamp(localTemp); + if (emType == 3u || emType == 4u) { + // Plasma / thermal pool accent-tinted HDR emission + bb = mix(bb, em.tintSoftness.rgb * (1.35 + 1.85 * localTemp), 0.80); + } + emissionSum += bb * rho_k * (0.65 + 0.55 * localTemp); + } + } + } + } + + if (rhoSum > 0.002) { + // 2 tile-local directional sun shadow taps along sunDir (closest 8 tile emitters) + float tauSun = 0.0; + uint shadowCount = min(sTileCount, 8u); + for (int st = 0; st < 2; st++) { + float sDist = st == 0 ? 1.2 : 3.4; + vec3 sPos = worldPos + sunDir * sDist; + for (uint j = 0u; j < shadowCount; j++) { + VolumetricEmitter se = sEmitters[j]; + vec3 sA = se.posRadius.xyz; + vec3 sB = se.endRadiusTemp.xyz; + vec3 sAB = sB - sA; + float sAB2 = dot(sAB, sAB); + float sSegT = sAB2 > 1e-5 ? clamp(dot(sPos - sA, sAB) / sAB2, 0.0, 1.0) : 0.0; + float sRad = mix(se.posRadius.w, se.params.y, sSegT); + float dN = length(sPos - (sA + sAB * sSegT)) / max(0.2, sRad); + if (dN < 1.05) { + tauSun += (1.0 - smoothstep(0.25, 1.05, dN)) * se.params.x * 0.85; + } + } + } + float sunTrans = exp(-tauSun * extScale * 2.2); + + vec3 albedo = albedoSum / rhoSum; + vec3 scatter = albedo * (sunRad * sunTrans * phase * 1.25 + ambRad * 0.42); + float sigmaT = rhoSum * extScale; + float stepTrans = exp(-sigmaT * ds); + vec3 stepLight = (scatter * sigmaT + emissionSum) * (sigmaT > 1e-4 ? (1.0 - stepTrans) / sigmaT : ds); + L += T * stepLight; + T *= stepTrans; + if (T < 0.01) { + T = 0.0; + break; + } + } + + t += ds; + steps++; + } + + imageStore(u_halfVol, px, vec4(min(L, vec3(24.0)), clamp(T, 0.0, 1.0))); +} diff --git a/client/volumetric_tile_cull.glsl b/client/volumetric_tile_cull.glsl new file mode 100644 index 0000000..240af8b --- /dev/null +++ b/client/volumetric_tile_cull.glsl @@ -0,0 +1,202 @@ +#version 450 + +layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in; + +#define MAX_TILE_EMITTERS 24u + +struct VolumetricEmitter { + vec4 posRadius; + vec4 endRadiusTemp; + vec4 params; + vec4 tintSoftness; +}; + +struct TileData { + uint count; + float minDepth; + float maxDepth; + uint _pad; + uint packedKeys[MAX_TILE_EMITTERS]; +}; + +layout(set = 0, binding = 0, std140) uniform VolumetricFrame { + mat4 invProj; + vec4 camPosTime; + vec4 camRightAspect; + vec4 camUpTanHalfFov; + vec4 camFwdNearFar; + vec4 sunDirIntensity; + vec4 sunColorExt; + vec4 ambientColorFog; + vec4 viewportInfo; + uvec4 tileGridParams; + vec4 flowOriginVoxel; + vec4 flowInvExtentDt; + ivec4 flowDeltaImpulse; +} u_frame; + +layout(set = 0, binding = 1, std430) readonly buffer EmitterBuffer { + VolumetricEmitter emitters[]; +} u_emitters; + +layout(set = 0, binding = 2, std430) writeonly buffer TileBuffer { + TileData tiles[]; +} u_tiles; + +layout(set = 0, binding = 3) uniform sampler2D u_depthTex; + +shared uint sMinDepthBits; +shared uint sMaxDepthBits; +shared uint sTileCount; +shared uint sKeys[32]; + +float linearizeReverseZ(float rawDepth) { + if (rawDepth <= 0.0) { + return u_frame.viewportInfo.z; + } + float zN = u_frame.ambientColorFog.w; + float zF = u_frame.viewportInfo.z; + return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN)); +} + +void main() { + uint tid = gl_LocalInvocationIndex; + ivec2 tileCoord = ivec2(gl_WorkGroupID.xy); + uint tilesX = u_frame.tileGridParams.z; + uint tileIdx = uint(tileCoord.y) * tilesX + uint(tileCoord.x); + + if (tid == 0u) { + sMinDepthBits = 0x7F7FFFFFu; + sMaxDepthBits = 0u; + sTileCount = 0u; + } + if (tid < 32u) { + sKeys[tid] = 0xFFFFFFFFu; + } + memoryBarrierShared(); + barrier(); + + ivec2 halfRes = ivec2(u_frame.tileGridParams.xy); + ivec2 fullRes = ivec2(u_frame.viewportInfo.xy); + ivec2 hx = ivec2(gl_GlobalInvocationID.xy); + + float dMin = u_frame.viewportInfo.z; + float dMax = 0.0; + if (all(lessThan(hx, halfRes))) { + ivec2 basePx = hx * 2; + for (int dy = 0; dy < 2; dy++) { + for (int dx = 0; dx < 2; dx++) { + ivec2 sp = min(basePx + ivec2(dx, dy), fullRes - ivec2(1)); + float rawD = texelFetch(u_depthTex, sp, 0).r; + float linD = linearizeReverseZ(rawD); + dMin = min(dMin, linD); + dMax = max(dMax, linD); + } + } + atomicMin(sMinDepthBits, floatBitsToUint(max(0.0, dMin))); + atomicMax(sMaxDepthBits, floatBitsToUint(max(0.0, dMax))); + } + memoryBarrierShared(); + barrier(); + + float tileMinDepth = uintBitsToFloat(sMinDepthBits); + float tileMaxDepth = uintBitsToFloat(sMaxDepthBits); + if (tileMaxDepth <= 0.0) { + tileMaxDepth = u_frame.viewportInfo.z; + } + + // Tile frustum bounds in view space (view looks down -Z, +X right, +Y up) + vec2 tileMinPx = vec2(tileCoord * 16) * 2.0; + vec2 tileMaxPx = min(vec2((tileCoord + ivec2(1)) * 16) * 2.0, vec2(fullRes)); + vec2 uv0 = tileMinPx / vec2(fullRes); + vec2 uv1 = tileMaxPx / vec2(fullRes); + + float tanY = u_frame.camUpTanHalfFov.w; + float aspect = u_frame.camRightAspect.w; + float x0 = (uv0.x * 2.0 - 1.0) * aspect * tanY; + float x1 = (uv1.x * 2.0 - 1.0) * aspect * tanY; + float yTop = (1.0 - 2.0 * uv0.y) * tanY; + float yBot = (1.0 - 2.0 * uv1.y) * tanY; + + vec3 nLeft = normalize(vec3(-1.0, 0.0, -x0)); + vec3 nRight = normalize(vec3(1.0, 0.0, x1)); + vec3 nTop = normalize(vec3(0.0, 1.0, yTop)); + vec3 nBot = normalize(vec3(0.0, -1.0, -yBot)); + + uint emitterCount = min(uint(max(0.0, u_frame.viewportInfo.w + 0.5)), 128u); + if (tid < emitterCount) { + VolumetricEmitter em = u_emitters.emitters[tid]; + float rA = em.posRadius.w; + float rB = em.params.y; + float rBound = max(rA, rB) * 1.85; + + vec3 wA = em.posRadius.xyz - u_frame.camPosTime.xyz; + vec3 wB = em.endRadiusTemp.xyz - u_frame.camPosTime.xyz; + + vec3 camR = u_frame.camRightAspect.xyz; + vec3 camU = u_frame.camUpTanHalfFov.xyz; + vec3 camF = u_frame.camFwdNearFar.xyz; + + // View-space coordinates: +X right, +Y up, -Z forward + vec3 vA = vec3(dot(wA, camR), dot(wA, camU), -dot(wA, camF)); + vec3 vB = vec3(dot(wB, camR), dot(wB, camU), -dot(wB, camF)); + + float dMinEm = min(-vA.z - rBound, -vB.z - rBound); + float dMaxEm = max(-vA.z + rBound, -vB.z + rBound); + + // Reject only behind camera or completely behind tileMaxDepth (NEVER clip against tileMinDepth!) + bool visible = (dMaxEm > 0.0) && (dMinEm < tileMaxDepth); + if (visible) { + if (dot(vA, nLeft) > rBound && dot(vB, nLeft) > rBound) visible = false; + else if (dot(vA, nRight) > rBound && dot(vB, nRight) > rBound) visible = false; + else if (dot(vA, nTop) > rBound && dot(vB, nTop) > rBound) visible = false; + else if (dot(vA, nBot) > rBound && dot(vB, nBot) > rBound) visible = false; + } + + if (visible) { + vec3 ab = vB - vA; + float ab2 = dot(ab, ab); + float segT = ab2 > 1e-5 ? clamp(dot(-vA, ab) / ab2, 0.0, 1.0) : 0.0; + vec3 closest = vA + ab * segT; + float tMinConservative = max(0.0, length(closest) - rBound); + uint packedKey = (floatBitsToUint(tMinConservative) & 0xFFFFFF80u) | (tid & 0x7Fu); + uint slot = atomicAdd(sTileCount, 1u); + if (slot < 32u) { + sKeys[slot] = packedKey; + } + } + } + memoryBarrierShared(); + barrier(); + + // 1-warp 32-element Bitonic sort (barriers kept in uniform workgroup control flow) + for (uint k = 2u; k <= 32u; k <<= 1u) { + for (uint j = k >> 1u; j > 0u; j >>= 1u) { + if (tid < 32u) { + uint ixj = tid ^ j; + if (ixj > tid) { + bool ascending = ((tid & k) == 0u); + uint a = sKeys[tid]; + uint b = sKeys[ixj]; + if ((a > b) == ascending) { + sKeys[tid] = b; + sKeys[ixj] = a; + } + } + } + memoryBarrierShared(); + barrier(); + } + } + + if (tid == 0u) { + uint outCount = min(sTileCount, MAX_TILE_EMITTERS); + u_tiles.tiles[tileIdx].count = outCount; + u_tiles.tiles[tileIdx].minDepth = tileMinDepth; + u_tiles.tiles[tileIdx].maxDepth = tileMaxDepth; + u_tiles.tiles[tileIdx]._pad = 0u; + } + if (tid < MAX_TILE_EMITTERS) { + u_tiles.tiles[tileIdx].packedKeys[tid] = sKeys[tid]; + } +}