diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs index fe524e3..7f71bbc 100644 --- a/client/ArenaRenderer.cs +++ b/client/ArenaRenderer.cs @@ -76,6 +76,7 @@ public partial class ArenaRenderer : Node3D private MultiMeshPartPool _partPool = null!; private PomDecalPool _pomDecals = null!; private DebrisSystem _debris = null!; + private ParticlePool _particles = null!; private MeshInstance3D _safeRingMesh = null!; private ImmediateMesh _safeRingImm = null!; @@ -85,7 +86,7 @@ public partial class ArenaRenderer : Node3D private MultiMesh _dropPillarMm = null!; private MultiMeshInstance3D _dropPillarMmi = null!; - // Pooled weapon VFX MultiMeshes + // Pooled weapon VFX MultiMeshes (beams/tracers, explosive detonation cores, shockwave rings) private ShaderMaterial _vfxMat = null!; private MultiMesh _vfxBeamMm = null!; private MultiMeshInstance3D _vfxBeamMmi = null!; @@ -93,10 +94,14 @@ public partial class ArenaRenderer : Node3D private MultiMeshInstance3D _vfxSphereMmi = null!; private MultiMesh _vfxRingMm = null!; private MultiMeshInstance3D _vfxRingMmi = null!; - private readonly List _transientVfx = new(256); - private long _lastVfxHitId; - private int _lastSpawnedTracerId; - private uint _vfxRng = 0x51F15A3Du; + private readonly List _transientVfx = new(128); + private int _activeBeamCount; + + // Continuous emitter rate limiters (keyed by (IsContender, EntityId)) + private readonly Dictionary<(bool IsContender, int Id), float> _tireDustNextTime = new(); + private readonly Dictionary<(bool IsContender, int Id), float> _thermalVentNextTime = new(); + private readonly Dictionary<(bool IsContender, int Id), float> _damageSmokeNextTime = new(); + private float _vfxClock; private readonly Dictionary _contenderVisuals = new(); private readonly Dictionary _spectatorVisuals = new(); @@ -111,6 +116,7 @@ public partial class ArenaRenderer : Node3D public VehicleAssetCache AssetCache => _assetCache; public DebrisSystem Debris => _debris; + public ParticlePool Particles => _particles; internal MultiMeshPartPool PartPool => _partPool; internal PomDecalPool PomDecals => _pomDecals; @@ -126,7 +132,6 @@ public partial class ArenaRenderer : Node3D : null; internal int ActiveDropVisualCount => _dropVisuals.Count; - internal int LastSpawnedTracerId => _lastSpawnedTracerId; internal int TransientVfxCount => _transientVfx.Count; internal bool TryGetChassisDropVisual(int dropId, out VehicleVisualInstance? visual, out float baseY) @@ -151,11 +156,13 @@ public partial class ArenaRenderer : Node3D _partPool = new MultiMeshPartPool { Name = "PartPool" }; _pomDecals = new PomDecalPool { Name = "PomDecals" }; _debris = new DebrisSystem { Name = "Debris" }; + _particles = new ParticlePool { Name = "ParticlePool" }; AddChild(_staticGroup); AddChild(_actorsGroup); AddChild(_partPool); AddChild(_pomDecals); AddChild(_debris); + AddChild(_particles); _coverMat = new StandardMaterial3D { AlbedoColor = CoverRust, Roughness = 0.88f, Metallic = 0.25f }; _bermMat = new StandardMaterial3D { AlbedoColor = BermDark, Roughness = 0.94f, Metallic = 0.1f }; @@ -341,8 +348,37 @@ public partial class ArenaRenderer : Node3D _debris.SubmitToPool(_partPool); _partPool.EndFrame(); - _pomDecals.Sync(session, dt, ResolveEntityVisual); - SyncWeaponVfx(state, dt); + SyncTracerBeams(state); + } + + public void ConsumeEvents( + IClientArenaSession session, + IReadOnlyList events, + IReadOnlyList footsteps, + float dt, + Func sampleGroundTint) + { + Camera3D? cam = GetViewport()?.GetCamera3D(); + bool hasCam = cam is not null && cam.IsInsideTree(); + Vector3 camPos = hasCam ? cam!.GlobalPosition : Vector3.Zero; + + float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; + _vfxClock += stepDt; + + var state = session.ViewState; + _pomDecals.ConsumeEvents(session, events, stepDt, ResolveEntityVisual); + _particles.ConsumeEvents(events, state, camPos, hasCam, sampleGroundTint); + + for (int i = 0; i < footsteps.Count; i++) + { + FootstepPulse pulse = footsteps[i]; + Color gTint = sampleGroundTint(pulse.WorldPos.X, pulse.WorldPos.Z); + _particles.EmitFootstepDust(in pulse, gTint, camPos, hasCam); + } + + EmitContinuousActorParticles(session, hasCam, camPos, sampleGroundTint); + UpdateExplosiveRingsAndCores(events, stepDt); + _particles.AdvanceAndCommit(stepDt); } private VehicleVisualInstance? ResolveEntityVisual(bool isContender, int id) => @@ -431,9 +467,28 @@ public partial class ArenaRenderer : Node3D _partPool.ClearAll(); _pomDecals.ClearAll(); _debris.ClearAll(); + _particles.ClearAll(); _transientVfx.Clear(); - _lastVfxHitId = 0; - _lastSpawnedTracerId = 0; + _tireDustNextTime.Clear(); + _thermalVentNextTime.Clear(); + _damageSmokeNextTime.Clear(); + _vfxClock = 0f; + _activeBeamCount = 0; + if (_vfxBeamMm is not null) + { + _vfxBeamMm.VisibleInstanceCount = 0; + _vfxBeamMmi.Visible = false; + } + if (_vfxSphereMm is not null) + { + _vfxSphereMm.VisibleInstanceCount = 0; + _vfxSphereMmi.Visible = false; + } + if (_vfxRingMm is not null) + { + _vfxRingMm.VisibleInstanceCount = 0; + _vfxRingMmi.Visible = false; + } _contenderVisuals.Clear(); _spectatorVisuals.Clear(); foreach (var kv in _dropVisuals) @@ -950,52 +1005,13 @@ public partial class ArenaRenderer : Node3D _dropPillarMmi.Visible = pillarCount > 0; } - private void SyncWeaponVfx(MatchState state, float dt) + private void SyncTracerBeams(MatchState state) { - float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; - - // 1. Advance existing transient bursts (sparks, muzzle flashes, flak puffs, detonations, shockwaves) - for (int i = _transientVfx.Count - 1; i >= 0; i--) - { - TransientVfx v = _transientVfx[i]; - v.Age += stepDt; - if (v.Age >= v.Lifetime) - { - _transientVfx.RemoveAt(i); - continue; - } - v.Position += v.Velocity * stepDt; - _transientVfx[i] = v; - } - - // 2. Spawn impact VFX once per HitFeedbackEvent - var hits = state.HitEvents; - for (int i = 0; i < hits.Count; i++) - { - var ev = hits[i]; - if (ev.EventId <= _lastVfxHitId) - { - continue; - } - _lastVfxHitId = ev.EventId; - SpawnHitVfx(in ev); - } - - // 3. Emit pooled beams/tracers + new-shot muzzle/smoke puffs from active TracerEvents int beamIdx = 0; - int sphereIdx = 0; - int ringIdx = 0; - var tracers = state.Tracers; for (int i = 0; i < tracers.Count; i++) { var t = tracers[i]; - bool isNewShot = t.Id > _lastSpawnedTracerId; - if (isNewShot) - { - _lastSpawnedTracerId = t.Id; - } - Vector3 start = new(t.StartX, t.StartY, t.StartZ); Vector3 end = new(t.EndX, t.EndY, t.EndZ); Vector3 delta = end - start; @@ -1019,22 +1035,13 @@ public partial class ArenaRenderer : Node3D ? 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); - if (isNewShot) - { - EmitMuzzleFlash(start, 0.32f, new Color(2.8f, 2.0f, 0.7f, 0.95f)); - } break; } case WeaponVisualClass.Autocannon: { - // Thick dual-tone amber-orange heavy bolt (outer jacket + bright core) 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)); - if (isNewShot) - { - EmitMuzzleFlash(start, 0.68f, new Color(3.2f, 1.65f, 0.35f, 0.98f)); - } break; } @@ -1043,29 +1050,6 @@ public partial class ArenaRenderer : Node3D 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)); - if (isNewShot) - { - EmitMuzzleFlash(start, isRecoilless ? 1.15f : 0.58f, new Color(3.4f, 1.55f, 0.35f, 0.98f)); - int puffs = isRecoilless ? 4 : 2; - for (int p = 1; p <= puffs; p++) - { - float frac = p / (float)(puffs + 1); - Vector3 smokePos = start.Lerp(end, frac); - AddTransient(new TransientVfx - { - Shape = VfxShape.Sphere, - Position = smokePos, - Velocity = new Vector3(0f, 1.4f, 0f), - BaseRotation = Basis.Identity, - StartScale = Vector3.One * (isRecoilless ? 0.45f : 0.28f), - EndScale = Vector3.One * (isRecoilless ? 1.55f : 0.85f), - ColorStart = new Color(0.62f, 0.56f, 0.48f, 0.65f), - ColorEnd = new Color(0.45f, 0.40f, 0.36f, 0.0f), - Age = 0f, - Lifetime = isRecoilless ? 0.48f : 0.32f - }); - } - } break; } @@ -1082,16 +1066,85 @@ public partial class ArenaRenderer : Node3D : 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); - if (isNewShot) - { - EmitMuzzleFlash(start, isLance ? 0.85f : 0.52f, outerCol with { A = 0.95f }); - } break; } } } - // 4. Write active transient VFX into MultiMesh buffers + _activeBeamCount = beamIdx; + _vfxBeamMm.VisibleInstanceCount = beamIdx; + _vfxBeamMmi.Visible = beamIdx > 0; + } + + private void UpdateExplosiveRingsAndCores(IReadOnlyList events, float stepDt) + { + for (int i = _transientVfx.Count - 1; i >= 0; i--) + { + TransientVfx v = _transientVfx[i]; + v.Age += stepDt; + if (v.Age >= v.Lifetime) + { + _transientVfx.RemoveAt(i); + continue; + } + v.Position += v.Velocity * stepDt; + _transientVfx[i] = v; + } + + for (int i = 0; i < events.Count; i++) + { + if (events[i] is not HitImpactEvent ev) + { + continue; + } + if ((WeaponVisualClass)ev.WeaponClass != WeaponVisualClass.Explosive || ev.IsAirburst) + { + continue; + } + + Vector3 pos = new(ev.HitX, ev.HitY, ev.HitZ); + Vector3 normal = new(ev.NormalX, ev.NormalY, ev.NormalZ); + if (normal.LengthSquared() < 1e-4f) normal = Vector3.Up; + normal = normal.Normalized(); + + bool isRecoilless = string.Equals(ev.WeaponId, "recoilless", StringComparison.Ordinal); + float detSize = isRecoilless ? 3.2f : 1.7f; + float ringSize = isRecoilless ? 6.2f : 2.9f; + 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 = new Color(3.6f, 2.0f, 0.55f, 0.92f), + ColorEnd = new Color(0.85f, 0.28f, 0.08f, 0.0f), + Age = 0f, + Lifetime = isRecoilless ? 0.28f : 0.20f + }); + + Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 right = upRef.Cross(normal).Normalized(); + Vector3 fwd = normal.Cross(right).Normalized(); + Basis ringBasis = new(right, normal, fwd); + AddTransient(new TransientVfx + { + Shape = VfxShape.Ring, + Position = pos + normal * 0.18f, + Velocity = Vector3.Zero, + BaseRotation = ringBasis, + StartScale = new Vector3(0.7f, 1.0f, 0.7f), + EndScale = new Vector3(ringSize, 0.4f, ringSize), + ColorStart = new Color(3.2f, 1.65f, 0.45f, 0.92f), + ColorEnd = new Color(1.4f, 0.55f, 0.20f, 0.0f), + Age = 0f, + Lifetime = isRecoilless ? 0.32f : 0.22f + }); + } + + int sphereIdx = 0; + int ringIdx = 0; for (int i = 0; i < _transientVfx.Count; i++) { TransientVfx v = _transientVfx[i]; @@ -1100,13 +1153,7 @@ public partial class ArenaRenderer : Node3D Color col = v.ColorStart.Lerp(v.ColorEnd, frac); Transform3D xf = new(v.BaseRotation * Basis.FromScale(sc), v.Position); - if (v.Shape == VfxShape.Beam && beamIdx < MaxVfxBeams) - { - _vfxBeamMm.SetInstanceTransform(beamIdx, xf); - _vfxBeamMm.SetInstanceCustomData(beamIdx, col); - beamIdx++; - } - else if (v.Shape == VfxShape.Sphere && sphereIdx < MaxVfxSpheres) + if (v.Shape == VfxShape.Sphere && sphereIdx < MaxVfxSpheres) { _vfxSphereMm.SetInstanceTransform(sphereIdx, xf); _vfxSphereMm.SetInstanceCustomData(sphereIdx, col); @@ -1120,161 +1167,148 @@ public partial class ArenaRenderer : Node3D } } - _vfxBeamMm.VisibleInstanceCount = beamIdx; - _vfxBeamMmi.Visible = beamIdx > 0; _vfxSphereMm.VisibleInstanceCount = sphereIdx; _vfxSphereMmi.Visible = sphereIdx > 0; _vfxRingMm.VisibleInstanceCount = ringIdx; _vfxRingMmi.Visible = ringIdx > 0; } - private void SpawnHitVfx(in HitFeedbackEvent ev) + private void EmitContinuousActorParticles( + IClientArenaSession session, + bool hasCam, + Vector3 camPos, + Func sampleGroundTint) { - Vector3 pos = new(ev.HitX, ev.HitY, ev.HitZ); - Vector3 normal = new(ev.NormalX, ev.NormalY, ev.NormalZ); - if (normal.LengthSquared() < 1e-4f) normal = Vector3.Up; - normal = normal.Normalized(); - - if (ev.IsAirburst || (ev.WeaponClass == WeaponVisualClass.KineticLight && string.Equals(ev.WeaponId, "pd_flak", StringComparison.Ordinal))) + var state = session.ViewState; + var contenders = state.Contenders; + for (int i = 0; i < contenders.Count; i++) { - // Crisp dark-orange flak airburst puff + ember sparks - AddTransient(new TransientVfx + var c = contenders[i]; + if (!c.Alive || !session.IsContenderVisible(c.Id)) { - Shape = VfxShape.Sphere, - Position = pos, - Velocity = Vector3.Zero, - BaseRotation = Basis.Identity, - StartScale = Vector3.One * 0.4f, - EndScale = Vector3.One * 2.3f, - ColorStart = new Color(2.4f, 0.72f, 0.14f, 0.92f), - ColorEnd = new Color(0.28f, 0.14f, 0.08f, 0.0f), - Age = 0f, - Lifetime = 0.28f - }); - SpawnSparkBurst(pos, normal, 4, new Color(3.0f, 1.5f, 0.35f, 0.98f), 11f); - return; - } - - switch (ev.WeaponClass) - { - case WeaponVisualClass.KineticLight: - SpawnSparkBurst(pos, normal, 3, new Color(3.2f, 2.6f, 1.1f, 0.98f), 9f); - break; - - case WeaponVisualClass.Autocannon: - AddTransient(new TransientVfx - { - Shape = VfxShape.Sphere, - Position = pos + normal * 0.15f, - Velocity = normal * 2.2f, - BaseRotation = Basis.Identity, - StartScale = Vector3.One * 0.45f, - EndScale = Vector3.One * 1.55f, - ColorStart = new Color(1.5f, 0.95f, 0.55f, 0.85f), - ColorEnd = new Color(0.55f, 0.48f, 0.38f, 0.0f), - Age = 0f, - Lifetime = 0.26f - }); - SpawnSparkBurst(pos, normal, 4, new Color(3.2f, 1.85f, 0.55f, 0.98f), 12f); - break; - - case WeaponVisualClass.Explosive: - { - bool isRecoilless = string.Equals(ev.WeaponId, "recoilless", StringComparison.Ordinal); - float detSize = isRecoilless ? 4.4f : 2.1f; - float ringSize = isRecoilless ? 6.2f : 2.9f; - AddTransient(new TransientVfx - { - Shape = VfxShape.Sphere, - Position = pos + normal * 0.25f, - Velocity = normal * 1.6f, - BaseRotation = Basis.Identity, - StartScale = Vector3.One * 0.6f, - EndScale = Vector3.One * detSize, - ColorStart = new Color(3.8f, 2.1f, 0.65f, 0.98f), - ColorEnd = new Color(0.85f, 0.28f, 0.08f, 0.0f), - Age = 0f, - Lifetime = isRecoilless ? 0.34f : 0.24f - }); - - Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up; - Vector3 right = upRef.Cross(normal).Normalized(); - Vector3 fwd = normal.Cross(right).Normalized(); - Basis ringBasis = new(right, normal, fwd); - AddTransient(new TransientVfx - { - Shape = VfxShape.Ring, - Position = pos + normal * 0.18f, - Velocity = Vector3.Zero, - BaseRotation = ringBasis, - StartScale = new Vector3(0.7f, 1.0f, 0.7f), - EndScale = new Vector3(ringSize, 0.4f, ringSize), - ColorStart = new Color(3.2f, 1.65f, 0.45f, 0.92f), - ColorEnd = new Color(1.4f, 0.55f, 0.20f, 0.0f), - Age = 0f, - Lifetime = isRecoilless ? 0.32f : 0.22f - }); - SpawnSparkBurst(pos, normal, isRecoilless ? 6 : 4, new Color(3.4f, 1.6f, 0.35f, 0.98f), 15f); - break; + continue; } - case WeaponVisualClass.ThermalBeam: - AddTransient(new TransientVfx - { - Shape = VfxShape.Sphere, - Position = pos, - Velocity = Vector3.Zero, - BaseRotation = Basis.Identity, - StartScale = Vector3.One * 0.45f, - EndScale = Vector3.One * 1.65f, - ColorStart = new Color(1.6f, 3.4f, 3.8f, 0.95f), - ColorEnd = new Color(2.6f, 1.5f, 0.3f, 0.0f), - Age = 0f, - Lifetime = 0.22f - }); - SpawnSparkBurst(pos, normal, 5, new Color(2.0f, 3.2f, 3.6f, 0.98f), 13f); - break; - } - } - - private void SpawnSparkBurst(Vector3 pos, Vector3 normal, int count, Color color, float speed) - { - for (int i = 0; i < count; i++) - { - Vector3 rand = new(NextVfxSigned(), MathF.Abs(NextVfxSigned()) + 0.35f, NextVfxSigned()); - Vector3 dir = (normal * 0.8f + rand).Normalized(); - Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; - AddTransient(new TransientVfx + Vector3 pos = _contenderVisuals.TryGetValue(c.Id, out var av) + ? av.Visual.Root.GlobalPosition + : new Vector3(c.X, c.Y, c.Z); + if (hasCam && pos.DistanceSquaredTo(camPos) > 125f * 125f) { - Shape = VfxShape.Beam, - Position = pos, - Velocity = dir * (speed * (0.65f + 0.7f * NextVfxFloat())), - BaseRotation = Basis.LookingAt(dir, up), - StartScale = new Vector3(0.05f, 0.05f, 0.55f), - EndScale = new Vector3(0.02f, 0.02f, 0.12f), - ColorStart = color, - ColorEnd = color with { A = 0f }, - Age = 0f, - Lifetime = 0.16f + 0.08f * NextVfxFloat() - }); + continue; + } + + var key = (true, c.Id); + float coreHpRatio = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 1f; + float thermalRatio = c.MaxThermalRatio > 0f ? c.MaxThermalRatio : c.Grid.ComputeMaxThermalRatio(); + + if ((c.Grid.Spec.Mobility == MobilityKind.Wheeled || c.Grid.Spec.Mobility == MobilityKind.Tracked) && + c.Speed > 8.5f) + { + float nextDust = _tireDustNextTime.GetValueOrDefault(key); + if (_vfxClock >= nextDust) + { + _tireDustNextTime[key] = _vfxClock + 0.07f; // ~14 Hz + float sinY = MathF.Sin(c.Yaw); + float cosY = MathF.Cos(c.Yaw); + Vector3 rearPos = pos - new Vector3(sinY, 0f, cosY) * (c.Grid.Spec.HalfLength * 0.72f); + rearPos.Y = state.Terrain.SampleHeight(rearPos.X, rearPos.Z) + 0.12f; + Vector3 vel = new(c.VelX, 0f, c.VelZ); + _particles.EmitTireDust( + rearPos, + vel, + sampleGroundTint(rearPos.X, rearPos.Z), + Math.Clamp(c.Speed / 16f, 0.7f, 1.35f), + camPos, + hasCam); + } + } + + if (thermalRatio >= 0.85f) + { + float nextVent = _thermalVentNextTime.GetValueOrDefault(key); + if (_vfxClock >= nextVent) + { + _thermalVentNextTime[key] = _vfxClock + 0.10f; // 10 Hz + Vector3 ventPos = ResolveHotAnchorWorld(av?.Visual, c.Grid, pos, c.Grid.Spec.HalfHeight); + _particles.EmitThermalVent(ventPos, thermalRatio, camPos, hasCam); + } + } + + if (coreHpRatio < 0.35f) + { + float nextSmoke = _damageSmokeNextTime.GetValueOrDefault(key); + if (_vfxClock >= nextSmoke) + { + _damageSmokeNextTime[key] = _vfxClock + 0.10f; // 10 Hz + Vector3 dmgPos = pos + new Vector3(0f, c.Grid.Spec.HalfHeight * 0.6f, 0f); + _particles.EmitDamageSmokeAndFire(dmgPos, coreHpRatio, camPos, hasCam); + } + } + } + + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive || !session.IsSpectatorVisible(s.Id)) + { + continue; + } + + Vector3 pos = _spectatorVisuals.TryGetValue(s.Id, out var av) + ? av.Visual.Root.GlobalPosition + : new Vector3(s.X, s.Y, s.Z); + if (hasCam && pos.DistanceSquaredTo(camPos) > 125f * 125f) + { + continue; + } + + var key = (false, s.Id); + float coreHpRatio = s.Grid.MaxCoreHp > 0f ? s.Grid.CoreHp / s.Grid.MaxCoreHp : 1f; + float thermalRatio = s.Grid.ComputeMaxThermalRatio(); + + if (thermalRatio >= 0.85f) + { + float nextVent = _thermalVentNextTime.GetValueOrDefault(key); + if (_vfxClock >= nextVent) + { + _thermalVentNextTime[key] = _vfxClock + 0.11f; + Vector3 ventPos = ResolveHotAnchorWorld(av?.Visual, s.Grid, pos, s.Grid.Spec.HalfHeight); + _particles.EmitThermalVent(ventPos, thermalRatio, camPos, hasCam); + } + } + + if (coreHpRatio < 0.35f) + { + float nextSmoke = _damageSmokeNextTime.GetValueOrDefault(key); + if (_vfxClock >= nextSmoke) + { + _damageSmokeNextTime[key] = _vfxClock + 0.11f; + Vector3 dmgPos = pos + new Vector3(0f, s.Grid.Spec.HalfHeight * 0.6f, 0f); + _particles.EmitDamageSmokeAndFire(dmgPos, coreHpRatio, camPos, hasCam); + } + } } } - private void EmitMuzzleFlash(Vector3 pos, float size, Color color) + private static Vector3 ResolveHotAnchorWorld(VehicleVisualInstance? vis, ChassisGrid grid, Vector3 fallbackPos, float halfHeight) { - AddTransient(new TransientVfx + if (vis is not null && !vis.IsStaticLod) { - Shape = VfxShape.Sphere, - Position = pos, - Velocity = Vector3.Zero, - BaseRotation = Basis.Identity, - StartScale = Vector3.One * size, - EndScale = Vector3.One * (size * 0.25f), - ColorStart = color, - ColorEnd = color with { A = 0f }, - Age = 0f, - Lifetime = 0.065f - }); + var hps = grid.Spec.Hardpoints; + for (int i = 0; i < hps.Length; i++) + { + if (hps[i].Kind == HardpointKind.Radiator || hps[i].Kind == HardpointKind.Engine) + { + Node3D? anchor = vis.GetHardpointAnchorNode(hps[i].Id); + if (anchor is not null && GodotObject.IsInstanceValid(anchor) && anchor.IsInsideTree()) + { + return anchor.GlobalPosition; + } + } + } + } + return fallbackPos + new Vector3(0f, halfHeight * 0.7f, 0f); } private void EmitBeam(ref int beamIdx, Basis lookBasis, Vector3 mid, Vector3 scale, Color color) @@ -1290,25 +1324,13 @@ public partial class ArenaRenderer : Node3D private void AddTransient(in TransientVfx vfx) { - if (_transientVfx.Count >= 512) + if (_transientVfx.Count >= 256) { _transientVfx.RemoveAt(0); } _transientVfx.Add(vfx); } - private float NextVfxFloat() - { - uint x = _vfxRng; - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - _vfxRng = x; - return (x & 0x00FFFFFFu) / 16777216f; - } - - private float NextVfxSigned() => NextVfxFloat() * 2f - 1f; - private static void ClearChildren(Node parent) { for (int i = parent.GetChildCount() - 1; i >= 0; i--) diff --git a/client/CameraJuiceState.cs b/client/CameraJuiceState.cs new file mode 100644 index 0000000..d919eb2 --- /dev/null +++ b/client/CameraJuiceState.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Display-only post-anchor camera juice (recoil kick, quadratic trauma micro-shake, footstep thump, +/// and speed/VTOL FOV punch). Zero simulation authority and zero Godot dependency so unit tests and +/// headless smoke checks exercise the exact same state machine. +/// +/// Invariant: when is true, outputs exact +/// and 0f angles (strictly zero idle camera jitter). +/// +/// +public sealed class CameraJuiceState +{ + public const float BaseFovDeg = 58.0f; + private const float ZeroEpsilon = 1e-4f; + private const float TraumaDecayPerSec = 1.95f; + private const float RecoilDecayRate = 14.0f; + private const float FootstepDecayRate = 16.0f; + private const float FovBlendRate = 6.0f; + + private float _time; + + public float Trauma { get; private set; } + public float RecoilPitchRad { get; private set; } + public float RecoilBackMeters { get; private set; } + public float FootstepBumpY { get; private set; } + public float FovOffsetDeg { get; private set; } + + public bool IsIdle => + Trauma <= 0f && + RecoilPitchRad == 0f && + RecoilBackMeters == 0f && + FootstepBumpY == 0f; + + public void Reset() + { + Trauma = 0f; + RecoilPitchRad = 0f; + RecoilBackMeters = 0f; + FootstepBumpY = 0f; + FovOffsetDeg = 0f; + _time = 0f; + } + + public void ConsumeEvents(IReadOnlyList events, int localContenderId, Vector3 localPos) + { + for (int i = 0; i < events.Count; i++) + { + switch (events[i]) + { + case MatchResetEvent: + Reset(); + break; + + case ShotFiredEvent shot: + if (!shot.IsSpectatorShooter && shot.ShooterId == localContenderId) + { + ApplyWeaponRecoil(shot.WeaponId, (WeaponVisualClass)shot.WeaponClass); + } + break; + + case HitImpactEvent hit: + { + if (hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId == localContenderId) + { + float incomingTrauma = (WeaponVisualClass)hit.WeaponClass switch + { + WeaponVisualClass.Explosive => 0.34f, + WeaponVisualClass.Autocannon => 0.22f, + WeaponVisualClass.ThermalBeam => 0.20f, + _ => 0.10f + }; + AddTrauma(incomingTrauma); + } + else if ((WeaponVisualClass)hit.WeaponClass == WeaponVisualClass.Explosive) + { + float dx = hit.HitX - localPos.X; + float dy = hit.HitY - localPos.Y; + float dz = hit.HitZ - localPos.Z; + float distSq = dx * dx + dy * dy + dz * dz; + if (distSq < 36f * 36f) + { + float falloff = 1f - MathF.Sqrt(distSq) / 36f; + AddTrauma(0.24f * falloff); + } + } + break; + } + + case ContenderEliminatedEvent: + case SpectatorDestroyedEvent: + // Large chassis detonation thump when nearby (camera-local subtle shake) + AddTrauma(0.14f); + break; + } + } + } + + public void ConsumeFootsteps(IReadOnlyList footsteps, int localContenderId) + { + for (int i = 0; i < footsteps.Count; i++) + { + FootstepPulse pulse = footsteps[i]; + if (pulse.IsContender && pulse.EntityId == localContenderId) + { + float massFactor = Math.Clamp(pulse.MassKg / 3200f, 0.55f, 1.55f); + float loadFactor = Math.Clamp(pulse.LoadG, 0.5f, 1.8f); + float bump = -0.065f * massFactor * loadFactor; + FootstepBumpY = Math.Clamp(FootstepBumpY + bump, -0.18f, 0f); + } + } + } + + public void AddTrauma(float amount) + { + if (float.IsFinite(amount) && amount > 0f) + { + Trauma = Math.Clamp(Trauma + amount, 0f, 1.0f); + } + } + + public void Update(float dt, float localSpeedMps, bool isVtol) + { + float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.1f) : 0f; + if (stepDt > 0f) + { + _time += stepDt; + + Trauma = MathF.Max(0f, Trauma - stepDt * TraumaDecayPerSec); + if (Trauma < ZeroEpsilon) Trauma = 0f; + + float recoilDecay = MathF.Exp(-RecoilDecayRate * stepDt); + RecoilPitchRad *= recoilDecay; + RecoilBackMeters *= recoilDecay; + if (MathF.Abs(RecoilPitchRad) < ZeroEpsilon) RecoilPitchRad = 0f; + if (MathF.Abs(RecoilBackMeters) < ZeroEpsilon) RecoilBackMeters = 0f; + + float stepDecay = MathF.Exp(-FootstepDecayRate * stepDt); + FootstepBumpY *= stepDecay; + if (MathF.Abs(FootstepBumpY) < ZeroEpsilon) FootstepBumpY = 0f; + } + + float speed = float.IsFinite(localSpeedMps) ? MathF.Max(0f, localSpeedMps) : 0f; + float speedStart = isVtol ? 14f : 12f; + float speedFull = isVtol ? 46f : 36f; + float targetFovOffset = speed > speedStart + ? Math.Clamp((speed - speedStart) / (speedFull - speedStart), 0f, 1f) * (isVtol ? 4.8f : 3.4f) + : 0f; + + if (stepDt > 0f) + { + float blend = 1f - MathF.Exp(-FovBlendRate * stepDt); + FovOffsetDeg += (targetFovOffset - FovOffsetDeg) * blend; + if (MathF.Abs(FovOffsetDeg) < 0.002f && targetFovOffset == 0f) + { + FovOffsetDeg = 0f; + } + } + } + + public void ComputeOffsets( + out Vector3 localOffset, + out float pitchOffsetRad, + out float yawOffsetRad, + out float rollOffsetRad) + { + if (IsIdle) + { + localOffset = Vector3.Zero; + pitchOffsetRad = 0f; + yawOffsetRad = 0f; + rollOffsetRad = 0f; + return; + } + + float shake = Trauma * Trauma; + float sx = MathF.Sin(_time * 43.0f) * 0.65f + MathF.Sin(_time * 71.0f) * 0.35f; + float sy = MathF.Cos(_time * 37.0f) * 0.65f + MathF.Sin(_time * 63.0f) * 0.35f; + float sr = MathF.Sin(_time * 29.0f + 1.1f); + + localOffset = new Vector3( + sx * shake * 0.14f, + sy * shake * 0.11f + FootstepBumpY, + RecoilBackMeters); + + pitchOffsetRad = RecoilPitchRad + sy * shake * 0.015f; + yawOffsetRad = sx * shake * 0.012f; + rollOffsetRad = sr * shake * 0.016f; + } + + private void ApplyWeaponRecoil(string weaponId, WeaponVisualClass weaponClass) + { + switch (weaponClass) + { + case WeaponVisualClass.Explosive: + if (string.Equals(weaponId, "recoilless", StringComparison.Ordinal)) + { + RecoilPitchRad = MathF.Min(RecoilPitchRad + 0.022f, 0.042f); + RecoilBackMeters = MathF.Min(RecoilBackMeters + 0.34f, 0.60f); + AddTrauma(0.32f); + } + else + { + RecoilPitchRad = MathF.Min(RecoilPitchRad + 0.011f, 0.030f); + RecoilBackMeters = MathF.Min(RecoilBackMeters + 0.16f, 0.40f); + AddTrauma(0.18f); + } + break; + + case WeaponVisualClass.Autocannon: + RecoilPitchRad = MathF.Min(RecoilPitchRad + 0.010f, 0.026f); + RecoilBackMeters = MathF.Min(RecoilBackMeters + 0.14f, 0.35f); + AddTrauma(0.16f); + break; + + case WeaponVisualClass.ThermalBeam: + { + bool isLance = string.Equals(weaponId, "gilded_lance", StringComparison.Ordinal); + RecoilPitchRad = MathF.Min(RecoilPitchRad + (isLance ? 0.012f : 0.008f), 0.026f); + RecoilBackMeters = MathF.Min(RecoilBackMeters + (isLance ? 0.16f : 0.10f), 0.35f); + AddTrauma(isLance ? 0.18f : 0.12f); + break; + } + + default: // KineticLight (mg_762, pd_flak) + RecoilPitchRad = MathF.Min(RecoilPitchRad + 0.0022f, 0.012f); + RecoilBackMeters = MathF.Min(RecoilBackMeters + 0.030f, 0.15f); + AddTrauma(0.035f); + break; + } + } +} diff --git a/client/Hud.cs b/client/Hud.cs index fa954f1..d9a10c0 100644 --- a/client/Hud.cs +++ b/client/Hud.cs @@ -6,6 +6,14 @@ using RustToDust.Core; namespace RustToDust.Client; +public enum HitMarkerKind +{ + None = 0, + Armor = 1, + Core = 2, + Kill = 3 +} + /// /// Rust to Dust industrial HUD: /// - Top-Left: Chassis badge (DORSAL/CORONAL), Core HP, Speed, Contenders Alive, Safe Circle status, Pickup prompt. @@ -44,7 +52,13 @@ public partial class Hud : CanvasLayer private RadarWidget _radar = null!; private Label _radarTitle = null!; private Label _mapAttribLabel = null!; + private ColorRect _vignetteRect = null!; + private ShaderMaterial _vignetteMat = null!; private CrosshairOverlay _crosshair = null!; + private float _damagePulse; + private float _lowCoreRatio; + private float _overheatPulse; + private float _vignetteTime; private InventoryGridControl _schematic = null!; private Label _hoverLabel = null!; private VBoxContainer _cargoList = null!; @@ -91,8 +105,23 @@ public partial class Hud : CanvasLayer public bool IsUiTextInputFocused => _netPanel.Visible && (_callsignEdit.HasFocus() || _endpointEdit.HasFocus()); public InventoryGridControl Schematic => _schematic; internal int ActiveHitArcCount => _crosshair.ActiveHitArcCount; + internal bool HasActiveHitMarker => _crosshair.HasActiveHitMarker; + internal HitMarkerKind ActiveHitMarkerKind => _crosshair.ActiveHitMarkerKind; + internal bool IsVignetteVisible => _vignetteRect is not null && _vignetteRect.Visible; internal void PushTestHitArc(float sourceX, float sourceZ, WeaponVisualClass weaponClass) => _crosshair.PushTestHitArc(sourceX, sourceZ, weaponClass); + internal void ResetFeedback() + { + _damagePulse = 0f; + _lowCoreRatio = 0f; + _overheatPulse = 0f; + _vignetteTime = 0f; + if (_vignetteRect is not null) + { + _vignetteRect.Visible = false; + } + _crosshair?.ResetFeedback(); + } internal Rect2 BottomLeftPanelRect => _bottomLeftPanel.GetGlobalRect(); internal Rect2 ChyronPanelRect => _chyronPanel.GetGlobalRect(); @@ -147,7 +176,77 @@ public partial class Hud : CanvasLayer public override void _Process(double delta) { - _crosshair?.Advance((float)delta); + float dt = (float)delta; + _crosshair?.Advance(dt); + + if (_vignetteRect is not null) + { + if (_damagePulse > 0f && dt > 0f) + { + _damagePulse = MathF.Max(0f, _damagePulse - dt * 2.4f); + if (_damagePulse < 0.005f) _damagePulse = 0f; + } + bool active = _damagePulse >= 0.01f || _lowCoreRatio >= 0.01f || _overheatPulse >= 0.01f; + _vignetteRect.Visible = active; + if (active) + { + _vignetteTime += MathF.Max(0f, dt); + _vignetteMat.SetShaderParameter("damage_pulse", _damagePulse); + _vignetteMat.SetShaderParameter("low_core_ratio", _lowCoreRatio); + _vignetteMat.SetShaderParameter("overheat_pulse", _overheatPulse); + _vignetteMat.SetShaderParameter("time_sec", _vignetteTime); + } + } + } + + public void ConsumeEvents( + IReadOnlyList events, + int localContenderId, + float localCoreHpRatio, + float localMaxThermalRatio) + { + for (int i = 0; i < events.Count; i++) + { + switch (events[i]) + { + case MatchResetEvent: + ResetFeedback(); + break; + + case HitImpactEvent hit: + if (hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId == localContenderId) + { + _crosshair?.PushTestHitArc(hit.SourceX, hit.SourceZ, (WeaponVisualClass)hit.WeaponClass); + float pulse = (WeaponVisualClass)hit.WeaponClass == WeaponVisualClass.Explosive ? 0.95f : 0.62f; + _damagePulse = MathF.Max(_damagePulse, pulse); + } + if (hit.IsContenderShooter && hit.ShooterId == localContenderId) + { + _crosshair?.TriggerHitMarker(hit.CoreDamage > 0.001f, hit.Killed); + } + break; + } + } + + _lowCoreRatio = localCoreHpRatio < 0.35f + ? Math.Clamp((0.35f - localCoreHpRatio) / 0.35f, 0f, 1f) + : 0f; + _overheatPulse = localMaxThermalRatio >= 0.85f + ? Math.Clamp((localMaxThermalRatio - 0.85f) / 0.25f, 0.35f, 1.0f) + : 0f; + + if (_vignetteRect is not null) + { + bool active = _damagePulse >= 0.01f || _lowCoreRatio >= 0.01f || _overheatPulse >= 0.01f; + _vignetteRect.Visible = active; + if (active) + { + _vignetteMat.SetShaderParameter("damage_pulse", _damagePulse); + _vignetteMat.SetShaderParameter("low_core_ratio", _lowCoreRatio); + _vignetteMat.SetShaderParameter("overheat_pulse", _overheatPulse); + _vignetteMat.SetShaderParameter("time_sec", _vignetteTime); + } + } } public override void _Ready() @@ -346,6 +445,19 @@ public partial class Hud : CanvasLayer private void BuildCrosshair() { + Shader vigShader = GD.Load("res://hud_vignette.gdshader") + ?? throw new InvalidOperationException("Failed to load res://hud_vignette.gdshader"); + _vignetteMat = new ShaderMaterial { Shader = vigShader }; + _vignetteRect = new ColorRect + { + Name = "HudVignette", + Material = _vignetteMat, + MouseFilter = Control.MouseFilterEnum.Ignore, + Visible = false + }; + _vignetteRect.SetAnchorsPreset(Control.LayoutPreset.FullRect); + AddChild(_vignetteRect); + _crosshair = new CrosshairOverlay { Name = "Crosshair" }; _crosshair.SetAnchorsPreset(Control.LayoutPreset.FullRect); _crosshair.MouseFilter = Control.MouseFilterEnum.Ignore; @@ -1051,63 +1163,84 @@ public partial class Hud : CanvasLayer private ContenderState? _player; private float _cameraYaw; private MatchState? _lastState; - private long _lastProcessedHitId; private readonly List _incomingArcs = new(); + private HitMarkerKind _hitMarkerKind; + private float _hitMarkerRemaining; + private float _hitMarkerDuration; public void SetState(MatchState state, ContenderState player, float cameraYaw) { if (!ReferenceEquals(_lastState, state)) { _lastState = state; - _lastProcessedHitId = 0; - _incomingArcs.Clear(); + ResetFeedback(); } _player = player; _cameraYaw = cameraYaw; + } - var hits = state.HitEvents; - for (int i = 0; i < hits.Count; i++) + public void ResetFeedback() + { + _incomingArcs.Clear(); + _hitMarkerKind = HitMarkerKind.None; + _hitMarkerRemaining = 0f; + _hitMarkerDuration = 0f; + QueueRedraw(); + } + + public void TriggerHitMarker(bool coreHit, bool killed) + { + HitMarkerKind nextKind = killed + ? HitMarkerKind.Kill + : (coreHit ? HitMarkerKind.Core : HitMarkerKind.Armor); + // Preserve stronger hit-marker kind while active (Kill > Core > Armor) + if (_hitMarkerRemaining > 0f && (int)nextKind < (int)_hitMarkerKind) { - var ev = hits[i]; - if (ev.EventId <= _lastProcessedHitId) - { - continue; - } - _lastProcessedHitId = ev.EventId; - - if (ev.TargetKind == HitTargetKind.Contender && ev.TargetId == player.Id) - { - if (_incomingArcs.Count >= 8) - { - _incomingArcs.RemoveAt(0); - } - _incomingArcs.Add(new IncomingHitArc - { - SourceX = ev.SourceX, - SourceZ = ev.SourceZ, - WeaponClass = ev.WeaponClass, - Age = 0f - }); - } + nextKind = _hitMarkerKind; } + _hitMarkerKind = nextKind; + _hitMarkerDuration = nextKind switch + { + HitMarkerKind.Kill => 0.38f, + HitMarkerKind.Core => 0.26f, + _ => 0.18f + }; + _hitMarkerRemaining = _hitMarkerDuration; + QueueRedraw(); } public void Advance(float dt) { - if (_incomingArcs.Count == 0 || dt <= 0f) + bool dirty = false; + if (_incomingArcs.Count > 0 && dt > 0f) { - return; - } - for (int i = _incomingArcs.Count - 1; i >= 0; i--) - { - _incomingArcs[i].Age += dt; - if (_incomingArcs[i].Age >= HitArcDuration) + for (int i = _incomingArcs.Count - 1; i >= 0; i--) { - _incomingArcs.RemoveAt(i); + _incomingArcs[i].Age += dt; + if (_incomingArcs[i].Age >= HitArcDuration) + { + _incomingArcs.RemoveAt(i); + } } + dirty = true; + } + + if (_hitMarkerRemaining > 0f && dt > 0f) + { + _hitMarkerRemaining = MathF.Max(0f, _hitMarkerRemaining - dt); + if (_hitMarkerRemaining <= 0.001f) + { + _hitMarkerRemaining = 0f; + _hitMarkerKind = HitMarkerKind.None; + } + dirty = true; + } + + if (dirty) + { + QueueRedraw(); } - QueueRedraw(); } public void PushTestHitArc(float sourceX, float sourceZ, WeaponVisualClass weaponClass) @@ -1124,6 +1257,8 @@ public partial class Hud : CanvasLayer } public int ActiveHitArcCount => _incomingArcs.Count; + public bool HasActiveHitMarker => _hitMarkerRemaining > 0f && _hitMarkerKind != HitMarkerKind.None; + public HitMarkerKind ActiveHitMarkerKind => HasActiveHitMarker ? _hitMarkerKind : HitMarkerKind.None; public override void _Draw() { @@ -1144,6 +1279,34 @@ public partial class Hud : CanvasLayer DrawLine(center + new Vector2(0f, -gap - tick), center + new Vector2(0f, -gap), retCol, 1.6f); DrawLine(center + new Vector2(0f, gap), center + new Vector2(0f, gap + tick), retCol, 1.6f); + // Outgoing reticle hit-marker X-flash (white/gold armor, crimson core, crimson double-X kill) + if (_hitMarkerRemaining > 0f && _hitMarkerDuration > 0.001f && _hitMarkerKind != HitMarkerKind.None) + { + float frac = Math.Clamp(_hitMarkerRemaining / _hitMarkerDuration, 0f, 1f); + float pop = 1.0f + (1.0f - frac) * 0.25f; + Color xCol = _hitMarkerKind switch + { + HitMarkerKind.Kill => new Color(RedCol.R, RedCol.G, RedCol.B, frac * 0.98f), + HitMarkerKind.Core => new Color(1.0f, 0.28f, 0.16f, frac * 0.95f), + _ => new Color(1.0f, 0.95f, 0.78f, frac * 0.92f) + }; + float xWidth = _hitMarkerKind == HitMarkerKind.Armor ? 2.0f : 2.8f; + float rIn = 6.5f * pop; + float rOut = (_hitMarkerKind == HitMarkerKind.Armor ? 13.5f : 15.5f) * pop; + const float diag = 0.70710678f; + for (int q = 0; q < 4; q++) + { + float sx = (q & 1) == 0 ? 1f : -1f; + float sy = (q & 2) == 0 ? 1f : -1f; + Vector2 dir = new(sx * diag, sy * diag); + DrawLine(center + dir * rIn, center + dir * rOut, xCol, xWidth); + if (_hitMarkerKind == HitMarkerKind.Kill) + { + DrawLine(center + dir * (rOut + 4f), center + dir * (rOut + 10.5f), new Color(GoldCol.R, GoldCol.G, GoldCol.B, frac * 0.95f), 2.2f); + } + } + } + if (allDisabled) { DrawString( diff --git a/client/Main.cs b/client/Main.cs index d32ff9a..ed6c26a 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -34,6 +34,7 @@ public partial class Main : Node3D private MatchState? _boundViewState; private bool _wasNetConnected; private readonly WalkerFootstepTracker _footsteps = new(); + private readonly CameraJuiceState _camJuice = new(); private readonly List _frameEvents = new(128); private readonly List _frameFootsteps = new(32); private ArenaMapKind _mapKind = ArenaMapKind.Sion; @@ -46,6 +47,9 @@ public partial class Main : Node3D private float _cameraZoom = 1.0f; private float _smoothedShoulderY; private string? _lastCamChassisId; + private Vector3 _baseCamPos; + private Vector3 _baseLookDir = Vector3.Forward; + private bool _hasBaseCamPose; private float _elapsedSeconds; private bool _interactQueued; private int _seed = 42; @@ -80,12 +84,17 @@ public partial class Main : Node3D public ArenaRenderer Arena => _arena; public ArenaAudioSystem Audio => _audio; public WalkerFootstepTracker Footsteps => _footsteps; + public CameraJuiceState CameraJuice => _camJuice; + public Camera3D Camera => _camera; public Hud Hud => _hud; public ArenaMapKind MapKind => _mapKind; public ArenaMapKind? InitialMapKindOverride { get; set; } public string? Failure { get; private set; } public int Seed => _seed; public float CameraYaw => _cameraYaw; + internal Vector3 BaseCameraPosition => _baseCamPos; + internal Vector3 BaseCameraLookDir => _baseLookDir; + internal (float AimX, float AimY, float AimZ) ProbeCenterScreenAim() => ComputeCenterScreenAim(); public override void _Ready() { @@ -401,10 +410,13 @@ public partial class Main : Node3D _cameraPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(5f) : Mathf.DegToRad(12f); _cameraZoom = 1.0f; _lastCamChassisId = null; + _hasBaseCamPose = false; + _camJuice.Reset(); _footsteps.Clear(); _frameEvents.Clear(); _frameFootsteps.Clear(); _audio.ClearAll(); + _hud.ResetFeedback(); } _camera.Far = _mapKind == ArenaMapKind.Sion ? 4200f : 1800f; @@ -718,13 +730,14 @@ public partial class Main : Node3D } long tt1 = Stopwatch.GetTimestamp(); _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); + DrainAndFanSimEvents((float)delta, alpha); long ta1 = Stopwatch.GetTimestamp(); _perfPendingTerrainMs = (tt1 - tt0) * toMs; _perfPendingArenaMs = (ta1 - tt1) * toMs; long tc0 = Stopwatch.GetTimestamp(); UpdateCamera((float)delta, alpha); - StepAudioAndFootsteps((float)delta, alpha); + _audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha); if (_mapKind == ArenaMapKind.Sion) { _sionMap.UpdateLod(_camera.GlobalPosition); @@ -734,6 +747,9 @@ public partial class Main : Node3D _terrain.UpdateTileLod(_camera.GlobalPosition); } long th0 = Stopwatch.GetTimestamp(); + var localP = _session.LocalContender; + float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f; + _hud.ConsumeEvents(_frameEvents, _session.LocalContenderId, coreRatio, localP.MaxThermalRatio); _hud.Sync(_session); long th1 = Stopwatch.GetTimestamp(); _perfCamMsSum += (th0 - tc0) * toMs; @@ -776,8 +792,9 @@ public partial class Main : Node3D _terrain.Sync(_session.ViewState.Terrain); } _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); + DrainAndFanSimEvents((float)delta, alpha); UpdateCamera((float)delta, alpha); - StepAudioAndFootsteps((float)delta, alpha); + _audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha); if (_mapKind == ArenaMapKind.Sion) { _sionMap.UpdateLod(_camera.GlobalPosition); @@ -786,11 +803,14 @@ public partial class Main : Node3D { _terrain.UpdateTileLod(_camera.GlobalPosition); } + var localP = _session.LocalContender; + float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f; + _hud.ConsumeEvents(_frameEvents, _session.LocalContenderId, coreRatio, localP.MaxThermalRatio); _hud.Sync(_session); } } - private void StepAudioAndFootsteps(float dt, float alpha) + private void DrainAndFanSimEvents(float dt, float alpha) { if (_session is null) { @@ -802,9 +822,22 @@ public partial class Main : Node3D _frameFootsteps.Clear(); _footsteps.StepSession(_session, dt, alpha, _frameFootsteps, ResolveLiveWalkerFootWorld); - _audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, dt, alpha); + _arena.ConsumeEvents(_session, _frameEvents, _frameFootsteps, dt, SampleCurrentMapGroundTint); + + var local = _session.LocalContender; + var localPos = new System.Numerics.Vector3(local.X, local.Y, local.Z); + _camJuice.ConsumeEvents(_frameEvents, _session.LocalContenderId, localPos); + _camJuice.ConsumeFootsteps(_frameFootsteps, _session.LocalContenderId); + _camJuice.Update(dt, local.Speed, local.Grid.Spec.IsVtol); } + private static readonly Color DesertDustTint = new(0.76f, 0.59f, 0.40f, 1.0f); + + internal Color SampleCurrentMapGroundTint(float worldX, float worldZ) => + _mapKind == ArenaMapKind.Sion + ? _sionMap.SampleGroundTint(worldX, worldZ) + : DesertDustTint; + private System.Numerics.Vector3? ResolveLiveWalkerFootWorld(bool isContender, int id, int legIndex) { VehicleVisualInstance? vis = isContender @@ -874,7 +907,7 @@ 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} 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} particlesActive={_arena.Particles.ActiveParticleCount} flashLightsPeak={_arena.Particles.PeakFlashLightCount} tracers={_session?.ViewState.Tracers.Count ?? 0}"); if (_session is not null) { var net = _session.ConnectionStatus; @@ -1005,8 +1038,12 @@ public partial class Main : Node3D } Vector2 center = screenSize * 0.5f; - Vector3 rayOrigin = _camera.ProjectRayOrigin(center); - Vector3 rayDir = _camera.ProjectRayNormal(center); + Vector3 rayOrigin = _hasBaseCamPose + ? _baseCamPos + _baseLookDir * _camera.Near + : _camera.ProjectRayOrigin(center); + Vector3 rayDir = _hasBaseCamPose + ? _baseLookDir + : _camera.ProjectRayNormal(center); const float maxAimDist = 450f; ulong playerStableId = ContenderStableIdBase + (ulong)player.Id; @@ -1161,8 +1198,72 @@ public partial class Main : Node3D } } - _camera.GlobalPosition = camPos; - _camera.LookAt(camPos + lookDir * 60f, Vector3.Up); + _baseCamPos = camPos; + _baseLookDir = lookDir; + _hasBaseCamPose = true; + + float targetFov = CameraJuiceState.BaseFovDeg + _camJuice.FovOffsetDeg; + if (MathF.Abs(_camera.Fov - targetFov) > 0.005f) + { + _camera.Fov = targetFov; + } + + if (_camJuice.IsIdle) + { + _camera.GlobalPosition = camPos; + _camera.LookAt(camPos + lookDir * 60f, Vector3.Up); + return; + } + + _camJuice.ComputeOffsets( + out System.Numerics.Vector3 jOff, + out float pitchOffRad, + out float yawOffRad, + out float rollOffRad); + + Vector3 juicedCamPos = camPos + + camRight * jOff.X + + Vector3.Up * jOff.Y + - lookDir * jOff.Z; + + Vector3 juiceDelta = juicedCamPos - camPos; + float juiceDist = juiceDelta.Length(); + if (juiceDist > 0.02f) + { + Vector3 juiceDir = juiceDelta / juiceDist; + if (CastStaticCameraRay(camPos, juiceDir, juiceDist, out float juiceHitDist)) + { + juicedCamPos = camPos + juiceDir * SafeCameraPullbackDist(juiceHitDist); + } + } + + float minJuicedY = Session.ViewState.Terrain.SampleHeight(juicedCamPos.X, juicedCamPos.Z) + 1.15f; + if (juicedCamPos.Y < minJuicedY) + { + juicedCamPos.Y = minJuicedY; + } + + Vector3 juicedLookDir = lookDir; + if (MathF.Abs(yawOffRad) > 1e-6f) + { + juicedLookDir = juicedLookDir.Rotated(Vector3.Up, yawOffRad); + } + if (MathF.Abs(pitchOffRad) > 1e-6f) + { + Vector3 pitchAxis = Vector3.Up.Cross(juicedLookDir); + if (pitchAxis.LengthSquared() > 1e-6f) + { + juicedLookDir = juicedLookDir.Rotated(pitchAxis.Normalized(), pitchOffRad); + } + } + juicedLookDir = juicedLookDir.Normalized(); + + Vector3 camUp = MathF.Abs(rollOffRad) > 1e-6f + ? Vector3.Up.Rotated(juicedLookDir, rollOffRad) + : Vector3.Up; + + _camera.GlobalPosition = juicedCamPos; + _camera.LookAt(juicedCamPos + juicedLookDir * 60f, camUp); } private static float SafeCameraPullbackDist(float rawDist) => diff --git a/client/ParticlePool.cs b/client/ParticlePool.cs new file mode 100644 index 0000000..73495f7 --- /dev/null +++ b/client/ParticlePool.cs @@ -0,0 +1,1000 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Single-draw-call GPU billboard particle pool ( backed by +/// particle_billboard.gdshader) plus the strictly capped [4] +/// dynamic combat flash pool for OpenGL 3.3 (gl_compatibility). +/// +public partial class ParticlePool : Node3D +{ + public const int MaxParticles = 768; + public const int MaxFlashLights = 4; + + 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; + public bool Active; + public int Priority; + public float Age; + public float Duration; + public float StartEnergy; + public float Range; + 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) + private readonly int[] _recentShotIds = new int[64]; + private int _recentShotCursor; + 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 bool _initialized; + private uint _rng = 0x7A3B91E5u; + + public int ActiveParticleCount { get; private set; } + public int FlashLightPoolSize => MaxFlashLights; + + public int ActiveFlashLightCount + { + get + { + int count = 0; + for (int i = 0; i < _flashLights.Length; i++) + { + if (_flashLights[i].Active) count++; + } + return count; + } + } + + public int PeakFlashLightCount { get; private set; } + + public override void _Ready() + { + EnsureInitialized(); + } + + public void EnsureInitialized() + { + if (_initialized) + { + return; + } + _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 + { + Name = $"CombatFlashLight_{i}", + ShadowEnabled = false, + OmniAttenuation = 1.6f, + OmniRange = 10f, + LightEnergy = 0f, + Visible = false + }; + AddChild(light); + _flashLights[i] = new FlashLightSlot { Light = light }; + } + } + + 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; + ActiveParticleCount = 0; + PeakFlashLightCount = 0; + + _multiMesh.VisibleInstanceCount = 0; + _instanceNode.Visible = false; + + for (int i = 0; i < _flashLights.Length; i++) + { + _flashLights[i].Active = false; + _flashLights[i].Age = 0f; + _flashLights[i].Duration = 0f; + _flashLights[i].Light.Visible = false; + _flashLights[i].Light.LightEnergy = 0f; + } + } + + public void ConsumeEvents( + IReadOnlyList events, + MatchState state, + Vector3 camPos, + bool hasCam, + Func sampleGroundTint) + { + EnsureInitialized(); + + for (int i = 0; i < events.Count; i++) + { + switch (events[i]) + { + case MatchResetEvent: + ClearAll(); + break; + + case ShotFiredEvent shot: + HandleShotFired(shot, camPos, hasCam, sampleGroundTint); + break; + + case HitImpactEvent hit: + HandleHitImpact(hit, camPos, hasCam, sampleGroundTint); + break; + + case ContenderEliminatedEvent elim: + if (elim.VictimId >= 0 && elim.VictimId < state.Contenders.Count) + { + var v = state.Contenders[elim.VictimId]; + EmitChassisExplosion(new Vector3(v.X, v.Y + 0.6f, v.Z), v.Grid.Spec.MassKg, camPos, hasCam, sampleGroundTint); + } + break; + + case SpectatorDestroyedEvent sdet: + { + var specs = state.Spectators.Spectators; + for (int s = 0; s < specs.Count; s++) + { + if (specs[s].Id == sdet.SpectatorId) + { + var sp = specs[s]; + EmitChassisExplosion(new Vector3(sp.X, sp.Y + 0.5f, sp.Z), sp.Grid.Spec.MassKg, camPos, hasCam, sampleGroundTint); + break; + } + } + break; + } + } + } + } + + public void EmitFootstepDust(in FootstepPulse pulse, Color groundTint, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + Vector3 footPos = new(pulse.WorldPos.X, pulse.WorldPos.Y + 0.14f, pulse.WorldPos.Z); + if (hasCam && footPos.DistanceSquaredTo(camPos) > 115f * 115f) + { + return; + } + + 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 ? 5 : 3; + + Color dustStart = new(groundTint.R, groundTint.G, groundTint.B, 0.52f); + 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.65f * massScale, + EndSize = 2.35f * massScale, + AspectY = 1.0f, + Rotation = NextFloat() * MathF.Tau, + AngularVel = NextSigned() * 1.4f, + Emissive = 0f, + ColorStart = dustStart, + ColorEnd = dustEnd, + Lifetime = 0.42f + NextFloat() * 0.24f + }); + } + } + + public void EmitTireDust(Vector3 worldPos, Vector3 vehicleVel, Color groundTint, float intensity, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && worldPos.DistanceSquaredTo(camPos) > 95f * 95f) + { + return; + } + + float scale = Math.Clamp(intensity, 0.5f, 1.5f); + Color dustStart = new(groundTint.R, groundTint.G, groundTint.B, 0.44f); + 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.55f * scale, + EndSize = 2.15f * scale, + AspectY = 1.0f, + Rotation = NextFloat() * MathF.Tau, + AngularVel = NextSigned() * 1.2f, + Emissive = 0f, + ColorStart = dustStart, + ColorEnd = dustEnd, + Lifetime = 0.45f + NextFloat() * 0.20f + }); + } + + public void EmitThermalVent(Vector3 worldPos, float thermalRatio, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && worldPos.DistanceSquaredTo(camPos) > 105f * 105f) + { + return; + } + + float heatT = Math.Clamp((thermalRatio - 0.85f) / 0.25f, 0f, 1f); + SpawnParticle(new ParticleSlot + { + 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.42f, + EndSize = 1.45f + heatT * 0.45f, + 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.65f), + ColorEnd = new Color(0.65f, 0.58f, 0.54f, 0.0f), + Lifetime = 0.42f + NextFloat() * 0.18f + }); + + 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 + }); + } + } + + public void EmitDamageSmokeAndFire(Vector3 worldPos, float coreHpRatio, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && worldPos.DistanceSquaredTo(camPos) > 125f * 125f) + { + return; + } + + float dmgT = Math.Clamp((0.35f - coreHpRatio) / 0.35f, 0f, 1f); + SpawnParticle(new ParticleSlot + { + 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.65f, + EndSize = 2.25f + dmgT * 0.8f, + AspectY = 1.0f, + Rotation = NextFloat() * MathF.Tau, + AngularVel = NextSigned() * 1.1f, + Emissive = 0f, + ColorStart = new Color(0.18f, 0.16f, 0.15f, 0.72f), + ColorEnd = new Color(0.10f, 0.10f, 0.10f, 0.0f), + Lifetime = 0.70f + NextFloat() * 0.30f + }); + + if (dmgT > 0.3f && NextFloat() < 0.65f) + { + 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 + }); + } + } + + public void TriggerFlashLightForTest(Vector3 pos, Color color, float energy, float range, float duration, int priority) + { + EnsureInitialized(); + SpawnFlashLight(pos, color, energy, range, duration, priority); + } + + public void AdvanceAndCommit(float dt) + { + 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[4] dynamic flashes + int activeLights = 0; + for (int i = 0; i < _flashLights.Length; i++) + { + ref FlashLightSlot slot = ref _flashLights[i]; + if (!slot.Active) + { + continue; + } + + if (stepDt > 0f) + { + slot.Age += stepDt; + if (slot.Age >= slot.Duration) + { + slot.Active = false; + slot.Light.Visible = false; + slot.Light.LightEnergy = 0f; + continue; + } + } + + float t = Math.Clamp(slot.Age / MathF.Max(0.01f, slot.Duration), 0f, 1f); + float decay = MathF.Pow(1f - t, 1.8f); + slot.Light.LightColor = slot.Color; + slot.Light.OmniRange = slot.Range; + slot.Light.LightEnergy = slot.StartEnergy * decay; + slot.Light.Visible = slot.Light.LightEnergy > 0.01f; + if (slot.Light.Visible) + { + activeLights++; + } + } + if (activeLights > PeakFlashLightCount) + { + PeakFlashLightCount = activeLights; + } + } + + private void HandleShotFired( + ShotFiredEvent shot, + Vector3 camPos, + bool hasCam, + Func sampleGroundTint) + { + if (shot.TracerId != 0) + { + for (int k = 0; k < _recentShotIds.Length; k++) + { + if (_recentShotIds[k] == shot.TracerId) + { + return; + } + } + _recentShotIds[_recentShotCursor] = shot.TracerId; + _recentShotCursor = (_recentShotCursor + 1) % _recentShotIds.Length; + } + + Vector3 start = new(shot.StartX, shot.StartY, shot.StartZ); + Vector3 end = new(shot.EndX, shot.EndY, shot.EndZ); + if (hasCam && start.DistanceSquaredTo(camPos) > 160f * 160f) + { + return; + } + + var wClass = (WeaponVisualClass)shot.WeaponClass; + 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); + + 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 + }); + if (!hasCam || start.DistanceSquaredTo(camPos) <= 95f * 95f) + { + SpawnFlashLight(start, new Color(1.0f, 0.82f, 0.45f), 1.45f, 6.5f, 0.08f, priority: 1); + } + 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 + }); + } + if (!hasCam || start.DistanceSquaredTo(camPos) <= 120f * 120f) + { + 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 + }); + } + + if (!hasCam || start.DistanceSquaredTo(camPos) <= 140f * 140f) + { + 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 + }); + if (!hasCam || start.DistanceSquaredTo(camPos) <= 130f * 130f) + { + SpawnFlashLight(start, beamCol with { A = 1f }, isLance ? 3.5f : 2.6f, 11.5f, 0.12f, priority: 4); + } + break; + } + } + } + + private void HandleHitImpact( + HitImpactEvent hit, + Vector3 camPos, + bool hasCam, + Func sampleGroundTint) + { + if (hit.EventId != 0) + { + for (int k = 0; k < _recentHitIds.Length; k++) + { + if (_recentHitIds[k] == hit.EventId) + { + return; + } + } + _recentHitIds[_recentHitCursor] = hit.EventId; + _recentHitCursor = (_recentHitCursor + 1) % _recentHitIds.Length; + } + + Vector3 pos = new(hit.HitX, hit.HitY, hit.HitZ); + if (hasCam && pos.DistanceSquaredTo(camPos) > 165f * 165f) + { + return; + } + + Vector3 normal = new(hit.NormalX, hit.NormalY, hit.NormalZ); + if (normal.LengthSquared() < 1e-4f) normal = Vector3.Up; + normal = normal.Normalized(); + + var wClass = (WeaponVisualClass)hit.WeaponClass; + bool isTerrain = hit.TargetKind == (byte)HitTargetKind.Terrain; + Color groundTint = isTerrain ? sampleGroundTint(pos.X, pos.Z) : new Color(0.46f, 0.42f, 0.38f, 1f); + + 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.55f, + EndSize = 2.45f, + 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.28f + }); + SpawnSparkBurst(pos, normal, 4, new Color(1.0f, 0.68f, 0.24f, 0.98f), 10f); + return; + } + + switch (wClass) + { + case WeaponVisualClass.KineticLight: + if (isTerrain) + { + EmitImpactDustPlume(pos, normal, groundTint, count: 2, size: 1.0f); + } + else + { + SpawnSparkBurst(pos, normal, 3, new Color(1.0f, 0.88f, 0.45f, 0.96f), 8.5f); + } + break; + + case WeaponVisualClass.Autocannon: + EmitImpactDustPlume(pos, normal, groundTint, count: 2, size: 1.55f); + SpawnSparkBurst(pos, normal, 4, new Color(1.0f, 0.72f, 0.26f, 0.98f), 11.5f); + if (!hasCam || pos.DistanceSquaredTo(camPos) <= 130f * 130f) + { + SpawnFlashLight(pos + normal * 0.3f, new Color(1.0f, 0.68f, 0.24f), 2.8f, 9.5f, 0.10f, priority: 4); + } + break; + + case WeaponVisualClass.Explosive: + { + bool isRecoilless = string.Equals(hit.WeaponId, "recoilless", StringComparison.Ordinal); + EmitImpactDustPlume(pos, normal, groundTint, count: isRecoilless ? 5 : 3, size: isRecoilless ? 2.6f : 1.7f); + 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 ? 1.1f : 0.7f, + EndSize = isRecoilless ? 3.5f : 2.1f, + 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.36f : 0.26f + }); + } + SpawnSparkBurst(pos, normal, isRecoilless ? 6 : 4, new Color(1.0f, 0.64f, 0.20f, 0.98f), 14f); + if (!hasCam || pos.DistanceSquaredTo(camPos) <= 155f * 155f) + { + SpawnFlashLight(pos + normal * 0.45f, new Color(1.0f, 0.55f, 0.16f), isRecoilless ? 4.8f : 3.2f, isRecoilless ? 16f : 11f, 0.16f, priority: 7); + } + break; + } + + case WeaponVisualClass.ThermalBeam: + SpawnParticle(new ParticleSlot + { + Active = true, + Mode = ModeSteamFire, + Position = pos, + Velocity = normal * 1.4f, + StartSize = 0.65f, + EndSize = 1.85f, + 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.24f + }); + SpawnSparkBurst(pos, normal, 5, new Color(0.55f, 0.92f, 1.0f, 0.98f), 12f); + if (!hasCam || pos.DistanceSquaredTo(camPos) <= 135f * 135f) + { + SpawnFlashLight(pos + normal * 0.3f, new Color(0.45f, 0.90f, 1.0f), 3.2f, 10.5f, 0.12f, priority: 5); + } + break; + } + } + + private void EmitChassisExplosion( + Vector3 pos, + float massKg, + Vector3 camPos, + bool hasCam, + Func sampleGroundTint) + { + if (hasCam && pos.DistanceSquaredTo(camPos) > 220f * 220f) + { + return; + } + + float sizeScale = Math.Clamp(massKg / 2800f, 0.85f, 1.55f); + Color gTint = sampleGroundTint(pos.X, pos.Z); + + for (int i = 0; i < 5; 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.3f * sizeScale, + EndSize = 4.2f * 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.46f + NextFloat() * 0.22f + }); + } + + for (int i = 0; i < 6; 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.4f * sizeScale, + EndSize = 4.8f * 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.82f), + ColorEnd = new Color(0.10f, 0.10f, 0.10f, 0.0f), + Lifetime = 0.95f + NextFloat() * 0.45f + }); + } + + SpawnSparkBurst(pos, Vector3.Up, 8, new Color(1.0f, 0.68f, 0.22f, 0.98f), 17f); + SpawnFlashLight(pos + new Vector3(0f, 1.2f, 0f), new Color(1.0f, 0.56f, 0.14f), 6.2f, 22f, 0.22f, priority: 10); + } + + private void EmitImpactDustPlume(Vector3 pos, Vector3 normal, Color groundTint, int count, float size) + { + Color c0 = new(groundTint.R, groundTint.G, groundTint.B, 0.62f); + Color c1 = new(groundTint.R * 0.88f, groundTint.G * 0.88f, groundTint.B * 0.88f, 0.0f); + 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.42f, + EndSize = size * 1.35f, + AspectY = 1f, + Rotation = NextFloat() * MathF.Tau, + AngularVel = NextSigned() * 1.4f, + Emissive = 0f, + ColorStart = c0, + ColorEnd = c1, + Lifetime = 0.38f + NextFloat() * 0.20f + }); + } + } + + 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; + for (int i = 0; i < _flashLights.Length; i++) + { + if (!_flashLights[i].Active) + { + targetIdx = i; + break; + } + } + + if (targetIdx < 0) + { + int lowestPri = int.MaxValue; + float oldestAge = -1f; + for (int i = 0; i < _flashLights.Length; i++) + { + if (_flashLights[i].Priority < lowestPri || + (_flashLights[i].Priority == lowestPri && _flashLights[i].Age > oldestAge)) + { + lowestPri = _flashLights[i].Priority; + oldestAge = _flashLights[i].Age; + targetIdx = i; + } + } + if (targetIdx < 0 || lowestPri > priority) + { + return; + } + } + + ref FlashLightSlot slot = ref _flashLights[targetIdx]; + slot.Active = true; + slot.Priority = priority; + slot.Age = 0f; + slot.Duration = MathF.Max(0.04f, duration); + slot.StartEnergy = energy; + slot.Range = range; + slot.Color = color; + slot.Light.Position = pos; + slot.Light.LightColor = color; + slot.Light.OmniRange = range; + slot.Light.LightEnergy = energy; + slot.Light.Visible = true; + + int active = ActiveFlashLightCount; + if (active > PeakFlashLightCount) + { + 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/PomDecalPool.cs b/client/PomDecalPool.cs index 5099dbb..5d0cf3f 100644 --- a/client/PomDecalPool.cs +++ b/client/PomDecalPool.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using Godot; using RustToDust.Core; @@ -41,7 +42,6 @@ public partial class PomDecalPool : Node3D private readonly DecalSlot[] _slots = new DecalSlot[MaxDecals]; private int _writeCursor; - private long _lastProcessedHitId; private MatchState? _boundState; private MultiMesh _multiMesh = null!; @@ -110,7 +110,6 @@ public partial class PomDecalPool : Node3D { Array.Clear(_slots, 0, _slots.Length); _writeCursor = 0; - _lastProcessedHitId = 0; ActiveCount = 0; if (_multiMesh is not null) { @@ -119,8 +118,9 @@ public partial class PomDecalPool : Node3D } } - public void Sync( + public void ConsumeEvents( IClientArenaSession session, + IReadOnlyList events, float dt, Func getVisual) { @@ -132,16 +132,17 @@ public partial class PomDecalPool : Node3D ClearAll(); } - var hits = state.HitEvents; - for (int i = 0; i < hits.Count; i++) + for (int i = 0; i < events.Count; i++) { - var ev = hits[i]; - if (ev.EventId <= _lastProcessedHitId) + switch (events[i]) { - continue; + case MatchResetEvent: + ClearAll(); + break; + case HitImpactEvent hit: + StampHit(in hit, state, getVisual); + break; } - _lastProcessedHitId = ev.EventId; - StampHit(ev, state, getVisual); } UpdateAndCommit(dt); @@ -172,23 +173,25 @@ public partial class PomDecalPool : Node3D } private void StampHit( - in HitFeedbackEvent ev, + in HitImpactEvent ev, MatchState state, Func getVisual) { - if (ev.IsAirburst && ev.TargetKind == HitTargetKind.StaticCover && ev.TargetId < 0) + var targetKind = (HitTargetKind)ev.TargetKind; + var weaponClass = (WeaponVisualClass)ev.WeaponClass; + if (ev.IsAirburst && targetKind == HitTargetKind.StaticCover && ev.TargetId < 0) { return; } - bool isVehicle = ev.TargetKind == HitTargetKind.Contender || ev.TargetKind == HitTargetKind.Spectator; + bool isVehicle = targetKind == HitTargetKind.Contender || targetKind == HitTargetKind.Spectator; int tile; float size; float heat; float depth; float lifetime; - switch (ev.WeaponClass) + switch (weaponClass) { case WeaponVisualClass.ThermalBeam: tile = string.Equals(ev.WeaponId, "gilded_lance", StringComparison.Ordinal) || !isVehicle @@ -235,7 +238,7 @@ public partial class PomDecalPool : Node3D if (isVehicle) { - bool isContender = ev.TargetKind == HitTargetKind.Contender; + bool isContender = targetKind == HitTargetKind.Contender; VehicleVisualInstance? vis = getVisual(isContender, ev.TargetId); if (vis is null || !vis.Root.IsInsideTree() || !vis.Root.Visible) { diff --git a/client/SionMapRenderer.cs b/client/SionMapRenderer.cs index 70d0236..17ec55e 100644 --- a/client/SionMapRenderer.cs +++ b/client/SionMapRenderer.cs @@ -30,12 +30,17 @@ public partial class SionMapRenderer : Node3D public required MeshInstance3D Instance; } + private const int GroundTintGridSize = 128; + private static readonly Color NeutralAlpineDustTint = new(0.56f, 0.53f, 0.46f, 1.0f); + private readonly List _terrainChunks = new(36); private readonly List _buildingTiles = new(36); private readonly Dictionary _sharedBuildingMaterials = new(StringComparer.Ordinal); private string? _builtForDir; private ShaderMaterial? _terrainMat; private ImageTexture? _surfaceTex; + private Color[]? _groundTintGrid; + private float _groundTintSizeM; public bool IsBuilt { get; private set; } public int TerrainChunkCount => _terrainChunks.Count; @@ -132,6 +137,26 @@ public partial class SionMapRenderer : Node3D { throw new InvalidOperationException($"Failed to decode Sion terrain surface texture: {surfPath}"); } + + // Downsample CPU copy once for zero-readback terrain-tinted dust & impact plumes + var tintImg = (Image)img.Duplicate(); + tintImg.Resize(GroundTintGridSize, GroundTintGridSize, Image.Interpolation.Bilinear); + var grid = new Color[GroundTintGridSize * GroundTintGridSize]; + for (int y = 0; y < GroundTintGridSize; y++) + { + for (int x = 0; x < GroundTintGridSize; x++) + { + Color c = tintImg.GetPixel(x, y); + grid[y * GroundTintGridSize + x] = new Color( + Math.Clamp(c.R + 0.11f, 0.20f, 0.90f), + Math.Clamp(c.G + 0.11f, 0.20f, 0.88f), + Math.Clamp(c.B + 0.10f, 0.18f, 0.84f), + 1.0f); + } + } + _groundTintGrid = grid; + _groundTintSizeM = sion.Metadata.SizeMeters; + img.GenerateMipmaps(); _surfaceTex = ImageTexture.CreateFromImage(img); @@ -476,6 +501,39 @@ public partial class SionMapRenderer : Node3D return (defaultKey, defMat); } + public Color SampleGroundTint(float worldX, float worldZ) + { + Color[]? grid = _groundTintGrid; + float sizeM = _groundTintSizeM; + if (grid is null || sizeM <= 1f || !float.IsFinite(worldX) || !float.IsFinite(worldZ)) + { + return NeutralAlpineDustTint; + } + + float half = sizeM * 0.5f; + float u = (worldX + half) / sizeM; + float v = (worldZ + half) / sizeM; + if (u < 0f || u > 1f || v < 0f || v > 1f) + { + return NeutralAlpineDustTint; + } + + float fx = u * (GroundTintGridSize - 1); + float fy = v * (GroundTintGridSize - 1); + int x0 = Math.Clamp((int)MathF.Floor(fx), 0, GroundTintGridSize - 1); + int y0 = Math.Clamp((int)MathF.Floor(fy), 0, GroundTintGridSize - 1); + int x1 = Math.Min(x0 + 1, GroundTintGridSize - 1); + int y1 = Math.Min(y0 + 1, GroundTintGridSize - 1); + float tx = fx - x0; + float ty = fy - y0; + + Color c00 = grid[y0 * GroundTintGridSize + x0]; + Color c10 = grid[y0 * GroundTintGridSize + x1]; + Color c01 = grid[y1 * GroundTintGridSize + x0]; + Color c11 = grid[y1 * GroundTintGridSize + x1]; + return c00.Lerp(c10, tx).Lerp(c01.Lerp(c11, tx), ty); + } + private void ClearBuilt() { for (int i = 0; i < _terrainChunks.Count; i++) @@ -493,6 +551,8 @@ public partial class SionMapRenderer : Node3D _sharedBuildingMaterials.Clear(); _terrainMat = null; _surfaceTex = null; + _groundTintGrid = null; + _groundTintSizeM = 0f; _builtForDir = null; IsBuilt = false; ActiveLod1TileCount = 0; diff --git a/client/hud_vignette.gdshader b/client/hud_vignette.gdshader new file mode 100644 index 0000000..fbfaede --- /dev/null +++ b/client/hud_vignette.gdshader @@ -0,0 +1,32 @@ +shader_type canvas_item; +render_mode blend_mix; + +// OpenGL 3.3 (gl_compatibility) fullscreen combat vignette for damage impact, low core HP, and thermal overheat. +uniform float damage_pulse : hint_range(0.0, 1.0) = 0.0; +uniform float low_core_ratio : hint_range(0.0, 1.0) = 0.0; +uniform float overheat_pulse : hint_range(0.0, 1.0) = 0.0; +uniform float time_sec = 0.0; + +void fragment() { + vec2 p = UV * 2.0 - vec2(1.0); + float ellip_r = length(vec2(p.x * 0.88, p.y)); + float edge_mask = smoothstep(0.42, 1.18, ellip_r); + float tight_edge = smoothstep(0.68, 1.24, ellip_r); + + float low_heartbeat = low_core_ratio * (0.55 + 0.45 * sin(time_sec * 5.2)); + float red_strength = clamp(damage_pulse * 0.82 + low_heartbeat * 0.48, 0.0, 0.92); + + float thermal_wave = 0.72 + 0.28 * sin(time_sec * 11.0 + UV.y * 16.0); + float heat_strength = clamp(overheat_pulse * thermal_wave * 0.72, 0.0, 0.85); + + vec3 dmg_col = vec3(0.92, 0.14, 0.09); + vec3 heat_col = vec3(0.98, 0.50, 0.10); + + float dmg_a = edge_mask * red_strength * 0.58; + float heat_a = tight_edge * heat_strength * 0.52; + + float total_a = clamp(dmg_a + heat_a, 0.0, 0.78); + vec3 rgb = (dmg_col * dmg_a + heat_col * heat_a) / max(dmg_a + heat_a, 0.0001); + + COLOR = vec4(rgb, total_a); +} diff --git a/client/particle_billboard.gdshader b/client/particle_billboard.gdshader new file mode 100644 index 0000000..371d137 --- /dev/null +++ b/client/particle_billboard.gdshader @@ -0,0 +1,109 @@ +shader_type spatial; +render_mode unshaded, cull_disabled, blend_mix, depth_draw_never; + +// OpenGL 3.3 (gl_compatibility) 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 RGB tint + 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) { + vec2 i = floor(p); + vec2 f = fract(p); + vec2 u = f * f * (3.0 - 2.0 * f); + float a = hash21(i); + float b = hash21(i + vec2(1.0, 0.0)); + float c = hash21(i + vec2(0.0, 1.0)); + float d = hash21(i + vec2(1.0, 1.0)); + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); +} + +void vertex() { + v_color = COLOR; + 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 afea217..e769d14 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -1227,36 +1227,157 @@ public partial class Smoke : Node $"Expected zero StandardMaterial3D duplicates, got {VehicleVisualInstance.PerfMaterialDupCount}"); } - // 12. Finding 2: Monotonic TracerEvent.Id spawns muzzle flash + recoilless smoke puffs ONCE regardless of TTL or FPS + // 12. Cut 5d-2: Unified SimEvent -> ParticlePool idempotency + OmniLight3D[4] cap + CameraJuice zero-idle-jitter + Hud X-flash & vignette { - var tracers = _main.Session.ViewState.Tracers; - tracers.Clear(); - _main.Arena.Sync(_main.Session, 1.69f, 0f); - int vfxBefore = _main.Arena.TransientVfxCount; + var particles = _main.Arena.Particles; + particles.ClearAll(); + int beforeCount = particles.ActiveParticleCount; int tracerId = _main.Session.ViewState.AllocateTracerId(); var localC = _main.Session.LocalContender; Vector3 pPos = new(localC.X, localC.Y, localC.Z); - tracers.Add(new TracerEvent( - pPos.X, pPos.Y + 1f, pPos.Z, - pPos.X + 20f, pPos.Y + 1f, pPos.Z, - 0xFFEEDDAAu, - 0.03f, // Low TTL (< old 0.085f threshold) simulating <=30 FPS decay - WeaponVisualClass.Explosive, - "recoilless", - tracerId)); + var shotEvent = new ShotFiredEvent + { + TracerId = tracerId, + IsSpectatorShooter = false, + ShooterId = _main.Session.LocalContenderId, + StartX = pPos.X, + StartY = pPos.Y + 1f, + StartZ = pPos.Z, + EndX = pPos.X + 20f, + EndY = pPos.Y + 1f, + EndZ = pPos.Z, + ColorRgba = 0xFFEEDDAAu, + Ttl = 0.03f, + WeaponClass = (byte)WeaponVisualClass.Explosive, + WeaponId = "recoilless" + }; - _main.Arena.Sync(_main.Session, 1.70f, 0f); - int vfxAfterFirst = _main.Arena.TransientVfxCount; - Check(vfxAfterFirst == vfxBefore + 5 && _main.Arena.LastSpawnedTracerId == tracerId, - $"Expected recoilless tracer #{tracerId} with Ttl=0.03 to spawn 1 muzzle + 4 smoke puffs (+5 VFX), got +{vfxAfterFirst - vfxBefore} (lastId={_main.Arena.LastSpawnedTracerId})"); + 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}"); - // Re-sync with dt=0 (simulating >=60/120 FPS seeing the same TracerEvent again): must NOT re-emit - _main.Arena.Sync(_main.Session, 1.71f, 0f); - _main.Arena.Sync(_main.Session, 1.72f, 0f); - Check(_main.Arena.TransientVfxCount == vfxAfterFirst, - $"Expected same TracerEvent #{tracerId} across repeated render frames to spawn VFX once, got {vfxAfterFirst} -> {_main.Arena.TransientVfxCount}"); - tracers.Clear(); + // 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}"); + + // OmniLight3D[4] pool strictly capped at <= 4 active lights even under 12 simultaneous flashes + particles.ClearAll(); + for (int f = 0; f < 12; f++) + { + particles.TriggerFlashLightForTest( + pPos + new Vector3(f * 2f, 1.5f, 0f), + new Color(1f, 0.7f, 0.3f), + 3.0f, + 12f, + 0.15f, + priority: f); + } + particles.AdvanceAndCommit(0f); + Check(particles.FlashLightPoolSize == 4 && particles.ActiveFlashLightCount <= 4 && particles.PeakFlashLightCount <= 4, + $"Expected OmniLight3D pool capped at <= 4, got active={particles.ActiveFlashLightCount} peak={particles.PeakFlashLightCount}"); + + // Far walker footstep pulse (>70m static LOD, <=110m) still emits terrain-tinted dust in ParticlePool + particles.ClearAll(); + var farStep = new FootstepPulse( + IsContender: true, + EntityId: 99, + LegIndex: 0, + ChassisId: "bastion", + MassKg: 4600f, + 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}"); + particles.ClearAll(); + + // CameraJuiceState zero-idle-jitter & ComputeCenterScreenAim invariance under trauma + var juice = _main.CameraJuice; + juice.Reset(); + Check(juice.IsIdle, "Expected CameraJuiceState idle after Reset"); + var (aimIdleX, aimIdleY, aimIdleZ) = _main.ProbeCenterScreenAim(); + juice.ConsumeEvents(simBatch, _main.Session.LocalContenderId, new System.Numerics.Vector3(pPos.X, pPos.Y, pPos.Z)); + juice.Update(0.016f, 0f, false); + Check(!juice.IsIdle && juice.RecoilPitchRad > 0f, "Expected CameraJuiceState recoil after local recoilless shot"); + var (aimJuiceX, aimJuiceY, aimJuiceZ) = _main.ProbeCenterScreenAim(); + Check(MathF.Abs(aimIdleX - aimJuiceX) < 1e-4f && MathF.Abs(aimIdleY - aimJuiceY) < 1e-4f && MathF.Abs(aimIdleZ - aimJuiceZ) < 1e-4f, + "Expected ComputeCenterScreenAim to remain strictly invariant during camera recoil/trauma"); + juice.Reset(); + + // Hud reticle hit-marker X-flash + hud_vignette.gdshader falsification + _main.Hud.ResetFeedback(); + Check(!_main.Hud.HasActiveHitMarker && !_main.Hud.IsVignetteVisible, + "Expected HUD hit-marker & vignette inactive when cool and unhit"); + + // Non-local shooter must produce ZERO reticle hit-marker flash + var aiHit = new HitImpactEvent + { + EventId = 8801, + ShooterId = _main.Session.LocalContenderId + 1, + IsContenderShooter = true, + TargetKind = (byte)HitTargetKind.Contender, + TargetId = _main.Session.LocalContenderId + 2, + ArmorDamage = 18f, + CoreDamage = 0f, + Killed = false + }; + _main.Hud.ConsumeEvents(new ISimEvent[] { aiHit }, _main.Session.LocalContenderId, 1.0f, 0.2f); + Check(!_main.Hud.HasActiveHitMarker, "Expected AI/other shooter hit NOT to trigger local reticle hit-marker"); + + // Local armor hit -> Armor X-flash + var localArmorHit = new HitImpactEvent + { + EventId = 8802, + ShooterId = _main.Session.LocalContenderId, + IsContenderShooter = true, + TargetKind = (byte)HitTargetKind.Contender, + TargetId = _main.Session.LocalContenderId + 1, + ArmorDamage = 22f, + CoreDamage = 0f, + Killed = false + }; + _main.Hud.ConsumeEvents(new ISimEvent[] { localArmorHit }, _main.Session.LocalContenderId, 1.0f, 0.2f); + Check(_main.Hud.HasActiveHitMarker && _main.Hud.ActiveHitMarkerKind == HitMarkerKind.Armor, + $"Expected Armor hit-marker, got {_main.Hud.ActiveHitMarkerKind}"); + + // Local core hit -> Core X-flash + var localCoreHit = new HitImpactEvent + { + EventId = 8803, + ShooterId = _main.Session.LocalContenderId, + IsContenderShooter = true, + TargetKind = (byte)HitTargetKind.Contender, + TargetId = _main.Session.LocalContenderId + 1, + ArmorDamage = 10f, + CoreDamage = 14f, + Killed = false + }; + _main.Hud.ConsumeEvents(new ISimEvent[] { localCoreHit }, _main.Session.LocalContenderId, 1.0f, 0.2f); + Check(_main.Hud.HasActiveHitMarker && _main.Hud.ActiveHitMarkerKind == HitMarkerKind.Core, + $"Expected Core hit-marker, got {_main.Hud.ActiveHitMarkerKind}"); + + // Local kill + overheat -> Kill double-X + vignette active + var localKillHit = new HitImpactEvent + { + EventId = 8804, + ShooterId = _main.Session.LocalContenderId, + IsContenderShooter = true, + TargetKind = (byte)HitTargetKind.Contender, + TargetId = _main.Session.LocalContenderId + 1, + ArmorDamage = 0f, + CoreDamage = 35f, + Killed = true + }; + _main.Hud.ConsumeEvents(new ISimEvent[] { localKillHit }, _main.Session.LocalContenderId, 1.0f, 0.92f); + Check(_main.Hud.HasActiveHitMarker && _main.Hud.ActiveHitMarkerKind == HitMarkerKind.Kill && _main.Hud.IsVignetteVisible, + $"Expected Kill hit-marker & overheat vignette active, got kind={_main.Hud.ActiveHitMarkerKind} vig={_main.Hud.IsVignetteVisible}"); + _main.Hud.ResetFeedback(); } // 13. Loopback IClientArenaSession check: ServerMatchHost + RemoteArenaSession join + snapshot sync @@ -1655,7 +1776,15 @@ public partial class Smoke : Node float disp = MathF.Sqrt((player.X - startX) * (player.X - startX) + (player.Z - startZ) * (player.Z - startZ)); Check(disp > 1.5f, $"Expected player displacement > 1.5m on Sion after 30 frames, got {disp:F2}m"); - GD.Print($"SMOKE INFO: Sion verified (chunks={_main.SionMap.TerrainChunkCount}, tiles={_main.SionMap.BuildingTileCount}, lod1={_main.SionMap.ActiveLod1TileCount}, lod2={_main.SionMap.ActiveLod2TileCount}, disp={disp:F2}m)"); + + Color inBoundsTint = _main.SionMap.SampleGroundTint(player.X, player.Z); + Color outBoundsTint = _main.SionMap.SampleGroundTint(9999f, 9999f); + Check(float.IsFinite(inBoundsTint.R) && float.IsFinite(inBoundsTint.G) && float.IsFinite(inBoundsTint.B) && inBoundsTint.R > 0.1f, + $"Expected valid Sion SampleGroundTint at player pos, got {inBoundsTint}"); + Check(MathF.Abs(outBoundsTint.R - 0.56f) < 0.01f && MathF.Abs(outBoundsTint.G - 0.53f) < 0.01f, + $"Expected neutral alpine fallback tint outside Sion bounds, got {outBoundsTint}"); + + GD.Print($"SMOKE INFO: Sion verified (chunks={_main.SionMap.TerrainChunkCount}, tiles={_main.SionMap.BuildingTileCount}, lod1={_main.SionMap.ActiveLod1TileCount}, lod2={_main.SionMap.ActiveLod2TileCount}, disp={disp:F2}m, tint=({inBoundsTint.R:F2},{inBoundsTint.G:F2},{inBoundsTint.B:F2}))"); } private static int CountPremulViolations(Image img, float tolerance) diff --git a/tests/RustToDust.Tests/CameraJuiceTests.cs b/tests/RustToDust.Tests/CameraJuiceTests.cs new file mode 100644 index 0000000..c742cdd --- /dev/null +++ b/tests/RustToDust.Tests/CameraJuiceTests.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using RustToDust.Client; +using RustToDust.Core; +using Xunit; + +namespace RustToDust.Tests; + +public sealed class CameraJuiceTests +{ + [Fact] + public void CameraJuiceState_ZeroIdleJitter_AndMonotonicDecayToExactZero() + { + var juice = new CameraJuiceState(); + Assert.True(juice.IsIdle); + + for (int i = 0; i < 60; i++) + { + juice.Update(1f / 60f, localSpeedMps: 5f, isVtol: false); + juice.ComputeOffsets(out Vector3 off, out float pitch, out float yaw, out float roll); + Assert.True(juice.IsIdle); + Assert.Equal(Vector3.Zero, off); + Assert.Equal(0f, pitch); + Assert.Equal(0f, yaw); + Assert.Equal(0f, roll); + Assert.Equal(0f, juice.FovOffsetDeg); + } + + // Fire local recoilless shot + var events = new List + { + new ShotFiredEvent + { + TracerId = 1, + IsSpectatorShooter = false, + ShooterId = 0, + WeaponClass = (byte)WeaponVisualClass.Explosive, + WeaponId = "recoilless" + } + }; + juice.ConsumeEvents(events, localContenderId: 0, Vector3.Zero); + Assert.False(juice.IsIdle); + Assert.True(juice.RecoilPitchRad > 0f); + Assert.True(juice.RecoilBackMeters > 0f); + Assert.True(juice.Trauma > 0f); + + juice.ComputeOffsets(out Vector3 kickOff, out float kickPitch, out _, out _); + Assert.True(kickOff.Z > 0f); + Assert.True(kickPitch > 0f); + + // Decays monotonically back to exact zero + float prevPitch = juice.RecoilPitchRad; + for (int i = 0; i < 120; i++) + { + juice.Update(1f / 60f, localSpeedMps: 0f, isVtol: false); + Assert.True(juice.RecoilPitchRad <= prevPitch); + prevPitch = juice.RecoilPitchRad; + } + + Assert.True(juice.IsIdle); + juice.ComputeOffsets(out Vector3 settledOff, out float settledPitch, out float settledYaw, out float settledRoll); + Assert.Equal(Vector3.Zero, settledOff); + Assert.Equal(0f, settledPitch); + Assert.Equal(0f, settledYaw); + Assert.Equal(0f, settledRoll); + } + + [Fact] + public void CameraJuiceState_IgnoresRemoteShots_ClampsTrauma_AndResetsCleanly() + { + var juice = new CameraJuiceState(); + + // Remote contender or spectator shot must NOT kick local camera + var remoteEvents = new List + { + new ShotFiredEvent + { + TracerId = 10, + IsSpectatorShooter = false, + ShooterId = 3, + WeaponClass = (byte)WeaponVisualClass.Explosive, + WeaponId = "recoilless" + }, + new ShotFiredEvent + { + TracerId = 11, + IsSpectatorShooter = true, + ShooterId = 0, + WeaponClass = (byte)WeaponVisualClass.Explosive, + WeaponId = "recoilless" + } + }; + juice.ConsumeEvents(remoteEvents, localContenderId: 0, new Vector3(100f, 0f, 100f)); + Assert.True(juice.IsIdle); + + // Clamp trauma to [0, 1] + juice.AddTrauma(5.0f); + Assert.Equal(1.0f, juice.Trauma); + + // Footstep bump triggers only for local contender + var steps = new List + { + new(true, 2, 0, "bastion", 4600f, 1.2f, Vector3.Zero), + new(true, 0, 0, "bastion", 4600f, 1.2f, Vector3.Zero) + }; + juice.ConsumeFootsteps(steps, localContenderId: 0); + Assert.True(juice.FootstepBumpY < 0f); + + // Reset zeroes everything immediately + juice.Reset(); + Assert.True(juice.IsIdle); + Assert.Equal(0f, juice.Trauma); + Assert.Equal(0f, juice.FootstepBumpY); + Assert.Equal(0f, juice.FovOffsetDeg); + } +} diff --git a/tests/RustToDust.Tests/RustToDust.Tests.csproj b/tests/RustToDust.Tests/RustToDust.Tests.csproj index 4a60325..81797aa 100644 --- a/tests/RustToDust.Tests/RustToDust.Tests.csproj +++ b/tests/RustToDust.Tests/RustToDust.Tests.csproj @@ -16,6 +16,7 @@ +