From c2f1e5bf90d5343e0493facbb1c4662633ab795c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 5 Dec 2026 11:26:18 +0100 Subject: [PATCH] Cut 6a: headless orbital drop kinematics, hover-slam, wave respawns, and DropPodEvent net seam --- client/PomDecalPool.cs | 1 + client/tests/Smoke.cs | 3 + src/RustToDust.Core/Broadcast.cs | 13 +- src/RustToDust.Core/IClientArenaSession.cs | 3 + src/RustToDust.Core/MatchRules.cs | 44 +- src/RustToDust.Core/MatchState.cs | 206 ++- src/RustToDust.Core/OrbitalDropSystem.cs | 1435 +++++++++++++++++ src/RustToDust.Core/SimEvents.cs | 61 +- src/RustToDust.Core/SionMapLoader.cs | 30 + src/RustToDust.Net/ListenHostArenaSession.cs | 6 +- src/RustToDust.Net/RemoteArenaSession.cs | 73 +- src/RustToDust.Net/ServerMatchHost.cs | 108 +- src/RustToDust.Net/SnapshotCodec.cs | 36 +- src/RustToDust.Ymir/ArenaSession.cs | 369 ++++- src/RustToDust.Ymir/LocalArenaSession.cs | 10 +- tests/RustToDust.Tests/ArenaSessionTests.cs | 8 +- tests/RustToDust.Tests/AudioSynthTests.cs | 8 +- .../CultNetMultiplayerTests.cs | 2 +- .../MultiplayerSimulationTests.cs | 2 +- tests/RustToDust.Tests/OrbitalDropTests.cs | 586 +++++++ tests/RustToDust.Tests/PlaytestFixesTests.cs | 22 +- tests/RustToDust.Tests/SionMapTests.cs | 2 +- tests/RustToDust.Tests/TerrainTests.cs | 2 +- tests/RustToDust.Tests/VehiclePackageTests.cs | 7 +- tests/RustToDust.Tests/VtolAndArcTests.cs | 6 +- 25 files changed, 2928 insertions(+), 115 deletions(-) create mode 100644 src/RustToDust.Core/OrbitalDropSystem.cs create mode 100644 tests/RustToDust.Tests/OrbitalDropTests.cs diff --git a/client/PomDecalPool.cs b/client/PomDecalPool.cs index dfaa909..d97bc85 100644 --- a/client/PomDecalPool.cs +++ b/client/PomDecalPool.cs @@ -192,6 +192,7 @@ public partial class PomDecalPool : Node3D WorldXform = xf, DetachedFadeRemaining = -1f }); + UpdateAndCommit(0f); } private void StampHit( diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index 19d34da..0f04ab2 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -1967,6 +1967,9 @@ public partial class Smoke : Node public IReadOnlyDictionary LocalContenderContacts => _inner.LocalContenderContacts; public IReadOnlyDictionary LocalSpectatorContacts => _inner.LocalSpectatorContacts; public NetworkStatusSnapshot ConnectionStatus => _inner.ConnectionStatus; + public IReadOnlyList ActivePods => _inner.ActivePods; + public DropWaveState DropWaveState => _inner.DropWaveState; + public IReadOnlyList PodEvents => _inner.PodEvents; public bool IsContenderVisible(int contenderId) => contenderId == _inner.LocalContenderId; public bool IsSpectatorVisible(int spectatorId) => false; public void BeginRenderFrame(double dt, float physicsAlpha) => _inner.BeginRenderFrame(dt, physicsAlpha); diff --git a/src/RustToDust.Core/Broadcast.cs b/src/RustToDust.Core/Broadcast.cs index 193f0a1..d4ddd23 100644 --- a/src/RustToDust.Core/Broadcast.cs +++ b/src/RustToDust.Core/Broadcast.cs @@ -13,7 +13,8 @@ namespace RustToDust.Core QuickBolt, Overheat, Elimination, - Victory + Victory, + DropWave } public readonly record struct BroadcastLine(float Timestamp, BroadcastKind Kind, string Text); @@ -81,5 +82,15 @@ namespace RustToDust.Core public void EmitVictory(float timestamp, int winnerId, ArenaMapKind mapKind = ArenaMapKind.Desert) => Emit(timestamp, BroadcastKind.Victory, $"Contender {winnerId + 1:00} {(mapKind == ArenaMapKind.Sion ? "outlasts the alpine ring" : "outlasts the dust")} and the gallery's patience. Broadcast closes with reluctant applause."); + + public void EmitDropWave(float timestamp, int waveIndex, int gearCount, int respawnCount, bool respawnsClosed) + { + string line = waveIndex == 0 + ? $"Orbital insertion underway: {gearCount} Imperial salvage pods and 12 contender drop capsules inbound." + : respawnsClosed + ? $"Patron Drop Wave {waveIndex}: {gearCount} high-tier salvage pods inbound. Final-ring cutoff reached — redeployments closed." + : $"Patron Drop Wave {waveIndex}: {gearCount} Imperial salvage pods and {respawnCount} redeployed contender(s) inbound."; + Emit(timestamp, BroadcastKind.DropWave, line); + } } } diff --git a/src/RustToDust.Core/IClientArenaSession.cs b/src/RustToDust.Core/IClientArenaSession.cs index 1d1a449..0ad5b7e 100644 --- a/src/RustToDust.Core/IClientArenaSession.cs +++ b/src/RustToDust.Core/IClientArenaSession.cs @@ -44,6 +44,9 @@ namespace RustToDust.Core IReadOnlyDictionary LocalContenderContacts { get; } IReadOnlyDictionary LocalSpectatorContacts { get; } NetworkStatusSnapshot ConnectionStatus { get; } + IReadOnlyList ActivePods { get; } + DropWaveState DropWaveState { get; } + IReadOnlyList PodEvents { get; } bool IsContenderVisible(int contenderId); bool IsSpectatorVisible(int spectatorId); diff --git a/src/RustToDust.Core/MatchRules.cs b/src/RustToDust.Core/MatchRules.cs index f9f2ec2..af11df2 100644 --- a/src/RustToDust.Core/MatchRules.cs +++ b/src/RustToDust.Core/MatchRules.cs @@ -270,6 +270,20 @@ namespace RustToDust.Core return; } + if (human.IsInDropPod) + { + human.ThrottleCmd = Math.Clamp(input.Throttle, -1f, 1f); + human.SteerCmd = Math.Clamp(input.Steer, -1f, 1f); + human.VerticalThrottleCmd = 0f; + human.AimX = float.IsFinite(input.AimWorldX) ? input.AimWorldX : human.AimX; + human.AimY = float.IsFinite(input.AimWorldY) ? input.AimWorldY : float.NaN; + human.AimZ = float.IsFinite(input.AimWorldZ) ? input.AimWorldZ : human.AimZ; + human.FireCmd = false; + human.BrakeCmd = false; + state.OrbitalDrop.ApplyPlayerSteerInput(human); + return; + } + human.ThrottleCmd = Math.Clamp(input.Throttle, -1f, 1f); human.SteerCmd = Math.Clamp(input.Steer, -1f, 1f); human.VerticalThrottleCmd = Math.Clamp(input.VerticalThrottle, -1f, 1f); @@ -292,7 +306,17 @@ namespace RustToDust.Core for (int i = 0; i < state.Contenders.Count; i++) { var ai = state.Contenders[i]; - if (ai.IsHuman || !ai.Alive) + if (ai.IsHuman) + { + continue; + } + if (ai.IsInDropPod) + { + ai.FireCmd = false; + state.OrbitalDrop.UpdateAiPodSteering(ai); + continue; + } + if (!ai.IsGroundedActive) { continue; } @@ -320,7 +344,7 @@ namespace RustToDust.Core for (int j = 0; j < state.Contenders.Count; j++) { var other = state.Contenders[j]; - if (other.Id == ai.Id || !other.Alive) + if (other.Id == ai.Id || !other.IsGroundedActive) { continue; } @@ -816,18 +840,28 @@ namespace RustToDust.Core return; } + state.OrbitalDrop.CheckFinalRingCutoff(); + + bool canRespawn = state.OrbitalDrop.CanAnyWaitingContenderRespawn(); int aliveCount = 0; + int waitingCount = 0; ContenderState? survivor = null; + for (int i = 0; i < state.Contenders.Count; i++) { - if (state.Contenders[i].Alive) + var c = state.Contenders[i]; + if (c.Alive) { aliveCount++; - survivor = state.Contenders[i]; + survivor = c; + } + else if (c.WaitingForRespawn && canRespawn) + { + waitingCount++; } } - if (aliveCount <= 1) + if (aliveCount + waitingCount <= 1) { state.Phase = MatchPhase.Completed; state.WinnerContenderId = survivor?.Id; diff --git a/src/RustToDust.Core/MatchState.cs b/src/RustToDust.Core/MatchState.cs index 283dec4..bff4569 100644 --- a/src/RustToDust.Core/MatchState.cs +++ b/src/RustToDust.Core/MatchState.cs @@ -162,7 +162,12 @@ namespace RustToDust.Core public int Id { get; } public string Name { get; set; } public bool IsHuman { get; set; } - public ChassisGrid Grid { get; } + public ChassisGrid Grid { get; set; } + public ContenderLifecycle Lifecycle { get; set; } = ContenderLifecycle.Active; + public int RespawnsRemaining { get; set; } = 1; + public int? ActivePodId { get; set; } + public bool HasTouchdownPose { get; set; } + public bool TouchdownOnRoof { get; set; } public int LoadoutVersion { get; set; } = 1; public int DamageVersion { get; set; } = 1; public float MaxThermalRatio { get; set; } @@ -206,7 +211,47 @@ namespace RustToDust.Core public int InArcWeaponCount { get; set; } public int DisabledWeaponCount { get; set; } - public bool Alive => !Grid.IsDestroyed; + public bool IsInDropPod => Lifecycle == ContenderLifecycle.Deploying; + public bool IsGroundedActive => Lifecycle == ContenderLifecycle.Active && !Grid.IsDestroyed; + public bool WaitingForRespawn => Lifecycle == ContenderLifecycle.WaitingForRespawnWave; + public bool Alive => !Grid.IsDestroyed && (Lifecycle == ContenderLifecycle.Active || Lifecycle == ContenderLifecycle.Deploying); + + public void ResetForRedrop(ChassisGrid grid, float x, float y, float z, float yaw) + { + Grid = grid; + X = x; + Y = y; + Z = z; + Yaw = yaw; + VelX = 0f; + VelY = 0f; + VelZ = 0f; + Speed = 0f; + ThrottleCmd = 0f; + SteerCmd = 0f; + VerticalThrottleCmd = 0f; + TargetHoverAltAgl = grid.Spec.IsVtol ? 10.0f : 3.0f; + FireCmd = false; + BrakeCmd = false; + OverheatWarned = false; + MaxThermalRatio = 0f; + AllWeaponsOutOfArc = false; + OutOfArcWeaponCount = 0; + InArcWeaponCount = 0; + DisabledWeaponCount = 0; + HasTouchdownPose = false; + TouchdownOnRoof = false; + Lifecycle = ContenderLifecycle.Deploying; + LoadoutVersion++; + DamageVersion++; + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw); + CurrRotX = q.X; + CurrRotY = q.Y; + CurrRotZ = q.Z; + CurrRotW = q.W; + SnapPreviousPose(); + ResetAimTracker(yaw); + } public void SnapPreviousPose() { @@ -245,13 +290,15 @@ namespace RustToDust.Core private long _nextHitEventId = 1; private int _nextTracerId = 1; - public MatchState(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert) + public MatchState(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool skipInitialDrop = false) { Seed = seed; MapKind = mapKind; Rng = new Random(seed); Broadcast = new BroadcastFeed(); + OrbitalDrop = new OrbitalDropSystem(this); + List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> lootTargets; if (mapKind == ArenaMapKind.Sion) { SionMap = SionMapLoader.Load(); @@ -275,7 +322,7 @@ namespace RustToDust.Core SionMap.Metadata.MaxY + 140f); SeatSpectatorsOnSion(); SpawnContendersSion(); - ScatterInitialLootSion(); + lootTargets = BuildInitialLootTargetsSion(); } else { @@ -285,7 +332,31 @@ namespace RustToDust.Core ArenaCoverBoxes = SeatBoxesOnTerrain(rawCover, Terrain); ArenaBoundaryBoxes = BuildBoundaryBoxes(ArenaHalfExtent, -48f, 72f); SpawnContenders(); - ScatterInitialLoot(); + lootTargets = BuildInitialLootTargetsDesert(); + } + + if (skipInitialDrop) + { + for (int i = 0; i < Contenders.Count; i++) + { + Contenders[i].Lifecycle = ContenderLifecycle.Active; + } + for (int i = 0; i < lootTargets.Count; i++) + { + var t = lootTargets[i]; + if (t.Chassis is not null) SpawnChassisDrop(t.X, t.Z, t.Chassis); + else if (t.Module is not null) SpawnModuleDrop(t.X, t.Z, t.Module); + } + } + else + { + var contenderTargets = new List<(int ContenderId, float X, float Z, float Yaw)>(Contenders.Count); + for (int i = 0; i < Contenders.Count; i++) + { + var c = Contenders[i]; + contenderTargets.Add((c.Id, c.X, c.Z, c.Yaw)); + } + OrbitalDrop.BeginWave0(contenderTargets, lootTargets, DefaultDropSurfaceQuery); } Broadcast.EmitMatchStart(0f, mapKind); @@ -306,6 +377,8 @@ namespace RustToDust.Core public List Tracers { get; } = new(); public List HitEvents { get; } = new(); public BroadcastFeed Broadcast { get; } + public OrbitalDropSystem OrbitalDrop { get; } + public List PodEvents { get; } = new(); public IReadOnlyList ArenaCoverBoxes { get; } public IReadOnlyList ArenaBoundaryBoxes { get; } @@ -320,6 +393,11 @@ namespace RustToDust.Core public event Action? LoadoutChanged; public event Action? DropSpawned; public event Action? DropPickedUp; + public event Action? ContenderPodTouchedDown; + public event Action? ContenderRespawned; + + internal void NotifyContenderPodTouchedDown(ContenderState c) => ContenderPodTouchedDown?.Invoke(c); + internal void NotifyContenderRespawned(ContenderState c) => ContenderRespawned?.Invoke(c); public long AllocateHitEventId() => _nextHitEventId++; public int AllocateTracerId() => _nextTracerId++; @@ -402,7 +480,7 @@ namespace RustToDust.Core } var contender = Contenders[contenderId]; - if (!contender.Alive) + if (!contender.IsGroundedActive) { return false; } @@ -431,7 +509,7 @@ namespace RustToDust.Core } var contender = Contenders[contenderId]; - if (!contender.Alive) + if (!contender.IsGroundedActive) { return null; } @@ -488,7 +566,7 @@ namespace RustToDust.Core } var contender = Contenders[contenderId]; - if (!contender.Alive) + if (!contender.IsGroundedActive) { return false; } @@ -525,7 +603,7 @@ namespace RustToDust.Core } var contender = Contenders[contenderId]; - if (!contender.Alive) + if (!contender.IsGroundedActive) { return false; } @@ -853,8 +931,9 @@ namespace RustToDust.Core } } - private void ScatterInitialLoot() + private List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> BuildInitialLootTargetsDesert() { + var targets = new List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)>(40); // 14 deterministic salvageable chassis wrecks covering all non-starter vehicles in the 15-vehicle roster var chassisPool = new List(Catalog.AllChassis.Count); for (int i = 0; i < Catalog.AllChassis.Count; i++) @@ -870,7 +949,8 @@ namespace RustToDust.Core { float angle = (i / (float)chassisPool.Count) * MathF.Tau + 0.35f; float r = i >= chassisPool.Count - 3 ? (55f + (i % 3) * 18f) : (135f + (i % 4) * 85f); - SpawnChassisDrop(MathF.Cos(angle) * r, MathF.Sin(angle) * r, chassisPool[i]); + var (dx, dz) = FindClearDropPoint(MathF.Cos(angle) * r, MathF.Sin(angle) * r, 3.5f); + targets.Add((dx, dz, chassisPool[i], null)); } // 26 ground salvage module drops spread across canyons, passes, and ruins (including 1x1 Wide-Arc PD!) @@ -889,8 +969,10 @@ namespace RustToDust.Core { float angle = (i / (float)salvagePool.Length) * MathF.Tau + 0.19f; float r = 75f + (i % 5) * 95f; - SpawnModuleDrop(MathF.Cos(angle) * r, MathF.Sin(angle) * r, salvagePool[i]); + var (mx, mz) = FindClearDropPoint(MathF.Cos(angle) * r, MathF.Sin(angle) * r, 2.5f); + targets.Add((mx, mz, null, salvagePool[i])); } + return targets; } private static IReadOnlyList BuildCoverBoxes() @@ -1106,8 +1188,9 @@ namespace RustToDust.Core } } - private void ScatterInitialLootSion() + private List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> BuildInitialLootTargetsSion() { + var targets = new List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)>(40); var chassisPool = new List(Catalog.AllChassis.Count); for (int i = 0; i < Catalog.AllChassis.Count; i++) { @@ -1151,7 +1234,7 @@ namespace RustToDust.Core candZ = MathF.Sin(angle) * r; } (float dx, float dz) = FindClearSionPoint(candX, candZ, pad, minNy: 0.84f, maxSearchRadius: 240f); - SpawnChassisDrop(dx, dz, chassisPool[i]); + targets.Add((dx, dz, chassisPool[i], null)); } ModuleSpec[] salvagePool = @@ -1193,8 +1276,101 @@ namespace RustToDust.Core candZ = MathF.Sin(angle) * r; } (float mx, float mz) = FindClearSionPoint(candX, candZ, pad: 2.5f, minNy: 0.84f, maxSearchRadius: 220f); - SpawnModuleDrop(mx, mz, salvagePool[i]); + targets.Add((mx, mz, null, salvagePool[i])); } + return targets; + } + + public DropSurfaceSample DefaultDropSurfaceQuery(float x, float z, float footRadius, float referenceMaxY) + { + float terrainY = Terrain.SampleHeight(x, z); + var (nx, ny, nz) = Terrain.SampleNormal(x, z); + Vector3 normal = new(nx, ny, nz); + if (normal.LengthSquared() < 1e-4f) normal = Vector3.UnitY; + else normal = Vector3.Normalize(normal); + + if (SionMap is not null && SionMap.TryGetBuildingAt(x, z, footRadius, out var bldg)) + { + bool insideExact = SionMap.TryGetBuildingAt(x, z, 0f, out var exactBldg); + float roofY = insideExact ? exactBldg.RoofY : bldg.RoofY; + if (roofY <= referenceMaxY && roofY > terrainY + 0.25f) + { + bool flat = bldg.Class == "Gebaeude Einzelhaus" + ? (bldg.HalfX >= footRadius + 2.2f && bldg.HalfZ >= footRadius + 2.2f) + : false; + return new DropSurfaceSample( + roofY, + Vector3.UnitY, + IsBuildingRoof: true, + IsFlatRoofValid: flat, + IsInsideBuildingFootprint: true); + } + return new DropSurfaceSample( + MathF.Max(terrainY, bldg.RoofY), + normal, + IsBuildingRoof: true, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: true); + } + + if (ArenaCoverBoxes.Count > 0) + { + for (int i = 0; i < ArenaCoverBoxes.Count; i++) + { + var box = ArenaCoverBoxes[i]; + if (MathF.Abs(x - box.X) <= box.HalfX + footRadius && + MathF.Abs(z - box.Z) <= box.HalfZ + footRadius) + { + float topY = box.Y + box.HalfY; + if (topY <= referenceMaxY) + { + return new DropSurfaceSample( + MathF.Max(terrainY, topY), + Vector3.UnitY, + IsBuildingRoof: false, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: true); + } + } + } + } + + return new DropSurfaceSample( + terrainY, + normal, + IsBuildingRoof: false, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: false); + } + + public (float X, float Z) FindClearDropPoint(float targetX, float targetZ, float pad) + { + if (MapKind == ArenaMapKind.Sion && SionMap is not null) + { + return FindClearSionPoint(targetX, targetZ, pad, minNy: 0.72f, maxSearchRadius: 260f); + } + + float maxB = Terrain.MapHalfExtent - 28f; + float bx = Math.Clamp(targetX, -maxB, maxB); + float bz = Math.Clamp(targetZ, -maxB, maxB); + if (!IsNearCoverBox(bx, bz, pad)) + { + return (bx, bz); + } + for (float r = 6f; r <= 60f; r += 6f) + { + for (int a = 0; a < 12; a++) + { + float ang = (a / 12f) * MathF.Tau; + float cx = Math.Clamp(bx + MathF.Cos(ang) * r, -maxB, maxB); + float cz = Math.Clamp(bz + MathF.Sin(ang) * r, -maxB, maxB); + if (!IsNearCoverBox(cx, cz, pad)) + { + return (cx, cz); + } + } + } + return (bx, bz); } private (float X, float Z) FindClearSionPoint( diff --git a/src/RustToDust.Core/OrbitalDropSystem.cs b/src/RustToDust.Core/OrbitalDropSystem.cs new file mode 100644 index 0000000..4158cc9 --- /dev/null +++ b/src/RustToDust.Core/OrbitalDropSystem.cs @@ -0,0 +1,1435 @@ +using System; +using System.Collections.Generic; +using System.Numerics; + +namespace RustToDust.Core +{ + public enum ContenderLifecycle : byte + { + Deploying = 0, + Active = 1, + WaitingForRespawnWave = 2, + Eliminated = 3 + } + + public enum OrbitalPodKind : byte + { + Contender = 0, + Chassis = 1, + Module = 2 + } + + public enum OrbitalPodPhase : byte + { + Freefall = 0, + RetroBurn = 1, + Popped = 2 + } + + public readonly record struct DropSurfaceSample( + float SurfaceY, + Vector3 Normal, + bool IsBuildingRoof, + bool IsFlatRoofValid, + bool IsInsideBuildingFootprint); + + public delegate DropSurfaceSample DropSurfaceQuery(float x, float z, float footRadius, float referenceMaxY); + + public delegate (float X, float Z) DropClearPointQuery(float x, float z, float pad); + + public readonly record struct DropPodLifecycleEvent( + long EventId, + DropPodEventKind Kind, + int WaveIndex, + int PodId, + OrbitalPodKind PodKind, + int ContenderId, + float X, + float Y, + float Z, + float VelX, + float VelY, + float VelZ, + Vector3 SurfaceNormal, + string? ChassisId, + string? ModuleId, + int DropId, + bool RespawnsClosed, + int GearCount, + int RespawnCount); + + public readonly record struct DropWaveState( + int CurrentWaveIndex, + int NextWaveIndex, + float? NextWaveAtSec, + bool RespawnCutoffReached, + int ActivePodCount, + int WaitingRespawnCount); + + public static class DropWaveConfig + { + public static readonly float[] WaveTimes = { 0f, 75f, 155f, 235f }; + public const int MaxRespawnWave = 2; + public const float SionCutoffRadius = 580f; + public const float DesertCutoffRadius = 260f; + public const float Gravity = 20.0f; + + public static float GetCutoffRadius(ArenaMapKind mapKind) => + mapKind == ArenaMapKind.Sion ? SionCutoffRadius : DesertCutoffRadius; + } + + public readonly record struct OrbitalPodPreset( + float StartAltAgl, + float InitialVelY, + float TerminalSpeed, + float NominalRetroAccel, + float TargetTouchdownSpeed, + float SteerAccel, + float FreefallHorizDrag, + float BurnHorizDrag, + float PodFootRadius, + float SafetyMarginM) + { + public static readonly OrbitalPodPreset Contender = new( + StartAltAgl: 410f, + InitialVelY: -28.0f, + TerminalSpeed: 78.0f, + NominalRetroAccel: 105.0f, + TargetTouchdownSpeed: 2.2f, + SteerAccel: 28.0f, + FreefallHorizDrag: 0.90f, + BurnHorizDrag: 4.5f, + PodFootRadius: 1.65f, + SafetyMarginM: 4.0f); + + public static readonly OrbitalPodPreset Gear = new( + StartAltAgl: 260f, + InitialVelY: -52.0f, + TerminalSpeed: 90.0f, + NominalRetroAccel: 140.0f, + TargetTouchdownSpeed: 2.2f, + SteerAccel: 0f, + FreefallHorizDrag: 0.90f, + BurnHorizDrag: 4.5f, + PodFootRadius: 1.1f, + SafetyMarginM: 3.5f); + } + + public sealed class OrbitalPod + { + public int PodId { get; set; } + public OrbitalPodKind PodKind { get; set; } + public OrbitalPodPhase Phase { get; set; } = OrbitalPodPhase.Freefall; + public int WaveIndex { get; set; } + public int ContenderId { get; set; } = -1; + public ChassisSpec? Chassis { get; set; } + public ModuleSpec? Module { get; set; } + public bool AllowFlatRoofLanding { get; set; } + + public float TargetX { get; set; } + public float TargetZ { get; set; } + + // Y is the pod base (bottom) world Y (minY == 0 in GLB). + public float X { get; set; } + public float Y { get; set; } + public float Z { get; set; } + public float PrevX { get; set; } + public float PrevY { get; set; } + public float PrevZ { get; set; } + + public float VelX { get; set; } + public float VelY { get; set; } + public float VelZ { get; set; } + public float Yaw { get; set; } + + public float CurrRotX { get; set; } + public float CurrRotY { get; set; } + public float CurrRotZ { get; set; } + public float CurrRotW { get; set; } = 1f; + public float PrevRotX { get; set; } + public float PrevRotY { get; set; } + public float PrevRotZ { get; set; } + public float PrevRotW { get; set; } = 1f; + + public float SteerForwardCmd { get; set; } + public float SteerRightCmd { get; set; } + public float LookForwardX { get; set; } + public float LookForwardZ { get; set; } = 1f; + + public float LaunchTime { get; set; } + public float FlightTime { get; set; } + public float BurnElapsed { get; set; } + public float HeatGlow { get; set; } + public float Scorch { get; set; } + public float LastAgl { get; set; } + + public Vector3 TouchdownNormal { get; set; } = Vector3.UnitY; + public float TouchdownSpeed { get; set; } + public bool TouchdownOnRoof { get; set; } + public int GroundDropId { get; set; } + + public void SnapPreviousPose() + { + PrevX = X; + PrevY = Y; + PrevZ = Z; + PrevRotX = CurrRotX; + PrevRotY = CurrRotY; + PrevRotZ = CurrRotZ; + PrevRotW = CurrRotW; + } + } + + public static class OrbitalDropKinematics + { + public static OrbitalPodPreset GetPreset(OrbitalPodKind kind) => + kind == OrbitalPodKind.Contender ? OrbitalPodPreset.Contender : OrbitalPodPreset.Gear; + + public static bool StepPod( + OrbitalPod pod, + float dt, + TerrainField terrain, + DropSurfaceQuery surfaceQuery, + DropClearPointQuery findClearPoint, + out bool retroBurnStarted, + out DropSurfaceSample touchdownSample) + { + retroBurnStarted = false; + touchdownSample = default; + + if (pod.Phase == OrbitalPodPhase.Popped) + { + return false; + } + + var preset = GetPreset(pod.PodKind); + float maxBound = MathF.Max(16f, terrain.MapHalfExtent - 10f); + float g = DropWaveConfig.Gravity; + float aNetNom = MathF.Max(10f, preset.NominalRetroAccel - g); + float vTouch = preset.TargetTouchdownSpeed; + + pod.FlightTime += dt; + + // 1. Surface & slope query + DropSurfaceSample sampleNow = surfaceQuery(pod.X, pod.Z, preset.PodFootRadius, pod.Y + 1.0f); + float terrainNow = terrain.SampleHeight(pod.X, pod.Z); + float terrainAhead = MathF.Max( + terrainNow, + terrain.SampleHeight(pod.X + pod.VelX * 0.28f, pod.Z + pod.VelZ * 0.28f)); + + float surfaceNow = sampleNow.IsBuildingRoof + ? MathF.Max(terrainNow, sampleNow.SurfaceY) + : terrainNow; + + float hAgl = pod.Y - surfaceNow; + float hEff = pod.Y - MathF.Max(surfaceNow, terrainAhead); + pod.LastAgl = MathF.Max(0f, hAgl); + + // 2. Horizontal steering & building wall/roof safety (computed first so surfaceRiseRate sees horizontal motion) + float vxNext = pod.VelX; + float vzNext = pod.VelZ; + + if (pod.Phase == OrbitalPodPhase.Freefall && preset.SteerAccel > 0f) + { + Vector2 fwd = new(pod.LookForwardX, pod.LookForwardZ); + if (fwd.LengthSquared() < 1e-4f) + { + fwd = new Vector2(MathF.Sin(pod.Yaw), MathF.Cos(pod.Yaw)); + } + else + { + fwd = Vector2.Normalize(fwd); + } + Vector2 right = new(-fwd.Y, fwd.X); + Vector2 wish = fwd * pod.SteerForwardCmd + right * pod.SteerRightCmd; + float wishLen = wish.Length(); + if (wishLen > 1f) + { + wish /= wishLen; + } + + vxNext += (wish.X * preset.SteerAccel - pod.VelX * preset.FreefallHorizDrag) * dt; + vzNext += (wish.Y * preset.SteerAccel - pod.VelZ * preset.FreefallHorizDrag) * dt; + } + else + { + vxNext += (-pod.VelX * preset.BurnHorizDrag) * dt; + vzNext += (-pod.VelZ * preset.BurnHorizDrag) * dt; + } + + // Roof / building deflection when over an invalid landing spot (start early at < 85m above terrain so gear/AI clear roofs before retro-burn) + bool invalidRoofOrBuilding = + (sampleNow.IsInsideBuildingFootprint || sampleNow.IsBuildingRoof) && + !(pod.AllowFlatRoofLanding && sampleNow.IsFlatRoofValid); + if ((hAgl < 55f || (pod.Y - terrainNow) < 85f) && invalidRoofOrBuilding) + { + var (clearX, clearZ) = findClearPoint(pod.X, pod.Z, preset.PodFootRadius + 1.5f); + float dx = clearX - pod.X; + float dz = clearZ - pod.Z; + float dist = MathF.Sqrt(dx * dx + dz * dz); + if (dist > 0.1f) + { + float maxPull = hAgl < 12f ? 14f : 28f; + float pullSpeed = Math.Clamp(dist * 3.5f, 10f, maxPull); + vxNext = (dx / dist) * pullSpeed; + vzNext = (dz / dist) * pullSpeed; + } + } + + float xCand = Math.Clamp(pod.X + vxNext * dt, -maxBound, maxBound); + float zCand = Math.Clamp(pod.Z + vzNext * dt, -maxBound, maxBound); + + // Lateral Building Wall Guard: prevent horizontal entry into building walls during descent + DropSurfaceSample sampleNext = surfaceQuery(xCand, zCand, preset.PodFootRadius, pod.Y + 1.0f); + if (sampleNext.SurfaceY > pod.Y - 0.5f && sampleNow.SurfaceY <= pod.Y - 0.5f) + { + DropSurfaceSample slideX = surfaceQuery(xCand, pod.Z, preset.PodFootRadius, pod.Y + 1.0f); + DropSurfaceSample slideZ = surfaceQuery(pod.X, zCand, preset.PodFootRadius, pod.Y + 1.0f); + if (slideX.SurfaceY <= pod.Y - 0.5f) + { + zCand = pod.Z; + vzNext = 0f; + sampleNext = slideX; + } + else if (slideZ.SurfaceY <= pod.Y - 0.5f) + { + xCand = pod.X; + vxNext = 0f; + sampleNext = slideZ; + } + else + { + xCand = pod.X; + zCand = pod.Z; + vxNext = 0f; + vzNext = 0f; + sampleNext = sampleNow; + } + } + + float terrainNext = terrain.SampleHeight(xCand, zCand); + float surfaceNext = sampleNext.IsBuildingRoof + ? MathF.Max(terrainNext, sampleNext.SurfaceY) + : terrainNext; + + // 3. Closing speed & burn trigger (accounts for both terrain slope and surface step) + float vDown = MathF.Max(0f, -pod.VelY); + float surfaceRiseRate = MathF.Max(0f, (surfaceNext - surfaceNow) / dt); + float vClose = vDown + surfaceRiseRate; + float hBurn = MathF.Max( + 8.0f, + MathF.Max(0f, vClose * vClose - vTouch * vTouch) / (2f * aNetNom) + preset.SafetyMarginM); + + if (pod.Phase == OrbitalPodPhase.Freefall && hEff <= hBurn) + { + pod.Phase = OrbitalPodPhase.RetroBurn; + retroBurnStarted = true; + } + + // 4. Vertical dynamics (exact closed-form hover-slam) + float vyNext; + if (pod.Phase == OrbitalPodPhase.Freefall) + { + float kAir = g / (preset.TerminalSpeed * preset.TerminalSpeed); + // VelY < 0 while falling, so -kAir * VelY * |VelY| > 0 (upward drag resisting fall) + float ay = -g - kAir * pod.VelY * MathF.Abs(pod.VelY); + vyNext = pod.VelY + ay * dt; + float speedFrac = Math.Clamp(MathF.Abs(vyNext) / preset.TerminalSpeed, 0f, 1f); + pod.HeatGlow = MathF.Max(pod.HeatGlow * 0.96f, speedFrac * 0.85f); + pod.Scorch = MathF.Min(0.45f, pod.Scorch + speedFrac * 0.08f * dt); + } + else + { + pod.BurnElapsed += dt; + float dRem = MathF.Max(0.05f, pod.Y - surfaceNext); + float aNetReq = (vClose * vClose - vTouch * vTouch) / (2f * dRem); + + float aNet; + if (vClose <= vTouch) + { + aNet = dRem > 3.5f ? -g * 0.6f : 0f; + } + else + { + aNet = Math.Clamp(aNetReq, 0f, 380f); + } + + vyNext = pod.VelY + aNet * dt; + if (dRem < 12f && vyNext > -vTouch) + { + vyNext = -vTouch; + } + + pod.HeatGlow = 1.0f; + pod.Scorch = MathF.Min(0.75f, pod.Scorch + 0.45f * dt); + } + + float yCand = pod.Y + vyNext * dt; + + // Tilt pod subtly into horizontal motion during freefall, snap upright in retro-burn + float tiltX = pod.Phase == OrbitalPodPhase.Freefall ? Math.Clamp(vzNext * 0.008f, -0.22f, 0.22f) : 0f; + float tiltZ = pod.Phase == OrbitalPodPhase.Freefall ? Math.Clamp(-vxNext * 0.008f, -0.22f, 0.22f) : 0f; + Quaternion qPod = Quaternion.CreateFromYawPitchRoll(pod.Yaw, tiltX, tiltZ); + pod.CurrRotX = qPod.X; + pod.CurrRotY = qPod.Y; + pod.CurrRotZ = qPod.Z; + pod.CurrRotW = qPod.W; + + pod.X = xCand; + pod.Z = zCand; + pod.VelX = vxNext; + pod.VelZ = vzNext; + + if (yCand <= surfaceNext) + { + // Guarantee 0 building-interior / invalid-roof touchdowns + bool touchInvalidBuilding = + (sampleNext.IsInsideBuildingFootprint || sampleNext.IsBuildingRoof) && + !(pod.AllowFlatRoofLanding && sampleNext.IsFlatRoofValid); + if (touchInvalidBuilding) + { + var (clearX, clearZ) = findClearPoint(pod.X, pod.Z, preset.PodFootRadius + 1.5f); + pod.X = Math.Clamp(clearX, -maxBound, maxBound); + pod.Z = Math.Clamp(clearZ, -maxBound, maxBound); + sampleNext = surfaceQuery(pod.X, pod.Z, preset.PodFootRadius, pod.Y + 60f); + terrainNext = terrain.SampleHeight(pod.X, pod.Z); + if (!sampleNext.IsBuildingRoof && !sampleNext.IsInsideBuildingFootprint) + { + surfaceNext = terrainNext; + } + else if (pod.AllowFlatRoofLanding && sampleNext.IsFlatRoofValid) + { + surfaceNext = MathF.Max(terrainNext, sampleNext.SurfaceY); + } + else + { + surfaceNext = terrainNext; + sampleNext = new DropSurfaceSample( + terrainNext, + ToNormalVec(terrain.SampleNormal(pod.X, pod.Z)), + IsBuildingRoof: false, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: false); + } + } + + pod.Y = surfaceNext; + pod.VelY = vyNext; + pod.TouchdownSpeed = MathF.Abs(vyNext); + pod.TouchdownNormal = sampleNext.Normal.LengthSquared() > 1e-4f + ? Vector3.Normalize(sampleNext.Normal) + : Vector3.UnitY; + pod.TouchdownOnRoof = sampleNext.IsBuildingRoof && pod.AllowFlatRoofLanding && sampleNext.IsFlatRoofValid; + pod.Phase = OrbitalPodPhase.Popped; + pod.LastAgl = 0f; + + Quaternion qTouch = Quaternion.CreateFromYawPitchRoll(pod.Yaw, 0f, 0f); + pod.CurrRotX = qTouch.X; + pod.CurrRotY = qTouch.Y; + pod.CurrRotZ = qTouch.Z; + pod.CurrRotW = qTouch.W; + + touchdownSample = sampleNext with { SurfaceY = surfaceNext }; + return true; + } + + pod.Y = yCand; + pod.VelY = vyNext; + pod.LastAgl = MathF.Max(0f, pod.Y - surfaceNext); + return false; + } + + private static Vector3 ToNormalVec((float Nx, float Ny, float Nz) n) + { + var v = new Vector3(n.Nx, n.Ny, n.Nz); + return v.LengthSquared() > 1e-4f ? Vector3.Normalize(v) : Vector3.UnitY; + } + } + + public sealed class OrbitalDropSystem + { + private readonly MatchState _state; + private readonly List _activePods = new(); + private readonly List _replicatedPods = new(); + private int _nextPodId = 1; + private long _nextPodEventId = 1; + private int _currentWaveIndex; + private int _nextWaveIndex; + private bool _respawnCutoffReached; + private bool _wave0Started; + + public OrbitalDropSystem(MatchState state) + { + _state = state; + } + + public IReadOnlyList ActivePods => _activePods; + public int CurrentWaveIndex => _currentWaveIndex; + public int NextWaveIndex => _nextWaveIndex; + public bool RespawnCutoffReached => _respawnCutoffReached; + public float? NextWaveAtSec => + _nextWaveIndex < DropWaveConfig.WaveTimes.Length + ? DropWaveConfig.WaveTimes[_nextWaveIndex] + : null; + + public DropWaveState WaveState + { + get + { + int waiting = 0; + for (int i = 0; i < _state.Contenders.Count; i++) + { + if (_state.Contenders[i].WaitingForRespawn) waiting++; + } + return new DropWaveState( + _currentWaveIndex, + _nextWaveIndex, + NextWaveAtSec, + _respawnCutoffReached, + _activePods.Count, + waiting); + } + } + + public long AllocatePodEventId() => _nextPodEventId++; + + public void BeginWave0( + IReadOnlyList<(int ContenderId, float X, float Z, float Yaw)> contenderTargets, + IReadOnlyList<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> gearTargets, + DropSurfaceQuery? surfaceQuery = null) + { + _wave0Started = true; + _currentWaveIndex = 0; + _nextWaveIndex = 1; + _respawnCutoffReached = false; + _activePods.Clear(); + + surfaceQuery ??= _state.DefaultDropSurfaceQuery; + + EmitLifecycleEvent( + DropPodEventKind.WaveAnnounced, + waveIndex: 0, + podId: 0, + podKind: OrbitalPodKind.Contender, + contenderId: -1, + x: 0f, y: 0f, z: 0f, + velX: 0f, velY: 0f, velZ: 0f, + normal: Vector3.UnitY, + chassisId: null, + moduleId: null, + dropId: 0, + respawnsClosed: false, + gearCount: gearTargets.Count, + respawnCount: contenderTargets.Count); + + _state.Broadcast.EmitDropWave(_state.Time, 0, gearTargets.Count, contenderTargets.Count, false); + + for (int i = 0; i < gearTargets.Count; i++) + { + var g = gearTargets[i]; + LaunchGearPod(waveIndex: 0, g.X, g.Z, g.Chassis, g.Module, surfaceQuery); + } + + for (int i = 0; i < contenderTargets.Count; i++) + { + var t = contenderTargets[i]; + if (t.ContenderId < 0 || t.ContenderId >= _state.Contenders.Count) continue; + var c = _state.Contenders[t.ContenderId]; + LaunchContenderPod(c, waveIndex: 0, t.X, t.Z, t.Yaw, surfaceQuery, isRespawn: false); + } + } + + public OrbitalPod LaunchContenderPod( + ContenderState c, + int waveIndex, + float targetX, + float targetZ, + float yaw, + DropSurfaceQuery surfaceQuery, + bool isRespawn) + { + CancelContenderPod(c.Id); + + var preset = OrbitalPodPreset.Contender; + float groundY = ResolveGroundSurfaceY(targetX, targetZ, preset.PodFootRadius, surfaceQuery); + float stagger = ((c.Id % 3) - 1) * 6f; + float startY = groundY + preset.StartAltAgl + stagger; + + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw); + var pod = new OrbitalPod + { + PodId = _nextPodId++, + PodKind = OrbitalPodKind.Contender, + Phase = OrbitalPodPhase.Freefall, + WaveIndex = waveIndex, + ContenderId = c.Id, + Chassis = c.Grid.Spec, + AllowFlatRoofLanding = c.IsHuman && _state.MapKind == ArenaMapKind.Sion, + TargetX = targetX, + TargetZ = targetZ, + X = targetX, + Y = startY, + Z = targetZ, + VelX = 0f, + VelY = preset.InitialVelY, + VelZ = 0f, + Yaw = yaw, + CurrRotX = q.X, + CurrRotY = q.Y, + CurrRotZ = q.Z, + CurrRotW = q.W, + LookForwardX = MathF.Sin(yaw), + LookForwardZ = MathF.Cos(yaw), + LaunchTime = _state.Time, + LastAgl = startY - groundY + }; + pod.SnapPreviousPose(); + _activePods.Add(pod); + + c.Lifecycle = ContenderLifecycle.Deploying; + c.ActivePodId = pod.PodId; + c.HasTouchdownPose = false; + c.TouchdownOnRoof = false; + c.X = pod.X; + c.Y = pod.Y + c.Grid.Spec.HalfHeight; + c.Z = pod.Z; + c.Yaw = yaw; + c.CurrRotX = q.X; + c.CurrRotY = q.Y; + c.CurrRotZ = q.Z; + c.CurrRotW = q.W; + c.VelX = pod.VelX; + c.VelY = pod.VelY; + c.VelZ = pod.VelZ; + c.Speed = 0f; + c.FireCmd = false; + c.ThrottleCmd = 0f; + c.SteerCmd = 0f; + c.SnapPreviousPose(); + c.ResetAimTracker(yaw); + + EmitLifecycleEvent( + DropPodEventKind.PodLaunched, + waveIndex, + pod.PodId, + OrbitalPodKind.Contender, + c.Id, + pod.X, pod.Y, pod.Z, + pod.VelX, pod.VelY, pod.VelZ, + Vector3.UnitY, + c.Grid.Spec.Id, + null, + dropId: 0, + _respawnCutoffReached, + gearCount: 0, + respawnCount: isRespawn ? 1 : 0); + + return pod; + } + + public OrbitalPod LaunchGearPod( + int waveIndex, + float targetX, + float targetZ, + ChassisSpec? chassis, + ModuleSpec? module, + DropSurfaceQuery surfaceQuery) + { + var preset = OrbitalPodPreset.Gear; + float groundY = ResolveGroundSurfaceY(targetX, targetZ, preset.PodFootRadius, surfaceQuery); + float startY = groundY + preset.StartAltAgl; + float yaw = (float)((_nextPodId * 1.17f) % MathF.Tau); + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw); + + var pod = new OrbitalPod + { + PodId = _nextPodId++, + PodKind = chassis is not null ? OrbitalPodKind.Chassis : OrbitalPodKind.Module, + Phase = OrbitalPodPhase.Freefall, + WaveIndex = waveIndex, + ContenderId = -1, + Chassis = chassis, + Module = module, + AllowFlatRoofLanding = false, + TargetX = targetX, + TargetZ = targetZ, + X = targetX, + Y = startY, + Z = targetZ, + VelX = 0f, + VelY = preset.InitialVelY, + VelZ = 0f, + Yaw = yaw, + CurrRotX = q.X, + CurrRotY = q.Y, + CurrRotZ = q.Z, + CurrRotW = q.W, + LaunchTime = _state.Time, + LastAgl = startY - groundY + }; + pod.SnapPreviousPose(); + _activePods.Add(pod); + + EmitLifecycleEvent( + DropPodEventKind.PodLaunched, + waveIndex, + pod.PodId, + pod.PodKind, + contenderId: -1, + pod.X, pod.Y, pod.Z, + pod.VelX, pod.VelY, pod.VelZ, + Vector3.UnitY, + chassis?.Id, + module?.Id, + dropId: 0, + _respawnCutoffReached, + gearCount: 0, + respawnCount: 0); + + return pod; + } + + public void CancelContenderPod(int contenderId) + { + for (int i = _activePods.Count - 1; i >= 0; i--) + { + if (_activePods[i].PodKind == OrbitalPodKind.Contender && _activePods[i].ContenderId == contenderId) + { + _activePods.RemoveAt(i); + } + } + if (contenderId >= 0 && contenderId < _state.Contenders.Count) + { + _state.Contenders[contenderId].ActivePodId = null; + } + } + + public void DeployAllPodsImmediately(DropSurfaceQuery? surfaceQuery = null) + { + surfaceQuery ??= _state.DefaultDropSurfaceQuery; + for (int i = _activePods.Count - 1; i >= 0; i--) + { + var pod = _activePods[i]; + var preset = OrbitalDropKinematics.GetPreset(pod.PodKind); + float groundY = _state.Terrain.SampleHeight(pod.TargetX, pod.TargetZ); + var sample = surfaceQuery(pod.TargetX, pod.TargetZ, preset.PodFootRadius, groundY + 120f); + pod.X = pod.TargetX; + pod.Z = pod.TargetZ; + pod.Y = sample.SurfaceY; + pod.VelX = 0f; + pod.VelY = -preset.TargetTouchdownSpeed; + pod.VelZ = 0f; + pod.TouchdownSpeed = preset.TargetTouchdownSpeed; + pod.TouchdownNormal = sample.Normal; + pod.TouchdownOnRoof = false; + pod.Phase = OrbitalPodPhase.Popped; + HandlePodTouchdown(pod, sample, surfaceQuery, null, emitEvents: false); + _activePods.RemoveAt(i); + } + } + + public void SnapshotPreviousPoses() + { + for (int i = 0; i < _activePods.Count; i++) + { + _activePods[i].SnapPreviousPose(); + } + } + + public void UpdateAiPodSteering(ContenderState ai) + { + if (!ai.IsInDropPod || !ai.ActivePodId.HasValue) + { + return; + } + + OrbitalPod? pod = FindPodById(ai.ActivePodId.Value); + if (pod is null || pod.Phase != OrbitalPodPhase.Freefall) + { + return; + } + + // AI steers gently toward nearest unpicked GroundDrop within 180m or inward away from ring perimeter + float goalX = 0f; + float goalZ = 0f; + bool hasGoal = false; + float safeLimit = MathF.Max(40f, _state.Spectators.SafeRadius - 35f); + float distFromCenter = MathF.Sqrt(pod.X * pod.X + pod.Z * pod.Z); + if (distFromCenter > safeLimit) + { + hasGoal = true; + } + else + { + float bestSq = 180f * 180f; + for (int i = 0; i < _state.GroundDrops.Count; i++) + { + var d = _state.GroundDrops[i]; + if (d.PickedUp) continue; + float dx = d.X - pod.X; + float dz = d.Z - pod.Z; + float d2 = dx * dx + dz * dz; + if (d2 < bestSq) + { + bestSq = d2; + goalX = d.X; + goalZ = d.Z; + hasGoal = true; + } + } + } + + if (hasGoal) + { + float dx = goalX - pod.X; + float dz = goalZ - pod.Z; + float len = MathF.Sqrt(dx * dx + dz * dz); + if (len > 4f) + { + pod.LookForwardX = dx / len; + pod.LookForwardZ = dz / len; + pod.SteerForwardCmd = 0.65f; + pod.SteerRightCmd = 0f; + return; + } + } + + pod.SteerForwardCmd = 0f; + pod.SteerRightCmd = 0f; + } + + public void ApplyPlayerSteerInput(ContenderState human, DropSurfaceQuery? surfaceQuery = null) + { + if (!human.IsInDropPod || !human.ActivePodId.HasValue) + { + return; + } + var pod = FindPodById(human.ActivePodId.Value); + if (pod is null) + { + return; + } + pod.AllowFlatRoofLanding = human.IsHuman && _state.MapKind == ArenaMapKind.Sion; + pod.SteerForwardCmd = Math.Clamp(human.ThrottleCmd, -1f, 1f); + pod.SteerRightCmd = Math.Clamp(human.SteerCmd, -1f, 1f); + + float dx = human.AimX - pod.X; + float dz = human.AimZ - pod.Z; + float d2 = dx * dx + dz * dz; + if (float.IsFinite(d2) && d2 > 0.25f) + { + float inv = 1f / MathF.Sqrt(d2); + pod.LookForwardX = dx * inv; + pod.LookForwardZ = dz * inv; + pod.Yaw = MathF.Atan2(pod.LookForwardX, pod.LookForwardZ); + } + } + + public void Step( + float dt, + DropSurfaceQuery? surfaceQuery = null, + Action? onPodTouchedDown = null) + { + surfaceQuery ??= _state.DefaultDropSurfaceQuery; + + // 1. Check Final-Ring Cutoff against current ring radius + CheckFinalRingCutoff(); + + // 2. Launch scheduled Patron Drop Waves (1..3) + if (_wave0Started) + { + while (_nextWaveIndex < DropWaveConfig.WaveTimes.Length && + _state.Time >= DropWaveConfig.WaveTimes[_nextWaveIndex]) + { + LaunchScheduledWave(_nextWaveIndex, surfaceQuery); + _nextWaveIndex++; + if (_nextWaveIndex > DropWaveConfig.MaxRespawnWave) + { + TriggerRespawnCutoff(); + } + } + } + + // 3. Step all airborne pods + for (int i = _activePods.Count - 1; i >= 0; i--) + { + var pod = _activePods[i]; + if (pod.PodKind == OrbitalPodKind.Contender && + pod.ContenderId >= 0 && + pod.ContenderId < _state.Contenders.Count) + { + var c = _state.Contenders[pod.ContenderId]; + pod.AllowFlatRoofLanding = c.IsHuman && _state.MapKind == ArenaMapKind.Sion; + } + + bool touched = OrbitalDropKinematics.StepPod( + pod, + dt, + _state.Terrain, + surfaceQuery, + _state.FindClearDropPoint, + out bool retroBurnStarted, + out DropSurfaceSample touchSample); + + if (retroBurnStarted) + { + EmitLifecycleEvent( + DropPodEventKind.PodRetroBurnStart, + pod.WaveIndex, + pod.PodId, + pod.PodKind, + pod.ContenderId, + pod.X, pod.Y, pod.Z, + pod.VelX, pod.VelY, pod.VelZ, + Vector3.UnitY, + pod.Chassis?.Id, + pod.Module?.Id, + dropId: 0, + _respawnCutoffReached, + gearCount: 0, + respawnCount: 0); + } + + if (pod.PodKind == OrbitalPodKind.Contender && + pod.ContenderId >= 0 && + pod.ContenderId < _state.Contenders.Count && + !touched) + { + var c = _state.Contenders[pod.ContenderId]; + c.X = pod.X; + c.Y = pod.Y + c.Grid.Spec.HalfHeight; + c.Z = pod.Z; + c.Yaw = pod.Yaw; + c.CurrRotX = pod.CurrRotX; + c.CurrRotY = pod.CurrRotY; + c.CurrRotZ = pod.CurrRotZ; + c.CurrRotW = pod.CurrRotW; + c.VelX = pod.VelX; + c.VelY = pod.VelY; + c.VelZ = pod.VelZ; + c.Speed = MathF.Sqrt(pod.VelX * pod.VelX + pod.VelZ * pod.VelZ); + } + + if (touched) + { + HandlePodTouchdown(pod, touchSample, surfaceQuery, onPodTouchedDown, emitEvents: true); + _activePods.RemoveAt(i); + } + } + } + + public bool CanAnyWaitingContenderRespawn() + { + if (_respawnCutoffReached || _nextWaveIndex > DropWaveConfig.MaxRespawnWave) + { + return false; + } + float cutoff = DropWaveConfig.GetCutoffRadius(_state.MapKind); + return _state.Spectators.SafeRadius > cutoff; + } + + public void OnContenderEliminated(ContenderState victim) + { + CancelContenderPod(victim.Id); + CheckFinalRingCutoff(); + + if (victim.RespawnsRemaining > 0 && CanAnyWaitingContenderRespawn()) + { + victim.Lifecycle = ContenderLifecycle.WaitingForRespawnWave; + } + else + { + victim.Lifecycle = ContenderLifecycle.Eliminated; + } + } + + public void CheckFinalRingCutoff() + { + if (_respawnCutoffReached) + { + EvictWaitingContenders(); + return; + } + + float cutoff = DropWaveConfig.GetCutoffRadius(_state.MapKind); + if (_state.Spectators.SafeRadius <= cutoff || _nextWaveIndex > DropWaveConfig.MaxRespawnWave) + { + TriggerRespawnCutoff(); + } + } + + private void TriggerRespawnCutoff() + { + _respawnCutoffReached = true; + EvictWaitingContenders(); + } + + private void EvictWaitingContenders() + { + for (int i = 0; i < _state.Contenders.Count; i++) + { + var c = _state.Contenders[i]; + if (c.Lifecycle == ContenderLifecycle.WaitingForRespawnWave) + { + c.Lifecycle = ContenderLifecycle.Eliminated; + } + } + } + + private void LaunchScheduledWave(int waveIndex, DropSurfaceQuery surfaceQuery) + { + _currentWaveIndex = waveIndex; + var gearSpecs = BuildEscalatingWaveGear(waveIndex); + var gearTargets = new List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)>(gearSpecs.Count); + float safeR = MathF.Max(65f, _state.Spectators.SafeRadius * 0.68f); + + for (int i = 0; i < gearSpecs.Count; i++) + { + float ang = (i / (float)Math.Max(1, gearSpecs.Count)) * MathF.Tau + waveIndex * 0.55f + (float)_state.Rng.NextDouble() * 0.25f; + float r = (0.20f + 0.65f * (float)_state.Rng.NextDouble()) * safeR; + float rawX = MathF.Cos(ang) * r; + float rawZ = MathF.Sin(ang) * r; + var (cx, cz) = _state.FindClearDropPoint(rawX, rawZ, 3.5f); + gearTargets.Add((cx, cz, gearSpecs[i].Chassis, gearSpecs[i].Module)); + } + + bool allowRespawnsThisWave = waveIndex <= DropWaveConfig.MaxRespawnWave && + !_respawnCutoffReached && + _state.Spectators.SafeRadius > DropWaveConfig.GetCutoffRadius(_state.MapKind); + + var respawnQueue = new List(); + if (allowRespawnsThisWave) + { + for (int i = 0; i < _state.Contenders.Count; i++) + { + var c = _state.Contenders[i]; + if (c.Lifecycle == ContenderLifecycle.WaitingForRespawnWave && c.RespawnsRemaining > 0) + { + respawnQueue.Add(c); + } + } + } + + bool respawnsClosed = !allowRespawnsThisWave || waveIndex >= DropWaveConfig.MaxRespawnWave; + + EmitLifecycleEvent( + DropPodEventKind.WaveAnnounced, + waveIndex, + podId: 0, + podKind: OrbitalPodKind.Contender, + contenderId: -1, + 0f, 0f, 0f, + 0f, 0f, 0f, + Vector3.UnitY, + chassisId: null, + moduleId: null, + dropId: 0, + respawnsClosed: respawnsClosed, + gearCount: gearTargets.Count, + respawnCount: respawnQueue.Count); + + _state.Broadcast.EmitDropWave(_state.Time, waveIndex, gearTargets.Count, respawnQueue.Count, respawnsClosed); + + for (int i = 0; i < gearTargets.Count; i++) + { + var g = gearTargets[i]; + LaunchGearPod(waveIndex, g.X, g.Z, g.Chassis, g.Module, surfaceQuery); + } + + for (int i = 0; i < respawnQueue.Count; i++) + { + var c = respawnQueue[i]; + c.RespawnsRemaining = Math.Max(0, c.RespawnsRemaining - 1); + float ang = (i / (float)Math.Max(1, respawnQueue.Count)) * MathF.Tau + waveIndex * 0.9f; + float r = MathF.Min(safeR * 0.72f, MathF.Max(80f, safeR * 0.48f)); + var (rx, rz) = _state.FindClearDropPoint(MathF.Cos(ang) * r, MathF.Sin(ang) * r, 4.0f); + float yaw = MathF.Atan2(-rx, -rz); + c.ResetForRedrop(Catalog.CreateStarterBuggy(), rx, 0f, rz, yaw); + LaunchContenderPod(c, waveIndex, rx, rz, yaw, surfaceQuery, isRespawn: true); + _state.NotifyContenderRespawned(c); + } + } + + private static List<(ChassisSpec? Chassis, ModuleSpec? Module)> BuildEscalatingWaveGear(int waveIndex) + { + var list = new List<(ChassisSpec?, ModuleSpec?)>(8); + switch (waveIndex) + { + case 1: + list.Add((Catalog.Hornet, null)); + list.Add((Catalog.Condor, null)); + list.Add((null, Catalog.Autocannon)); + list.Add((null, Catalog.Recoilless)); + list.Add((null, Catalog.Flak)); + list.Add((null, Catalog.TurboCore)); + list.Add((null, Catalog.CopperRad)); + list.Add((null, Catalog.TouringPlasma)); + break; + case 2: + list.Add((Catalog.Paladin, null)); + list.Add((Catalog.Manticore, null)); + list.Add((null, Catalog.GildedLance)); + list.Add((null, Catalog.TouringPlasma)); + list.Add((null, Catalog.ImperialAegisPd)); + list.Add((null, Catalog.NobleCore)); + list.Add((null, Catalog.GoldRadiator)); + list.Add((null, Catalog.GildedPlate)); + break; + default: + list.Add((Catalog.Bastion, null)); + list.Add((Catalog.Kestrel, null)); + list.Add((null, Catalog.GildedLance)); + list.Add((null, Catalog.TouringPlasma)); + list.Add((null, Catalog.ImperialAegisPd)); + list.Add((null, Catalog.NobleCore)); + break; + } + return list; + } + + private void HandlePodTouchdown( + OrbitalPod pod, + DropSurfaceSample touchSample, + DropSurfaceQuery surfaceQuery, + Action? onPodTouchedDown, + bool emitEvents) + { + if (emitEvents && !touchSample.IsBuildingRoof) + { + _state.Terrain.StampCrater(pod.X, pod.Z, pod.PodKind == OrbitalPodKind.Contender ? 3.4f : 2.1f, 0.32f); + _state.Terrain.StampScorch(pod.X, pod.Z, pod.PodKind == OrbitalPodKind.Contender ? 4.2f : 2.6f); + } + + // Re-sample ground height after crater stamp + float postCraterSurfaceY = touchSample.IsBuildingRoof + ? touchSample.SurfaceY + : _state.Terrain.SampleHeight(pod.X, pod.Z); + var postSample = touchSample with { SurfaceY = postCraterSurfaceY }; + + if (pod.PodKind == OrbitalPodKind.Contender && + pod.ContenderId >= 0 && + pod.ContenderId < _state.Contenders.Count) + { + var c = _state.Contenders[pod.ContenderId]; + c.ActivePodId = null; + c.Lifecycle = ContenderLifecycle.Active; + c.X = pod.X; + c.Z = pod.Z; + c.Yaw = pod.Yaw; + + // Orient chassis up-vector toward surface normal (blended 0.85f, clamped <= 38 deg) + var spec = c.Grid.Spec; + float physHalfH = spec.IsWalker ? spec.HalfHeight * (spec.Plane == GridPlane.Dorsal ? 0.62f : 0.72f) : spec.HalfHeight; + Quaternion yawQ = Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw); + Vector3 upNorm = postSample.Normal.LengthSquared() > 1e-4f ? Vector3.Normalize(postSample.Normal) : Vector3.UnitY; + Vector3 desiredUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, upNorm, 0.85f)); + const float maxTiltRad = MathF.PI * 38f / 180f; + float tiltAngle = MathF.Acos(Math.Clamp(desiredUp.Y, -1f, 1f)); + if (tiltAngle > maxTiltRad) + { + Vector3 horiz = new(desiredUp.X, 0f, desiredUp.Z); + float hLen = horiz.Length(); + desiredUp = hLen > 1e-4f + ? Vector3.UnitY * MathF.Cos(maxTiltRad) + (horiz / hLen) * MathF.Sin(maxTiltRad) + : Vector3.UnitY; + } + + Quaternion rot = AlignUp(yawQ, desiredUp); + + // Exact zero-penetration corner clearance + float maxReqCenterY = postCraterSurfaceY + physHalfH; + Span localCorners = stackalloc Vector3[4] + { + new Vector3(-spec.HalfWidth, -physHalfH, -spec.HalfLength), + new Vector3( spec.HalfWidth, -physHalfH, -spec.HalfLength), + new Vector3(-spec.HalfWidth, -physHalfH, spec.HalfLength), + new Vector3( spec.HalfWidth, -physHalfH, spec.HalfLength) + }; + for (int k = 0; k < 4; k++) + { + Vector3 r = Vector3.Transform(localCorners[k], rot); + float cornerSurfY; + if (postSample.IsBuildingRoof) + { + var cs = surfaceQuery(pod.X + r.X, pod.Z + r.Z, 0.25f, pod.Y + 6f); + cornerSurfY = cs.IsBuildingRoof ? cs.SurfaceY : _state.Terrain.SampleHeight(pod.X + r.X, pod.Z + r.Z); + } + else + { + cornerSurfY = _state.Terrain.SampleHeight(pod.X + r.X, pod.Z + r.Z); + } + float reqCenter = cornerSurfY - r.Y; + if (reqCenter > maxReqCenterY) + { + maxReqCenterY = reqCenter; + } + } + + float spawnY = maxReqCenterY + 0.04f; + if (spec.IsVtol) + { + spawnY += Math.Clamp(c.TargetHoverAltAgl, MatchRules.VtolMinClearanceAgl, MathF.Max(MatchRules.VtolMinClearanceAgl, spec.HoverMaxAltitudeM)); + } + + c.Y = spawnY; + c.CurrRotX = rot.X; + c.CurrRotY = rot.Y; + c.CurrRotZ = rot.Z; + c.CurrRotW = rot.W; + c.VelX = 0f; + c.VelY = -MathF.Min(pod.TouchdownSpeed, 2.6f); + c.VelZ = 0f; + c.Speed = 0f; + c.HasTouchdownPose = true; + c.TouchdownOnRoof = pod.TouchdownOnRoof; + c.SnapPreviousPose(); + c.ResetAimTracker(c.Yaw); + + _state.NotifyContenderPodTouchedDown(c); + } + else + { + GroundDrop drop = pod.Chassis is not null + ? _state.SpawnChassisDrop(pod.X, pod.Z, pod.Chassis) + : _state.SpawnModuleDrop(pod.X, pod.Z, pod.Module!); + pod.GroundDropId = drop.Id; + } + + onPodTouchedDown?.Invoke(pod, postSample); + + if (emitEvents) + { + EmitLifecycleEvent( + DropPodEventKind.PodTouchdownBlowPetals, + pod.WaveIndex, + pod.PodId, + pod.PodKind, + pod.ContenderId, + pod.X, postCraterSurfaceY, pod.Z, + pod.VelX, pod.VelY, pod.VelZ, + postSample.Normal, + pod.Chassis?.Id, + pod.Module?.Id, + pod.GroundDropId, + _respawnCutoffReached, + gearCount: 0, + respawnCount: 0); + } + } + + private float ResolveGroundSurfaceY(float x, float z, float radius, DropSurfaceQuery surfaceQuery) + { + float terrainY = _state.Terrain.SampleHeight(x, z); + var sample = surfaceQuery(x, z, radius, terrainY + 250f); + return sample.IsBuildingRoof ? MathF.Max(terrainY, sample.SurfaceY) : terrainY; + } + + private OrbitalPod? FindPodById(int podId) + { + for (int i = 0; i < _activePods.Count; i++) + { + if (_activePods[i].PodId == podId) + { + return _activePods[i]; + } + } + return null; + } + + private void EmitLifecycleEvent( + DropPodEventKind kind, + int waveIndex, + int podId, + OrbitalPodKind podKind, + int contenderId, + float x, + float y, + float z, + float velX, + float velY, + float velZ, + Vector3 normal, + string? chassisId, + string? moduleId, + int dropId, + bool respawnsClosed, + int gearCount, + int respawnCount) + { + var ev = new DropPodLifecycleEvent( + AllocatePodEventId(), + kind, + waveIndex, + podId, + podKind, + contenderId, + x, y, z, + velX, velY, velZ, + normal, + chassisId, + moduleId, + dropId, + respawnsClosed, + gearCount, + respawnCount); + _state.PodEvents.Add(ev); + if (_state.PodEvents.Count > 2048) + { + _state.PodEvents.RemoveRange(0, _state.PodEvents.Count - 2048); + } + } + + public void ApplyReplicatedWaveState(int currentWaveIndex, int nextWaveIndex, bool respawnCutoffReached) + { + _currentWaveIndex = currentWaveIndex; + _nextWaveIndex = nextWaveIndex; + _respawnCutoffReached = respawnCutoffReached; + } + + public void ApplyReplicatedActivePods(IEnumerable pods) + { + _activePods.Clear(); + foreach (var dto in pods) + { + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, dto.Yaw); + var pod = new OrbitalPod + { + PodId = dto.PodId, + PodKind = (OrbitalPodKind)dto.PodKind, + Phase = (OrbitalPodPhase)dto.Phase, + WaveIndex = dto.WaveIndex, + ContenderId = dto.ContenderId, + Chassis = dto.ChassisId is not null && Catalog.ChassisById.TryGetValue(dto.ChassisId, out var cs) ? cs : null, + Module = dto.ModuleId is not null && Catalog.ModulesById.TryGetValue(dto.ModuleId, out var ms) ? ms : null, + X = dto.X, + Y = dto.Y, + Z = dto.Z, + VelX = dto.VelX, + VelY = dto.VelY, + VelZ = dto.VelZ, + Yaw = dto.Yaw, + CurrRotX = q.X, + CurrRotY = q.Y, + CurrRotZ = q.Z, + CurrRotW = q.W + }; + pod.SnapPreviousPose(); + _activePods.Add(pod); + if (dto.PodId >= _nextPodId) _nextPodId = dto.PodId + 1; + } + } + + public void ApplyReplicatedDropPodEvent(DropPodEvent ev) + { + var kind = (DropPodEventKind)ev.Kind; + switch (kind) + { + case DropPodEventKind.WaveAnnounced: + _currentWaveIndex = ev.WaveIndex; + _nextWaveIndex = Math.Min(DropWaveConfig.WaveTimes.Length, ev.WaveIndex + 1); + _respawnCutoffReached = ev.RespawnsClosed; + break; + case DropPodEventKind.PodLaunched: + { + var existing = FindPodById(ev.PodId); + if (existing is null) + { + var pod = new OrbitalPod + { + PodId = ev.PodId, + PodKind = (OrbitalPodKind)ev.PodKind, + Phase = OrbitalPodPhase.Freefall, + WaveIndex = ev.WaveIndex, + ContenderId = ev.ContenderId, + Chassis = ev.ChassisId is not null && Catalog.ChassisById.TryGetValue(ev.ChassisId, out var cs) ? cs : null, + Module = ev.ModuleId is not null && Catalog.ModulesById.TryGetValue(ev.ModuleId, out var ms) ? ms : null, + X = ev.X, + Y = ev.Y, + Z = ev.Z, + VelX = ev.VelX, + VelY = ev.VelY, + VelZ = ev.VelZ + }; + pod.SnapPreviousPose(); + _activePods.Add(pod); + } + if (ev.ContenderId >= 0 && ev.ContenderId < _state.Contenders.Count) + { + var c = _state.Contenders[ev.ContenderId]; + c.Lifecycle = ContenderLifecycle.Deploying; + c.ActivePodId = ev.PodId; + } + break; + } + case DropPodEventKind.PodRetroBurnStart: + { + var pod = FindPodById(ev.PodId); + if (pod is not null) + { + pod.Phase = OrbitalPodPhase.RetroBurn; + pod.X = ev.X; + pod.Y = ev.Y; + pod.Z = ev.Z; + pod.VelX = ev.VelX; + pod.VelY = ev.VelY; + pod.VelZ = ev.VelZ; + } + break; + } + case DropPodEventKind.PodTouchdownBlowPetals: + { + for (int i = _activePods.Count - 1; i >= 0; i--) + { + if (_activePods[i].PodId == ev.PodId) + { + _activePods.RemoveAt(i); + } + } + if (ev.ContenderId >= 0 && ev.ContenderId < _state.Contenders.Count) + { + var c = _state.Contenders[ev.ContenderId]; + c.Lifecycle = ContenderLifecycle.Active; + c.ActivePodId = null; + } + break; + } + } + + _state.PodEvents.Add(new DropPodLifecycleEvent( + ev.EventId > 0 ? ev.EventId : AllocatePodEventId(), + kind, + ev.WaveIndex, + ev.PodId, + (OrbitalPodKind)ev.PodKind, + ev.ContenderId, + ev.X, ev.Y, ev.Z, + ev.VelX, ev.VelY, ev.VelZ, + new Vector3(ev.NormalX, ev.NormalY, ev.NormalZ), + ev.ChassisId, + ev.ModuleId, + ev.DropId, + ev.RespawnsClosed, + ev.GearCount, + ev.RespawnCount)); + if (_state.PodEvents.Count > 2048) + { + _state.PodEvents.RemoveRange(0, _state.PodEvents.Count - 2048); + } + } + + private static Quaternion AlignUp(Quaternion baseYawQ, Vector3 targetUp) + { + Vector3 currentUp = Vector3.Transform(Vector3.UnitY, baseYawQ); + float dot = Math.Clamp(Vector3.Dot(currentUp, targetUp), -1f, 1f); + if (dot > 0.9999f) return baseYawQ; + if (dot < -0.9999f) + { + Vector3 ortho = MathF.Abs(currentUp.X) < 0.9f ? Vector3.UnitX : Vector3.UnitZ; + return Quaternion.Normalize(Quaternion.CreateFromAxisAngle(Vector3.Normalize(Vector3.Cross(currentUp, ortho)), MathF.PI) * baseYawQ); + } + Vector3 axis = Vector3.Normalize(Vector3.Cross(currentUp, targetUp)); + float angle = MathF.Acos(dot); + return Quaternion.Normalize(Quaternion.CreateFromAxisAngle(axis, angle) * baseYawQ); + } + } +} diff --git a/src/RustToDust.Core/SimEvents.cs b/src/RustToDust.Core/SimEvents.cs index 18c6cd4..d1e592c 100644 --- a/src/RustToDust.Core/SimEvents.cs +++ b/src/RustToDust.Core/SimEvents.cs @@ -31,12 +31,46 @@ namespace RustToDust.Core [Union(9, typeof(SpectatorDestroyedEvent))] [Union(10, typeof(OverheatAlertEvent))] [Union(11, typeof(MatchResetEvent))] - // Reserved [Union(12)] DropPodEvent (Cut 6) + [Union(12, typeof(DropPodEvent))] // Reserved [Union(13)] OrdnanceNodeEvent (Cut 7) public interface ISimEvent { } + public enum DropPodEventKind : byte + { + WaveAnnounced = 0, + PodLaunched = 1, + PodRetroBurnStart = 2, + PodTouchdownBlowPetals = 3 + } + + [MessagePackObject] + public sealed class DropPodEvent : ISimEvent + { + [Key(0)] public long EventId { get; set; } + [Key(1)] public byte Kind { get; set; } + [Key(2)] public int WaveIndex { get; set; } + [Key(3)] public int PodId { get; set; } + [Key(4)] public byte PodKind { get; set; } + [Key(5)] public int ContenderId { get; set; } = -1; + [Key(6)] public float X { get; set; } + [Key(7)] public float Y { get; set; } + [Key(8)] public float Z { get; set; } + [Key(9)] public float VelX { get; set; } + [Key(10)] public float VelY { get; set; } + [Key(11)] public float VelZ { get; set; } + [Key(12)] public float NormalX { get; set; } + [Key(13)] public float NormalY { get; set; } + [Key(14)] public float NormalZ { get; set; } + [Key(15)] public string? ChassisId { get; set; } + [Key(16)] public string? ModuleId { get; set; } + [Key(17)] public int DropId { get; set; } + [Key(18)] public bool RespawnsClosed { get; set; } + [Key(19)] public int GearCount { get; set; } + [Key(20)] public int RespawnCount { get; set; } + } + [MessagePackObject] public sealed class ShotFiredEvent : ISimEvent { @@ -161,6 +195,7 @@ namespace RustToDust.Core [Key(1)] public int KillerId { get; set; } [Key(2)] public bool IsSpectatorKiller { get; set; } [Key(3)] public int KillerKills { get; set; } + [Key(4)] public byte VictimLifecycleByte { get; set; } } [MessagePackObject] @@ -190,6 +225,27 @@ namespace RustToDust.Core [Key(6)] public float Yaw { get; set; } [Key(7)] public int Kills { get; set; } [Key(8)] public ContenderLoadoutEvent Loadout { get; set; } = new(); + [Key(9)] public byte LifecycleByte { get; set; } + [Key(10)] public byte RespawnsRemaining { get; set; } + } + + [MessagePackObject] + public sealed class OrbitalPodDto + { + [Key(0)] public int PodId { get; set; } + [Key(1)] public byte PodKind { get; set; } + [Key(2)] public byte Phase { get; set; } + [Key(3)] public int WaveIndex { get; set; } + [Key(4)] public int ContenderId { get; set; } = -1; + [Key(5)] public float X { get; set; } + [Key(6)] public float Y { get; set; } + [Key(7)] public float Z { get; set; } + [Key(8)] public float VelX { get; set; } + [Key(9)] public float VelY { get; set; } + [Key(10)] public float VelZ { get; set; } + [Key(11)] public float Yaw { get; set; } + [Key(12)] public string? ChassisId { get; set; } + [Key(13)] public string? ModuleId { get; set; } } [MessagePackObject] @@ -235,6 +291,9 @@ namespace RustToDust.Core [Key(9)] public List GroundDrops { get; set; } = new(); [Key(10)] public List TerrainStamps { get; set; } = new(); [Key(11)] public int ConnectedHumans { get; set; } + [Key(12)] public int CurrentWaveIndex { get; set; } + [Key(13)] public bool RespawnCutoffReached { get; set; } + [Key(14)] public List ActivePods { get; set; } = new(); } [MessagePackObject] diff --git a/src/RustToDust.Core/SionMapLoader.cs b/src/RustToDust.Core/SionMapLoader.cs index 5bc1a7d..2e4b3dc 100644 --- a/src/RustToDust.Core/SionMapLoader.cs +++ b/src/RustToDust.Core/SionMapLoader.cs @@ -158,6 +158,36 @@ namespace RustToDust.Core return false; } + public bool TryGetBuildingAt(float x, float z, float padding, out SionBuildingAabb building) + { + float pad = MathF.Max(0f, padding); + WorldToCell(x - pad, z - pad, out int minCx, out int minCz); + WorldToCell(x + pad, z + pad, out int maxCx, out int maxCz); + + bool found = false; + building = default; + float bestRoofY = float.NegativeInfinity; + + for (int cz = minCz; cz <= maxCz; cz++) + { + for (int cx = minCx; cx <= maxCx; cx++) + { + var list = _cellBuildings[cz * SpatialGridRes + cx]; + for (int i = 0; i < list.Count; i++) + { + ref readonly var b = ref _buildings[list[i]]; + if (b.ContainsXz(x, z, pad) && b.RoofY > bestRoofY) + { + bestRoofY = b.RoofY; + building = b; + found = true; + } + } + } + } + return found; + } + public bool IntersectsAnyBuildingAabb( float ox, float oy, float oz, float dx, float dy, float dz, diff --git a/src/RustToDust.Net/ListenHostArenaSession.cs b/src/RustToDust.Net/ListenHostArenaSession.cs index e5dfc7a..7220337 100644 --- a/src/RustToDust.Net/ListenHostArenaSession.cs +++ b/src/RustToDust.Net/ListenHostArenaSession.cs @@ -35,7 +35,7 @@ namespace RustToDust.Net public ClientMatchOutcome LocalOutcome => _host.Session.State.Phase == MatchPhase.Active - ? (LocalContender.Alive ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) + ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) : (_host.Session.State.WinnerContenderId == 0 ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat); public int LocalDetectedByCount => @@ -56,6 +56,10 @@ namespace RustToDust.Net MaxHumans: MatchState.ContenderCount, StateLabel: $"HOST :{_host.BoundPort} ({_host.ConnectedHumanCount}/12)"); + public IReadOnlyList ActivePods => _host.Session.State.OrbitalDrop.ActivePods; + public DropWaveState DropWaveState => _host.Session.State.OrbitalDrop.WaveState; + public IReadOnlyList PodEvents => _host.Session.State.PodEvents; + public bool IsContenderVisible(int contenderId) => true; public bool IsSpectatorVisible(int spectatorId) => true; diff --git a/src/RustToDust.Net/RemoteArenaSession.cs b/src/RustToDust.Net/RemoteArenaSession.cs index b5c3a05..e7183cf 100644 --- a/src/RustToDust.Net/RemoteArenaSession.cs +++ b/src/RustToDust.Net/RemoteArenaSession.cs @@ -95,7 +95,7 @@ namespace RustToDust.Net for (int i = 0; i < _contenderTimeline.Length; i++) _contenderTimeline[i] = new List(16); for (int i = 0; i < _spectatorTimeline.Length; i++) _spectatorTimeline[i] = new List(16); - _viewState = new MatchState(42, ArenaMapKind.Desert); + _viewState = new MatchState(42, ArenaMapKind.Desert, skipInitialDrop: true); for (int i = 0; i < _contenderVisible.Length; i++) _contenderVisible[i] = i == 0; _socket = new Socket(serverEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp) @@ -136,7 +136,7 @@ namespace RustToDust.Net public ClientMatchOutcome LocalOutcome => _viewState.Phase == MatchPhase.Active - ? (LocalContender.Alive ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) + ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) : (_viewState.WinnerContenderId == _localContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat); public int LocalDetectedByCount => _localDetectedByCount; @@ -159,6 +159,10 @@ namespace RustToDust.Net : (_lastError is not null ? $"DISCONNECTED ({_lastError})" : (_everJoined ? "DISCONNECTED" : "CONNECTING")), LastError: _lastError); + public IReadOnlyList ActivePods => _viewState.OrbitalDrop.ActivePods; + public DropWaveState DropWaveState => _viewState.OrbitalDrop.WaveState; + public IReadOnlyList PodEvents => _viewState.PodEvents; + public bool IsContenderVisible(int contenderId) => contenderId >= 0 && contenderId < _contenderVisible.Length && _contenderVisible[contenderId]; @@ -692,13 +696,18 @@ namespace RustToDust.Net _predErrorRot = Quaternion.Identity; Array.Clear(_lastCombatSpecSeenSeq); - _viewState = new MatchState(dto.Seed, (ArenaMapKind)dto.MapKind) + _viewState = new MatchState(dto.Seed, (ArenaMapKind)dto.MapKind, skipInitialDrop: true) { Time = dto.SimTime, Phase = dto.Phase == 1 ? MatchPhase.Completed : MatchPhase.Active, WinnerContenderId = dto.WinnerContenderId }; _viewState.Spectators.SetReplicatedSafeRadius(dto.SafeRadius); + _viewState.OrbitalDrop.ApplyReplicatedWaveState( + dto.CurrentWaveIndex, + Math.Min(DropWaveConfig.WaveTimes.Length, dto.CurrentWaveIndex + 1), + dto.RespawnCutoffReached); + _viewState.OrbitalDrop.ApplyReplicatedActivePods(dto.ActivePods); _latestServerSimTime = dto.SimTime; _renderTime = Math.Max(0f, dto.SimTime - InterpDelaySec); @@ -744,6 +753,8 @@ namespace RustToDust.Net c.Name = cd.Name; c.IsHuman = cd.IsHuman; if (cd.IsHuman) humans++; + c.Lifecycle = (ContenderLifecycle)cd.LifecycleByte; + c.RespawnsRemaining = cd.RespawnsRemaining; c.X = cd.X; c.Y = cd.Y; c.Z = cd.Z; c.Yaw = cd.Yaw; c.Kills = cd.Kills; var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, cd.Yaw); @@ -806,7 +817,7 @@ namespace RustToDust.Net { if (_predWorld is null) return; var local = LocalContender; - if (!local.Alive) + if (!local.IsGroundedActive) { if (_predBody.HasValue) { @@ -902,7 +913,7 @@ namespace RustToDust.Net } } - if (_predWorld is null || !_predBody.HasValue || !local.Alive) + if (_predWorld is null || !_predBody.HasValue || !local.IsGroundedActive) { return; } @@ -917,7 +928,8 @@ namespace RustToDust.Net _viewState.MapKind, _predWalker, ArenaSession.FixedDt, - injectEngineHeat: false); + injectEngineHeat: false, + world: _predWorld); _predWorld.Step(ArenaSession.FixedDt, subSteps); ArenaSession.SyncContenderPoseFromLane(local, _predWorld.View, _predBody.Value.Lane, _predWalker); } @@ -942,12 +954,22 @@ namespace RustToDust.Net } var local = LocalContender; + var prevLocalLifecycle = local.Lifecycle; + local.Lifecycle = pkt.LocalLifecycle; + int nextWaveIdx = pkt.RespawnCutoffReached + ? DropWaveConfig.WaveTimes.Length + : Math.Min(DropWaveConfig.WaveTimes.Length, pkt.CurrentWaveIndex + 1); + _viewState.OrbitalDrop.ApplyReplicatedWaveState(pkt.CurrentWaveIndex, nextWaveIdx, pkt.RespawnCutoffReached); + if (local.Lifecycle != ContenderLifecycle.Deploying) + { + _viewState.OrbitalDrop.CancelContenderPod(local.Id); + } local.InArcWeaponCount = pkt.InArcWeapons; local.OutOfArcWeaponCount = pkt.OutOfArcWeapons; local.DisabledWeaponCount = pkt.DisabledWeapons; local.AllWeaponsOutOfArc = pkt.AllWeaponsOutOfArc; local.MaxThermalRatio = pkt.LocalMaxThermalRatio; - if (!pkt.LocalAlive && local.Alive) + if (!pkt.LocalAlive && local.Grid.CoreHp > 0f) { local.Grid.ApplyReplicatedDamage(0, 0, 0f, local.Grid.Temperature[0, 0], 0f, local.Grid.HitSequence + 1); } @@ -1017,7 +1039,7 @@ namespace RustToDust.Net Quaternion deltaRot = NormalizeQuat(prevVisRot * Quaternion.Inverse(newPredRot)); if (deltaRot.W < 0f) deltaRot = -deltaRot; - bool hardSnap = !pkt.LocalAlive || chassisChanged || _pendingChassisSwapSnap || deltaPos.Length() > HardSnapThresholdM; + bool hardSnap = !pkt.LocalAlive || prevLocalLifecycle != local.Lifecycle || !local.IsGroundedActive || chassisChanged || _pendingChassisSwapSnap || deltaPos.Length() > HardSnapThresholdM; if (hardSnap) { _predErrorPos = Vector3.Zero; @@ -1061,6 +1083,30 @@ namespace RustToDust.Net if (nc.SlotId == _localContenderId || nc.SlotId >= _viewState.Contenders.Count) continue; var c = _viewState.Contenders[nc.SlotId]; c.IsHuman = nc.IsHuman; + c.Lifecycle = nc.Lifecycle; + if (nc.Lifecycle != ContenderLifecycle.Deploying) + { + _viewState.OrbitalDrop.CancelContenderPod(c.Id); + } + else + { + var pods = _viewState.OrbitalDrop.ActivePods; + for (int p = 0; p < pods.Count; p++) + { + if (pods[p].PodKind == OrbitalPodKind.Contender && pods[p].ContenderId == c.Id) + { + pods[p].SnapPreviousPose(); + pods[p].X = nc.Pos.X; + pods[p].Y = nc.Pos.Y - c.Grid.Spec.HalfHeight; + pods[p].Z = nc.Pos.Z; + pods[p].VelX = nc.Vel.X; + pods[p].VelY = nc.Vel.Y; + pods[p].VelZ = nc.Vel.Z; + pods[p].Phase = nc.PodRetroBurn ? OrbitalPodPhase.RetroBurn : OrbitalPodPhase.Freefall; + break; + } + } + } c.FireCmd = nc.Fire; c.BrakeCmd = nc.Brake; c.ThrottleCmd = nc.Throttle; @@ -1286,8 +1332,11 @@ namespace RustToDust.Net _pendingChassisSwapSnap = true; _predErrorPos = Vector3.Zero; _predErrorRot = Quaternion.Identity; - float groundY = _viewState.Terrain.SampleHeight(l.X, l.Z); - l.Y = MathF.Max(l.Y, groundY + l.Grid.Spec.HalfHeight + 0.1f); + if (l.IsGroundedActive) + { + float groundY = _viewState.Terrain.SampleHeight(l.X, l.Z); + l.Y = MathF.Max(l.Y, groundY + l.Grid.Spec.HalfHeight + 0.1f); + } l.SnapPreviousPose(); } SpawnLocalPredictionBody( @@ -1314,6 +1363,7 @@ namespace RustToDust.Net if (elim.VictimId >= 0 && elim.VictimId < _viewState.Contenders.Count) { var v = _viewState.Contenders[elim.VictimId]; + v.Lifecycle = (ContenderLifecycle)elim.VictimLifecycleByte; v.Grid.ApplyReplicatedDamage(0, 0, 0f, v.Grid.Temperature[0, 0], 0f, v.Grid.HitSequence + 1); } if (!elim.IsSpectatorKiller && elim.KillerId >= 0 && elim.KillerId < _viewState.Contenders.Count) @@ -1321,6 +1371,9 @@ namespace RustToDust.Net _viewState.Contenders[elim.KillerId].Kills = elim.KillerKills; } break; + case DropPodEvent dpe: + _viewState.OrbitalDrop.ApplyReplicatedDropPodEvent(dpe); + break; case SpectatorDestroyedEvent sdet: { int sIdx = sdet.SpectatorId >= 1000 ? sdet.SpectatorId - 1000 : sdet.SpectatorId; diff --git a/src/RustToDust.Net/ServerMatchHost.cs b/src/RustToDust.Net/ServerMatchHost.cs index ceabc2b..def3e5c 100644 --- a/src/RustToDust.Net/ServerMatchHost.cs +++ b/src/RustToDust.Net/ServerMatchHost.cs @@ -38,6 +38,7 @@ namespace RustToDust.Net public bool SnapNext; public int AckedLoadoutVersion; public int AckedDamageVersion; + public ContenderLifecycle LastLifecycle; } private readonly Socket _socket; @@ -545,7 +546,8 @@ namespace RustToDust.Net InPvs = inPvs, SnapNext = false, AckedLoadoutVersion = inPvs ? c.LoadoutVersion : -1, - AckedDamageVersion = inPvs ? c.DamageVersion : -1 + AckedDamageVersion = inPvs ? c.DamageVersion : -1, + LastLifecycle = c.Lifecycle }; } for (int i = 0; i < _session.State.Spectators.Spectators.Count; i++) @@ -586,6 +588,11 @@ namespace RustToDust.Net var c = _session.State.Contenders[i]; bool inPvs = _session.IsEntityInPeerPvs(obsId, true, c.Id); ref var tracker = ref peer.ContenderTrackers[i]; + if (c.Lifecycle != tracker.LastLifecycle) + { + tracker.SnapNext = true; + tracker.LastLifecycle = c.Lifecycle; + } if (inPvs && !tracker.InPvs) { tracker.SnapNext = true; @@ -757,6 +764,20 @@ namespace RustToDust.Net filtered.Add(oh); } break; + case DropPodEvent dpe: + { + var kind = (DropPodEventKind)dpe.Kind; + bool deliver = kind == DropPodEventKind.WaveAnnounced || + (dpe.ContenderId == obsId) || + (dpe.PodKind == (byte)OrbitalPodKind.Contender && dpe.ContenderId >= 0 && + _session.IsEntityInPeerPvs(obsId, true, dpe.ContenderId)) || + _session.IsPointInPeerPvs(obsId, dpe.X, dpe.Y + 2.0f, dpe.Z); + if (deliver) + { + filtered.Add(dpe); + } + break; + } default: filtered.Add(ev); break; @@ -867,6 +888,20 @@ namespace RustToDust.Net new Vector3(c.AimX - c.X, (float.IsNaN(c.AimY) ? c.Y : c.AimY) - c.Y, c.AimZ - c.Z), new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW)); + bool isRetroBurn = false; + if (c.IsInDropPod && c.ActivePodId is { } podId) + { + var pods = _session.State.OrbitalDrop.ActivePods; + for (int p = 0; p < pods.Count; p++) + { + if (pods[p].PodId == podId) + { + isRetroBurn = pods[p].Phase == OrbitalPodPhase.RetroBurn; + break; + } + } + } + pvsContenders.Add(new NetContenderState { SlotId = (byte)c.Id, @@ -875,6 +910,8 @@ namespace RustToDust.Net Fire = c.FireCmd, Brake = c.BrakeCmd, Snap = snap, + Lifecycle = c.Lifecycle, + PodRetroBurn = isRetroBurn, Pos = new Vector3(c.X, c.Y, c.Z), Rot = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW), Vel = new Vector3(c.VelX, c.VelY, c.VelZ), @@ -887,7 +924,7 @@ namespace RustToDust.Net }); float d2 = (c.X - local.X) * (c.X - local.X) + (c.Z - local.Z) * (c.Z - local.Z); - if (c.Alive && c.Grid.Spec.IsWalker && d2 <= 220f * 220f && + if (c.IsGroundedActive && c.Grid.Spec.IsWalker && d2 <= 220f * 220f && _session.TrySampleInterpolatedWalkerPose(true, c.Id, 1f, out var ws)) { walkerCandidates.Add((d2, new NetWalkerEntry { IsContender = true, EntityId = (byte)c.Id, Snapshot = ws })); @@ -954,6 +991,25 @@ namespace RustToDust.Net ? (byte)Math.Clamp(obsState.DetectedByCount, 0, 255) : (byte)0; + OrbitalPodPhase localPodPhase = OrbitalPodPhase.Freefall; + if (local.IsInDropPod && local.ActivePodId is { } localPodId) + { + var pods = _session.State.OrbitalDrop.ActivePods; + for (int p = 0; p < pods.Count; p++) + { + if (pods[p].PodId == localPodId) + { + localPodPhase = pods[p].Phase; + break; + } + } + } + + var wave = _session.State.OrbitalDrop.WaveState; + ushort nextWaveAtTick = wave.NextWaveAtSec.HasValue + ? (ushort)Math.Clamp((int)MathF.Round(wave.NextWaveAtSec.Value / ArenaSession.FixedDt), 0, ushort.MaxValue - 1) + : ushort.MaxValue; + byte[] corePayload = SnapshotCodec.EncodeCorePvs( _matchGeneration, _snapshotSeq, @@ -971,7 +1027,11 @@ namespace RustToDust.Net pvsContenders, walkers, combatSpecs, - out int combatSpecsWritten); + out int combatSpecsWritten, + (byte)wave.CurrentWaveIndex, + nextWaveAtTick, + wave.RespawnCutoffReached, + localPodPhase); SendLatestToPeer(peer, corePayload); @@ -1061,9 +1121,45 @@ namespace RustToDust.Net SafeRadius = _session.State.Spectators.SafeRadius, Phase = (byte)(_session.State.Phase == MatchPhase.Completed ? 1 : 0), WinnerContenderId = _session.State.WinnerContenderId, - ConnectedHumans = ConnectedHumanCount + ConnectedHumans = ConnectedHumanCount, + CurrentWaveIndex = _session.State.OrbitalDrop.CurrentWaveIndex, + RespawnCutoffReached = _session.State.OrbitalDrop.RespawnCutoffReached }; + var activePods = _session.State.OrbitalDrop.ActivePods; + for (int i = 0; i < activePods.Count; i++) + { + var pod = activePods[i]; + if (pod.PodKind == OrbitalPodKind.Contender && + pod.ContenderId != forContenderId && + !_session.IsEntityInPeerPvs(forContenderId, true, pod.ContenderId)) + { + continue; + } + if (pod.PodKind != OrbitalPodKind.Contender && + !_session.IsPointInPeerPvs(forContenderId, pod.X, pod.Y + 2.0f, pod.Z)) + { + continue; + } + dto.ActivePods.Add(new OrbitalPodDto + { + PodId = pod.PodId, + PodKind = (byte)pod.PodKind, + Phase = (byte)pod.Phase, + WaveIndex = pod.WaveIndex, + ContenderId = pod.ContenderId, + X = pod.X, + Y = pod.Y, + Z = pod.Z, + VelX = pod.VelX, + VelY = pod.VelY, + VelZ = pod.VelZ, + Yaw = pod.Yaw, + ChassisId = pod.Chassis?.Id, + ModuleId = pod.Module?.Id + }); + } + for (int i = 0; i < _terrainStampHistory.Count; i++) { var ts = _terrainStampHistory[i]; @@ -1087,7 +1183,9 @@ namespace RustToDust.Net IsHuman = c.IsHuman, X = c.X, Y = c.Y, Z = c.Z, Yaw = c.Yaw, Kills = c.Kills, - Loadout = ArenaSession.BuildContenderLoadoutEvent(c, includeCargo: c.Id == forContenderId) + Loadout = ArenaSession.BuildContenderLoadoutEvent(c, includeCargo: c.Id == forContenderId), + LifecycleByte = (byte)c.Lifecycle, + RespawnsRemaining = (byte)Math.Clamp(c.RespawnsRemaining, 0, 255) }); } diff --git a/src/RustToDust.Net/SnapshotCodec.cs b/src/RustToDust.Net/SnapshotCodec.cs index 7d21c13..91c1168 100644 --- a/src/RustToDust.Net/SnapshotCodec.cs +++ b/src/RustToDust.Net/SnapshotCodec.cs @@ -31,6 +31,8 @@ namespace RustToDust.Net public bool Fire; public bool Brake; public bool Snap; + public ContenderLifecycle Lifecycle; + public bool PodRetroBurn; public Vector3 Pos; public Quaternion Rot; public Vector3 Vel; @@ -89,8 +91,13 @@ namespace RustToDust.Net public int DisabledWeapons; public bool AllWeaponsOutOfArc; public ushort ContenderPvsMask; + public byte CurrentWaveIndex; + public ushort NextWaveAtTick; + public bool RespawnCutoffReached; public bool LocalAlive; + public ContenderLifecycle LocalLifecycle; + public OrbitalPodPhase LocalPodPhase; public Vector3 LocalPos; public Quaternion LocalRot; public Vector3 LocalVel; @@ -308,7 +315,11 @@ namespace RustToDust.Net IReadOnlyList pvsContenders, IReadOnlyList pvsWalkers, IReadOnlyList combatSpectators, - out int combatSpecsWritten) + out int combatSpecsWritten, + byte currentWaveIndex = 0, + ushort nextWaveAtTick = ushort.MaxValue, + bool respawnCutoffReached = false, + OrbitalPodPhase localPodPhase = OrbitalPodPhase.Freefall) { Span buf = stackalloc byte[MaxLatestPayloadBytes]; int offset = 0; @@ -335,9 +346,15 @@ namespace RustToDust.Net (localContender.AllWeaponsOutOfArc ? (1 << 12) : 0)); BinaryPrimitives.WriteUInt16LittleEndian(buf.Slice(offset), arc); offset += 2; BinaryPrimitives.WriteUInt16LittleEndian(buf.Slice(offset), contenderPvsMask); offset += 2; + buf[offset++] = (byte)((currentWaveIndex & 0x07) | (respawnCutoffReached ? 0x80 : 0)); + BinaryPrimitives.WriteUInt16LittleEndian(buf.Slice(offset), nextWaveAtTick); offset += 2; // Local prediction + telemetry block - buf[offset++] = (byte)(localContender.Alive ? 1 : 0); + byte localFlags = (byte)( + (localContender.Alive ? 1 : 0) | + (((byte)localContender.Lifecycle & 0x03) << 1) | + (((byte)localPodPhase & 0x03) << 3)); + buf[offset++] = localFlags; BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.X); offset += 4; BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.Y); offset += 4; BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.Z); offset += 4; @@ -397,6 +414,8 @@ namespace RustToDust.Net if (c.Fire) flags |= 4; if (c.Brake) flags |= 8; if (c.Snap) flags |= 16; + flags |= (byte)(((byte)c.Lifecycle & 0x03) << 5); + if (c.PodRetroBurn) flags |= 128; buf[offset++] = flags; BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), c.Pos.X); offset += 4; BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), c.Pos.Y); offset += 4; @@ -464,7 +483,7 @@ namespace RustToDust.Net public static bool TryDecodeCorePvs(ReadOnlySpan span, out DecodedCorePvsSnapshot res) { res = null!; - if (span.Length < 89 || span[0] != (byte)LatestPacketKind.CorePvs) + if (span.Length < 92 || span[0] != (byte)LatestPacketKind.CorePvs) { return false; } @@ -493,8 +512,15 @@ namespace RustToDust.Net decoded.DisabledWeapons = (arc >> 8) & 0xF; decoded.AllWeaponsOutOfArc = (arc & (1 << 12)) != 0; decoded.ContenderPvsMask = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(offset)); offset += 2; + byte waveByte = span[offset++]; + decoded.CurrentWaveIndex = (byte)(waveByte & 0x07); + decoded.RespawnCutoffReached = (waveByte & 0x80) != 0; + decoded.NextWaveAtTick = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(offset)); offset += 2; - decoded.LocalAlive = (span[offset++] & 1) != 0; + byte localFlags = span[offset++]; + decoded.LocalAlive = (localFlags & 1) != 0; + decoded.LocalLifecycle = (ContenderLifecycle)((localFlags >> 1) & 0x03); + decoded.LocalPodPhase = (OrbitalPodPhase)((localFlags >> 3) & 0x03); decoded.LocalPos = new Vector3( BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)), BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)), @@ -559,6 +585,8 @@ namespace RustToDust.Net Fire = (flags & 4) != 0, Brake = (flags & 8) != 0, Snap = (flags & 16) != 0, + Lifecycle = (ContenderLifecycle)((flags >> 5) & 0x03), + PodRetroBurn = (flags & 128) != 0, Pos = pos, Rot = rot, Vel = vel, diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs index 6b84a48..c53a525 100644 --- a/src/RustToDust.Ymir/ArenaSession.cs +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -31,23 +31,37 @@ namespace RustToDust.Ymir private readonly bool[,] _contenderPvs = new bool[MatchState.ContenderCount, MatchState.ContenderCount]; private readonly bool[,] _spectatorPvs; private readonly List _stepEvents = new(); + private long _forwardedPodEventId; private bool _disposed; - public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false) + public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false) { - State = new MatchState(seed, mapKind); + State = new MatchState(seed, mapKind, skipInitialDrop); _spectatorPvs = new bool[MatchState.ContenderCount, State.Spectators.Spectators.Count]; + _forwardedPodEventId = State.PodEvents.Count > 0 ? State.PodEvents[^1].EventId : 0; State.ChassisSwapped += OnContenderChassisSwapped; State.LoadoutChanged += OnContenderLoadoutChanged; State.DropSpawned += OnDropSpawned; State.DropPickedUp += OnDropPickedUp; + State.ContenderPodTouchedDown += OnContenderPodTouchedDown; State.Broadcast.LineEmitted += OnBroadcastLineEmitted; if (slot0Human && State.Contenders.Count > 0) { State.Contenders[0].IsHuman = true; State.Contenders[0].Name = "Contender 01 (You)"; + if (State.Contenders[0].ActivePodId is { } podId) + { + foreach (var p in State.OrbitalDrop.ActivePods) + { + if (p.PodId == podId) + { + p.AllowFlatRoofLanding = State.MapKind == ArenaMapKind.Sion; + break; + } + } + } } _world = new Box3DSoaWorld( @@ -106,6 +120,17 @@ namespace RustToDust.Ymir { State.GetOrCreateObserverState(contenderId); } + if (c.ActivePodId is { } activePodId) + { + for (int p = 0; p < State.OrbitalDrop.ActivePods.Count; p++) + { + if (State.OrbitalDrop.ActivePods[p].PodId == activePodId) + { + State.OrbitalDrop.ActivePods[p].AllowFlatRoofLanding = isHuman && State.MapKind == ArenaMapKind.Sion; + break; + } + } + } if (changed) { @@ -267,6 +292,13 @@ namespace RustToDust.Ymir return; } var c = State.Contenders[contenderId]; + State.OrbitalDrop.CancelContenderPod(contenderId); + if (c.Lifecycle == ContenderLifecycle.Deploying || c.Lifecycle == ContenderLifecycle.WaitingForRespawnWave) + { + c.Lifecycle = ContenderLifecycle.Active; + c.HasTouchdownPose = false; + c.TouchdownOnRoof = false; + } c.X = x; c.Z = z; if (yaw.HasValue) c.Yaw = yaw.Value; @@ -277,7 +309,7 @@ namespace RustToDust.Ymir _contenderBodies.Remove(contenderId); } _contenderWalkers.Remove(contenderId); - if (c.Alive) + if (c.IsGroundedActive) { SpawnContenderBody(c); } @@ -544,6 +576,7 @@ namespace RustToDust.Ymir private void SnapshotPreviousPoses() { + State.OrbitalDrop.SnapshotPreviousPoses(); for (int i = 0; i < State.Contenders.Count; i++) { State.Contenders[i].SnapPreviousPose(); @@ -603,6 +636,7 @@ namespace RustToDust.Ymir UpdateRingClearance(); ApplyAllHumanInputs(); MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight); + State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown); ApplyPhysicsDrives(); _world.Step(FixedDt, subSteps); @@ -611,6 +645,7 @@ namespace RustToDust.Ymir UpdateObserverDetectionMemories(); StepThermalAndCooldowns(); ProcessWeapons(); + FlushPodEventsToStepEvents(); MatchRules.UpdateMatchOutcome(State); return; } @@ -621,6 +656,7 @@ namespace RustToDust.Ymir long t1 = Stopwatch.GetTimestamp(); ApplyAllHumanInputs(); MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight); + State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown); long t2 = Stopwatch.GetTimestamp(); ApplyPhysicsDrives(); long t3 = Stopwatch.GetTimestamp(); @@ -633,6 +669,7 @@ namespace RustToDust.Ymir StepThermalAndCooldowns(); ProcessWeapons(); long t7 = Stopwatch.GetTimestamp(); + FlushPodEventsToStepEvents(); MatchRules.UpdateMatchOutcome(State); PerfRingMs += (t1 - t0) * toMs; @@ -726,10 +763,161 @@ namespace RustToDust.Ymir for (int i = 0; i < State.Contenders.Count; i++) { var c = State.Contenders[i]; + if (c.IsGroundedActive) + { + SpawnContenderBody(c); + } + } + } + + private void OnContenderPodTouchedDown(ContenderState c) + { + if (_contenderBodies.TryGetValue(c.Id, out var oldHandle)) + { + _world.RemoveBody(oldHandle); + _contenderBodies.Remove(c.Id); + } + _contenderWalkers.Remove(c.Id); + if (c.IsGroundedActive) + { SpawnContenderBody(c); } } + private void OnPodTouchedDown(OrbitalPod pod, DropSurfaceSample sample) + { + if (!sample.IsBuildingRoof) + { + float craterR = pod.PodKind == OrbitalPodKind.Contender ? 3.4f : 2.1f; + float scorchR = pod.PodKind == OrbitalPodKind.Contender ? 4.2f : 2.6f; + _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = pod.X, Z = pod.Z, Radius = craterR, Depth = 0.32f }); + _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = pod.X, Z = pod.Z, Radius = scorchR }); + } + } + + private void FlushPodEventsToStepEvents() + { + var podEvents = State.PodEvents; + for (int i = 0; i < podEvents.Count; i++) + { + var ev = podEvents[i]; + if (ev.EventId <= _forwardedPodEventId) + { + continue; + } + _forwardedPodEventId = ev.EventId; + _stepEvents.Add(new DropPodEvent + { + EventId = ev.EventId, + Kind = (byte)ev.Kind, + WaveIndex = ev.WaveIndex, + PodId = ev.PodId, + PodKind = (byte)ev.PodKind, + ContenderId = ev.ContenderId, + X = ev.X, + Y = ev.Y, + Z = ev.Z, + VelX = ev.VelX, + VelY = ev.VelY, + VelZ = ev.VelZ, + NormalX = ev.SurfaceNormal.X, + NormalY = ev.SurfaceNormal.Y, + NormalZ = ev.SurfaceNormal.Z, + ChassisId = ev.ChassisId, + ModuleId = ev.ModuleId, + DropId = ev.DropId, + RespawnsClosed = ev.RespawnsClosed, + GearCount = ev.GearCount, + RespawnCount = ev.RespawnCount + }); + } + } + + public DropSurfaceSample QueryDropSurface(float x, float z, float footRadius, float referenceMaxY) + { + float terrainY = State.Terrain.SampleHeight(x, z); + var (nx, ny, nz) = State.Terrain.SampleNormal(x, z); + Vector3 terrainNorm = new(nx, ny, nz); + if (terrainNorm.LengthSquared() < 1e-4f) terrainNorm = Vector3.UnitY; + else terrainNorm = Vector3.Normalize(terrainNorm); + + if (State.MapKind == ArenaMapKind.Sion && State.SionMap is { } sionMap) + { + if (!sionMap.TryGetBuildingAt(x, z, footRadius, out var bldg)) + { + return new DropSurfaceSample( + terrainY, + terrainNorm, + IsBuildingRoof: false, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: false); + } + + float castStartY = MathF.Max(referenceMaxY, bldg.RoofY + 6f); + float castSpan = MathF.Max(20f, castStartY - (terrainY - 12f)); + var centerHit = _world.CastRayClosest((x, castStartY, z), (0f, -castSpan, 0f)); + if (centerHit.Hit && + centerHit.StableId >= StaticMeshStableIdBase && + centerHit.StableId < ContenderStableIdBase) + { + float roofY = centerHit.Point.Y; + Vector3 roofNorm = new(centerHit.Normal.X, centerHit.Normal.Y, centerHit.Normal.Z); + if (roofNorm.LengthSquared() < 1e-4f) roofNorm = Vector3.UnitY; + else roofNorm = Vector3.Normalize(roofNorm); + + bool flatValid = false; + if (roofNorm.Y >= 0.90f) + { + flatValid = true; + float r = MathF.Max(0.8f, footRadius); + ReadOnlySpan<(float Ox, float Oz)> offsets = stackalloc (float, float)[] + { + (-r, -r), (r, -r), (-r, r), (r, r) + }; + for (int k = 0; k < 4; k++) + { + float cx = x + offsets[k].Ox; + float cz = z + offsets[k].Oz; + var cornerHit = _world.CastRayClosest((cx, roofY + 2.5f, cz), (0f, -5.0f, 0f)); + if (!cornerHit.Hit || + cornerHit.StableId < StaticMeshStableIdBase || + cornerHit.StableId >= ContenderStableIdBase || + MathF.Abs(cornerHit.Point.Y - roofY) > 0.45f) + { + flatValid = false; + break; + } + var aboveHit = _world.CastRayClosest((cx, roofY + 60f, cz), (0f, -58f, 0f)); + if (aboveHit.Hit && + aboveHit.StableId >= StaticMeshStableIdBase && + aboveHit.StableId < ContenderStableIdBase && + aboveHit.Point.Y > roofY + 0.6f) + { + flatValid = false; + break; + } + } + } + + return new DropSurfaceSample( + MathF.Max(terrainY, roofY), + roofNorm, + IsBuildingRoof: true, + IsFlatRoofValid: flatValid, + IsInsideBuildingFootprint: true); + } + + return new DropSurfaceSample( + MathF.Max(terrainY, bldg.RoofY), + terrainNorm, + IsBuildingRoof: true, + IsFlatRoofValid: false, + IsInsideBuildingFootprint: true); + } + + return State.DefaultDropSurfaceQuery(x, z, footRadius, referenceMaxY); + } + public static float GetPhysicsHalfHeight(ChassisSpec spec) => spec.IsWalker ? spec.HalfHeight * (spec.Plane == GridPlane.Dorsal ? 0.62f : 0.72f) @@ -737,44 +925,62 @@ namespace RustToDust.Ymir private void SpawnContenderBody(ContenderState c) { + if (!c.IsGroundedActive) + { + return; + } var spec = c.Grid.Spec; float physHalfH = GetPhysicsHalfHeight(spec); float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; float density = spec.MassKg / MathF.Max(0.1f, volume); - var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw); + Quaternion q; + float spawnY; + float initVelY = 0f; ulong stableId = ContenderStableIdBase + (ulong)c.Id; - float clearance = spec.IsVtol - ? Math.Clamp(c.TargetHoverAltAgl, MatchRules.VtolMinClearanceAgl, MathF.Max(MatchRules.VtolMinClearanceAgl, spec.HoverMaxAltitudeM)) - : 0.15f; - float spawnY = State.Terrain.SampleHeight(c.X, c.Z) + spec.HalfHeight + clearance; - if (spec.IsWalker && spec.Plane == GridPlane.Dorsal) - { - var (nx, ny, nz) = State.Terrain.SampleNormal(c.X, c.Z); - Vector3 centerNorm = new Vector3(nx, ny, nz); - centerNorm = centerNorm.LengthSquared() > 1e-6f ? Vector3.Normalize(centerNorm) : Vector3.UnitY; - Vector3 fwd = Vector3.Transform(Vector3.UnitZ, q); - fwd.Y = 0f; - fwd = fwd.LengthSquared() > 1e-5f ? Vector3.Normalize(fwd) : Vector3.UnitZ; - Vector3 right = Vector3.Cross(fwd, Vector3.UnitY); - Vector3 hullSlope = WalkerLocomotion.ComputeHullSlopeNormal(State.Terrain, c.X, c.Z, fwd, right, spec.HalfWidth, spec.HalfLength, centerNorm, out _); - q = WalkerLocomotion.AlignUpToSlope(q, hullSlope, 0.90f, 0.350f); - float minCornerClr = float.PositiveInfinity; - foreach (float sx in new[] { -spec.HalfWidth, spec.HalfWidth }) + if (c.HasTouchdownPose) + { + q = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW); + q = q.LengthSquared() < 1e-6f ? Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw) : Quaternion.Normalize(q); + spawnY = c.Y; + initVelY = c.VelY; + } + else + { + q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw); + float clearance = spec.IsVtol + ? Math.Clamp(c.TargetHoverAltAgl, MatchRules.VtolMinClearanceAgl, MathF.Max(MatchRules.VtolMinClearanceAgl, spec.HoverMaxAltitudeM)) + : 0.15f; + spawnY = State.Terrain.SampleHeight(c.X, c.Z) + spec.HalfHeight + clearance; + if (spec.IsWalker && spec.Plane == GridPlane.Dorsal) { - foreach (float sz in new[] { -spec.HalfLength, spec.HalfLength }) + var (nx, ny, nz) = State.Terrain.SampleNormal(c.X, c.Z); + Vector3 centerNorm = new Vector3(nx, ny, nz); + centerNorm = centerNorm.LengthSquared() > 1e-6f ? Vector3.Normalize(centerNorm) : Vector3.UnitY; + Vector3 fwd = Vector3.Transform(Vector3.UnitZ, q); + fwd.Y = 0f; + fwd = fwd.LengthSquared() > 1e-5f ? Vector3.Normalize(fwd) : Vector3.UnitZ; + Vector3 right = Vector3.Cross(fwd, Vector3.UnitY); + Vector3 hullSlope = WalkerLocomotion.ComputeHullSlopeNormal(State.Terrain, c.X, c.Z, fwd, right, spec.HalfWidth, spec.HalfLength, centerNorm, out _); + q = WalkerLocomotion.AlignUpToSlope(q, hullSlope, 0.90f, 0.350f); + + float minCornerClr = float.PositiveInfinity; + foreach (float sx in new[] { -spec.HalfWidth, spec.HalfWidth }) { - Vector3 corner = new Vector3(c.X, spawnY, c.Z) + Vector3.Transform(new Vector3(sx, -physHalfH, sz), q); - float clr = corner.Y - State.Terrain.SampleHeight(corner.X, corner.Z); - if (clr < minCornerClr) minCornerClr = clr; + foreach (float sz in new[] { -spec.HalfLength, spec.HalfLength }) + { + Vector3 corner = new Vector3(c.X, spawnY, c.Z) + Vector3.Transform(new Vector3(sx, -physHalfH, sz), q); + float clr = corner.Y - State.Terrain.SampleHeight(corner.X, corner.Z); + if (clr < minCornerClr) minCornerClr = clr; + } + } + if (minCornerClr < 0.25f) + { + spawnY += MathF.Min(1.2f, 0.25f - minCornerClr); } } - if (minCornerClr < 0.25f) - { - spawnY += MathF.Min(1.2f, 0.25f - minCornerClr); - } + c.Y = spawnY; } - c.Y = spawnY; var handle = _world.AddBox( stableId, @@ -792,8 +998,16 @@ namespace RustToDust.Ymir c.CurrRotZ = q.Z; c.CurrRotW = q.W; c.VelX = 0f; - c.VelY = 0f; + c.VelY = initVelY; c.VelZ = 0f; + if (MathF.Abs(initVelY) > 1e-3f) + { + float mass = _world.View.Mass[handle.Lane]; + if (mass > 0f) + { + _world.ApplyImpulse(handle.Lane, (0f, initVelY * mass, 0f), (c.X, spawnY, c.Z)); + } + } c.SnapPreviousPose(); c.ResetAimTracker(c.Yaw); @@ -811,13 +1025,15 @@ namespace RustToDust.Ymir private void OnContenderChassisSwapped(ContenderState c) { + c.HasTouchdownPose = false; + c.TouchdownOnRoof = false; if (_contenderBodies.TryGetValue(c.Id, out var oldHandle)) { _world.RemoveBody(oldHandle); _contenderBodies.Remove(c.Id); } _contenderWalkers.Remove(c.Id); - if (c.Alive) + if (c.IsGroundedActive) { SpawnContenderBody(c); } @@ -886,7 +1102,7 @@ namespace RustToDust.Ymir for (int i = 0; i < State.Contenders.Count; i++) { var c = State.Contenders[i]; - contacts[i] = new RingContact(c.Id, c.X, c.Z, c.Alive, c.Y, c.Grid.Spec.HalfHeight); + contacts[i] = new RingContact(c.Id, c.X, c.Z, c.IsGroundedActive, c.Y, c.Grid.Spec.HalfHeight); } State.Spectators.UpdateClearance(contacts, FixedDt, HasSpectatorLos); @@ -934,7 +1150,8 @@ namespace RustToDust.Ymir ArenaMapKind mapKind, WalkerState? walker, float dt, - bool injectEngineHeat) + bool injectEngineHeat, + Box3DSoaWorld? world = null) { float mass = view.Mass[lane]; if (mass <= 0f) @@ -985,7 +1202,8 @@ namespace RustToDust.Ymir out Vector3 supportForce, out Vector3 supportTorque, out Vector3 terrainNormal, - out int groundedCorners); + out int groundedCorners, + world); var forward = Vector3.Transform(Vector3.UnitZ, q); forward.Y = 0f; @@ -1073,7 +1291,7 @@ namespace RustToDust.Ymir for (int i = 0; i < State.Contenders.Count; i++) { var c = State.Contenders[i]; - if (!c.Alive || !_contenderBodies.TryGetValue(c.Id, out var handle)) + if (!c.IsGroundedActive || !_contenderBodies.TryGetValue(c.Id, out var handle)) { continue; } @@ -1093,7 +1311,7 @@ namespace RustToDust.Ymir _contenderWalkers[c.Id] = ws; } - StepContenderPhysicsDrive(c, view, handle.Lane, State.Terrain, State.MapKind, ws, FixedDt, injectEngineHeat: true); + StepContenderPhysicsDrive(c, view, handle.Lane, State.Terrain, State.MapKind, ws, FixedDt, injectEngineHeat: true, world: _world); } // Spectators @@ -1489,7 +1707,8 @@ namespace RustToDust.Ymir out Vector3 supportForce, out Vector3 supportTorque, out Vector3 terrainNormal, - out int groundedCorners) + out int groundedCorners, + Box3DSoaWorld? world = null) { supportForce = Vector3.Zero; supportTorque = Vector3.Zero; @@ -1498,12 +1717,34 @@ namespace RustToDust.Ymir var (nx, ny, nz) = terrain.SampleNormal(pos.X, pos.Z); terrainNormal = new Vector3(nx, ny, nz); + bool isSion = mapKind == ArenaMapKind.Sion; + float ghCenterRaw = terrain.SampleHeight(pos.X, pos.Z); + float centerGap = (pos.Y - spec.HalfHeight) - ghCenterRaw; + bool checkRoofSupport = isSion && centerGap > 1.5f && world is not null; + if (checkRoofSupport) + { + var centerRoof = world!.CastRayClosest((pos.X, pos.Y + 0.5f, pos.Z), (0f, -6.0f, 0f)); + if (centerRoof.Hit && centerRoof.StableId >= StaticMeshStableIdBase && centerRoof.StableId < ContenderStableIdBase) + { + ghCenterRaw = MathF.Max(ghCenterRaw, centerRoof.Point.Y); + Vector3 rn = new(centerRoof.Normal.X, centerRoof.Normal.Y, centerRoof.Normal.Z); + if (rn.LengthSquared() > 1e-4f) + { + terrainNormal = Vector3.Normalize(rn); + } + centerGap = (pos.Y - spec.HalfHeight) - ghCenterRaw; + } + else + { + checkRoofSupport = false; + } + } + // Blend smoothly from pure vertical on flat ground to surface normal on steep mesa/dune slopes float slopeBlend = Math.Clamp((0.985f - terrainNormal.Y) / 0.18f, 0f, 1f); Vector3 supportDir = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, slopeBlend)); float orthoScale = MathF.Max(0.35f, terrainNormal.Y); - bool isSion = mapKind == ArenaMapKind.Sion; float hx = MathF.Min(spec.HalfWidth * 0.9f, 2.4f); float hz = MathF.Min(spec.HalfLength * 0.9f, 2.8f); float bottomY = -spec.HalfHeight; @@ -1525,6 +1766,14 @@ namespace RustToDust.Ymir Vector3 r = Vector3.Transform(corners[k], q); Vector3 wp = pos + r; float gh = terrain.SampleHeight(wp.X, wp.Z); + if (checkRoofSupport) + { + var cornerRoof = world!.CastRayClosest((wp.X, pos.Y + 0.5f, wp.Z), (0f, -6.0f, 0f)); + if (cornerRoof.Hit && cornerRoof.StableId >= StaticMeshStableIdBase && cornerRoof.StableId < ContenderStableIdBase) + { + gh = MathF.Max(gh, cornerRoof.Point.Y); + } + } float pen = (gh + restTravel) - wp.Y; if (pen > 0f) { @@ -1541,8 +1790,7 @@ namespace RustToDust.Ymir } // Center skid-plate bump-stop prevents belly clipping when straddling sharp ridge crests at speed - float ghCenter = terrain.SampleHeight(pos.X, pos.Z); - float centerGap = (pos.Y - spec.HalfHeight) - ghCenter; + float ghCenter = ghCenterRaw; float centerPen = (ghCenter + 0.08f) - (pos.Y - spec.HalfHeight); if (!isSion && centerPen > 0f) { @@ -1617,7 +1865,7 @@ namespace RustToDust.Ymir for (int i = 0; i < State.Contenders.Count; i++) { var c = State.Contenders[i]; - if (!c.Alive || !_contenderBodies.TryGetValue(c.Id, out var handle)) + if (!c.IsGroundedActive || !_contenderBodies.TryGetValue(c.Id, out var handle)) { continue; } @@ -1630,7 +1878,7 @@ namespace RustToDust.Ymir float stepDist = MathF.Sqrt((c.X - prevX) * (c.X - prevX) + (c.Z - prevZ) * (c.Z - prevZ)); float groundY = State.Terrain.SampleHeight(c.X, c.Z); - if (c.Speed > 2.0f && c.Y - c.Grid.Spec.HalfHeight <= groundY + 0.65f) + if (c.Speed > 2.0f && !c.TouchdownOnRoof && c.Y - c.Grid.Spec.HalfHeight <= groundY + 0.65f) { _trackDistAccum[i] += stepDist; if (_trackDistAccum[i] >= 2.2f) @@ -1855,7 +2103,7 @@ namespace RustToDust.Ymir for (int i = 0; i < State.Contenders.Count; i++) { var c = State.Contenders[i]; - if (!c.Alive) + if (!c.IsGroundedActive) { continue; } @@ -1916,7 +2164,7 @@ namespace RustToDust.Ymir for (int i = 0; i < State.Contenders.Count; i++) { var c = State.Contenders[i]; - if (!c.Alive || !_contenderBodies.TryGetValue(c.Id, out var handle)) + if (!c.IsGroundedActive || !_contenderBodies.TryGetValue(c.Id, out var handle)) { continue; } @@ -2080,7 +2328,7 @@ namespace RustToDust.Ymir for (int j = 0; j < State.Contenders.Count; j++) { var other = State.Contenders[j]; - if (other.Id == shooter.Id || !other.Alive || !other.Grid.Spec.IsVtol) + if (other.Id == shooter.Id || !other.IsGroundedActive || !other.Grid.Spec.IsVtol) { continue; } @@ -2531,7 +2779,7 @@ namespace RustToDust.Ymir if (targetRef.IsContender) { var target = State.Contenders[targetRef.Index]; - if (!target.Alive || !_contenderBodies.TryGetValue(target.Id, out var body)) + if (!target.IsGroundedActive || !_contenderBodies.TryGetValue(target.Id, out var body)) { return; } @@ -2678,6 +2926,26 @@ namespace RustToDust.Ymir } } + public void ForceEliminateContender(int contenderId, ContenderState? killer = null) + { + if (contenderId < 0 || contenderId >= State.Contenders.Count) + { + return; + } + var victim = State.Contenders[contenderId]; + if (!victim.IsGroundedActive && !victim.IsInDropPod) + { + return; + } + victim.Grid.ApplyHit(0f, 0f, 0.5f, 50000f, 0f); + HandleContenderEliminated( + victim, + killer, + killer?.Id ?? -1, + killer?.Name ?? "System", + isSpectatorShooter: false); + } + private void HandleContenderEliminated( ContenderState victim, ContenderState? shooterContender, @@ -2705,6 +2973,7 @@ namespace RustToDust.Ymir State.Terrain.StampCrater(victim.X, victim.Z, radius: 5.2f, depth: 1.3f); State.Terrain.StampScorch(victim.X, victim.Z, radius: 6.2f); + State.OrbitalDrop.OnContenderEliminated(victim); _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = victim.X, Z = victim.Z, Radius = 5.2f, Depth = 1.3f }); _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = victim.X, Z = victim.Z, Radius = 6.2f }); _stepEvents.Add(new ContenderEliminatedEvent @@ -2712,7 +2981,8 @@ namespace RustToDust.Ymir VictimId = victim.Id, KillerId = shooterEntityId, IsSpectatorKiller = isSpectatorShooter, - KillerKills = shooterContender?.Kills ?? 0 + KillerKills = shooterContender?.Kills ?? 0, + VictimLifecycleByte = (byte)victim.Lifecycle }); State.Broadcast.EmitElimination(State.Time, shooterLabel, victim.Name, isSpectatorShooter); } @@ -2821,7 +3091,7 @@ namespace RustToDust.Ymir for (int i = 0; i < State.Contenders.Count; i++) { var c = State.Contenders[i]; - if (!c.Alive || ContenderStableIdBase + (ulong)c.Id == shooterStableId) + if (!c.IsGroundedActive || ContenderStableIdBase + (ulong)c.Id == shooterStableId) { continue; } @@ -2879,6 +3149,7 @@ namespace RustToDust.Ymir State.LoadoutChanged -= OnContenderLoadoutChanged; State.DropSpawned -= OnDropSpawned; State.DropPickedUp -= OnDropPickedUp; + State.ContenderPodTouchedDown -= OnContenderPodTouchedDown; State.Broadcast.LineEmitted -= OnBroadcastLineEmitted; _world.Dispose(); } diff --git a/src/RustToDust.Ymir/LocalArenaSession.cs b/src/RustToDust.Ymir/LocalArenaSession.cs index 8bdd91b..c6b269d 100644 --- a/src/RustToDust.Ymir/LocalArenaSession.cs +++ b/src/RustToDust.Ymir/LocalArenaSession.cs @@ -9,9 +9,9 @@ namespace RustToDust.Ymir { private readonly List _pendingEvents = new(); - public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null) + public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null, bool skipInitialDrop = false) { - Inner = new ArenaSession(seed, mapKind, slot0Human: true) + Inner = new ArenaSession(seed, mapKind, slot0Human: true, skipInitialDrop: skipInitialDrop) { EnableNetworkPvs = false }; @@ -28,7 +28,7 @@ namespace RustToDust.Ymir public ClientMatchOutcome LocalOutcome => Inner.State.Phase == MatchPhase.Active - ? (LocalContender.Alive ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) + ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) : (Inner.State.WinnerContenderId == LocalContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat); public int LocalDetectedByCount => @@ -43,6 +43,10 @@ namespace RustToDust.Ymir public NetworkStatusSnapshot ConnectionStatus => new(NetworkMode.Solo, Connected: true, PingMs: 0, ConnectedHumans: 1, MaxHumans: 1, StateLabel: "SOLO"); + public IReadOnlyList ActivePods => Inner.State.OrbitalDrop.ActivePods; + public DropWaveState DropWaveState => Inner.State.OrbitalDrop.WaveState; + public IReadOnlyList PodEvents => Inner.State.PodEvents; + public bool IsContenderVisible(int contenderId) => true; public bool IsSpectatorVisible(int spectatorId) => true; diff --git a/tests/RustToDust.Tests/ArenaSessionTests.cs b/tests/RustToDust.Tests/ArenaSessionTests.cs index 4fb51df..8a45924 100644 --- a/tests/RustToDust.Tests/ArenaSessionTests.cs +++ b/tests/RustToDust.Tests/ArenaSessionTests.cs @@ -11,7 +11,7 @@ namespace RustToDust.Tests [Fact] public void DrivingAndFiring_MovesBuggyInYmirAndBuildsWeaponHeat() { - using var session = new ArenaSession(seed: 42, slot0Human: true); + using var session = new ArenaSession(seed: 42, slot0Human: true, skipInitialDrop: true); var player = session.State.Contenders[0]; float startX = player.X; float startZ = player.Z; @@ -53,7 +53,7 @@ namespace RustToDust.Tests [Fact] public void ChassisSwap_ToManticoreAndRaptor_ReplacesBodyWithoutLeakingYmirLanes() { - using var session = new ArenaSession(seed: 77, slot0Human: true); + using var session = new ArenaSession(seed: 77, slot0Human: true, skipInitialDrop: true); var player = session.State.Contenders[0]; int initialFreeSlots = session.World.FreeBodySlots; @@ -102,7 +102,7 @@ namespace RustToDust.Tests [Fact] public void BroadsideFire_UsesDirectionalSupportRadiusNotMaxExtent() { - using var session = new ArenaSession(seed: 19, slot0Human: true); + using var session = new ArenaSession(seed: 19, slot0Human: true, skipInitialDrop: true); var player = session.State.Contenders[0]; // Swap to Tank / Anvil (HalfWidth = 1.93m, HalfLength = 2.83m) where broadside vs forward differs by ~0.9m. @@ -139,7 +139,7 @@ namespace RustToDust.Tests [Fact] public void TracerEvent_AssignsMonotonicId_AndPreservesAcrossAdvance() { - using var session = new ArenaSession(seed: 19, slot0Human: true); + using var session = new ArenaSession(seed: 19, slot0Human: true, skipInitialDrop: true); var player = session.State.Contenders[0]; float aimX = player.X + MathF.Sin(player.Yaw) * 25f; float aimZ = player.Z + MathF.Cos(player.Yaw) * 25f; diff --git a/tests/RustToDust.Tests/AudioSynthTests.cs b/tests/RustToDust.Tests/AudioSynthTests.cs index 6cfafd2..d3c97b9 100644 --- a/tests/RustToDust.Tests/AudioSynthTests.cs +++ b/tests/RustToDust.Tests/AudioSynthTests.cs @@ -227,7 +227,7 @@ public sealed class AudioSynthTests [Fact] public void ClientArenaSession_DrainSimEvents_WorksInSoloAndLoopbackRemote() { - using var local = new LocalArenaSession(seed: 42, ArenaMapKind.Desert, "AudioTester"); + using var local = new LocalArenaSession(seed: 42, ArenaMapKind.Desert, "AudioTester", skipInitialDrop: true); IClientArenaSession localIface = local; var events = new List(); @@ -264,6 +264,12 @@ public sealed class AudioSynthTests remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f); } Assert.True(remote.IsJoined); + host.Session.SetContenderPose(remote.LocalContenderId, 0f, 0f, 0f); + for (int s = 0; s < 4; s++) + { + host.StepOnce(nowMs + 240 + s * 16); + remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f); + } var rLocal = remoteIface.LocalContender; var fireInput = new PlayerInput(0f, 0f, rLocal.X + 30f, rLocal.Z, true, false, false); diff --git a/tests/RustToDust.Tests/CultNetMultiplayerTests.cs b/tests/RustToDust.Tests/CultNetMultiplayerTests.cs index 7b2b601..7a862dc 100644 --- a/tests/RustToDust.Tests/CultNetMultiplayerTests.cs +++ b/tests/RustToDust.Tests/CultNetMultiplayerTests.cs @@ -697,7 +697,7 @@ namespace RustToDust.Tests // b) Malformed 120B packet with cellCount=200 must return false cleanly without throwing! byte[] bad = new byte[120]; bad[0] = (byte)LatestPacketKind.CorePvs; - bad[88] = 200; // cellCount = 200 > 64 and > remaining bytes + bad[91] = 200; // cellCount = 200 > 64 and > remaining bytes Assert.False(SnapshotCodec.TryDecodeCorePvs(bad, out _)); bad[0] = (byte)LatestPacketKind.SpectatorOrbitHalf; bad[10] = 250; diff --git a/tests/RustToDust.Tests/MultiplayerSimulationTests.cs b/tests/RustToDust.Tests/MultiplayerSimulationTests.cs index 84b0a3a..a2da7fc 100644 --- a/tests/RustToDust.Tests/MultiplayerSimulationTests.cs +++ b/tests/RustToDust.Tests/MultiplayerSimulationTests.cs @@ -67,7 +67,7 @@ namespace RustToDust.Tests [Fact] public void PerObserverDetectionIsolation_Human0SeesRivalWhileOccludedHuman5DoesNot() { - using var session = new ArenaSession(seed: 12, mapKind: ArenaMapKind.Desert, slot0Human: false); + using var session = new ArenaSession(seed: 12, mapKind: ArenaMapKind.Desert, slot0Human: false, skipInitialDrop: true); session.SetHumanSlot(0, true, "Alpha"); session.SetHumanSlot(5, true, "Bravo"); diff --git a/tests/RustToDust.Tests/OrbitalDropTests.cs b/tests/RustToDust.Tests/OrbitalDropTests.cs new file mode 100644 index 0000000..4a9a621 --- /dev/null +++ b/tests/RustToDust.Tests/OrbitalDropTests.cs @@ -0,0 +1,586 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Numerics; +using System.Threading; +using GameCult.Networking; +using RustToDust.Core; +using RustToDust.Net; +using RustToDust.Ymir; +using Xunit; +using Xunit.Abstractions; + +namespace RustToDust.Tests +{ + public sealed class OrbitalDropTests + { + private readonly ITestOutputHelper _output; + + public OrbitalDropTests(ITestOutputHelper output) + { + _output = output; + } + + [Fact] + public void HoverSlam_FlatDesertAnd30DegSionSlope_TouchdownUnder3MsAndZeroPenetration() + { + // 1. Flat Desert trajectory & cross-range steering [120m, 180m] + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true); + var player = session.State.Contenders[0]; + float startX = player.X; + float startZ = player.Z; + float aimX = startX; + float aimZ = startZ + 100f; + + int maxTicks = 600; + float impactSpeed = -1f; + float touchTime = -1f; + float snapDiffAtTouchdown = float.NaN; + session.State.ContenderPodTouchedDown += c => + { + if (c.Id == 0) + { + snapDiffAtTouchdown = MathF.Abs(c.PrevY - c.Y); + } + }; + for (int t = 0; t < maxTicks; t++) + { + session.SetHumanInput(0, new PlayerInput( + Throttle: 1.0f, + Steer: 0f, + AimWorldX: player.X, + AimWorldZ: player.Z + 100f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + if (player.IsGroundedActive) + { + touchTime = session.State.Time; + var tdEvent = session.State.PodEvents.LastOrDefault(e => + e.Kind == DropPodEventKind.PodTouchdownBlowPetals && e.ContenderId == 0); + impactSpeed = MathF.Abs(tdEvent.VelY); + break; + } + } + + Assert.True(player.IsGroundedActive, "Player pod failed to touch down within 10s on Desert"); + Assert.InRange(impactSpeed, 0.5f, 2.99f); + Assert.InRange(touchTime, 5.5f, 9.5f); + + float glideDist = MathF.Sqrt((player.X - startX) * (player.X - startX) + (player.Z - startZ) * (player.Z - startZ)); + Assert.InRange(glideDist, 120f, 180f); + + // Verify PrevY == Y right at touchdown SnapPreviousPose() and continuous post-Step settlement (< 0.06m, zero sky pop) + Assert.True(snapDiffAtTouchdown < 1e-4f, + $"Expected SnapPreviousPose clean right at touchdown: diff={snapDiffAtTouchdown:F6}"); + Assert.True(MathF.Abs(player.PrevY - player.Y) < 0.06f, + $"Expected smooth 1-tick settlement post-touchdown: PrevY={player.PrevY:F5}, Y={player.Y:F5}"); + AssertZeroChassisPenetration(session.State, player); + _output.WriteLine($"Desert flat glide: touchTime={touchTime:F2}s, impactSpeed={impactSpeed:F2} m/s, glide={glideDist:F1}m"); + } + + // 2. ~30 deg Sion mountain slope (uphill + downhill) + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + + // Find a steep Sion mountain slope spot (~25-33 deg, Ny in [0.83, 0.90]) outside buildings + float slopeX = 0f; + float slopeZ = 0f; + float bestDiff = float.PositiveInfinity; + float targetNy = MathF.Cos(30f * MathF.PI / 180f); // ~0.866 + for (float z = -1200f; z <= 1200f; z += 24f) + { + for (float x = -1200f; x <= 1200f; x += 24f) + { + if (sion.IsInsideAnyBuildingXz(x, z, 14f)) continue; + var (_, ny, _) = session.State.Terrain.SampleNormal(x, z); + if (ny >= 0.80f && ny <= 0.91f) + { + float diff = MathF.Abs(ny - targetNy); + if (diff < bestDiff) + { + bestDiff = diff; + slopeX = x; + slopeZ = z; + } + } + } + } + Assert.True(bestDiff < 0.08f, "Expected to find a ~30 deg Sion slope test site"); + + var (snx, sny, snz) = session.State.Terrain.SampleNormal(slopeX, slopeZ); + float slopeDeg = MathF.Acos(Math.Clamp(sny, -1f, 1f)) * (180f / MathF.PI); + + // Test launching pod directly above slope with uphill lateral input + var c = session.State.Contenders[1]; + float uphillYaw = MathF.Atan2(-snx, -snz); + var pod = session.State.OrbitalDrop.LaunchContenderPod( + c, waveIndex: 0, slopeX, slopeZ, uphillYaw, session.QueryDropSurface, isRespawn: false); + pod.AllowFlatRoofLanding = false; + + float snapDiffAtTouchdown = float.NaN; + session.State.ContenderPodTouchedDown += tc => + { + if (tc.Id == c.Id) snapDiffAtTouchdown = MathF.Abs(tc.PrevY - tc.Y); + }; + + float impactSpeed = -1f; + for (int t = 0; t < 600; t++) + { + pod.LookForwardX = -snx; + pod.LookForwardZ = -snz; + pod.SteerForwardCmd = 0.8f; + session.Step(); + if (c.IsGroundedActive) + { + var td = session.State.PodEvents.Last(e => + e.Kind == DropPodEventKind.PodTouchdownBlowPetals && e.PodId == pod.PodId); + impactSpeed = MathF.Abs(td.VelY); + break; + } + } + + Assert.True(c.IsGroundedActive, $"Pod failed to land on {slopeDeg:F1} deg Sion slope"); + Assert.InRange(impactSpeed, 0.5f, 2.99f); + Assert.True(snapDiffAtTouchdown < 1e-4f); + Assert.True(MathF.Abs(c.PrevY - c.Y) < 0.06f); + AssertZeroChassisPenetration(session.State, c); + _output.WriteLine($"Sion {slopeDeg:F1} deg slope: impactSpeed={impactSpeed:F2} m/s, terrainY={session.State.Terrain.SampleHeight(c.X, c.Z):F2}, chassisY={c.Y:F2}"); + } + } + + [Fact] + public void Wave0_GearPodsTouchDownAheadOfContenders_Around3Point3Seconds() + { + foreach (var map in new[] { ArenaMapKind.Desert, ArenaMapKind.Sion }) + { + using var session = new ArenaSession(seed: 42, map, slot0Human: true); + Assert.True(session.State.OrbitalDrop.ActivePods.Count >= 52, + $"Expected 12 contender + 40 gear pods at t=0, got {session.State.OrbitalDrop.ActivePods.Count}"); + Assert.Empty(session.State.GroundDrops); + + float maxGearTouchTime = 0f; + float minContenderTouchTime = float.PositiveInfinity; + + for (int t = 0; t < 660; t++) + { + session.Step(); + if (session.State.OrbitalDrop.ActivePods.Count == 0) + { + break; + } + } + + Assert.Empty(session.State.OrbitalDrop.ActivePods); + Assert.True(session.State.GroundDrops.Count >= 40, + $"Expected >= 40 GroundDrops after Wave 0, got {session.State.GroundDrops.Count}"); + Assert.Equal(40, session.State.PodEvents.Count(e => + e.Kind == DropPodEventKind.PodTouchdownBlowPetals && e.PodKind != OrbitalPodKind.Contender)); + + foreach (var ev in session.State.PodEvents) + { + if (ev.Kind != DropPodEventKind.PodTouchdownBlowPetals) continue; + // Use Wave 0 launch time (0s) and PodEvents order/timestamps via simulation + } + + // Re-measure exact per-pod FlightTime on a MatchState sweep + var state = new MatchState(seed: 42, map); + var gearTouchTimes = new List(); + var contenderTouchTimes = new List(); + for (int t = 0; t < 660; t++) + { + state.Time += ArenaSession.FixedDt; + state.OrbitalDrop.Step(ArenaSession.FixedDt, state.DefaultDropSurfaceQuery, (pod, _) => + { + if (pod.PodKind == OrbitalPodKind.Contender) contenderTouchTimes.Add(pod.FlightTime); + else gearTouchTimes.Add(pod.FlightTime); + }); + } + + maxGearTouchTime = gearTouchTimes.Max(); + minContenderTouchTime = contenderTouchTimes.Min(); + float lead = minContenderTouchTime - maxGearTouchTime; + _output.WriteLine($"{map}: maxGearTouch={maxGearTouchTime:F2}s, minContenderTouch={minContenderTouchTime:F2}s, lead={lead:F2}s"); + + Assert.Equal(40, gearTouchTimes.Count); + Assert.Equal(12, contenderTouchTimes.Count); + Assert.InRange(lead, 2.5f, 4.2f); + } + } + + [Fact] + public void Sion64TargetSweep_ZeroBuildingInteriorLandings_AndZeroHoverStalls() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + + // Pick 64 targets deliberately across Old Town dense buildings (center & towers) + valley + var rng = new Random(101); + int tested = 0; + int buildingOverTargets = 0; + float worstTouchTime = 0f; + float worstImpactSpeed = 0f; + + for (int i = 0; i < 64; i++) + { + float tx; + float tz; + if (i < 32) + { + // Aim directly onto real Sion building rooftops in Old Town & towers to stress deflection! + var b = sion.Buildings[(i * 71) % sion.Buildings.Count]; + tx = Math.Clamp(b.CenterX, -1350f, 1350f); + tz = Math.Clamp(b.CenterZ, -1350f, 1350f); + buildingOverTargets++; + } + else + { + tx = (float)(rng.NextDouble() * 1800.0 - 900.0); + tz = (float)(rng.NextDouble() * 1800.0 - 900.0); + } + + var pod = session.State.OrbitalDrop.LaunchGearPod(0, tx, tz, null, Catalog.Autocannon, session.QueryDropSurface); + bool landed = false; + for (int t = 0; t < 600; t++) + { + bool touched = OrbitalDropKinematics.StepPod( + pod, + ArenaSession.FixedDt, + session.State.Terrain, + session.QueryDropSurface, + session.State.FindClearDropPoint, + out _, + out var touchSample); + if (touched) + { + landed = true; + worstTouchTime = MathF.Max(worstTouchTime, pod.FlightTime); + worstImpactSpeed = MathF.Max(worstImpactSpeed, pod.TouchdownSpeed); + Assert.False(sion.IsInsideAnyBuildingXz(pod.X, pod.Z, 0f), + $"Target #{i} ({tx:F1},{tz:F1}) landed inside Sion building at ({pod.X:F1},{pod.Z:F1})!"); + Assert.False(touchSample.IsBuildingRoof); + Assert.InRange(pod.TouchdownSpeed, 0.5f, 2.99f); + break; + } + } + Assert.True(landed, $"Target #{i} ({tx:F1},{tz:F1}) hover-stalled!"); + Assert.True(pod.FlightTime <= 9.5f, $"Target #{i} took too long: {pod.FlightTime:F2}s"); + tested++; + } + + _output.WriteLine($"Sion 64-target sweep ({buildingOverTargets} directly over buildings): {tested}/64 clear street landings, maxFlight={worstTouchTime:F2}s, maxImpact={worstImpactSpeed:F2} m/s"); + } + + [Fact] + public void SionHumanPod_FlatRoofValidLanding_AndSkyscraperLateralWallGuard() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + + // 1. Find a tall wide flat-roofed Sion building (HalfX >= 7m, HalfZ >= 7m, height >= 10m) + SionBuildingAabb? flatRoofBldg = null; + for (int i = 0; i < sion.Buildings.Count; i++) + { + var b = sion.Buildings[i]; + if (b.Class == "Gebaeude Einzelhaus" && + b.HalfX >= 7f && b.HalfZ >= 7f && + (b.RoofY - b.GroundY) >= 10f && + MathF.Abs(b.CenterX) < 800f && MathF.Abs(b.CenterZ) < 800f) + { + var sample = session.QueryDropSurface(b.CenterX, b.CenterZ, 1.65f, b.RoofY + 20f); + if (sample.IsBuildingRoof && sample.IsFlatRoofValid) + { + flatRoofBldg = b; + break; + } + } + } + Assert.NotNull(flatRoofBldg); + var fr = flatRoofBldg!.Value; + + // Land human player pod on that flat roof and verify driving on roof works! + var player = session.State.Contenders[0]; + var roofPod = session.State.OrbitalDrop.LaunchContenderPod( + player, 0, fr.CenterX, fr.CenterZ, 0f, session.QueryDropSurface, isRespawn: false); + roofPod.AllowFlatRoofLanding = true; + + for (int t = 0; t < 600 && !player.IsGroundedActive; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 20f, false, false, false)); + session.Step(); + } + + Assert.True(player.IsGroundedActive); + Assert.True(player.TouchdownOnRoof); + float terrainUnder = session.State.Terrain.SampleHeight(player.X, player.Z); + Assert.True(player.Y > terrainUnder + 6f, $"Expected player seated on roof above terrain ({player.Y:F2} > {terrainUnder + 6f:F2})"); + + // Drive forward slightly on roof -> stays supported on roof (doesn't fall through roof) + float yStartOnRoof = player.Y; + for (int t = 0; t < 20; t++) + { + session.SetHumanInput(0, new PlayerInput(0.4f, 0f, player.X, player.Z + 20f, false, false, false)); + session.Step(); + } + Assert.True(player.Y >= yStartOnRoof - 0.6f, $"Player sank through flat Sion roof: {yStartOnRoof:F2} -> {player.Y:F2}"); + + // 2. Lateral Building Wall Guard: steer straight into a tall Sion building face at mid-height + SionBuildingAabb? tallBldg = null; + for (int i = 0; i < sion.Buildings.Count; i++) + { + var b = sion.Buildings[i]; + if ((b.RoofY - b.GroundY) >= 22f && MathF.Abs(b.CenterX) < 900f && MathF.Abs(b.CenterZ) < 900f) + { + if (!sion.IsInsideAnyBuildingXz(b.CenterX, b.CenterZ - b.HalfZ - 12f, 3f)) + { + tallBldg = b; + break; + } + } + } + Assert.NotNull(tallBldg); + var tb = tallBldg!.Value; + + var c2 = session.State.Contenders[2]; + c2.IsHuman = true; + float wallStartX = tb.CenterX; + float wallStartZ = tb.CenterZ - tb.HalfZ - 10f; + var wallPod = session.State.OrbitalDrop.LaunchContenderPod( + c2, 0, wallStartX, wallStartZ, 0f, session.QueryDropSurface, isRespawn: false); + // Position pod below roof height (~mid-wall) with high speed straight into the building wall + wallPod.Y = tb.GroundY + (tb.RoofY - tb.GroundY) * 0.5f + 45f; + wallPod.VelY = -30f; + + for (int t = 0; t < 360 && !c2.IsGroundedActive; t++) + { + session.SetHumanInput(c2.Id, new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: tb.CenterX, + AimWorldZ: tb.CenterZ + 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + if (wallPod.Phase != OrbitalPodPhase.Popped && wallPod.Y < tb.RoofY - 1.0f) + { + Assert.False(sion.IsInsideAnyBuildingXz(wallPod.X, wallPod.Z, 0f), + $"Pod clipped laterally inside tall building {tb.Id} at y={wallPod.Y:F1}m (roof={tb.RoofY:F1}m)"); + } + } + + Assert.True(c2.IsGroundedActive, "Pod stalled against building wall"); + Assert.False(sion.IsInsideAnyBuildingXz(c2.X, c2.Z, 0f), "Pod ended inside tall building interior!"); + _output.WriteLine($"Wall guard verified against {tb.Id} (height={tb.RoofY - tb.GroundY:F1}m): landed outside at ({c2.X:F1}, {c2.Z:F1})"); + } + + [Fact] + public void Wave1To3Respawns_AndFinalRingCutoff_CompletesMatchCleanly() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true); + var state = session.State; + var player = state.Contenders[0]; + + // Step until Wave 0 contenders touch down (~7.5s) + for (int t = 0; t < 480 && !state.Contenders.All(c => c.IsGroundedActive); t++) + { + session.Step(); + } + Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive)); + + // 1. Kill 11 AIs at t = 15s -> must enter WaitingForRespawnWave and match stays Active! + while (state.Time < 15f) + { + session.Step(); + } + for (int i = 1; i < state.Contenders.Count; i++) + { + session.ForceEliminateContender(i); + } + MatchRules.UpdateMatchOutcome(state); + Assert.Equal(MatchPhase.Active, state.Phase); + for (int i = 1; i < state.Contenders.Count; i++) + { + Assert.Equal(ContenderLifecycle.WaitingForRespawnWave, state.Contenders[i].Lifecycle); + Assert.True(state.Contenders[i].WaitingForRespawn); + } + + // 2. Step past Wave 1 (t = 75s) + drop time -> all 11 AIs re-drop in stock Jackals with RespawnsRemaining == 0! + while (state.Time < 75.5f) + { + session.Step(); + } + Assert.Equal(1, state.OrbitalDrop.CurrentWaveIndex); + for (int i = 1; i < state.Contenders.Count; i++) + { + Assert.Equal(ContenderLifecycle.Deploying, state.Contenders[i].Lifecycle); + Assert.Equal(0, state.Contenders[i].RespawnsRemaining); + Assert.Equal(Catalog.Jackal.Id, state.Contenders[i].Grid.Spec.Id); + } + for (int t = 0; t < 480; t++) + { + session.Step(); + if (state.Contenders.All(c => c.IsGroundedActive)) break; + } + Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive)); + + // 3. Kill Player before Wave 2 (t = 120s) -> match MUST stay Active (Player.WaitingForRespawn == true) + while (state.Time < 120f) + { + session.Step(); + } + session.ForceEliminateContender(0); + MatchRules.UpdateMatchOutcome(state); + + Assert.Equal(MatchPhase.Active, state.Phase); + Assert.True(player.WaitingForRespawn); + + // Step past Wave 2 (t = 155s) -> Player re-drops in stock Jackal (RespawnsRemaining == 0), RespawnCutoffReached == true! + while (state.Time < 155.5f) + { + session.Step(); + } + Assert.Equal(2, state.OrbitalDrop.CurrentWaveIndex); + Assert.True(state.OrbitalDrop.RespawnCutoffReached); + Assert.Equal(ContenderLifecycle.Deploying, player.Lifecycle); + Assert.Equal(0, player.RespawnsRemaining); + + // 4. Kill an AI at t = 158.1s (after Wave 2 cutoff) -> immediately Eliminated (never WaitingForRespawnWave)! + while (state.Time < 158.1f) + { + session.Step(); + } + var aiLate = state.Contenders[1]; + session.ForceEliminateContender(1); + Assert.Equal(ContenderLifecycle.Eliminated, aiLate.Lifecycle); + + // Kill all remaining rivals after cutoff -> MatchPhase becomes Completed, WinnerContenderId == 0! + for (int i = 2; i < state.Contenders.Count; i++) + { + session.ForceEliminateContender(i); + } + MatchRules.UpdateMatchOutcome(state); + Assert.Equal(MatchPhase.Completed, state.Phase); + Assert.Equal(0, state.WinnerContenderId); + + // 5. Verify SetContenderPose mid-drop cleanly cancels active pod + using var midDropSession = new ArenaSession(seed: 77, ArenaMapKind.Desert, slot0Human: true); + Assert.True(midDropSession.State.Contenders[0].IsInDropPod); + midDropSession.SetContenderPose(0, 15f, -20f, 0.5f); + Assert.True(midDropSession.State.Contenders[0].IsGroundedActive); + Assert.Null(midDropSession.State.Contenders[0].ActivePodId); + Assert.DoesNotContain(midDropSession.State.OrbitalDrop.ActivePods, + p => p.PodKind == OrbitalPodKind.Contender && p.ContenderId == 0); + } + + [Fact] + public void NetworkSync_Wave0OrbitalPods_ReplicateUnder1152ByteUdpCap() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var client = new RemoteArenaSession(ep, "DropPilot"); + IClientArenaSession clientIface = client; + + int maxUdpBytes = 0; + int latestPacketsSeen = 0; + client.DebugInboundLatestDropFilter = payload => + { + byte[] frame = SnapshotCodec.WrapLatest(payload, host.MatchGeneration, (uint)(latestPacketsSeen + 1)); + byte[] udp = CultNetRudpPacketCodec.Encode(new CultNetRudpPacket + { + PacketType = CultNetRudpPacketType.Data, + ConnectionId = 0x52544431, + Sequence = (uint)(latestPacketsSeen + 1), + ChannelId = SnapshotCodec.ChannelLatest, + Sequenced = true, + Payload = frame + }); + maxUdpBytes = Math.Max(maxUdpBytes, udp.Length); + latestPacketsSeen++; + return false; + }; + + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var deadline = DateTimeOffset.UtcNow.AddSeconds(3); + while (DateTimeOffset.UtcNow < deadline && !client.IsJoined) + { + nowMs += 16; + host.StepOnce(nowMs); + client.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.True(client.IsJoined); + Assert.True(clientIface.LocalContender.IsInDropPod); + Assert.True(clientIface.ActivePods.Count >= 12, + $"Expected active Wave 0 pods on RemoteArenaSession join, got {clientIface.ActivePods.Count}"); + + // Step through full Wave 0 orbital drop (~7.8s = 470 ticks) with steering input + var simEvents = new List(); + for (int t = 0; t < 480; t++) + { + nowMs += 16; + clientIface.SubmitLocalInput(new PlayerInput( + Throttle: 0.7f, + Steer: 0f, + AimWorldX: clientIface.LocalContender.X, + AimWorldZ: clientIface.LocalContender.Z + 50f, + Fire: false, + InteractPickup: false, + Brake: false), isPhysicsTick: true); + host.StepOnce(nowMs); + client.PumpNetwork(nowMs); + clientIface.DrainSimEvents(simEvents); + if (clientIface.LocalContender.IsGroundedActive && + host.Session.State.Contenders[clientIface.LocalContenderId].IsGroundedActive) + { + break; + } + } + + Assert.True(latestPacketsSeen > 10); + Assert.True(maxUdpBytes > 0 && maxUdpBytes <= SnapshotCodec.MaxLatestDatagramBytes, + $"UDP latest datagram exceeded {SnapshotCodec.MaxLatestDatagramBytes}B cap: max={maxUdpBytes}B"); + Assert.True(clientIface.LocalContender.IsGroundedActive, + $"Expected RemoteArenaSession LocalContender grounded after drop, lifecycle={clientIface.LocalContender.Lifecycle}"); + Assert.Contains(simEvents, e => e is DropPodEvent dpe && dpe.Kind == (byte)DropPodEventKind.PodTouchdownBlowPetals && dpe.ContenderId == clientIface.LocalContenderId); + + _output.WriteLine($"Network orbital drop: maxUdpBytes={maxUdpBytes}B (cap {SnapshotCodec.MaxLatestDatagramBytes}B), packets={latestPacketsSeen}, podEvents={simEvents.OfType().Count()}"); + } + + private static void AssertZeroChassisPenetration(MatchState state, ContenderState c) + { + var spec = c.Grid.Spec; + float physHalfH = ArenaSession.GetPhysicsHalfHeight(spec); + Quaternion q = Quaternion.Normalize(new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW)); + Vector3 center = new(c.X, c.Y, c.Z); + + float groundCenter = state.Terrain.SampleHeight(c.X, c.Z); + float centerClearance = (c.Y - physHalfH) - groundCenter; + Assert.True(centerClearance >= 0f, + $"Chassis center penetrated terrain: bottom={c.Y - physHalfH:F4} < ground={groundCenter:F4} (clearance={centerClearance:F4}m)"); + + Span localCorners = stackalloc Vector3[4] + { + new Vector3(-spec.HalfWidth, -physHalfH, -spec.HalfLength), + new Vector3( spec.HalfWidth, -physHalfH, -spec.HalfLength), + new Vector3(-spec.HalfWidth, -physHalfH, spec.HalfLength), + new Vector3( spec.HalfWidth, -physHalfH, spec.HalfLength) + }; + for (int k = 0; k < 4; k++) + { + Vector3 wp = center + Vector3.Transform(localCorners[k], q); + float gh = state.Terrain.SampleHeight(wp.X, wp.Z); + float clearance = wp.Y - gh; + Assert.True(clearance >= 0f, + $"Chassis corner {k} penetrated terrain: cornerY={wp.Y:F4} < ground={gh:F4} (clearance={clearance:F4}m)"); + } + } + } +} diff --git a/tests/RustToDust.Tests/PlaytestFixesTests.cs b/tests/RustToDust.Tests/PlaytestFixesTests.cs index b285163..2443389 100644 --- a/tests/RustToDust.Tests/PlaytestFixesTests.cs +++ b/tests/RustToDust.Tests/PlaytestFixesTests.cs @@ -67,7 +67,11 @@ namespace RustToDust.Tests } } - // 3. All 14 non-Jackal chassis drops exist in GroundDrops + // 3. Step 4.5s (270 ticks) so Wave 0 gear pods touch down into GroundDrops; all 14 non-Jackal chassis exist + for (int t = 0; t < 270; t++) + { + session.Step(); + } var droppedChassisIds = state.GroundDrops .Where(d => d.Chassis is not null) .Select(d => d.Chassis!.Id) @@ -91,15 +95,17 @@ namespace RustToDust.Tests $"Sion Seed={seed}: Expected >= 3 reachable drops within 110-190m ring sector, got {nearRingDrops}"); } - // 4. Zero tick-0 spawn ambush - var player = state.Contenders[0]; + // 4. Zero tick-0 spawn ambush (instant ground start check) + using var instantSession = new ArenaSession(seed, map, skipInitialDrop: true); + var instantState = instantSession.State; + var player = instantState.Contenders[0]; float initialHp = player.Grid.CoreHp; - session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 10f, false, false, true)); - session.Step(); + instantSession.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 10f, false, false, true)); + instantSession.Step(); - for (int i = 1; i < state.Contenders.Count; i++) + for (int i = 1; i < instantState.Contenders.Count; i++) { - var ai = state.Contenders[i]; + var ai = instantState.Contenders[i]; Assert.False(ai.FireCmd, $"Map={map}, Seed={seed}: AI {ai.Id} fired on tick 0!"); } Assert.Equal(initialHp, player.Grid.CoreHp); @@ -293,7 +299,7 @@ namespace RustToDust.Tests [Fact] public void RenderInterpolation_CameraAnchorAndContenderPose_ZeroHorizPhaseMismatchAcrossAlpha() { - using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true); + using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true, skipInitialDrop: true); IsolateContenders(session, 0); var player = session.State.Contenders[0]; diff --git a/tests/RustToDust.Tests/SionMapTests.cs b/tests/RustToDust.Tests/SionMapTests.cs index a68d3e2..3b4736f 100644 --- a/tests/RustToDust.Tests/SionMapTests.cs +++ b/tests/RustToDust.Tests/SionMapTests.cs @@ -118,7 +118,7 @@ namespace RustToDust.Tests [Fact] public void ArenaSession_SionLoadsHeightfieldAndMeshesSpawnsClearBlocksLosAndStepsCleanly() { - using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true); + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true); var state = session.State; var sion = state.SionMap!; diff --git a/tests/RustToDust.Tests/TerrainTests.cs b/tests/RustToDust.Tests/TerrainTests.cs index 231fc9e..79c9479 100644 --- a/tests/RustToDust.Tests/TerrainTests.cs +++ b/tests/RustToDust.Tests/TerrainTests.cs @@ -151,7 +151,7 @@ namespace RustToDust.Tests [Fact] public void ArenaSession_BuggyDrivesAcrossDunesWithoutNanAndTracksElevation() { - using var session = new ArenaSession(seed: 42, slot0Human: true); + using var session = new ArenaSession(seed: 42, slot0Human: true, skipInitialDrop: true); var player = session.State.Contenders[0]; int initialBrushes = session.State.Terrain.Brushes.Count; diff --git a/tests/RustToDust.Tests/VehiclePackageTests.cs b/tests/RustToDust.Tests/VehiclePackageTests.cs index 703d86a..237611d 100644 --- a/tests/RustToDust.Tests/VehiclePackageTests.cs +++ b/tests/RustToDust.Tests/VehiclePackageTests.cs @@ -123,8 +123,13 @@ namespace RustToDust.Tests Assert.True(Catalog.Condor.BaseCellArmor < Catalog.Anvil.BaseCellArmor, $"Condor armor ({Catalog.Condor.BaseCellArmor}) must be lighter than Anvil ({Catalog.Anvil.BaseCellArmor})"); - // All 14 non-starter chassis spawn as salvageable drops in MatchState + // All 14 non-starter chassis launch in Wave 0 orbital gear pods and touch down into GroundDrops var state = new MatchState(seed: 42); + for (int t = 0; t < 300; t++) + { + state.Time += 1f / 60f; + state.OrbitalDrop.Step(1f / 60f); + } var droppedChassisIds = state.GroundDrops .Where(d => d.Chassis is not null) .Select(d => d.Chassis!.Id) diff --git a/tests/RustToDust.Tests/VtolAndArcTests.cs b/tests/RustToDust.Tests/VtolAndArcTests.cs index 8a2ef77..c7fd2b2 100644 --- a/tests/RustToDust.Tests/VtolAndArcTests.cs +++ b/tests/RustToDust.Tests/VtolAndArcTests.cs @@ -227,7 +227,7 @@ namespace RustToDust.Tests [Fact] public void QuickBolt_MountsScavengedModuleIntoEmptyMatchingHardpointBeforeCargo() { - var state = new MatchState(seed: 42); + var state = new MatchState(seed: 42, skipInitialDrop: true); var player = state.Contenders[0]; player.IsHuman = true; @@ -269,7 +269,7 @@ namespace RustToDust.Tests [Fact] public void Vtol_ReverseIntoTallMesaAndCliffDrop_ZeroUndergroundTicks() { - using var session = new ArenaSession(seed: 42, slot0Human: true); + using var session = new ArenaSession(seed: 42, slot0Human: true, skipInitialDrop: true); var player = session.State.Contenders[0]; IsolateContenders(session, player.Id); @@ -494,7 +494,7 @@ namespace RustToDust.Tests [Fact] public void InteractPickup_UsesUnifiedNearestDropPriority_ChassisCloserThanModule() { - var state = new MatchState(seed: 42); + var state = new MatchState(seed: 42, skipInitialDrop: true); var player = state.Contenders[0]; player.IsHuman = true;