Cut 5c-1: Multi-human authoritative sim, SimSnapshot/SimEvent boundary, RustToDust.Net & RustToDust.Server

This commit is contained in:
Meta Vens 2026-12-05 08:35:07 +01:00
commit d8f5c49b8d
34 changed files with 5785 additions and 700 deletions

View file

@ -2,6 +2,8 @@
<Folder Name="/src/"> <Folder Name="/src/">
<Project Path="src/RustToDust.Core/RustToDust.Core.csproj" /> <Project Path="src/RustToDust.Core/RustToDust.Core.csproj" />
<Project Path="src/RustToDust.Ymir/RustToDust.Ymir.csproj" /> <Project Path="src/RustToDust.Ymir/RustToDust.Ymir.csproj" />
<Project Path="src/RustToDust.Net/RustToDust.Net.csproj" />
<Project Path="src/RustToDust.Server/RustToDust.Server.csproj" />
</Folder> </Folder>
<Folder Name="/tests/"> <Folder Name="/tests/">
<Project Path="tests/RustToDust.Tests/RustToDust.Tests.csproj" /> <Project Path="tests/RustToDust.Tests/RustToDust.Tests.csproj" />

View file

@ -520,7 +520,7 @@ public partial class ArenaRenderer : Node3D
vis.Visual.Root.QueueFree(); vis.Visual.Root.QueueFree();
} }
var role = c.IsPlayer ? VehicleVisualRole.Player : VehicleVisualRole.Rival; var role = c.Id == 0 ? VehicleVisualRole.Player : VehicleVisualRole.Rival;
var instance = VehicleVisualInstance.Create(_assetCache, c.Grid.Spec.Id, role); var instance = VehicleVisualInstance.Create(_assetCache, c.Grid.Spec.Id, role);
instance.SyncMountedGear(c.Grid); instance.SyncMountedGear(c.Grid);
_actorsGroup.AddChild(instance.Root); _actorsGroup.AddChild(instance.Root);
@ -537,15 +537,15 @@ public partial class ArenaRenderer : Node3D
vis.Visual.Root.Transform = new Transform3D(new Basis(q), pos); vis.Visual.Root.Transform = new Transform3D(new Basis(q), pos);
float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f; float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f;
bool castShadows = !hasCam || c.IsPlayer || distSq <= 75f * 75f; bool castShadows = !hasCam || c.Id == 0 || distSq <= 75f * 75f;
bool useStaticLod = hasCam && !c.IsPlayer && !vis.Visual.HasAnyStrippedCell && bool useStaticLod = hasCam && c.Id != 0 && !vis.Visual.HasAnyStrippedCell &&
(vis.Visual.IsStaticLod ? distSq > 64f * 64f : distSq > 68f * 68f); (vis.Visual.IsStaticLod ? distSq > 64f * 64f : distSq > 68f * 68f);
vis.Visual.SetLodState(useStaticLod, castShadows); vis.Visual.SetLodState(useStaticLod, castShadows);
vis.Visual.SyncMountedGear(c.Grid); vis.Visual.SyncMountedGear(c.Grid);
if (!useStaticLod) if (!useStaticLod)
{ {
if (!hasCam || c.IsPlayer || distSq <= 55f * 55f) if (!hasCam || c.Id == 0 || distSq <= 55f * 55f)
{ {
vis.RigDtAccum = 0f; vis.RigDtAccum = 0f;
vis.RigSkipFrames = 0; vis.RigSkipFrames = 0;

View file

@ -150,7 +150,7 @@ public partial class Hud : CanvasLayer
public void Sync(ArenaSession session) public void Sync(ArenaSession session)
{ {
var state = session.State; var state = session.State;
var player = state.Player; var player = state.Contenders[0];
// Top-Left Status // Top-Left Status
_chassisHeader.Text = player.Grid.Spec.Name.ToUpperInvariant(); _chassisHeader.Text = player.Grid.Spec.Name.ToUpperInvariant();
@ -202,9 +202,10 @@ public partial class Hud : CanvasLayer
_safeLabel.Modulate = RedCol; _safeLabel.Modulate = RedCol;
} }
if (state.PlayerDetectedByCount > 0) int detectedBy = state.ObserverStates.TryGetValue(0, out var obs0) ? obs0.DetectedByCount : 0;
if (detectedBy > 0)
{ {
_detectionLabel.Text = $"DETECTED BY {state.PlayerDetectedByCount}"; _detectionLabel.Text = $"DETECTED BY {detectedBy}";
_detectionLabel.Modulate = RedCol; _detectionLabel.Modulate = RedCol;
} }
else else
@ -237,14 +238,14 @@ public partial class Hud : CanvasLayer
SyncBroadcastChyron(state.Broadcast); SyncBroadcastChyron(state.Broadcast);
// Outcome // Outcome
if (state.Phase == MatchPhase.Victory) if (state.Phase == MatchPhase.Completed && state.WinnerContenderId == 0)
{ {
_outcomeBanner.Visible = true; _outcomeBanner.Visible = true;
_outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", OliveCol); _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", OliveCol);
_outcomeLabel.Text = "VICTORY — LAST RIG STANDING\n[R] New Drop"; _outcomeLabel.Text = "VICTORY — LAST RIG STANDING\n[R] New Drop";
_outcomeLabel.Modulate = OliveCol; _outcomeLabel.Modulate = OliveCol;
} }
else if (state.Phase == MatchPhase.Defeat) else if (!player.Alive || state.Phase == MatchPhase.Completed)
{ {
_outcomeBanner.Visible = true; _outcomeBanner.Visible = true;
_outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", RedCol); _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", RedCol);
@ -513,7 +514,7 @@ public partial class Hud : CanvasLayer
{ {
var session = _getSession(); var session = _getSession();
if (session is null) return; if (session is null) return;
var cargo = session.State.Player.Grid.Cargo; var cargo = session.State.Contenders[0].Grid.Cargo;
if (_selectedCargoIndex >= 0 && _selectedCargoIndex < cargo.Count) if (_selectedCargoIndex >= 0 && _selectedCargoIndex < cargo.Count)
{ {
_onEquipCargo(_selectedCargoIndex, hardpointId); _onEquipCargo(_selectedCargoIndex, hardpointId);
@ -1068,13 +1069,14 @@ public partial class Hud : CanvasLayer
} }
// Spectator Wall (LOS / Tourist horizon rule / 5s ghost memory; hidden Exemplars vanish!) // Spectator Wall (LOS / Tourist horizon rule / 5s ghost memory; hidden Exemplars vanish!)
var obs0 = _state.GetOrCreateObserverState(0);
var specs = _state.Spectators.Spectators; var specs = _state.Spectators.Spectators;
for (int i = 0; i < specs.Count; i++) for (int i = 0; i < specs.Count; i++)
{ {
var s = specs[i]; var s = specs[i];
if (!s.Alive) continue; if (!s.Alive) continue;
_state.SpectatorContacts.TryGetValue(s.Id, out var mem); obs0.SpectatorContacts.TryGetValue(s.Id, out var mem);
if (!MatchState.IsContactOnRadar(mem)) if (!MatchState.IsContactOnRadar(mem))
{ {
continue; continue;
@ -1100,11 +1102,11 @@ public partial class Hud : CanvasLayer
if (tid >= 0 && tid < _state.Contenders.Count && _state.Contenders[tid].Alive) if (tid >= 0 && tid < _state.Contenders.Count && _state.Contenders[tid].Alive)
{ {
var tgt = _state.Contenders[tid]; var tgt = _state.Contenders[tid];
bool targetVisible = tgt.IsPlayer || bool targetVisible = tgt.Id == 0 ||
(_state.ContenderContacts.TryGetValue(tgt.Id, out var tgtMem) && tgtMem.VisibleToPlayer); (obs0.ContenderContacts.TryGetValue(tgt.Id, out var tgtMem) && tgtMem.VisibleToPlayer);
if (targetVisible) if (targetVisible)
{ {
float tgtClampR = MathF.Max(4f, radius - (tgt.IsPlayer ? 7.5f : 4.3f)); float tgtClampR = MathF.Max(4f, radius - (tgt.Id == 0 ? 7.5f : 4.3f));
var tp = ClampToRadarDisc(center, tgtClampR, WorldToRadar(center, scale, tgt.X, tgt.Z, _cameraYaw)); var tp = ClampToRadarDisc(center, tgtClampR, WorldToRadar(center, scale, tgt.X, tgt.Z, _cameraYaw));
DrawLine(p, tp, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f), 1.3f); DrawLine(p, tp, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f), 1.3f);
} }
@ -1134,7 +1136,7 @@ public partial class Hud : CanvasLayer
var c = _state.Contenders[i]; var c = _state.Contenders[i];
if (!c.Alive) continue; if (!c.Alive) continue;
if (c.IsPlayer) if (c.Id == 0)
{ {
float playerClampR = MathF.Max(4f, radius - 6.5f - 1f); float playerClampR = MathF.Max(4f, radius - 6.5f - 1f);
var p = ClampToRadarDisc(center, playerClampR, WorldToRadar(center, scale, c.X, c.Z, _cameraYaw)); var p = ClampToRadarDisc(center, playerClampR, WorldToRadar(center, scale, c.X, c.Z, _cameraYaw));
@ -1152,7 +1154,7 @@ public partial class Hud : CanvasLayer
continue; continue;
} }
_state.ContenderContacts.TryGetValue(c.Id, out var mem); obs0.ContenderContacts.TryGetValue(c.Id, out var mem);
if (!MatchState.IsContactOnRadar(mem)) if (!MatchState.IsContactOnRadar(mem))
{ {
continue; continue;

View file

@ -126,7 +126,7 @@ public partial class Main : Node3D
private void SetupPerfCombatScenario(ArenaSession session) private void SetupPerfCombatScenario(ArenaSession session)
{ {
var p = session.State.Player; var p = session.State.Contenders[0];
float fwdX = MathF.Sin(p.Yaw); float fwdX = MathF.Sin(p.Yaw);
float fwdZ = MathF.Cos(p.Yaw); float fwdZ = MathF.Cos(p.Yaw);
float rightX = -fwdZ; float rightX = -fwdZ;
@ -187,8 +187,8 @@ public partial class Main : Node3D
try try
{ {
_session = new ArenaSession(seed, _mapKind); _session = new ArenaSession(seed, _mapKind, slot0Human: true);
var p = _session.State.Player; var p = _session.State.Contenders[0];
_cameraYaw = p.Yaw; _cameraYaw = p.Yaw;
_cameraPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(5f) : Mathf.DegToRad(12f); _cameraPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(5f) : Mathf.DegToRad(12f);
_cameraZoom = 1.0f; _cameraZoom = 1.0f;
@ -319,7 +319,8 @@ public partial class Main : Node3D
if (_perfTargetFrames > 0) if (_perfTargetFrames > 0)
{ {
long t0 = Stopwatch.GetTimestamp(); long t0 = Stopwatch.GetTimestamp();
_session.Step(input); _session.SetHumanInput(0, input);
_session.Step();
long t1 = Stopwatch.GetTimestamp(); long t1 = Stopwatch.GetTimestamp();
double toMs = 1000.0 / Stopwatch.Frequency; double toMs = 1000.0 / Stopwatch.Frequency;
_perfPendingStepMs += (t1 - t0) * toMs; _perfPendingStepMs += (t1 - t0) * toMs;
@ -327,7 +328,8 @@ public partial class Main : Node3D
} }
else else
{ {
_session.Step(input); _session.SetHumanInput(0, input);
_session.Step();
} }
} }
@ -536,7 +538,7 @@ public partial class Main : Node3D
if (Input.IsKeyPressed(Key.D) || Input.IsKeyPressed(Key.Right)) steer += 1f; if (Input.IsKeyPressed(Key.D) || Input.IsKeyPressed(Key.Right)) steer += 1f;
if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) steer -= 1f; if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) steer -= 1f;
bool isVtol = Session.State.Player.Grid.Spec.IsVtol; bool isVtol = Session.State.Contenders[0].Grid.Spec.IsVtol;
float verticalThrottle = 0f; float verticalThrottle = 0f;
if (Input.IsKeyPressed(Key.Space)) verticalThrottle += 1f; if (Input.IsKeyPressed(Key.Space)) verticalThrottle += 1f;
if (Input.IsKeyPressed(Key.C) || Input.IsKeyPressed(Key.Ctrl)) verticalThrottle -= 1f; if (Input.IsKeyPressed(Key.C) || Input.IsKeyPressed(Key.Ctrl)) verticalThrottle -= 1f;
@ -561,7 +563,7 @@ public partial class Main : Node3D
private (float AimX, float AimY, float AimZ) ComputeCenterScreenAim() private (float AimX, float AimY, float AimZ) ComputeCenterScreenAim()
{ {
var player = Session.State.Player; var player = Session.State.Contenders[0];
var spec = player.Grid.Spec; var spec = player.Grid.Spec;
Vector2 screenSize = GetViewport().GetVisibleRect().Size; Vector2 screenSize = GetViewport().GetVisibleRect().Size;
if (screenSize.X < 2f || screenSize.Y < 2f) if (screenSize.X < 2f || screenSize.Y < 2f)
@ -667,7 +669,7 @@ public partial class Main : Node3D
private void UpdateCamera(float dt, float alpha) private void UpdateCamera(float dt, float alpha)
{ {
var p = Session.State.Player; var p = Session.State.Contenders[0];
var spec = p.Grid.Spec; var spec = p.Grid.Spec;
var (posInterp, _, _) = Session.GetInterpolatedContenderPose(p.Id, alpha); var (posInterp, _, _) = Session.GetInterpolatedContenderPose(p.Id, alpha);
@ -794,7 +796,7 @@ public partial class Main : Node3D
private void OnEquipCargo(int cargoIndex, string hardpointId) private void OnEquipCargo(int cargoIndex, string hardpointId)
{ {
_session?.TryEquipCargo(cargoIndex, hardpointId); _session?.TryEquipCargo(0, cargoIndex, hardpointId);
} }
private void SetupLightingAndSky() private void SetupLightingAndSky()

View file

@ -62,7 +62,7 @@ public partial class Smoke : Node
Check(!_main.GetWorld3D().Space.IsValid, "Godot should have no active 3D physics space"); Check(!_main.GetWorld3D().Space.IsValid, "Godot should have no active 3D physics space");
Check(_main.Terrain.BakedTileCount == 64, $"Expected 64 baked terrain tiles, got {_main.Terrain.BakedTileCount}"); Check(_main.Terrain.BakedTileCount == 64, $"Expected 64 baked terrain tiles, got {_main.Terrain.BakedTileCount}");
var player = _main.Session.State.Player; var player = _main.Session.State.Contenders[0];
float startX = player.X; float startX = player.X;
float startZ = player.Z; float startZ = player.Z;
@ -580,7 +580,7 @@ public partial class Smoke : Node
} }
// Seed realistic combat telemetry so the preview clearly showcases armor stripping, hit-flash, cargo rack, and thermal heat // Seed realistic combat telemetry so the preview clearly showcases armor stripping, hit-flash, cargo rack, and thermal heat
var player = _main.Session.State.Player; var player = _main.Session.State.Contenders[0];
var grid = player.Grid; var grid = player.Grid;
grid.TryAddCargo(Catalog.TouringPlasma); grid.TryAddCargo(Catalog.TouringPlasma);
grid.TryAddCargo(Catalog.GoldRadiator); grid.TryAddCargo(Catalog.GoldRadiator);
@ -925,7 +925,7 @@ public partial class Smoke : Node
// 6. All 7 walkers (including Kestrel) walk through real ArenaSession + Hybrid B FK snapshot cleanly // 6. All 7 walkers (including Kestrel) walk through real ArenaSession + Hybrid B FK snapshot cleanly
{ {
using var walkSession = new RustToDust.Ymir.ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert); using var walkSession = new RustToDust.Ymir.ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: true);
for (int cIdx = 1; cIdx < walkSession.State.Contenders.Count; cIdx++) for (int cIdx = 1; cIdx < walkSession.State.Contenders.Count; cIdx++)
{ {
walkSession.SetContenderPose(cIdx, 450f + cIdx * 18f, 450f); walkSession.SetContenderPose(cIdx, 450f + cIdx * 18f, 450f);
@ -946,10 +946,10 @@ public partial class Smoke : Node
{ {
var wSpec = Catalog.ChassisById[wId]; var wSpec = Catalog.ChassisById[wId];
walkSession.SetContenderPose(0, 0f, 0f, 0f); walkSession.SetContenderPose(0, 0f, 0f, 0f);
if (walkSession.State.Player.Grid.Spec.Id != wId) if (walkSession.State.Contenders[0].Grid.Spec.Id != wId)
{ {
walkSession.State.SpawnChassisDrop(0f, 0f, wSpec); walkSession.State.SpawnChassisDrop(0f, 0f, wSpec);
Check(walkSession.TrySwapNearbyChassis(), $"Failed to swap walkSession player to '{wId}'"); Check(walkSession.TrySwapNearbyChassis(0), $"Failed to swap walkSession player to '{wId}'");
} }
var vis = VehicleVisualInstance.Create(cache, wId, VehicleVisualRole.Player); var vis = VehicleVisualInstance.Create(cache, wId, VehicleVisualRole.Player);
@ -961,10 +961,10 @@ public partial class Smoke : Node
Check(footNode is not null && pelvisNode is not null, Check(footNode is not null && pelvisNode is not null,
$"Missing FK nodes '{footNodeName}'/'{pelvisNodeName}' on walker '{wId}'"); $"Missing FK nodes '{footNodeName}'/'{pelvisNodeName}' on walker '{wId}'");
var player = walkSession.State.Player; var player = walkSession.State.Contenders[0];
for (int step = 0; step < 60; step++) for (int step = 0; step < 60; step++)
{ {
walkSession.Step(new PlayerInput( walkSession.SetHumanInput(0, new PlayerInput(
Throttle: 1f, Throttle: 1f,
Steer: 0f, Steer: 0f,
AimWorldX: player.X, AimWorldX: player.X,
@ -972,6 +972,7 @@ public partial class Smoke : Node
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
walkSession.Step();
bool hasSnap = walkSession.TrySampleInterpolatedWalkerPose(true, player.Id, 1f, out var walkerSnap); bool hasSnap = walkSession.TrySampleInterpolatedWalkerPose(true, player.Id, 1f, out var walkerSnap);
Check(hasSnap, $"Missing WalkerVisualSnapshot for '{wId}' at step {step}"); Check(hasSnap, $"Missing WalkerVisualSnapshot for '{wId}' at step {step}");
@ -1133,7 +1134,7 @@ public partial class Smoke : Node
// 10. MultiMeshPartPool & PomDecalPool sanity: live arena submits into MultiMeshPartPool and PomDecalPool stamps impacts cleanly // 10. MultiMeshPartPool & PomDecalPool sanity: live arena submits into MultiMeshPartPool and PomDecalPool stamps impacts cleanly
{ {
_main.Arena.PomDecals.StampTestDecal( _main.Arena.PomDecals.StampTestDecal(
new Vector3(_main.Session.State.Player.X + 2f, _main.Session.State.Terrain.SampleHeight(_main.Session.State.Player.X + 2f, _main.Session.State.Player.Z) + 0.03f, _main.Session.State.Player.Z), new Vector3(_main.Session.State.Contenders[0].X + 2f, _main.Session.State.Terrain.SampleHeight(_main.Session.State.Contenders[0].X + 2f, _main.Session.State.Contenders[0].Z) + 0.03f, _main.Session.State.Contenders[0].Z),
Vector3.Up, 1.2f, tileIndex: 14); Vector3.Up, 1.2f, tileIndex: 14);
_main.Arena.Sync(_main.Session, 1.6f, 1f / 60f); _main.Arena.Sync(_main.Session, 1.6f, 1f / 60f);
Check(_main.Arena.PartPool.TotalSubmittedInstances > 0, Check(_main.Arena.PartPool.TotalSubmittedInstances > 0,
@ -1141,7 +1142,7 @@ public partial class Smoke : Node
Check(_main.Arena.PomDecals.ActiveCount >= 1, Check(_main.Arena.PomDecals.ActiveCount >= 1,
$"Expected PomDecalPool to hold >= 1 active decal, got {_main.Arena.PomDecals.ActiveCount}"); $"Expected PomDecalPool to hold >= 1 active decal, got {_main.Arena.PomDecals.ActiveCount}");
_main.Hud.PushTestHitArc(_main.Session.State.Player.X + 20f, _main.Session.State.Player.Z + 10f, WeaponVisualClass.Explosive); _main.Hud.PushTestHitArc(_main.Session.State.Contenders[0].X + 20f, _main.Session.State.Contenders[0].Z + 10f, WeaponVisualClass.Explosive);
Check(_main.Hud.ActiveHitArcCount >= 1, "Expected CrosshairOverlay to accept incoming hit arc"); Check(_main.Hud.ActiveHitArcCount >= 1, "Expected CrosshairOverlay to accept incoming hit arc");
} }
@ -1223,7 +1224,7 @@ public partial class Smoke : Node
int vfxBefore = _main.Arena.TransientVfxCount; int vfxBefore = _main.Arena.TransientVfxCount;
int tracerId = _main.Session.State.AllocateTracerId(); int tracerId = _main.Session.State.AllocateTracerId();
Vector3 pPos = new(_main.Session.State.Player.X, _main.Session.State.Player.Y, _main.Session.State.Player.Z); Vector3 pPos = new(_main.Session.State.Contenders[0].X, _main.Session.State.Contenders[0].Y, _main.Session.State.Contenders[0].Z);
tracers.Add(new TracerEvent( tracers.Add(new TracerEvent(
pPos.X, pPos.Y + 1f, pPos.Z, pPos.X, pPos.Y + 1f, pPos.Z,
pPos.X + 20f, pPos.Y + 1f, pPos.Z, pPos.X + 20f, pPos.Y + 1f, pPos.Z,
@ -1400,7 +1401,7 @@ public partial class Smoke : Node
private async Task VerifyMaxLoadPaladinGarageAsync() private async Task VerifyMaxLoadPaladinGarageAsync()
{ {
var grid = _main.Session.State.Player.Grid; var grid = _main.Session.State.Contenders[0].Grid;
grid.SwapChassis(Catalog.Paladin); grid.SwapChassis(Catalog.Paladin);
Check(grid.TryMount(Catalog.TouringPlasma, "hp.weapon.sh_l"), "Expected TouringPlasma on Paladin hp.weapon.sh_l"); Check(grid.TryMount(Catalog.TouringPlasma, "hp.weapon.sh_l"), "Expected TouringPlasma on Paladin hp.weapon.sh_l");
Check(grid.TryMount(Catalog.WeldedPlate, "hp.armor.torso"), "Expected WeldedPlate on Paladin hp.armor.torso"); Check(grid.TryMount(Catalog.WeldedPlate, "hp.armor.torso"), "Expected WeldedPlate on Paladin hp.armor.torso");
@ -1483,7 +1484,7 @@ public partial class Smoke : Node
Vector2 vpSize = GetViewport().GetVisibleRect().Size; Vector2 vpSize = GetViewport().GetVisibleRect().Size;
Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Sion HUD panels overlapped or clipped at {vpSize}"); Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Sion HUD panels overlapped or clipped at {vpSize}");
var player = sionState.Player; var player = sionState.Contenders[0];
float startX = player.X; float startX = player.X;
float startZ = player.Z; float startZ = player.Z;
_main.SetScriptedInput(new PlayerInput( _main.SetScriptedInput(new PlayerInput(

View file

@ -1,3 +1,4 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace RustToDust.Core namespace RustToDust.Core
@ -25,6 +26,7 @@ namespace RustToDust.Core
public IReadOnlyList<BroadcastLine> Lines => _lines; public IReadOnlyList<BroadcastLine> Lines => _lines;
public BroadcastLine? Latest => _lines.Count > 0 ? _lines[_lines.Count - 1] : null; public BroadcastLine? Latest => _lines.Count > 0 ? _lines[_lines.Count - 1] : null;
public long Version { get; private set; } public long Version { get; private set; }
public event Action<BroadcastLine>? LineEmitted;
public void Emit(float timestamp, BroadcastKind kind, string text) public void Emit(float timestamp, BroadcastKind kind, string text)
{ {
@ -32,8 +34,10 @@ namespace RustToDust.Core
{ {
_lines.RemoveAt(0); _lines.RemoveAt(0);
} }
_lines.Add(new BroadcastLine(timestamp, kind, text)); var line = new BroadcastLine(timestamp, kind, text);
_lines.Add(line);
Version++; Version++;
LineEmitted?.Invoke(line);
} }
public void EmitMatchStart(float timestamp, ArenaMapKind mapKind = ArenaMapKind.Desert) => public void EmitMatchStart(float timestamp, ArenaMapKind mapKind = ArenaMapKind.Desert) =>

View file

@ -808,6 +808,167 @@ namespace RustToDust.Core
return max > 0f ? cur / max : 0f; return max > 0f ? cur / max : 0f;
} }
public float ComputeMaxThermalRatio()
{
float worst = 0f;
for (int i = 0; i < Mounted.Count; i++)
{
var m = Mounted[i];
float span = MathF.Max(1f, m.Spec.MaxTemp - AmbientTemp);
float ratio = Math.Clamp((m.CurrentTemp - AmbientTemp) / span, 0f, 1.5f);
if (ratio > worst) worst = ratio;
}
for (int y = 0; y < Spec.Height; y++)
{
for (int x = 0; x < Spec.Width; x++)
{
if (!Spec.IsActive(x, y)) continue;
float ratio = Math.Clamp((Temperature[x, y] - AmbientTemp) / 380f, 0f, 1.5f);
if (ratio > worst) worst = ratio;
}
}
return worst;
}
public byte[] QuantizeArmorBytes()
{
int count = 0;
for (int y = 0; y < Spec.Height; y++)
for (int x = 0; x < Spec.Width; x++)
if (Spec.IsActive(x, y)) count++;
var bytes = new byte[count];
int idx = 0;
for (int y = 0; y < Spec.Height; y++)
{
for (int x = 0; x < Spec.Width; x++)
{
if (!Spec.IsActive(x, y)) continue;
float max = MathF.Max(0.01f, MaxArmor[x, y]);
float ratio = Math.Clamp(Armor[x, y] / max, 0f, 1f);
bytes[idx++] = (byte)Math.Clamp((int)MathF.Round(ratio * 255f), 0, 255);
}
}
return bytes;
}
public void ApplyReplicatedArmorBytes(ReadOnlySpan<byte> armorBytes)
{
int idx = 0;
for (int y = 0; y < Spec.Height; y++)
{
for (int x = 0; x < Spec.Width; x++)
{
if (!Spec.IsActive(x, y)) continue;
if (idx >= armorBytes.Length) return;
Armor[x, y] = MaxArmor[x, y] * (armorBytes[idx++] / 255f);
}
}
}
public void ApplyReplicatedDamage(int cellX, int cellY, float cellArmor, float cellTemp, float coreHp, int hitSequence)
{
if (Spec.IsActive(cellX, cellY))
{
Armor[cellX, cellY] = MathF.Max(0f, cellArmor);
Temperature[cellX, cellY] = MathF.Max(AmbientTemp, cellTemp);
LastHitX = cellX;
LastHitY = cellY;
}
CoreHp = MathF.Max(0f, coreHp);
if (hitSequence > HitSequence)
{
HitSequence = hitSequence;
}
else
{
HitSequence++;
}
UpdateMountedTelemetry();
}
public void ApplyReplicatedThermal(ReadOnlySpan<byte> quantizedCellTemps, ReadOnlySpan<float> mountedTemps, ReadOnlySpan<float> mountedCooldowns)
{
int idx = 0;
for (int y = 0; y < Spec.Height; y++)
{
for (int x = 0; x < Spec.Width; x++)
{
if (!Spec.IsActive(x, y)) continue;
if (idx < quantizedCellTemps.Length)
{
Temperature[x, y] = AmbientTemp + quantizedCellTemps[idx++] * 2.0f;
}
}
}
for (int i = 0; i < Mounted.Count; i++)
{
if (i < mountedTemps.Length)
{
Mounted[i].CurrentTemp = mountedTemps[i];
Mounted[i].CurrentPerformance = Mounted[i].Spec.Performance(mountedTemps[i]);
}
if (i < mountedCooldowns.Length)
{
Mounted[i].Cooldown = mountedCooldowns[i];
}
}
}
public void ApplyReplicatedLoadout(
ChassisSpec spec,
float coreHp,
float maxCoreHp,
ReadOnlySpan<byte> armorBytes,
IReadOnlyList<(string ModuleId, string HardpointId)> mounted,
IReadOnlyList<string>? cargoIds,
Func<string, ModuleSpec?> moduleResolver)
{
if (!string.Equals(Spec.Id, spec.Id, StringComparison.Ordinal))
{
Spec = spec;
Temperature = new float[spec.Width, spec.Height];
Armor = new float[spec.Width, spec.Height];
MaxArmor = new float[spec.Width, spec.Height];
BorderCells = new bool[spec.Width, spec.Height];
_netHeat = new float[spec.Width, spec.Height];
_cellThermalMass = new float[spec.Width, spec.Height];
_cellConductivity = new float[spec.Width, spec.Height];
InitializeGridState(spec, preserveCoreRatio: false, previousRatio: 1f);
}
Mounted.Clear();
for (int i = 0; i < mounted.Count; i++)
{
var (modId, hpId) = mounted[i];
var modSpec = moduleResolver(modId);
if (modSpec is not null)
{
Mounted.Add(new MountedModule(modSpec, hpId, AmbientTemp));
}
}
if (cargoIds is not null)
{
Cargo.Clear();
for (int i = 0; i < cargoIds.Count; i++)
{
var modSpec = moduleResolver(cargoIds[i]);
if (modSpec is not null)
{
Cargo.Add(modSpec);
}
}
}
RecalculateArmorAndThermal(grantNewArmorDelta: false);
MaxCoreHp = maxCoreHp > 0f ? maxCoreHp : MaxCoreHp;
CoreHp = Math.Clamp(coreHp, 0f, MaxCoreHp);
ApplyReplicatedArmorBytes(armorBytes);
UpdateMountedTelemetry();
}
private (int X, int Y) ResolveHitCell(float localRight, float localForward, float localHeightNorm) private (int X, int Y) ResolveHitCell(float localRight, float localForward, float localHeightNorm)
{ {
int w = Spec.Width; int w = Spec.Width;

View file

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Numerics;
namespace RustToDust.Core
{
public enum ClientMatchOutcome
{
Active,
Victory,
Defeat
}
public enum NetworkMode
{
Solo,
ListenHost,
RemoteClient
}
public readonly record struct NetworkStatusSnapshot(
NetworkMode Mode,
bool Connected,
int PingMs,
int ConnectedHumans,
int MaxHumans,
string StateLabel,
string? LastError = null);
public readonly record struct ClientRayHit(
bool Hit,
ulong StableId,
Vector3 Point,
Vector3 Normal,
float Fraction);
public interface IClientArenaSession : IDisposable
{
MatchState ViewState { get; }
int LocalContenderId { get; }
ContenderState LocalContender { get; }
ClientMatchOutcome LocalOutcome { get; }
int LocalDetectedByCount { get; }
IReadOnlyDictionary<int, PlayerContactMemory> LocalContenderContacts { get; }
IReadOnlyDictionary<int, PlayerContactMemory> LocalSpectatorContacts { get; }
NetworkStatusSnapshot ConnectionStatus { get; }
bool IsContenderVisible(int contenderId);
bool IsSpectatorVisible(int spectatorId);
void BeginRenderFrame(double dt, float physicsAlpha);
void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick);
bool RequestEquipCargo(int cargoIndex, string hardpointId);
void RequestNewMatch(int seed, ArenaMapKind mapKind);
(Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha);
(Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha);
bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap);
ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation);
}
}

View file

@ -252,31 +252,36 @@ namespace RustToDust.Core
return rad; return rad;
} }
public static void ApplyPlayerInput(MatchState state, PlayerInput input) public static void ApplyHumanInput(MatchState state, int contenderId, in PlayerInput input)
{ {
var player = state.Player; if (contenderId < 0 || contenderId >= state.Contenders.Count)
if (!player.Alive)
{ {
player.ThrottleCmd = 0f;
player.SteerCmd = 0f;
player.VerticalThrottleCmd = 0f;
player.FireCmd = false;
player.BrakeCmd = true;
return; return;
} }
player.ThrottleCmd = Math.Clamp(input.Throttle, -1f, 1f); var human = state.Contenders[contenderId];
player.SteerCmd = Math.Clamp(input.Steer, -1f, 1f); if (!human.Alive)
player.VerticalThrottleCmd = Math.Clamp(input.VerticalThrottle, -1f, 1f); {
player.AimX = input.AimWorldX; human.ThrottleCmd = 0f;
player.AimY = input.AimWorldY; human.SteerCmd = 0f;
player.AimZ = input.AimWorldZ; human.VerticalThrottleCmd = 0f;
player.FireCmd = input.Fire; human.FireCmd = false;
player.BrakeCmd = input.Brake; human.BrakeCmd = true;
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);
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 = input.Fire;
human.BrakeCmd = input.Brake;
if (input.InteractPickup) if (input.InteractPickup)
{ {
state.TryInteractNearestDrop(0); state.TryInteractNearestDrop(contenderId);
} }
} }
@ -287,7 +292,7 @@ namespace RustToDust.Core
for (int i = 0; i < state.Contenders.Count; i++) for (int i = 0; i < state.Contenders.Count; i++)
{ {
var ai = state.Contenders[i]; var ai = state.Contenders[i];
if (ai.IsPlayer || !ai.Alive) if (ai.IsHuman || !ai.Alive)
{ {
continue; continue;
} }
@ -811,25 +816,25 @@ namespace RustToDust.Core
return; return;
} }
if (!state.Player.Alive)
{
state.Phase = MatchPhase.Defeat;
return;
}
int aliveCount = 0; int aliveCount = 0;
ContenderState? survivor = null;
for (int i = 0; i < state.Contenders.Count; i++) for (int i = 0; i < state.Contenders.Count; i++)
{ {
if (state.Contenders[i].Alive) if (state.Contenders[i].Alive)
{ {
aliveCount++; aliveCount++;
survivor = state.Contenders[i];
} }
} }
if (aliveCount <= 1 && state.Player.Alive) if (aliveCount <= 1)
{ {
state.Phase = MatchPhase.Victory; state.Phase = MatchPhase.Completed;
state.Broadcast.EmitVictory(state.Time, state.Player.Id, state.MapKind); state.WinnerContenderId = survivor?.Id;
if (survivor is not null)
{
state.Broadcast.EmitVictory(state.Time, survivor.Id, state.MapKind);
}
} }
} }

View file

@ -7,8 +7,7 @@ namespace RustToDust.Core
public enum MatchPhase public enum MatchPhase
{ {
Active, Active,
Victory, Completed
Defeat
} }
public readonly record struct PlayerInput( public readonly record struct PlayerInput(
@ -90,6 +89,33 @@ namespace RustToDust.Core
public bool FaintHorizonPing { get; set; } public bool FaintHorizonPing { get; set; }
} }
public sealed class ObserverDetectionState
{
public Dictionary<int, PlayerContactMemory> ContenderContacts { get; } = new();
public Dictionary<int, PlayerContactMemory> SpectatorContacts { get; } = new();
public int DetectedByCount { get; set; }
public PlayerContactMemory GetOrCreateContenderContact(int contenderId)
{
if (!ContenderContacts.TryGetValue(contenderId, out var mem))
{
mem = new PlayerContactMemory();
ContenderContacts[contenderId] = mem;
}
return mem;
}
public PlayerContactMemory GetOrCreateSpectatorContact(int spectatorId)
{
if (!SpectatorContacts.TryGetValue(spectatorId, out var mem))
{
mem = new PlayerContactMemory();
SpectatorContacts[spectatorId] = mem;
}
return mem;
}
}
public sealed class GroundDrop public sealed class GroundDrop
{ {
public GroundDrop(int id, float x, float z, ChassisSpec? chassis, ModuleSpec? module) public GroundDrop(int id, float x, float z, ChassisSpec? chassis, ModuleSpec? module)
@ -111,11 +137,11 @@ namespace RustToDust.Core
public sealed class ContenderState public sealed class ContenderState
{ {
public ContenderState(int id, string name, bool isPlayer, ChassisGrid grid, float x, float z, float yaw) public ContenderState(int id, string name, bool isHuman, ChassisGrid grid, float x, float z, float yaw)
{ {
Id = id; Id = id;
Name = name; Name = name;
IsPlayer = isPlayer; IsHuman = isHuman;
Grid = grid; Grid = grid;
X = x; X = x;
Y = grid.Spec.HalfHeight + 0.1f; Y = grid.Spec.HalfHeight + 0.1f;
@ -134,9 +160,12 @@ namespace RustToDust.Core
} }
public int Id { get; } public int Id { get; }
public string Name { get; } public string Name { get; set; }
public bool IsPlayer { get; } public bool IsHuman { get; set; }
public ChassisGrid Grid { get; } public ChassisGrid Grid { get; }
public int LoadoutVersion { get; set; } = 1;
public int DamageVersion { get; set; } = 1;
public float MaxThermalRatio { get; set; }
public float X { get; set; } public float X { get; set; }
public float Y { get; set; } public float Y { get; set; }
public float Z { get; set; } public float Z { get; set; }
@ -268,6 +297,7 @@ namespace RustToDust.Core
public Random Rng { get; } public Random Rng { get; }
public float Time { get; set; } public float Time { get; set; }
public MatchPhase Phase { get; set; } = MatchPhase.Active; public MatchPhase Phase { get; set; } = MatchPhase.Active;
public int? WinnerContenderId { get; set; }
public TerrainField Terrain { get; } public TerrainField Terrain { get; }
public List<ContenderState> Contenders { get; } = new(); public List<ContenderState> Contenders { get; } = new();
@ -279,17 +309,17 @@ namespace RustToDust.Core
public IReadOnlyList<ArenaBoxSpec> ArenaCoverBoxes { get; } public IReadOnlyList<ArenaBoxSpec> ArenaCoverBoxes { get; }
public IReadOnlyList<ArenaBoxSpec> ArenaBoundaryBoxes { get; } public IReadOnlyList<ArenaBoxSpec> ArenaBoundaryBoxes { get; }
public Dictionary<int, PlayerContactMemory> ContenderContacts { get; } = new(); public Dictionary<int, ObserverDetectionState> ObserverStates { get; } = new();
public Dictionary<int, PlayerContactMemory> SpectatorContacts { get; } = new(); public IReadOnlyDictionary<int, PlayerContactMemory> EmptyContacts { get; } = new Dictionary<int, PlayerContactMemory>();
public int PlayerDetectedByCount { get; set; }
public float? LastGunfireX { get; set; } public float? LastGunfireX { get; set; }
public float? LastGunfireZ { get; set; } public float? LastGunfireZ { get; set; }
public float LastGunfireTime { get; set; } = -100f; public float LastGunfireTime { get; set; } = -100f;
public ContenderState Player => Contenders[0];
public event Action<ContenderState>? ChassisSwapped; public event Action<ContenderState>? ChassisSwapped;
public event Action<ContenderState>? LoadoutChanged;
public event Action<GroundDrop>? DropSpawned;
public event Action<int, int>? DropPickedUp;
public long AllocateHitEventId() => _nextHitEventId++; public long AllocateHitEventId() => _nextHitEventId++;
public int AllocateTracerId() => _nextTracerId++; public int AllocateTracerId() => _nextTracerId++;
@ -311,30 +341,21 @@ namespace RustToDust.Core
return mem.VisibleToPlayer || mem.FaintHorizonPing || (mem.HasEverBeenSeen && mem.LastSeenAge <= ContactGhostDuration); return mem.VisibleToPlayer || mem.FaintHorizonPing || (mem.HasEverBeenSeen && mem.LastSeenAge <= ContactGhostDuration);
} }
public PlayerContactMemory GetOrCreateContenderContact(int contenderId) public ObserverDetectionState GetOrCreateObserverState(int observerId)
{ {
if (!ContenderContacts.TryGetValue(contenderId, out var mem)) if (!ObserverStates.TryGetValue(observerId, out var obs))
{ {
mem = new PlayerContactMemory(); obs = new ObserverDetectionState();
ContenderContacts[contenderId] = mem; ObserverStates[observerId] = obs;
} }
return mem; return obs;
}
public PlayerContactMemory GetOrCreateSpectatorContact(int spectatorId)
{
if (!SpectatorContacts.TryGetValue(spectatorId, out var mem))
{
mem = new PlayerContactMemory();
SpectatorContacts[spectatorId] = mem;
}
return mem;
} }
public GroundDrop SpawnModuleDrop(float x, float z, ModuleSpec module) public GroundDrop SpawnModuleDrop(float x, float z, ModuleSpec module)
{ {
var drop = new GroundDrop(_nextDropId++, x, z, null, module); var drop = new GroundDrop(_nextDropId++, x, z, null, module);
GroundDrops.Add(drop); GroundDrops.Add(drop);
DropSpawned?.Invoke(drop);
return drop; return drop;
} }
@ -342,11 +363,36 @@ namespace RustToDust.Core
{ {
var drop = new GroundDrop(_nextDropId++, x, z, chassis, null); var drop = new GroundDrop(_nextDropId++, x, z, chassis, null);
GroundDrops.Add(drop); GroundDrops.Add(drop);
DropSpawned?.Invoke(drop);
return drop; return drop;
} }
public bool TryEquipCargo(int cargoIndex, string hardpointId) => public GroundDrop ApplyReplicatedDropSpawned(int dropId, float x, float z, ChassisSpec? chassis, ModuleSpec? module)
TryEquipCargo(0, cargoIndex, hardpointId); {
for (int i = 0; i < GroundDrops.Count; i++)
{
if (GroundDrops[i].Id == dropId)
{
return GroundDrops[i];
}
}
if (dropId >= _nextDropId) _nextDropId = dropId + 1;
var drop = new GroundDrop(dropId, x, z, chassis, module);
GroundDrops.Add(drop);
return drop;
}
public void ApplyReplicatedDropPickedUp(int dropId)
{
for (int i = 0; i < GroundDrops.Count; i++)
{
if (GroundDrops[i].Id == dropId)
{
GroundDrops[i].PickedUp = true;
return;
}
}
}
public bool TryEquipCargo(int contenderId, int cargoIndex, string hardpointId) public bool TryEquipCargo(int contenderId, int cargoIndex, string hardpointId)
{ {
@ -372,10 +418,12 @@ namespace RustToDust.Core
{ {
SpawnModuleDrop(contender.X + 1.5f, contender.Z + 1.5f, displaced[i]); SpawnModuleDrop(contender.X + 1.5f, contender.Z + 1.5f, displaced[i]);
} }
contender.LoadoutVersion++;
LoadoutChanged?.Invoke(contender);
return true; return true;
} }
public GroundDrop? FindNearestInteractableDrop(int contenderId = 0) public GroundDrop? FindNearestInteractableDrop(int contenderId)
{ {
if (contenderId < 0 || contenderId >= Contenders.Count) if (contenderId < 0 || contenderId >= Contenders.Count)
{ {
@ -412,7 +460,7 @@ namespace RustToDust.Core
return nearest; return nearest;
} }
public bool TryInteractNearestDrop(int contenderId = 0) public bool TryInteractNearestDrop(int contenderId)
{ {
var nearest = FindNearestInteractableDrop(contenderId); var nearest = FindNearestInteractableDrop(contenderId);
if (nearest is null) if (nearest is null)
@ -432,7 +480,7 @@ namespace RustToDust.Core
return false; return false;
} }
public bool TryPickupNearbyModule(int contenderId = 0) public bool TryPickupNearbyModule(int contenderId)
{ {
if (contenderId < 0 || contenderId >= Contenders.Count) if (contenderId < 0 || contenderId >= Contenders.Count)
{ {
@ -469,7 +517,7 @@ namespace RustToDust.Core
return nearest is not null && ExecuteModuleDropPickup(contenderId, contender, nearest); return nearest is not null && ExecuteModuleDropPickup(contenderId, contender, nearest);
} }
public bool TrySwapNearbyChassis(int contenderId = 0, int? preferredDropId = null) public bool TrySwapNearbyChassis(int contenderId, int? preferredDropId = null)
{ {
if (contenderId < 0 || contenderId >= Contenders.Count) if (contenderId < 0 || contenderId >= Contenders.Count)
{ {
@ -527,10 +575,13 @@ namespace RustToDust.Core
} }
drop.PickedUp = true; drop.PickedUp = true;
DropPickedUp?.Invoke(drop.Id, contenderId);
if (boltedHardpointId is not null) if (boltedHardpointId is not null)
{ {
Broadcast.EmitQuickBolt(Time, contenderId, drop.Module.Name, boltedHardpointId); Broadcast.EmitQuickBolt(Time, contenderId, drop.Module.Name, boltedHardpointId);
} }
contender.LoadoutVersion++;
LoadoutChanged?.Invoke(contender);
return true; return true;
} }
@ -544,6 +595,7 @@ namespace RustToDust.Core
var oldChassis = contender.Grid.Spec; var oldChassis = contender.Grid.Spec;
var overflow = contender.Grid.SwapChassis(drop.Chassis); var overflow = contender.Grid.SwapChassis(drop.Chassis);
drop.PickedUp = true; drop.PickedUp = true;
DropPickedUp?.Invoke(drop.Id, contender.Id);
SpawnChassisDrop(contender.X - 2.2f, contender.Z - 2.2f, oldChassis); SpawnChassisDrop(contender.X - 2.2f, contender.Z - 2.2f, oldChassis);
for (int i = 0; i < overflow.Count; i++) for (int i = 0; i < overflow.Count; i++)
@ -558,8 +610,10 @@ namespace RustToDust.Core
contender.SnapPreviousPose(); contender.SnapPreviousPose();
contender.ResetAimTracker(contender.Yaw); contender.ResetAimTracker(contender.Yaw);
contender.AiScavengeCooldown = 4.0f; contender.AiScavengeCooldown = 4.0f;
contender.LoadoutVersion++;
Broadcast.EmitChassisSwap(Time, contender.Id, contender.Grid.Spec.Name); Broadcast.EmitChassisSwap(Time, contender.Id, contender.Grid.Spec.Name);
ChassisSwapped?.Invoke(contender); ChassisSwapped?.Invoke(contender);
LoadoutChanged?.Invoke(contender);
return true; return true;
} }
@ -788,23 +842,14 @@ namespace RustToDust.Core
float z = coords[i].Z; float z = coords[i].Z;
float yaw = MathF.Atan2(-x, -z); float yaw = MathF.Atan2(-x, -z);
string name = i == 0 ? "Contender 01 (You)" : $"Contender {i + 1:00}"; string name = $"Contender {i + 1:00}";
var grid = Catalog.CreateStarterBuggy(); var grid = Catalog.CreateStarterBuggy();
var contender = new ContenderState(i, name, i == 0, grid, x, z, yaw); var contender = new ContenderState(i, name, isHuman: false, grid, x, z, yaw);
contender.Y = Terrain.SampleHeight(x, z) + contender.Grid.Spec.HalfHeight + 0.15f; contender.Y = Terrain.SampleHeight(x, z) + contender.Grid.Spec.HalfHeight + 0.15f;
contender.AimY = contender.Y; contender.AimY = contender.Y;
contender.SnapPreviousPose(); contender.SnapPreviousPose();
contender.ResetAimTracker(yaw); contender.ResetAimTracker(yaw);
Contenders.Add(contender); Contenders.Add(contender);
if (i > 0)
{
ContenderContacts[i] = new PlayerContactMemory();
}
}
for (int i = 0; i < Spectators.Spectators.Count; i++)
{
SpectatorContacts[Spectators.Spectators[i].Id] = new PlayerContactMemory();
} }
} }
@ -941,17 +986,17 @@ namespace RustToDust.Core
const float minSepSq = 220f * 220f; const float minSepSq = 220f * 220f;
const float preferOccludedDistSq = 380f * 380f; const float preferOccludedDistSq = 380f * 380f;
// Player starts in the open Sion Old Town / Rhone plaza facing Basilique de Valere & Chateau de Tourbillon. // Slot 0 starts in the open Sion Old Town / Rhone plaza facing Basilique de Valere & Chateau de Tourbillon.
var playerGrid = Catalog.CreateStarterBuggy(); var anchorGrid = Catalog.CreateStarterBuggy();
float playerPad = MathF.Max(playerGrid.Spec.HalfWidth, playerGrid.Spec.HalfLength) + 2.0f; float anchorPad = MathF.Max(anchorGrid.Spec.HalfWidth, anchorGrid.Spec.HalfLength) + 2.0f;
(float px, float pz) = FindClearSionPoint(-60f, 360f, playerPad, minNy: 0.84f, maxSearchRadius: 120f); (float px, float pz) = FindClearSionPoint(-60f, 360f, anchorPad, minNy: 0.84f, maxSearchRadius: 120f);
float pYaw = MathF.Atan2(150f - px, -260f - pz); float pYaw = MathF.Atan2(150f - px, -260f - pz);
var player = new ContenderState(0, "Contender 01 (You)", true, playerGrid, px, pz, pYaw); var anchor = new ContenderState(0, "Contender 01", isHuman: false, anchorGrid, px, pz, pYaw);
player.Y = Terrain.SampleHeight(px, pz) + playerGrid.Spec.HalfHeight + 0.15f; anchor.Y = Terrain.SampleHeight(px, pz) + anchorGrid.Spec.HalfHeight + 0.15f;
player.AimY = player.Y; anchor.AimY = anchor.Y;
player.SnapPreviousPose(); anchor.SnapPreviousPose();
player.ResetAimTracker(pYaw); anchor.ResetAimTracker(pYaw);
Contenders.Add(player); Contenders.Add(anchor);
for (int i = 1; i < ContenderCount; i++) for (int i = 1; i < ContenderCount; i++)
{ {
@ -993,7 +1038,7 @@ namespace RustToDust.Core
} }
float playerDistSq = (cx - px) * (cx - px) + (cz - pz) * (cz - pz); float playerDistSq = (cx - px) * (cx - px) + (cz - pz) * (cz - pz);
if (playerDistSq >= preferOccludedDistSq || IsSionSpawnOccludedFromPlayer(player, cx, cz, grid.Spec)) if (playerDistSq >= preferOccludedDistSq || IsSionSpawnOccludedFromPlayer(anchor, cx, cz, grid.Spec))
{ {
x = cx; x = cx;
z = cz; z = cz;
@ -1052,18 +1097,12 @@ namespace RustToDust.Core
} }
float yaw = MathF.Atan2(-x, -z); float yaw = MathF.Atan2(-x, -z);
var contender = new ContenderState(i, $"Contender {i + 1:00}", false, grid, x, z, yaw); var contender = new ContenderState(i, $"Contender {i + 1:00}", isHuman: false, grid, x, z, yaw);
contender.Y = Terrain.SampleHeight(x, z) + grid.Spec.HalfHeight + 0.15f; contender.Y = Terrain.SampleHeight(x, z) + grid.Spec.HalfHeight + 0.15f;
contender.AimY = contender.Y; contender.AimY = contender.Y;
contender.SnapPreviousPose(); contender.SnapPreviousPose();
contender.ResetAimTracker(yaw); contender.ResetAimTracker(yaw);
Contenders.Add(contender); Contenders.Add(contender);
ContenderContacts[i] = new PlayerContactMemory();
}
for (int i = 0; i < Spectators.Spectators.Count; i++)
{
SpectatorContacts[Spectators.Spectators[i].Id] = new PlayerContactMemory();
} }
} }
@ -1079,7 +1118,7 @@ namespace RustToDust.Core
} }
} }
var p = Player; var p = Contenders[0];
float pYaw = p.Yaw; float pYaw = p.Yaw;
for (int i = 0; i < chassisPool.Count; i++) for (int i = 0; i < chassisPool.Count; i++)
{ {

View file

@ -0,0 +1,332 @@
using System;
using System.Collections.Generic;
using MessagePack;
namespace RustToDust.Core
{
public enum TerrainStampKind : byte
{
Crater = 0,
Scorch = 1,
Track = 2
}
public enum SlotControlReason : byte
{
Joined = 0,
HandedToAi = 1,
Reclaimed = 2,
Eliminated = 3
}
[Union(0, typeof(ShotFiredEvent))]
[Union(1, typeof(HitImpactEvent))]
[Union(2, typeof(TerrainStampEvent))]
[Union(3, typeof(DropSpawnedEvent))]
[Union(4, typeof(DropPickedUpEvent))]
[Union(5, typeof(ContenderLoadoutEvent))]
[Union(6, typeof(EntitySlotControlEvent))]
[Union(7, typeof(BroadcastLineEvent))]
[Union(8, typeof(ContenderEliminatedEvent))]
[Union(9, typeof(SpectatorDestroyedEvent))]
[Union(10, typeof(OverheatAlertEvent))]
[Union(11, typeof(MatchResetEvent))]
// Reserved [Union(12)] DropPodEvent (Cut 6)
// Reserved [Union(13)] OrdnanceNodeEvent (Cut 7)
public interface ISimEvent
{
}
[MessagePackObject]
public sealed class ShotFiredEvent : ISimEvent
{
[Key(0)] public int TracerId { get; set; }
[Key(1)] public bool IsSpectatorShooter { get; set; }
[Key(2)] public int ShooterId { get; set; }
[Key(3)] public float StartX { get; set; }
[Key(4)] public float StartY { get; set; }
[Key(5)] public float StartZ { get; set; }
[Key(6)] public float EndX { get; set; }
[Key(7)] public float EndY { get; set; }
[Key(8)] public float EndZ { get; set; }
[Key(9)] public uint ColorRgba { get; set; }
[Key(10)] public float Ttl { get; set; }
[Key(11)] public byte WeaponClass { get; set; }
[Key(12)] public string WeaponId { get; set; } = string.Empty;
}
[MessagePackObject]
public sealed class HitImpactEvent : ISimEvent
{
[Key(0)] public long EventId { get; set; }
[Key(1)] public float HitX { get; set; }
[Key(2)] public float HitY { get; set; }
[Key(3)] public float HitZ { get; set; }
[Key(4)] public float NormalX { get; set; }
[Key(5)] public float NormalY { get; set; }
[Key(6)] public float NormalZ { get; set; }
[Key(7)] public float SourceX { get; set; }
[Key(8)] public float SourceY { get; set; }
[Key(9)] public float SourceZ { get; set; }
[Key(10)] public byte TargetKind { get; set; }
[Key(11)] public int TargetId { get; set; }
[Key(12)] public int CellX { get; set; }
[Key(13)] public int CellY { get; set; }
[Key(14)] public byte WeaponClass { get; set; }
[Key(15)] public string WeaponId { get; set; } = string.Empty;
[Key(16)] public bool IsAirburst { get; set; }
[Key(17)] public float Ttl { get; set; }
[Key(18)] public float NewCellArmor { get; set; }
[Key(19)] public float NewCellTemp { get; set; }
[Key(20)] public float NewCoreHp { get; set; }
[Key(21)] public int HitSequence { get; set; }
// Cut 5d/6/7 forward contract fields (Ruling 4)
[Key(22)] public int ShooterId { get; set; }
[Key(23)] public bool IsContenderShooter { get; set; }
[Key(24)] public float ArmorDamage { get; set; }
[Key(25)] public float CoreDamage { get; set; }
[Key(26)] public bool Killed { get; set; }
}
[MessagePackObject]
public sealed class TerrainStampEvent : ISimEvent
{
[Key(0)] public byte Kind { get; set; }
[Key(1)] public float X { get; set; }
[Key(2)] public float Z { get; set; }
[Key(3)] public float Radius { get; set; }
[Key(4)] public float Depth { get; set; }
[Key(5)] public float Yaw { get; set; }
[Key(6)] public float Length { get; set; }
}
[MessagePackObject]
public sealed class DropSpawnedEvent : ISimEvent
{
[Key(0)] public int DropId { get; set; }
[Key(1)] public float X { get; set; }
[Key(2)] public float Z { get; set; }
[Key(3)] public string? ChassisId { get; set; }
[Key(4)] public string? ModuleId { get; set; }
}
[MessagePackObject]
public sealed class DropPickedUpEvent : ISimEvent
{
[Key(0)] public int DropId { get; set; }
[Key(1)] public int ContenderId { get; set; }
}
[MessagePackObject]
public sealed class MountedSlotDto
{
[Key(0)] public string ModuleId { get; set; } = string.Empty;
[Key(1)] public string HardpointId { get; set; } = string.Empty;
}
[MessagePackObject]
public sealed class ContenderLoadoutEvent : ISimEvent
{
[Key(0)] public int ContenderId { get; set; }
[Key(1)] public int LoadoutVersion { get; set; }
[Key(2)] public string ChassisId { get; set; } = string.Empty;
[Key(3)] public float CoreHp { get; set; }
[Key(4)] public float MaxCoreHp { get; set; }
[Key(5)] public byte[] ArmorBytes { get; set; } = Array.Empty<byte>();
[Key(6)] public List<MountedSlotDto> Mounted { get; set; } = new();
[Key(7)] public List<string>? CargoIds { get; set; }
}
[MessagePackObject]
public sealed class EntitySlotControlEvent : ISimEvent
{
[Key(0)] public int ContenderId { get; set; }
[Key(1)] public bool IsHuman { get; set; }
[Key(2)] public string Name { get; set; } = string.Empty;
[Key(3)] public byte Reason { get; set; }
}
[MessagePackObject]
public sealed class BroadcastLineEvent : ISimEvent
{
[Key(0)] public float Timestamp { get; set; }
[Key(1)] public byte Kind { get; set; }
[Key(2)] public string Text { get; set; } = string.Empty;
}
[MessagePackObject]
public sealed class ContenderEliminatedEvent : ISimEvent
{
[Key(0)] public int VictimId { get; set; }
[Key(1)] public int KillerId { get; set; }
[Key(2)] public bool IsSpectatorKiller { get; set; }
[Key(3)] public int KillerKills { get; set; }
}
[MessagePackObject]
public sealed class SpectatorDestroyedEvent : ISimEvent
{
[Key(0)] public int SpectatorId { get; set; }
[Key(1)] public int KillerContenderId { get; set; }
[Key(2)] public int KillerKills { get; set; }
}
[MessagePackObject]
public sealed class OverheatAlertEvent : ISimEvent
{
[Key(0)] public int ContenderId { get; set; }
[Key(1)] public bool IsOverheating { get; set; }
}
[MessagePackObject]
public sealed class ContenderInitialDto
{
[Key(0)] public int Id { get; set; }
[Key(1)] public string Name { get; set; } = string.Empty;
[Key(2)] public bool IsHuman { get; set; }
[Key(3)] public float X { get; set; }
[Key(4)] public float Y { get; set; }
[Key(5)] public float Z { get; set; }
[Key(6)] public float Yaw { get; set; }
[Key(7)] public int Kills { get; set; }
[Key(8)] public ContenderLoadoutEvent Loadout { get; set; } = new();
}
[MessagePackObject]
public sealed class SpectatorInitialDto
{
[Key(0)] public int Id { get; set; }
[Key(1)] public byte Tier { get; set; }
[Key(2)] public byte Stance { get; set; }
[Key(3)] public float X { get; set; }
[Key(4)] public float Y { get; set; }
[Key(5)] public float Z { get; set; }
[Key(6)] public float Yaw { get; set; }
[Key(7)] public string ChassisId { get; set; } = string.Empty;
[Key(8)] public float CoreHp { get; set; }
[Key(9)] public float MaxCoreHp { get; set; }
[Key(10)] public byte[] ArmorBytes { get; set; } = Array.Empty<byte>();
[Key(11)] public List<MountedSlotDto> Mounted { get; set; } = new();
}
[MessagePackObject]
public sealed class GroundDropDto
{
[Key(0)] public int Id { get; set; }
[Key(1)] public float X { get; set; }
[Key(2)] public float Z { get; set; }
[Key(3)] public string? ChassisId { get; set; }
[Key(4)] public string? ModuleId { get; set; }
[Key(5)] public bool PickedUp { get; set; }
}
[MessagePackObject]
public sealed class InitialMatchStateDto
{
[Key(0)] public uint MatchGeneration { get; set; }
[Key(1)] public int Seed { get; set; }
[Key(2)] public byte MapKind { get; set; }
[Key(3)] public float SimTime { get; set; }
[Key(4)] public float SafeRadius { get; set; }
[Key(5)] public byte Phase { get; set; }
[Key(6)] public int? WinnerContenderId { get; set; }
[Key(7)] public List<ContenderInitialDto> Contenders { get; set; } = new();
[Key(8)] public List<SpectatorInitialDto> Spectators { get; set; } = new();
[Key(9)] public List<GroundDropDto> GroundDrops { get; set; } = new();
[Key(10)] public List<TerrainStampEvent> TerrainStamps { get; set; } = new();
}
[MessagePackObject]
public sealed class MatchResetEvent : ISimEvent
{
[Key(0)] public uint MatchGeneration { get; set; }
[Key(1)] public int Seed { get; set; }
[Key(2)] public byte MapKind { get; set; }
[Key(3)] public int AssignedContenderId { get; set; }
[Key(4)] public InitialMatchStateDto FullInitialState { get; set; } = new();
}
[Union(0, typeof(JoinReqMsg))]
[Union(1, typeof(JoinAcceptedMsg))]
[Union(2, typeof(JoinRejectedMsg))]
[Union(3, typeof(LeaveMsg))]
[Union(4, typeof(EquipCargoCmdMsg))]
[Union(5, typeof(NewMatchCmdMsg))]
[Union(6, typeof(SimEventBatchMsg))]
[Union(7, typeof(EntitySyncSnapshotMsg))]
public interface ISchemaWireMessage
{
}
[MessagePackObject]
public sealed class JoinReqMsg : ISchemaWireMessage
{
[Key(0)] public string Callsign { get; set; } = string.Empty;
[Key(1)] public Guid ReconnectToken { get; set; }
[Key(2)] public string ClientVersion { get; set; } = "rtd-5c";
}
[MessagePackObject]
public sealed class JoinAcceptedMsg : ISchemaWireMessage
{
[Key(0)] public uint PeerId { get; set; }
[Key(1)] public Guid ReconnectToken { get; set; }
[Key(2)] public int AssignedContenderId { get; set; }
[Key(3)] public uint MatchGeneration { get; set; }
[Key(4)] public InitialMatchStateDto InitialState { get; set; } = new();
}
[MessagePackObject]
public sealed class JoinRejectedMsg : ISchemaWireMessage
{
[Key(0)] public string Reason { get; set; } = string.Empty;
}
[MessagePackObject]
public sealed class LeaveMsg : ISchemaWireMessage
{
[Key(0)] public string Reason { get; set; } = string.Empty;
}
[MessagePackObject]
public sealed class EquipCargoCmdMsg : ISchemaWireMessage
{
[Key(0)] public uint ReqSeq { get; set; }
[Key(1)] public int CargoIndex { get; set; }
[Key(2)] public string HardpointId { get; set; } = string.Empty;
}
[MessagePackObject]
public sealed class NewMatchCmdMsg : ISchemaWireMessage
{
[Key(0)] public uint ReqSeq { get; set; }
[Key(1)] public int Seed { get; set; }
[Key(2)] public byte MapKind { get; set; }
}
[MessagePackObject]
public sealed class SimEventBatchMsg : ISchemaWireMessage
{
[Key(0)] public ulong BatchSeq { get; set; }
[Key(1)] public uint SimTick { get; set; }
[Key(2)] public float SimTime { get; set; }
[Key(3)] public uint MatchGeneration { get; set; }
[Key(4)] public List<ISimEvent> Events { get; set; } = new();
}
[MessagePackObject]
public sealed class EntitySyncSnapshotMsg : ISchemaWireMessage
{
[Key(0)] public bool IsContender { get; set; }
[Key(1)] public int EntityId { get; set; }
[Key(2)] public bool Alive { get; set; }
[Key(3)] public float PosX { get; set; }
[Key(4)] public float PosY { get; set; }
[Key(5)] public float PosZ { get; set; }
[Key(6)] public float Yaw { get; set; }
[Key(7)] public float CoreHp { get; set; }
[Key(8)] public float MaxCoreHp { get; set; }
[Key(9)] public byte[] ArmorBytes { get; set; } = Array.Empty<byte>();
[Key(10)] public ContenderLoadoutEvent? ContenderLoadout { get; set; }
}
}

View file

@ -163,6 +163,8 @@ namespace RustToDust.Core
public float SafeRadius { get; private set; } public float SafeRadius { get; private set; }
public IReadOnlyList<SpectatorState> Spectators => _spectators; public IReadOnlyList<SpectatorState> Spectators => _spectators;
public void SetReplicatedSafeRadius(float radius) => SafeRadius = radius;
public void UpdateSafeRadius(float matchTime) public void UpdateSafeRadius(float matchTime)
{ {
if (matchTime <= GraceDuration) if (matchTime <= GraceDuration)

View file

@ -0,0 +1,73 @@
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
namespace RustToDust.Core
{
[InlineArray(4)]
public struct LegArray4<T>
{
private T _element0;
}
public struct WalkerLegAngles
{
public float HipPitch;
public float HipRoll;
public float KneeFlex;
public float HockFlex;
public float AnklePitch;
public static WalkerLegAngles Lerp(in WalkerLegAngles a, in WalkerLegAngles b, float t) => new()
{
HipPitch = a.HipPitch + (b.HipPitch - a.HipPitch) * t,
HipRoll = a.HipRoll + (b.HipRoll - a.HipRoll) * t,
KneeFlex = a.KneeFlex + (b.KneeFlex - a.KneeFlex) * t,
HockFlex = a.HockFlex + (b.HockFlex - a.HockFlex) * t,
AnklePitch = a.AnklePitch + (b.AnklePitch - a.AnklePitch) * t
};
}
public struct WalkerVisualSnapshot
{
public int LegCount;
public float GeomScale;
public bool IsDigitigrade;
public bool IsArachnidUp;
public Vector3 ComPos;
public Quaternion ComRot;
public LegArray4<WalkerLegAngles> LegAngles;
public LegArray4<Vector3> FootNormal;
public LegArray4<float> LoadG;
public static WalkerVisualSnapshot Interpolate(in WalkerVisualSnapshot prev, in WalkerVisualSnapshot curr, float alpha)
{
float t = Math.Clamp(alpha, 0f, 1f);
Quaternion q0 = prev.ComRot.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(prev.ComRot);
Quaternion q1 = curr.ComRot.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(curr.ComRot);
if (Quaternion.Dot(q0, q1) < 0f)
{
q1 = -q1;
}
WalkerVisualSnapshot res = new()
{
LegCount = curr.LegCount,
GeomScale = curr.GeomScale,
IsDigitigrade = curr.IsDigitigrade,
IsArachnidUp = curr.IsArachnidUp,
ComPos = Vector3.Lerp(prev.ComPos, curr.ComPos, t),
ComRot = Quaternion.Slerp(q0, q1, t)
};
for (int i = 0; i < curr.LegCount; i++)
{
res.LegAngles[i] = WalkerLegAngles.Lerp(prev.LegAngles[i], curr.LegAngles[i], t);
Vector3 n = Vector3.Lerp(prev.FootNormal[i], curr.FootNormal[i], t);
res.FootNormal[i] = n.LengthSquared() > 1e-6f ? Vector3.Normalize(n) : Vector3.UnitY;
res.LoadG[i] = prev.LoadG[i] + (curr.LoadG[i] - prev.LoadG[i]) * t;
}
return res;
}
}
}

View file

@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Numerics;
using RustToDust.Core;
namespace RustToDust.Net
{
public sealed class ListenHostArenaSession : IClientArenaSession
{
private readonly ServerMatchHost _host;
public ListenHostArenaSession(
IPAddress bindAddress,
int port,
int seed = 42,
ArenaMapKind mapKind = ArenaMapKind.Desert,
int maxHumans = MatchState.ContenderCount)
{
_host = new ServerMatchHost(
bindAddress,
port,
seed,
mapKind,
maxHumans: maxHumans,
autoRestartSec: 0,
allowClientReset: false,
hostContenderId: 0);
}
public ServerMatchHost Host => _host;
public MatchState ViewState => _host.Session.State;
public int LocalContenderId => 0;
public ContenderState LocalContender => _host.Session.State.Contenders[0];
public ClientMatchOutcome LocalOutcome =>
_host.Session.State.Phase == MatchPhase.Active
? (LocalContender.Alive ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
: (_host.Session.State.WinnerContenderId == 0 ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
public int LocalDetectedByCount =>
_host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.DetectedByCount : 0;
public IReadOnlyDictionary<int, PlayerContactMemory> LocalContenderContacts =>
_host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.ContenderContacts : _host.Session.State.EmptyContacts;
public IReadOnlyDictionary<int, PlayerContactMemory> LocalSpectatorContacts =>
_host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.SpectatorContacts : _host.Session.State.EmptyContacts;
public NetworkStatusSnapshot ConnectionStatus =>
new(
NetworkMode.ListenHost,
Connected: true,
PingMs: 0,
ConnectedHumans: _host.ConnectedHumanCount,
MaxHumans: MatchState.ContenderCount,
StateLabel: $"HOST :{_host.BoundPort} ({_host.ConnectedHumanCount}/12)");
public bool IsContenderVisible(int contenderId) => true;
public bool IsSpectatorVisible(int spectatorId) => true;
public void BeginRenderFrame(double dt, float physicsAlpha)
{
}
public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick)
{
if (!isPhysicsTick) return;
_host.SetHostInput(input);
_host.StepOnce(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
}
public bool RequestEquipCargo(int cargoIndex, string hardpointId) =>
_host.Session.TryEquipCargo(0, cargoIndex, hardpointId);
public void RequestNewMatch(int seed, ArenaMapKind mapKind) =>
_host.ResetMatch(seed, mapKind);
public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) =>
_host.Session.GetInterpolatedContenderPose(contenderId, alpha);
public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha) =>
_host.Session.GetInterpolatedSpectatorPose(spectatorId, alpha);
public bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap) =>
_host.Session.TrySampleInterpolatedWalkerPose(isContender, id, alpha, out snap);
public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation)
{
var hit = _host.Session.World.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z));
return new ClientRayHit(
hit.Hit,
hit.StableId,
new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z),
new Vector3(hit.Normal.X, hit.Normal.Y, hit.Normal.Z),
hit.Fraction);
}
public void Dispose()
{
_host.Dispose();
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\RustToDust.Core\RustToDust.Core.csproj" />
<ProjectReference Include="..\RustToDust.Ymir\RustToDust.Ymir.csproj" />
<ProjectReference Include="$(CultLibRoot)/src/GameCult.Networking/GameCult.Networking.csproj" />
<ProjectReference Include="$(CultLibRoot)/src/GameCult.Mesh/GameCult.Mesh.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,948 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Numerics;
using GameCult.Mesh;
using GameCult.Networking;
using RustToDust.Core;
using RustToDust.Ymir;
namespace RustToDust.Net
{
public sealed class ServerMatchHost : IDisposable
{
public const long IdleTimeoutMs = 5000;
private sealed class ConnectedPeer
{
public uint PeerId;
public CultNetRudpSocketServerPeer TransportPeer = null!;
public string EndpointKey = string.Empty;
public Guid ReconnectToken;
public int AssignedContenderId;
public string Callsign = string.Empty;
public long LastHeardUtcMs;
public uint LastAcceptedInputSeq;
public uint LastEchoSendMs;
public bool Active = true;
public readonly EntityPvsTracker[] ContenderTrackers = new EntityPvsTracker[MatchState.ContenderCount];
public readonly EntityPvsTracker[] SpectatorTrackers = new EntityPvsTracker[SpectatorRing.DefaultSpectatorCount];
}
private struct EntityPvsTracker
{
public bool InPvs;
public bool SnapNext;
public int AckedLoadoutVersion;
public int AckedDamageVersion;
}
private readonly Socket _socket;
private readonly CultNetRudpSocketTransportServer _server;
private readonly Dictionary<string, ConnectedPeer> _peersByEndpoint = new(StringComparer.Ordinal);
private readonly HashSet<CultNetRudpSocketServerPeer> _retiredTransportPeers = new();
private readonly Dictionary<Guid, (int SlotId, string Callsign)> _reconnectTokens = new();
private readonly List<ISimEvent> _stepEvents = new();
private readonly List<TerrainStampEvent> _terrainStampHistory = new();
private readonly int _maxHumans;
private readonly double _autoRestartSec;
private readonly bool _allowClientReset;
private readonly int? _hostContenderId;
private ArenaSession _session;
private uint _matchGeneration = 1;
private uint _simTick;
private uint _snapshotSeq;
private ulong _eventBatchSeq = 1;
private long _schemaOutSeq = 1;
private long _latestOutSeq = 1;
private uint _nextPeerId = 1;
private float _roundCompletedElapsed;
private bool _disposed;
public ServerMatchHost(
IPAddress bindAddress,
int port,
int seed = 42,
ArenaMapKind mapKind = ArenaMapKind.Desert,
int maxHumans = MatchState.ContenderCount,
double autoRestartSec = 8.0,
bool allowClientReset = false,
int? hostContenderId = null)
{
_maxHumans = Math.Clamp(maxHumans, 1, MatchState.ContenderCount);
_autoRestartSec = autoRestartSec;
_allowClientReset = allowClientReset;
_hostContenderId = hostContenderId;
_socket = new Socket(bindAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
{
Blocking = false
};
_socket.Bind(new IPEndPoint(bindAddress, port));
BoundPort = ((IPEndPoint)_socket.LocalEndPoint!).Port;
_server = new CultNetRudpSocketTransportServer(new CultNetRudpSocketTransportServerOptions
{
RuntimeId = "rtd-server",
Socket = _socket,
ConnectionId = 0x52544431,
ResendDelayMs = 100,
MaxFragmentBytes = SnapshotCodec.MaxLatestDatagramBytes,
MaxPayloadBytes = 256 * 1024,
MaxPendingReliablePackets = 2048
});
_server.PeerDisconnected += OnTransportPeerDisconnected;
_session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0);
if (hostContenderId.HasValue)
{
_session.SetHumanSlot(hostContenderId.Value, true, "Host");
}
}
public int BoundPort { get; }
public ArenaSession Session => _session;
public uint MatchGeneration => _matchGeneration;
public uint SimTick => _simTick;
public int ConnectedHumanCount => _peersByEndpoint.Count + (_hostContenderId.HasValue ? 1 : 0);
public void SetHostInput(in PlayerInput input)
{
if (_hostContenderId.HasValue)
{
_session.SetHumanInput(_hostContenderId.Value, input);
}
}
public void ResetMatch(int seed, ArenaMapKind mapKind)
{
_session.Dispose();
_session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0);
_matchGeneration++;
_simTick = 0;
_roundCompletedElapsed = 0f;
_terrainStampHistory.Clear();
_stepEvents.Clear();
_reconnectTokens.Clear();
if (_hostContenderId.HasValue)
{
_session.SetHumanSlot(_hostContenderId.Value, true, "Host");
}
foreach (var peer in _peersByEndpoint.Values)
{
if (!peer.Active) continue;
int slot = peer.AssignedContenderId;
_session.SetHumanSlot(slot, true, peer.Callsign);
_reconnectTokens[peer.ReconnectToken] = (slot, peer.Callsign);
InitPeerTrackers(peer);
var reset = new MatchResetEvent
{
MatchGeneration = _matchGeneration,
Seed = seed,
MapKind = (byte)mapKind,
AssignedContenderId = slot,
FullInitialState = BuildInitialMatchStateDto(slot)
};
SendSchemaToPeer(peer, new SimEventBatchMsg
{
BatchSeq = _eventBatchSeq++,
SimTick = _simTick,
SimTime = _session.State.Time,
MatchGeneration = _matchGeneration,
Events = new List<ISimEvent> { reset }
});
}
}
public void StepOnce(long nowUtcMs)
{
ObjectDisposedException.ThrowIf(_disposed, this);
PollIncoming(nowUtcMs);
SweepTimeouts(nowUtcMs);
_session.Step();
_simTick++;
_stepEvents.Clear();
_session.DrainStepEvents(_stepEvents);
for (int i = 0; i < _stepEvents.Count; i++)
{
if (_stepEvents[i] is TerrainStampEvent ts)
{
_terrainStampHistory.Add(ts);
}
}
FlushEventsAndPvsEnter();
BroadcastSnapshots();
_server.PollResends();
if (_autoRestartSec > 0 && _session.State.Phase == MatchPhase.Completed)
{
_roundCompletedElapsed += ArenaSession.FixedDt;
if (_roundCompletedElapsed >= _autoRestartSec)
{
ResetMatch(_session.State.Seed + 1, _session.State.MapKind);
}
}
}
private void PollIncoming(long nowUtcMs)
{
int processed = 0;
while (processed < 256 && _server.TryReceiveOnce(out var serverFrame))
{
processed++;
if (serverFrame is null || _retiredTransportPeers.Contains(serverFrame.Peer))
{
continue;
}
CultMeshRealtimeFrame rtFrame;
try
{
rtFrame = SnapshotCodec.Unwrap(serverFrame.Frame.Payload);
}
catch
{
continue;
}
string epKey = serverFrame.Peer.RemoteEndPoint.ToString() ?? string.Empty;
if (string.Equals(serverFrame.Frame.ChannelId, SnapshotCodec.ChannelSchema, StringComparison.Ordinal))
{
HandleSchemaFrame(serverFrame.Peer, epKey, rtFrame, nowUtcMs);
}
else if (string.Equals(serverFrame.Frame.ChannelId, SnapshotCodec.ChannelLatest, StringComparison.Ordinal))
{
HandleLatestFrame(serverFrame.Peer, epKey, rtFrame, nowUtcMs);
}
}
}
private void HandleSchemaFrame(CultNetRudpSocketServerPeer transportPeer, string epKey, CultMeshRealtimeFrame rtFrame, long nowUtcMs)
{
ISchemaWireMessage msg;
try
{
msg = SnapshotCodec.DeserializeSchemaMessage(rtFrame.Payload);
}
catch
{
return;
}
switch (msg)
{
case JoinReqMsg join:
HandleJoin(transportPeer, epKey, join, nowUtcMs);
break;
case LeaveMsg:
if (_peersByEndpoint.TryGetValue(epKey, out var leaving) && ReferenceEquals(leaving.TransportPeer, transportPeer))
{
RetirePeer(leaving, SlotControlReason.HandedToAi);
}
break;
case EquipCargoCmdMsg equip:
if (_peersByEndpoint.TryGetValue(epKey, out var eqPeer) && eqPeer.Active && ReferenceEquals(eqPeer.TransportPeer, transportPeer))
{
eqPeer.LastHeardUtcMs = nowUtcMs;
_session.TryEquipCargo(eqPeer.AssignedContenderId, equip.CargoIndex, equip.HardpointId);
}
break;
case NewMatchCmdMsg newMatch:
if (_peersByEndpoint.TryGetValue(epKey, out var nmPeer) && nmPeer.Active && ReferenceEquals(nmPeer.TransportPeer, transportPeer))
{
nmPeer.LastHeardUtcMs = nowUtcMs;
if (_allowClientReset)
{
ResetMatch(newMatch.Seed, (ArenaMapKind)newMatch.MapKind);
}
}
break;
}
}
private void HandleJoin(CultNetRudpSocketServerPeer transportPeer, string epKey, JoinReqMsg join, long nowUtcMs)
{
if (_peersByEndpoint.TryGetValue(epKey, out var existing))
{
if (ReferenceEquals(existing.TransportPeer, transportPeer) && existing.Active)
{
existing.LastHeardUtcMs = nowUtcMs;
SendJoinAccepted(existing);
return;
}
RetirePeer(existing, SlotControlReason.HandedToAi);
}
string callsign = string.IsNullOrWhiteSpace(join.Callsign) ? $"Pilot-{_nextPeerId}" : join.Callsign.Trim();
if (callsign.Length > 24) callsign = callsign.Substring(0, 24);
int slotId = -1;
SlotControlReason reason = SlotControlReason.Joined;
if (join.ReconnectToken != Guid.Empty && _reconnectTokens.TryGetValue(join.ReconnectToken, out var saved))
{
if (saved.SlotId >= 0 && saved.SlotId < _session.State.Contenders.Count)
{
var cand = _session.State.Contenders[saved.SlotId];
if (cand.Alive && !cand.IsHuman && saved.SlotId != _hostContenderId)
{
slotId = saved.SlotId;
reason = SlotControlReason.Reclaimed;
}
}
}
if (slotId < 0)
{
if (ConnectedHumanCount >= _maxHumans)
{
SendSchemaRaw(transportPeer, new JoinRejectedMsg { Reason = "Server human capacity reached." });
return;
}
for (int i = 0; i < _session.State.Contenders.Count; i++)
{
if (i == _hostContenderId) continue;
var c = _session.State.Contenders[i];
if (c.Alive && !c.IsHuman)
{
slotId = i;
break;
}
}
}
if (slotId < 0)
{
SendSchemaRaw(transportPeer, new JoinRejectedMsg { Reason = "No alive contender slots available." });
return;
}
Guid token = join.ReconnectToken != Guid.Empty ? join.ReconnectToken : Guid.NewGuid();
_reconnectTokens[token] = (slotId, callsign);
_session.SetHumanSlot(slotId, true, callsign);
var peer = new ConnectedPeer
{
PeerId = _nextPeerId++,
TransportPeer = transportPeer,
EndpointKey = epKey,
ReconnectToken = token,
AssignedContenderId = slotId,
Callsign = callsign,
LastHeardUtcMs = nowUtcMs
};
InitPeerTrackers(peer);
_peersByEndpoint[epKey] = peer;
SendJoinAccepted(peer);
_stepEvents.Add(new EntitySlotControlEvent
{
ContenderId = slotId,
IsHuman = true,
Name = callsign,
Reason = (byte)reason
});
}
private void HandleLatestFrame(CultNetRudpSocketServerPeer transportPeer, string epKey, CultMeshRealtimeFrame rtFrame, long nowUtcMs)
{
if (!_peersByEndpoint.TryGetValue(epKey, out var peer) || !peer.Active || !ReferenceEquals(peer.TransportPeer, transportPeer))
{
return;
}
peer.LastHeardUtcMs = nowUtcMs;
ClientInputPacket pkt;
try
{
pkt = SnapshotCodec.DecodeClientInput(rtFrame.Payload.Span);
}
catch
{
return;
}
if (pkt.MatchGeneration != _matchGeneration || pkt.InputSeq <= peer.LastAcceptedInputSeq)
{
return;
}
peer.LastAcceptedInputSeq = pkt.InputSeq;
peer.LastEchoSendMs = pkt.ClientSendMs;
_session.SetHumanInput(peer.AssignedContenderId, pkt.Input);
}
private void SweepTimeouts(long nowUtcMs)
{
List<ConnectedPeer>? timedOut = null;
foreach (var peer in _peersByEndpoint.Values)
{
if (peer.Active && (nowUtcMs - peer.LastHeardUtcMs) > IdleTimeoutMs)
{
timedOut ??= new List<ConnectedPeer>();
timedOut.Add(peer);
}
}
if (timedOut is null) return;
for (int i = 0; i < timedOut.Count; i++)
{
RetirePeer(timedOut[i], SlotControlReason.HandedToAi);
}
}
private void OnTransportPeerDisconnected(CultNetRudpSocketServerPeer transportPeer)
{
string epKey = transportPeer.RemoteEndPoint.ToString() ?? string.Empty;
if (_peersByEndpoint.TryGetValue(epKey, out var peer) && ReferenceEquals(peer.TransportPeer, transportPeer))
{
RetirePeer(peer, SlotControlReason.HandedToAi);
}
}
private void RetirePeer(ConnectedPeer peer, SlotControlReason reason)
{
if (!peer.Active) return;
peer.Active = false;
_peersByEndpoint.Remove(peer.EndpointKey);
_retiredTransportPeers.Add(peer.TransportPeer);
int slot = peer.AssignedContenderId;
if (slot >= 0 && slot < _session.State.Contenders.Count)
{
_session.SetHumanSlot(slot, false);
var c = _session.State.Contenders[slot];
_stepEvents.Add(new EntitySlotControlEvent
{
ContenderId = slot,
IsHuman = false,
Name = c.Name,
Reason = (byte)reason
});
}
}
private void InitPeerTrackers(ConnectedPeer peer)
{
for (int i = 0; i < _session.State.Contenders.Count; i++)
{
var c = _session.State.Contenders[i];
bool inPvs = _session.IsEntityInPeerPvs(peer.AssignedContenderId, true, c.Id);
peer.ContenderTrackers[i] = new EntityPvsTracker
{
InPvs = inPvs,
SnapNext = false,
AckedLoadoutVersion = c.LoadoutVersion,
AckedDamageVersion = c.DamageVersion
};
}
for (int i = 0; i < _session.State.Spectators.Spectators.Count; i++)
{
var s = _session.State.Spectators.Spectators[i];
bool inPvs = _session.IsEntityInPeerPvs(peer.AssignedContenderId, false, s.Id);
peer.SpectatorTrackers[i] = new EntityPvsTracker
{
InPvs = inPvs,
SnapNext = false,
AckedLoadoutVersion = 1,
AckedDamageVersion = s.Grid.HitSequence
};
}
}
private void FlushEventsAndPvsEnter()
{
if (_peersByEndpoint.Count == 0) return;
foreach (var peer in _peersByEndpoint.Values)
{
if (!peer.Active) continue;
int obsId = peer.AssignedContenderId;
// Check PVS-enter resyncs
for (int i = 0; i < _session.State.Contenders.Count; i++)
{
var c = _session.State.Contenders[i];
bool inPvs = _session.IsEntityInPeerPvs(obsId, true, c.Id);
ref var tracker = ref peer.ContenderTrackers[i];
if (inPvs && !tracker.InPvs)
{
tracker.SnapNext = true;
if (tracker.AckedLoadoutVersion != c.LoadoutVersion || tracker.AckedDamageVersion != c.DamageVersion)
{
tracker.AckedLoadoutVersion = c.LoadoutVersion;
tracker.AckedDamageVersion = c.DamageVersion;
SendSchemaToPeer(peer, new EntitySyncSnapshotMsg
{
IsContender = true,
EntityId = c.Id,
Alive = c.Alive,
PosX = c.X, PosY = c.Y, PosZ = c.Z, Yaw = c.Yaw,
CoreHp = c.Grid.CoreHp,
MaxCoreHp = c.Grid.MaxCoreHp,
ArmorBytes = c.Grid.QuantizeArmorBytes(),
ContenderLoadout = ArenaSession.BuildContenderLoadoutEvent(c, includeCargo: c.Id == obsId)
});
}
}
tracker.InPvs = inPvs;
}
for (int i = 0; i < _session.State.Spectators.Spectators.Count; i++)
{
var s = _session.State.Spectators.Spectators[i];
bool inPvs = _session.IsEntityInPeerPvs(obsId, false, s.Id);
ref var tracker = ref peer.SpectatorTrackers[i];
if (inPvs && !tracker.InPvs)
{
tracker.SnapNext = true;
if (tracker.AckedDamageVersion != s.Grid.HitSequence)
{
tracker.AckedDamageVersion = s.Grid.HitSequence;
SendSchemaToPeer(peer, new EntitySyncSnapshotMsg
{
IsContender = false,
EntityId = s.Id,
Alive = s.Alive,
PosX = s.X, PosY = s.Y, PosZ = s.Z, Yaw = s.Yaw,
CoreHp = s.Grid.CoreHp,
MaxCoreHp = s.Grid.MaxCoreHp,
ArmorBytes = s.Grid.QuantizeArmorBytes()
});
}
}
tracker.InPvs = inPvs;
}
if (_stepEvents.Count == 0) continue;
var obs = _session.State.Contenders[obsId];
var filtered = new List<ISimEvent>(_stepEvents.Count);
for (int e = 0; e < _stepEvents.Count; e++)
{
var ev = _stepEvents[e];
switch (ev)
{
case ContenderLoadoutEvent loadout:
if (loadout.ContenderId == obsId || _session.IsEntityInPeerPvs(obsId, true, loadout.ContenderId))
{
var c = _session.State.Contenders[loadout.ContenderId];
peer.ContenderTrackers[loadout.ContenderId].AckedLoadoutVersion = c.LoadoutVersion;
filtered.Add(loadout.ContenderId == obsId
? loadout
: ArenaSession.BuildContenderLoadoutEvent(c, includeCargo: false));
}
break;
case ShotFiredEvent shot:
bool shooterVisible = _session.IsEntityInPeerPvs(obsId, !shot.IsSpectatorShooter, shot.ShooterId);
float dxEnd = shot.EndX - obs.X;
float dzEnd = shot.EndZ - obs.Z;
if (shooterVisible || (dxEnd * dxEnd + dzEnd * dzEnd) <= 85f * 85f)
{
filtered.Add(shot);
}
break;
case HitImpactEvent hit:
if (hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId >= 0 && hit.TargetId < peer.ContenderTrackers.Length)
{
if (hit.TargetId == obsId || _session.IsEntityInPeerPvs(obsId, true, hit.TargetId))
{
peer.ContenderTrackers[hit.TargetId].AckedDamageVersion = _session.State.Contenders[hit.TargetId].DamageVersion;
filtered.Add(hit);
}
}
else if (hit.TargetKind == (byte)HitTargetKind.Spectator)
{
int specIdx = hit.TargetId >= 1000 ? hit.TargetId - 1000 : hit.TargetId;
if (specIdx >= 0 && specIdx < peer.SpectatorTrackers.Length &&
_session.IsEntityInPeerPvs(obsId, false, specIdx))
{
peer.SpectatorTrackers[specIdx].AckedDamageVersion = _session.State.Spectators.Spectators[specIdx].Grid.HitSequence;
filtered.Add(hit);
}
}
else
{
filtered.Add(hit);
}
break;
default:
filtered.Add(ev);
break;
}
}
if (filtered.Count > 0)
{
SendSchemaToPeer(peer, new SimEventBatchMsg
{
BatchSeq = _eventBatchSeq++,
SimTick = _simTick,
SimTime = _session.State.Time,
MatchGeneration = _matchGeneration,
Events = filtered
});
}
}
}
private void BroadcastSnapshots()
{
if (_peersByEndpoint.Count == 0) return;
bool sendCore = (_simTick % 2) == 0; // 30 Hz
bool sendRadar = (_simTick % 6) == 0; // 10 Hz
if (!sendCore && !sendRadar) return;
if (sendCore) _snapshotSeq++;
foreach (var peer in _peersByEndpoint.Values)
{
if (!peer.Active) continue;
int obsId = peer.AssignedContenderId;
var local = _session.State.Contenders[obsId];
if (sendCore)
{
SendCoreAndOrbit(peer, local);
}
if (sendRadar)
{
SendRadar(peer, obsId);
}
}
}
private void SendCoreAndOrbit(ConnectedPeer peer, ContenderState local)
{
int obsId = local.Id;
ushort pvsMask = 0;
var pvsContenders = new List<NetContenderState>(MatchState.ContenderCount);
var walkerCandidates = new List<(float DistSq, NetWalkerEntry Entry)>(12);
var combatSpecs = new List<NetSpectatorState>(12);
var neutralSpecsHalf = new List<NetSpectatorState>(28);
for (int i = 0; i < _session.State.Contenders.Count; i++)
{
var c = _session.State.Contenders[i];
if (c.Id == obsId)
{
pvsMask |= (ushort)(1 << c.Id);
if (c.Grid.Spec.IsWalker && _session.TrySampleInterpolatedWalkerPose(true, c.Id, 1f, out var lw))
{
walkerCandidates.Add((0f, new NetWalkerEntry { IsContender = true, EntityId = (byte)c.Id, Snapshot = lw }));
}
continue;
}
if (!_session.IsEntityInPeerPvs(obsId, true, c.Id))
{
continue;
}
pvsMask |= (ushort)(1 << c.Id);
bool snap = peer.ContenderTrackers[c.Id].SnapNext;
peer.ContenderTrackers[c.Id].SnapNext = false;
float pitchDeg = MatchRules.ComputeLocalPitchDeg(
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));
pvsContenders.Add(new NetContenderState
{
SlotId = (byte)c.Id,
Alive = c.Alive,
IsHuman = c.IsHuman,
Fire = c.FireCmd,
Brake = c.BrakeCmd,
Snap = snap,
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),
AimYaw = MathF.Atan2(c.AimX - c.X, c.AimZ - c.Z),
AimPitchDeg = pitchDeg,
Throttle = c.ThrottleCmd,
Steer = c.SteerCmd,
CoreHpRatio = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 0f,
MaxThermalRatio = c.MaxThermalRatio
});
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 &&
_session.TrySampleInterpolatedWalkerPose(true, c.Id, 1f, out var ws))
{
walkerCandidates.Add((d2, new NetWalkerEntry { IsContender = true, EntityId = (byte)c.Id, Snapshot = ws }));
}
}
byte halfIndex = (byte)(_snapshotSeq & 1);
var specs = _session.State.Spectators.Spectators;
for (int i = 0; i < specs.Count; i++)
{
var s = specs[i];
if (!_session.IsEntityInPeerPvs(obsId, false, i))
{
continue;
}
bool snap = peer.SpectatorTrackers[i].SnapNext;
peer.SpectatorTrackers[i].SnapNext = false;
var ns = new NetSpectatorState
{
Id = (byte)i,
Alive = s.Alive,
Stance = s.Stance,
Snap = snap,
TargetContenderId = (sbyte)(s.TargetContenderId ?? -1),
Pos = new Vector3(s.X, s.Y, s.Z),
Rot = new Quaternion(s.CurrRotX, s.CurrRotY, s.CurrRotZ, s.CurrRotW),
Vel = new Vector3(s.VelX, s.VelY, s.VelZ)
};
if (s.Stance != SpectatorStance.Neutral)
{
combatSpecs.Add(ns);
float d2 = (s.X - local.X) * (s.X - local.X) + (s.Z - local.Z) * (s.Z - local.Z);
if (s.Alive && s.Grid.Spec.IsWalker && d2 <= 220f * 220f &&
_session.TrySampleInterpolatedWalkerPose(false, s.Id, 1f, out var sws))
{
walkerCandidates.Add((d2, new NetWalkerEntry { IsContender = false, EntityId = (byte)i, Snapshot = sws }));
}
}
else if ((i & 1) == halfIndex)
{
neutralSpecsHalf.Add(ns);
}
}
walkerCandidates.Sort((a, b) => a.DistSq.CompareTo(b.DistSq));
var walkers = new List<NetWalkerEntry>(walkerCandidates.Count);
for (int i = 0; i < walkerCandidates.Count; i++)
{
walkers.Add(walkerCandidates[i].Entry);
}
Vector3 localAngVel = Vector3.Zero;
var body = _session.GetContenderBody(local.Id);
if (body is { } bHandle)
{
var v = _session.World.View;
localAngVel = new Vector3(v.AngularVelocityX[bHandle.Lane], v.AngularVelocityY[bHandle.Lane], v.AngularVelocityZ[bHandle.Lane]);
}
byte detectedBy = _session.State.ObserverStates.TryGetValue(obsId, out var obsState)
? (byte)Math.Clamp(obsState.DetectedByCount, 0, 255)
: (byte)0;
byte[] corePayload = SnapshotCodec.EncodeCorePvs(
_matchGeneration,
_snapshotSeq,
_simTick,
_session.State.Time,
peer.LastAcceptedInputSeq,
peer.LastEchoSendMs,
_session.State.Spectators.SafeRadius,
_session.State.Phase,
_session.State.WinnerContenderId,
detectedBy,
pvsMask,
local,
localAngVel,
pvsContenders,
walkers,
combatSpecs);
SendLatestToPeer(peer, corePayload);
if (neutralSpecsHalf.Count > 0)
{
byte[] orbitPayload = SnapshotCodec.EncodeSpectatorOrbitHalf(
_matchGeneration,
_snapshotSeq,
halfIndex,
neutralSpecsHalf);
SendLatestToPeer(peer, orbitPayload);
}
}
private void SendRadar(ConnectedPeer peer, int obsId)
{
if (!_session.State.ObserverStates.TryGetValue(obsId, out var obsState))
{
return;
}
var cList = new List<NetRadarContact>(12);
foreach (var kv in obsState.ContenderContacts)
{
if (!MatchState.IsContactOnRadar(kv.Value)) continue;
cList.Add(new NetRadarContact
{
EntityId = (byte)kv.Key,
Visible = kv.Value.VisibleToPlayer,
FaintHorizon = kv.Value.FaintHorizonPing,
HasEverBeenSeen = kv.Value.HasEverBeenSeen,
LastSeenAge = kv.Value.LastSeenAge,
LastSeenX = kv.Value.LastSeenX,
LastSeenZ = kv.Value.LastSeenZ
});
}
var sList = new List<NetRadarContact>(32);
foreach (var kv in obsState.SpectatorContacts)
{
if (!MatchState.IsContactOnRadar(kv.Value)) continue;
int specIdx = kv.Key >= 1000 ? kv.Key - 1000 : kv.Key;
if (specIdx < 0 || specIdx >= _session.State.Spectators.Spectators.Count) continue;
sList.Add(new NetRadarContact
{
EntityId = (byte)specIdx,
Visible = kv.Value.VisibleToPlayer,
FaintHorizon = kv.Value.FaintHorizonPing,
HasEverBeenSeen = kv.Value.HasEverBeenSeen,
LastSeenAge = kv.Value.LastSeenAge,
LastSeenX = kv.Value.LastSeenX,
LastSeenZ = kv.Value.LastSeenZ
});
}
byte[] payload = SnapshotCodec.EncodeRadarContacts(_matchGeneration, _snapshotSeq, cList, sList);
SendLatestToPeer(peer, payload);
}
private void SendJoinAccepted(ConnectedPeer peer)
{
var msg = new JoinAcceptedMsg
{
PeerId = peer.PeerId,
ReconnectToken = peer.ReconnectToken,
AssignedContenderId = peer.AssignedContenderId,
MatchGeneration = _matchGeneration,
InitialState = BuildInitialMatchStateDto(peer.AssignedContenderId)
};
SendSchemaToPeer(peer, msg);
}
private InitialMatchStateDto BuildInitialMatchStateDto(int forContenderId)
{
var dto = new InitialMatchStateDto
{
MatchGeneration = _matchGeneration,
Seed = _session.State.Seed,
MapKind = (byte)_session.State.MapKind,
SimTime = _session.State.Time,
SafeRadius = _session.State.Spectators.SafeRadius,
Phase = (byte)(_session.State.Phase == MatchPhase.Completed ? 1 : 0),
WinnerContenderId = _session.State.WinnerContenderId,
TerrainStamps = new List<TerrainStampEvent>(_terrainStampHistory)
};
for (int i = 0; i < _session.State.Contenders.Count; i++)
{
var c = _session.State.Contenders[i];
dto.Contenders.Add(new ContenderInitialDto
{
Id = c.Id,
Name = c.Name,
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)
});
}
for (int i = 0; i < _session.State.Spectators.Spectators.Count; i++)
{
var s = _session.State.Spectators.Spectators[i];
var mounted = new List<MountedSlotDto>(s.Grid.Mounted.Count);
for (int m = 0; m < s.Grid.Mounted.Count; m++)
{
mounted.Add(new MountedSlotDto { ModuleId = s.Grid.Mounted[m].Spec.Id, HardpointId = s.Grid.Mounted[m].HardpointId });
}
dto.Spectators.Add(new SpectatorInitialDto
{
Id = s.Id,
Tier = (byte)s.Tier,
Stance = (byte)s.Stance,
X = s.X, Y = s.Y, Z = s.Z, Yaw = s.Yaw,
ChassisId = s.Grid.Spec.Id,
CoreHp = s.Grid.CoreHp,
MaxCoreHp = s.Grid.MaxCoreHp,
ArmorBytes = s.Grid.QuantizeArmorBytes(),
Mounted = mounted
});
}
for (int i = 0; i < _session.State.GroundDrops.Count; i++)
{
var d = _session.State.GroundDrops[i];
dto.GroundDrops.Add(new GroundDropDto
{
Id = d.Id,
X = d.X,
Z = d.Z,
ChassisId = d.Chassis?.Id,
ModuleId = d.Module?.Id,
PickedUp = d.PickedUp
});
}
return dto;
}
private void SendSchemaToPeer(ConnectedPeer peer, ISchemaWireMessage msg)
{
if (!peer.Active || _retiredTransportPeers.Contains(peer.TransportPeer)) return;
SendSchemaRaw(peer.TransportPeer, msg);
}
private void SendSchemaRaw(CultNetRudpSocketServerPeer transportPeer, ISchemaWireMessage msg)
{
byte[] payload = SnapshotCodec.SerializeSchemaMessage(msg);
byte[] wire = SnapshotCodec.WrapSchema(payload, _matchGeneration, _schemaOutSeq++);
try
{
_server.SendSchema(transportPeer, wire);
}
catch
{
// Transport peer will be swept by timeout/disconnect
}
}
private void SendLatestToPeer(ConnectedPeer peer, byte[] payload)
{
if (!peer.Active || _retiredTransportPeers.Contains(peer.TransportPeer)) return;
byte[] wire = SnapshotCodec.WrapLatest(payload, _matchGeneration, _latestOutSeq++);
try
{
_server.Send(peer.TransportPeer, SnapshotCodec.ChannelLatest, wire);
}
catch
{
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_server.PeerDisconnected -= OnTransportPeerDisconnected;
_server.Dispose();
_socket.Dispose();
_session.Dispose();
}
}
}

View file

@ -0,0 +1,833 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Numerics;
using GameCult.Mesh;
using MessagePack;
using RustToDust.Core;
namespace RustToDust.Net
{
public enum LatestPacketKind : byte
{
CorePvs = 1,
SpectatorOrbitHalf = 2,
RadarContacts = 3,
ClientInput = 16
}
public readonly record struct ClientInputPacket(
uint MatchGeneration,
uint InputSeq,
uint ClientSendMs,
PlayerInput Input);
public struct NetContenderState
{
public byte SlotId;
public bool Alive;
public bool IsHuman;
public bool Fire;
public bool Brake;
public bool Snap;
public Vector3 Pos;
public Quaternion Rot;
public Vector3 Vel;
public float AimYaw;
public float AimPitchDeg;
public float Throttle;
public float Steer;
public float CoreHpRatio;
public float MaxThermalRatio;
}
public struct NetSpectatorState
{
public byte Id;
public bool Alive;
public SpectatorStance Stance;
public bool Snap;
public sbyte TargetContenderId;
public Vector3 Pos;
public Quaternion Rot;
public Vector3 Vel;
}
public struct NetWalkerEntry
{
public bool IsContender;
public byte EntityId;
public WalkerVisualSnapshot Snapshot;
}
public struct NetRadarContact
{
public byte EntityId;
public bool Visible;
public bool FaintHorizon;
public bool HasEverBeenSeen;
public float LastSeenAge;
public float LastSeenX;
public float LastSeenZ;
}
public sealed class DecodedCorePvsSnapshot
{
public uint MatchGeneration;
public uint SnapshotSeq;
public uint SimTick;
public float SimTime;
public uint AckedInputSeq;
public uint EchoSendMs;
public float SafeRadius;
public MatchPhase Phase;
public int? WinnerContenderId;
public byte DetectedByCount;
public int InArcWeapons;
public int OutOfArcWeapons;
public int DisabledWeapons;
public bool AllWeaponsOutOfArc;
public ushort ContenderPvsMask;
public bool LocalAlive;
public Vector3 LocalPos;
public Quaternion LocalRot;
public Vector3 LocalVel;
public Vector3 LocalAngVel;
public float LocalCoreHp;
public float LocalMaxThermalRatio;
public byte[] LocalCellTempsQuantized = Array.Empty<byte>();
public float[] LocalMountedTemps = Array.Empty<float>();
public float[] LocalMountedCooldowns = Array.Empty<float>();
public List<NetContenderState> Contenders = new();
public List<NetWalkerEntry> Walkers = new();
public List<NetSpectatorState> CombatSpectators = new();
}
public sealed class DecodedSpectatorOrbitSnapshot
{
public uint MatchGeneration;
public uint SnapshotSeq;
public byte HalfIndex;
public List<NetSpectatorState> Spectators = new();
}
public sealed class DecodedRadarContactsSnapshot
{
public uint MatchGeneration;
public uint SnapshotSeq;
public List<NetRadarContact> Contenders = new();
public List<NetRadarContact> Spectators = new();
}
public static class SnapshotCodec
{
public const int MaxLatestDatagramBytes = 1152;
public const string ChannelLatest = "latest";
public const string ChannelSchema = "schema";
public const string SchemaLatestId = "rtd.snap";
public const string SchemaInputId = "rtd.in";
public const string SchemaEventsId = "rtd.evt";
public const string BodyMatchId = "m";
// CultMeshRealtimeWireProtocol fixed header (37) + "latest" (6) + "rtd.snap" (8) + "m" (1) = 52 bytes
public const int CultMeshLatestOverheadBytes = 52;
public const int MaxLatestPayloadBytes = MaxLatestDatagramBytes - CultMeshLatestOverheadBytes; // 1100 bytes
public static byte[] WrapLatest(ReadOnlySpan<byte> payload, long producerEpoch, long sequence, string schemaId = SchemaLatestId)
{
var frame = new CultMeshRealtimeFrame
{
ChannelId = ChannelLatest,
SchemaId = schemaId,
BodyId = BodyMatchId,
ProducerEpoch = producerEpoch,
Sequence = sequence,
Delivery = CultMeshRealtimeDelivery.LatestOnly,
Payload = payload.ToArray()
};
byte[] encoded = CultMeshRealtimeWireProtocol.EncodeFrame(frame);
if (encoded.Length > MaxLatestDatagramBytes)
{
throw new InvalidOperationException(
$"Latest packet exceeded {MaxLatestDatagramBytes}B MTU cap ({encoded.Length}B).");
}
return encoded;
}
public static byte[] WrapSchema(ReadOnlySpan<byte> payload, long producerEpoch, long sequence, string schemaId = SchemaEventsId)
{
var frame = new CultMeshRealtimeFrame
{
ChannelId = ChannelSchema,
SchemaId = schemaId,
BodyId = BodyMatchId,
ProducerEpoch = producerEpoch,
Sequence = sequence,
Delivery = CultMeshRealtimeDelivery.ReliableOrdered,
Payload = payload.ToArray()
};
return CultMeshRealtimeWireProtocol.EncodeFrame(frame);
}
public static CultMeshRealtimeFrame Unwrap(byte[] wireBytes) =>
CultMeshRealtimeWireProtocol.DecodeFrame(wireBytes);
public static byte[] SerializeSchemaMessage(ISchemaWireMessage msg) =>
MessagePackSerializer.Serialize<ISchemaWireMessage>(msg);
public static ISchemaWireMessage DeserializeSchemaMessage(ReadOnlyMemory<byte> payload) =>
MessagePackSerializer.Deserialize<ISchemaWireMessage>(payload);
public static byte[] EncodeClientInput(in ClientInputPacket pkt)
{
byte[] buf = new byte[36];
var span = buf.AsSpan();
span[0] = (byte)LatestPacketKind.ClientInput;
BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(1), pkt.MatchGeneration);
BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(5), pkt.InputSeq);
BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(9), pkt.ClientSendMs);
BinaryPrimitives.WriteSingleLittleEndian(span.Slice(13), pkt.Input.AimWorldX);
BinaryPrimitives.WriteSingleLittleEndian(span.Slice(17), pkt.Input.AimWorldY);
BinaryPrimitives.WriteSingleLittleEndian(span.Slice(21), pkt.Input.AimWorldZ);
BinaryPrimitives.WriteInt16LittleEndian(span.Slice(25), EncodeSnorm16(pkt.Input.Throttle));
BinaryPrimitives.WriteInt16LittleEndian(span.Slice(27), EncodeSnorm16(pkt.Input.Steer));
BinaryPrimitives.WriteInt16LittleEndian(span.Slice(29), EncodeSnorm16(pkt.Input.VerticalThrottle));
byte flags = 0;
if (pkt.Input.Fire) flags |= 1;
if (pkt.Input.Brake) flags |= 2;
if (pkt.Input.InteractPickup) flags |= 4;
span[31] = flags;
return buf; // 32-36 B
}
public static ClientInputPacket DecodeClientInput(ReadOnlySpan<byte> span)
{
if (span.Length < 32 || span[0] != (byte)LatestPacketKind.ClientInput)
{
throw new InvalidOperationException("Invalid ClientInput packet.");
}
uint gen = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(1));
uint seq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(5));
uint sendMs = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(9));
float ax = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(13));
float ay = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(17));
float az = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(21));
float throttle = DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(25)));
float steer = DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(27)));
float vert = DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(29)));
byte flags = span[31];
return new ClientInputPacket(
gen,
seq,
sendMs,
new PlayerInput(
throttle,
steer,
ax,
az,
(flags & 1) != 0,
(flags & 4) != 0,
(flags & 2) != 0,
ay,
vert));
}
public static byte[] EncodeCorePvs(
uint matchGeneration,
uint snapshotSeq,
uint simTick,
float simTime,
uint ackedInputSeq,
uint echoSendMs,
float safeRadius,
MatchPhase phase,
int? winnerContenderId,
byte detectedByCount,
ushort contenderPvsMask,
ContenderState localContender,
Vector3 localAngVel,
IReadOnlyList<NetContenderState> pvsContenders,
IReadOnlyList<NetWalkerEntry> pvsWalkers,
IReadOnlyList<NetSpectatorState> combatSpectators)
{
Span<byte> buf = stackalloc byte[MaxLatestPayloadBytes];
int offset = 0;
buf[offset++] = (byte)LatestPacketKind.CorePvs;
BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), matchGeneration); offset += 4;
BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), snapshotSeq); offset += 4;
BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), simTick); offset += 4;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), simTime); offset += 4;
BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), ackedInputSeq); offset += 4;
BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), echoSendMs); offset += 4;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), safeRadius); offset += 4;
byte phaseByte = (byte)(phase == MatchPhase.Completed ? 1 : 0);
if (winnerContenderId.HasValue) phaseByte |= 2;
buf[offset++] = phaseByte;
buf[offset++] = (byte)(sbyte)(winnerContenderId ?? -1);
buf[offset++] = detectedByCount;
ushort arc = (ushort)(
(Math.Clamp(localContender.InArcWeaponCount, 0, 15)) |
(Math.Clamp(localContender.OutOfArcWeaponCount, 0, 15) << 4) |
(Math.Clamp(localContender.DisabledWeaponCount, 0, 15) << 8) |
(localContender.AllWeaponsOutOfArc ? (1 << 12) : 0));
BinaryPrimitives.WriteUInt16LittleEndian(buf.Slice(offset), arc); offset += 2;
BinaryPrimitives.WriteUInt16LittleEndian(buf.Slice(offset), contenderPvsMask); offset += 2;
// Local prediction + telemetry block
buf[offset++] = (byte)(localContender.Alive ? 1 : 0);
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;
WriteQuatSnorm16(buf.Slice(offset), new Quaternion(localContender.CurrRotX, localContender.CurrRotY, localContender.CurrRotZ, localContender.CurrRotW));
offset += 8;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.VelX); offset += 4;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.VelY); offset += 4;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.VelZ); offset += 4;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localAngVel.X); offset += 4;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localAngVel.Y); offset += 4;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localAngVel.Z); offset += 4;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.Grid.CoreHp); offset += 4;
buf[offset++] = EncodeRatioByte(localContender.MaxThermalRatio, maxVal: 1.5f);
int cellCountPos = offset++;
int cellCount = 0;
var grid = localContender.Grid;
for (int y = 0; y < grid.Spec.Height && cellCount < 64; y++)
{
for (int x = 0; x < grid.Spec.Width && cellCount < 64; x++)
{
if (!grid.Spec.IsActive(x, y)) continue;
int qTemp = (int)MathF.Round((grid.Temperature[x, y] - ChassisGrid.AmbientTemp) * 0.5f);
buf[offset++] = (byte)Math.Clamp(qTemp, 0, 255);
cellCount++;
}
}
buf[cellCountPos] = (byte)cellCount;
int mountedCount = Math.Min(8, grid.Mounted.Count);
buf[offset++] = (byte)mountedCount;
for (int i = 0; i < mountedCount; i++)
{
var m = grid.Mounted[i];
int qTemp = (int)MathF.Round((m.CurrentTemp - ChassisGrid.AmbientTemp) * 0.5f);
buf[offset++] = (byte)Math.Clamp(qTemp, 0, 255);
int qCd = (int)MathF.Round(m.Cooldown * 25f);
buf[offset++] = (byte)Math.Clamp(qCd, 0, 255);
}
// PVS Contenders (each 35 B)
int contenderCountPos = offset++;
int contendersWritten = 0;
for (int i = 0; i < pvsContenders.Count; i++)
{
if (offset + 35 > MaxLatestPayloadBytes - 2)
{
break;
}
var c = pvsContenders[i];
buf[offset++] = c.SlotId;
byte flags = 0;
if (c.Alive) flags |= 1;
if (c.IsHuman) flags |= 2;
if (c.Fire) flags |= 4;
if (c.Brake) flags |= 8;
if (c.Snap) flags |= 16;
buf[offset++] = flags;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), c.Pos.X); offset += 4;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), c.Pos.Y); offset += 4;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), c.Pos.Z); offset += 4;
WriteQuatSnorm16(buf.Slice(offset), c.Rot); offset += 8;
WriteVelShort(buf.Slice(offset), c.Vel); offset += 6;
BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeAngleShort(c.AimYaw)); offset += 2;
buf[offset++] = (byte)(sbyte)Math.Clamp(MathF.Round(c.AimPitchDeg), -90, 90);
buf[offset++] = EncodeSnorm8(c.Throttle);
buf[offset++] = EncodeSnorm8(c.Steer);
buf[offset++] = EncodeRatioByte(c.CoreHpRatio, 1.0f);
buf[offset++] = EncodeRatioByte(c.MaxThermalRatio, 1.5f);
contendersWritten++;
}
buf[contenderCountPos] = (byte)contendersWritten;
// Walkers (capped strictly by remaining MTU budget!)
int walkerCountPos = offset++;
int walkersWritten = 0;
for (int i = 0; i < pvsWalkers.Count; i++)
{
var w = pvsWalkers[i];
int legCount = Math.Clamp(w.Snapshot.LegCount, 0, 4);
int bytesNeeded = 2 + legCount * 13;
if (offset + bytesNeeded > MaxLatestPayloadBytes - 1)
{
break;
}
buf[offset++] = (byte)((w.IsContender ? 0x80 : 0x00) | (w.EntityId & 0x7F));
buf[offset++] = (byte)legCount;
for (int l = 0; l < legCount; l++)
{
var ang = w.Snapshot.LegAngles[l];
BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.HipPitch)); offset += 2;
BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.HipRoll)); offset += 2;
BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.KneeFlex)); offset += 2;
BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.HockFlex)); offset += 2;
BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.AnklePitch)); offset += 2;
WriteOctNormal(buf.Slice(offset), w.Snapshot.FootNormal[l]); offset += 2;
buf[offset++] = (byte)Math.Clamp((int)MathF.Round(w.Snapshot.LoadG[l] * 50f), 0, 255);
}
walkersWritten++;
}
buf[walkerCountPos] = (byte)walkersWritten;
// Active Combat Spectators (26 B each, capped strictly by remaining MTU budget!)
int combatSpecCountPos = offset++;
int specsWritten = 0;
for (int i = 0; i < combatSpectators.Count; i++)
{
if (offset + 26 > MaxLatestPayloadBytes)
{
break;
}
WriteCompactSpectator(buf.Slice(offset), combatSpectators[i]);
offset += 26;
specsWritten++;
}
buf[combatSpecCountPos] = (byte)specsWritten;
return buf.Slice(0, offset).ToArray();
}
public static DecodedCorePvsSnapshot DecodeCorePvs(ReadOnlySpan<byte> span)
{
if (span.Length < 40 || span[0] != (byte)LatestPacketKind.CorePvs)
{
throw new InvalidOperationException("Invalid CorePvs snapshot packet.");
}
int offset = 1;
var res = new DecodedCorePvsSnapshot
{
MatchGeneration = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)),
};
offset += 4;
res.SnapshotSeq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4;
res.SimTick = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4;
res.SimTime = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)); offset += 4;
res.AckedInputSeq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4;
res.EchoSendMs = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4;
res.SafeRadius = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)); offset += 4;
byte phaseByte = span[offset++];
res.Phase = (phaseByte & 1) != 0 ? MatchPhase.Completed : MatchPhase.Active;
sbyte winnerRaw = (sbyte)span[offset++];
res.WinnerContenderId = (phaseByte & 2) != 0 ? winnerRaw : null;
res.DetectedByCount = span[offset++];
ushort arc = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(offset)); offset += 2;
res.InArcWeapons = arc & 0xF;
res.OutOfArcWeapons = (arc >> 4) & 0xF;
res.DisabledWeapons = (arc >> 8) & 0xF;
res.AllWeaponsOutOfArc = (arc & (1 << 12)) != 0;
res.ContenderPvsMask = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(offset)); offset += 2;
res.LocalAlive = (span[offset++] & 1) != 0;
res.LocalPos = new Vector3(
BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)),
BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)),
BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 8)));
offset += 12;
res.LocalRot = ReadQuatSnorm16(span.Slice(offset)); offset += 8;
res.LocalVel = new Vector3(
BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)),
BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)),
BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 8)));
offset += 12;
res.LocalAngVel = new Vector3(
BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)),
BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)),
BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 8)));
offset += 12;
res.LocalCoreHp = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)); offset += 4;
res.LocalMaxThermalRatio = span[offset++] / 255f * 1.5f;
int cellCount = span[offset++];
res.LocalCellTempsQuantized = span.Slice(offset, cellCount).ToArray();
offset += cellCount;
int mountedCount = span[offset++];
res.LocalMountedTemps = new float[mountedCount];
res.LocalMountedCooldowns = new float[mountedCount];
for (int i = 0; i < mountedCount; i++)
{
res.LocalMountedTemps[i] = ChassisGrid.AmbientTemp + span[offset++] * 2.0f;
res.LocalMountedCooldowns[i] = span[offset++] / 25f;
}
int contenderCount = span[offset++];
for (int i = 0; i < contenderCount; i++)
{
byte slotId = span[offset++];
byte flags = span[offset++];
Vector3 pos = new(
BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)),
BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)),
BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 8)));
offset += 12;
Quaternion rot = ReadQuatSnorm16(span.Slice(offset)); offset += 8;
Vector3 vel = ReadVelShort(span.Slice(offset)); offset += 6;
float aimYaw = DecodeAngleShort(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset))); offset += 2;
float aimPitch = (sbyte)span[offset++];
float throttle = DecodeSnorm8(span[offset++]);
float steer = DecodeSnorm8(span[offset++]);
float coreRatio = span[offset++] / 255f;
float thermalRatio = span[offset++] / 255f * 1.5f;
res.Contenders.Add(new NetContenderState
{
SlotId = slotId,
Alive = (flags & 1) != 0,
IsHuman = (flags & 2) != 0,
Fire = (flags & 4) != 0,
Brake = (flags & 8) != 0,
Snap = (flags & 16) != 0,
Pos = pos,
Rot = rot,
Vel = vel,
AimYaw = aimYaw,
AimPitchDeg = aimPitch,
Throttle = throttle,
Steer = steer,
CoreHpRatio = coreRatio,
MaxThermalRatio = thermalRatio
});
}
int walkerCount = span[offset++];
for (int i = 0; i < walkerCount; i++)
{
byte tag = span[offset++];
bool isContender = (tag & 0x80) != 0;
byte entityId = (byte)(tag & 0x7F);
int legCount = span[offset++];
var snap = new WalkerVisualSnapshot { LegCount = legCount };
for (int l = 0; l < legCount; l++)
{
snap.LegAngles[l] = new WalkerLegAngles
{
HipPitch = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset))),
HipRoll = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset + 2))),
KneeFlex = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset + 4))),
HockFlex = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset + 6))),
AnklePitch = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset + 8)))
};
offset += 10;
snap.FootNormal[l] = ReadOctNormal(span.Slice(offset)); offset += 2;
snap.LoadG[l] = span[offset++] / 50f;
}
res.Walkers.Add(new NetWalkerEntry
{
IsContender = isContender,
EntityId = entityId,
Snapshot = snap
});
}
int specCount = span[offset++];
for (int i = 0; i < specCount; i++)
{
res.CombatSpectators.Add(ReadCompactSpectator(span.Slice(offset)));
offset += 26;
}
return res;
}
public static byte[] EncodeSpectatorOrbitHalf(
uint matchGeneration,
uint snapshotSeq,
byte halfIndex,
IReadOnlyList<NetSpectatorState> spectators)
{
Span<byte> buf = stackalloc byte[MaxLatestPayloadBytes];
int offset = 0;
buf[offset++] = (byte)LatestPacketKind.SpectatorOrbitHalf;
BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), matchGeneration); offset += 4;
BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), snapshotSeq); offset += 4;
buf[offset++] = halfIndex;
int countPos = offset++;
int count = 0;
for (int i = 0; i < spectators.Count; i++)
{
if (offset + 26 > MaxLatestPayloadBytes)
{
break;
}
WriteCompactSpectator(buf.Slice(offset), spectators[i]);
offset += 26;
count++;
}
buf[countPos] = (byte)count;
return buf.Slice(0, offset).ToArray();
}
public static DecodedSpectatorOrbitSnapshot DecodeSpectatorOrbitHalf(ReadOnlySpan<byte> span)
{
if (span.Length < 11 || span[0] != (byte)LatestPacketKind.SpectatorOrbitHalf)
{
throw new InvalidOperationException("Invalid SpectatorOrbitHalf packet.");
}
int offset = 1;
var res = new DecodedSpectatorOrbitSnapshot
{
MatchGeneration = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)),
};
offset += 4;
res.SnapshotSeq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4;
res.HalfIndex = span[offset++];
int count = span[offset++];
for (int i = 0; i < count; i++)
{
res.Spectators.Add(ReadCompactSpectator(span.Slice(offset)));
offset += 26;
}
return res;
}
public static byte[] EncodeRadarContacts(
uint matchGeneration,
uint snapshotSeq,
IReadOnlyList<NetRadarContact> contenders,
IReadOnlyList<NetRadarContact> spectators)
{
Span<byte> buf = stackalloc byte[MaxLatestPayloadBytes];
int offset = 0;
buf[offset++] = (byte)LatestPacketKind.RadarContacts;
BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), matchGeneration); offset += 4;
BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), snapshotSeq); offset += 4;
int cPos = offset++;
int cWritten = 0;
for (int i = 0; i < contenders.Count; i++)
{
if (offset + 11 > MaxLatestPayloadBytes - 1) break;
WriteRadarContact(buf.Slice(offset), contenders[i]);
offset += 11;
cWritten++;
}
buf[cPos] = (byte)cWritten;
int sPos = offset++;
int sWritten = 0;
for (int i = 0; i < spectators.Count; i++)
{
if (offset + 11 > MaxLatestPayloadBytes) break;
WriteRadarContact(buf.Slice(offset), spectators[i]);
offset += 11;
sWritten++;
}
buf[sPos] = (byte)sWritten;
return buf.Slice(0, offset).ToArray();
}
public static DecodedRadarContactsSnapshot DecodeRadarContacts(ReadOnlySpan<byte> span)
{
if (span.Length < 11 || span[0] != (byte)LatestPacketKind.RadarContacts)
{
throw new InvalidOperationException("Invalid RadarContacts packet.");
}
int offset = 1;
var res = new DecodedRadarContactsSnapshot
{
MatchGeneration = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)),
};
offset += 4;
res.SnapshotSeq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4;
int cCount = span[offset++];
for (int i = 0; i < cCount; i++)
{
res.Contenders.Add(ReadRadarContact(span.Slice(offset)));
offset += 11;
}
int sCount = span[offset++];
for (int i = 0; i < sCount; i++)
{
res.Spectators.Add(ReadRadarContact(span.Slice(offset)));
offset += 11;
}
return res;
}
private static void WriteRadarContact(Span<byte> dst, in NetRadarContact c)
{
dst[0] = c.EntityId;
byte flags = 0;
if (c.Visible) flags |= 1;
if (c.FaintHorizon) flags |= 2;
if (c.HasEverBeenSeen) flags |= 4;
dst[1] = flags;
int ageSteps = float.IsFinite(c.LastSeenAge) ? (int)MathF.Round(c.LastSeenAge / 0.025f) : 255;
dst[2] = (byte)Math.Clamp(ageSteps, 0, 255);
BinaryPrimitives.WriteSingleLittleEndian(dst.Slice(3), c.LastSeenX);
BinaryPrimitives.WriteSingleLittleEndian(dst.Slice(7), c.LastSeenZ);
}
private static NetRadarContact ReadRadarContact(ReadOnlySpan<byte> src)
{
byte id = src[0];
byte flags = src[1];
byte ageSteps = src[2];
return new NetRadarContact
{
EntityId = id,
Visible = (flags & 1) != 0,
FaintHorizon = (flags & 2) != 0,
HasEverBeenSeen = (flags & 4) != 0,
LastSeenAge = ageSteps >= 255 ? float.PositiveInfinity : ageSteps * 0.025f,
LastSeenX = BinaryPrimitives.ReadSingleLittleEndian(src.Slice(3)),
LastSeenZ = BinaryPrimitives.ReadSingleLittleEndian(src.Slice(7))
};
}
private static void WriteCompactSpectator(Span<byte> dst, in NetSpectatorState s)
{
dst[0] = s.Id;
byte flags = (byte)((s.Alive ? 1 : 0) | (((byte)s.Stance & 3) << 1) | (s.Snap ? 8 : 0));
dst[1] = flags;
dst[2] = (byte)s.TargetContenderId;
WriteInt24(dst.Slice(3), s.Pos.X);
WriteInt24(dst.Slice(6), s.Pos.Y);
WriteInt24(dst.Slice(9), s.Pos.Z);
WriteQuatSnorm16(dst.Slice(12), s.Rot);
WriteVelShort(dst.Slice(20), s.Vel);
}
private static NetSpectatorState ReadCompactSpectator(ReadOnlySpan<byte> src)
{
byte id = src[0];
byte flags = src[1];
sbyte target = (sbyte)src[2];
Vector3 pos = new(ReadInt24(src.Slice(3)), ReadInt24(src.Slice(6)), ReadInt24(src.Slice(9)));
Quaternion rot = ReadQuatSnorm16(src.Slice(12));
Vector3 vel = ReadVelShort(src.Slice(20));
return new NetSpectatorState
{
Id = id,
Alive = (flags & 1) != 0,
Stance = (SpectatorStance)((flags >> 1) & 3),
Snap = (flags & 8) != 0,
TargetContenderId = target,
Pos = pos,
Rot = rot,
Vel = vel
};
}
private static short EncodeSnorm16(float v) =>
(short)Math.Clamp(MathF.Round(Math.Clamp(v, -1f, 1f) * 32767f), -32767, 32767);
private static float DecodeSnorm16(short v) => v / 32767f;
private static byte EncodeSnorm8(float v) =>
(byte)(sbyte)Math.Clamp(MathF.Round(Math.Clamp(v, -1f, 1f) * 127f), -127, 127);
private static float DecodeSnorm8(byte b) => (sbyte)b / 127f;
private static byte EncodeRatioByte(float v, float maxVal) =>
(byte)Math.Clamp((int)MathF.Round((Math.Clamp(v, 0f, maxVal) / maxVal) * 255f), 0, 255);
private static short EncodeAngleShort(float rad) =>
(short)Math.Clamp((int)MathF.Round(MatchRules.NormalizeAngle(rad) / MathF.PI * 32767f), -32767, 32767);
private static float DecodeAngleShort(short v) => (v / 32767f) * MathF.PI;
private static short EncodeWalkerAngle(float rad) =>
(short)Math.Clamp((int)MathF.Round(rad * 4096f), short.MinValue, short.MaxValue);
private static float DecodeWalkerAngle(short v) => v / 4096f;
private static void WriteQuatSnorm16(Span<byte> dst, Quaternion q)
{
if (q.LengthSquared() < 1e-6f) q = Quaternion.Identity;
else q = Quaternion.Normalize(q);
BinaryPrimitives.WriteInt16LittleEndian(dst, EncodeSnorm16(q.X));
BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(2), EncodeSnorm16(q.Y));
BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(4), EncodeSnorm16(q.Z));
BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(6), EncodeSnorm16(q.W));
}
private static Quaternion ReadQuatSnorm16(ReadOnlySpan<byte> src)
{
var q = new Quaternion(
DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(src)),
DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(src.Slice(2))),
DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(src.Slice(4))),
DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(src.Slice(6))));
return q.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(q);
}
private static void WriteVelShort(Span<byte> dst, Vector3 v)
{
BinaryPrimitives.WriteInt16LittleEndian(dst, (short)Math.Clamp((int)MathF.Round(v.X * 100f), -32767, 32767));
BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(2), (short)Math.Clamp((int)MathF.Round(v.Y * 100f), -32767, 32767));
BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(4), (short)Math.Clamp((int)MathF.Round(v.Z * 100f), -32767, 32767));
}
private static Vector3 ReadVelShort(ReadOnlySpan<byte> src) => new(
BinaryPrimitives.ReadInt16LittleEndian(src) / 100f,
BinaryPrimitives.ReadInt16LittleEndian(src.Slice(2)) / 100f,
BinaryPrimitives.ReadInt16LittleEndian(src.Slice(4)) / 100f);
private static void WriteInt24(Span<byte> dst, float meters)
{
int scaled = Math.Clamp((int)MathF.Round(meters * 256f), -8388607, 8388607);
dst[0] = (byte)(scaled & 0xFF);
dst[1] = (byte)((scaled >> 8) & 0xFF);
dst[2] = (byte)((scaled >> 16) & 0xFF);
}
private static float ReadInt24(ReadOnlySpan<byte> src)
{
int v = src[0] | (src[1] << 8) | (src[2] << 16);
if ((v & 0x800000) != 0)
{
v |= unchecked((int)0xFF000000);
}
return v / 256f;
}
private static void WriteOctNormal(Span<byte> dst, Vector3 n)
{
if (n.LengthSquared() < 1e-6f) n = Vector3.UnitY;
else n = Vector3.Normalize(n);
float sum = MathF.Abs(n.X) + MathF.Abs(n.Y) + MathF.Abs(n.Z);
float ox = n.X / sum;
float oy = n.Z / sum;
if (n.Y < 0f)
{
float sx = (1f - MathF.Abs(oy)) * (ox >= 0f ? 1f : -1f);
float sy = (1f - MathF.Abs(ox)) * (oy >= 0f ? 1f : -1f);
ox = sx;
oy = sy;
}
dst[0] = EncodeSnorm8(ox);
dst[1] = EncodeSnorm8(oy);
}
private static Vector3 ReadOctNormal(ReadOnlySpan<byte> src)
{
float ox = DecodeSnorm8(src[0]);
float oy = DecodeSnorm8(src[1]);
float ny = 1f - MathF.Abs(ox) - MathF.Abs(oy);
if (ny < 0f)
{
float oldOx = ox;
ox = (1f - MathF.Abs(oy)) * (oldOx >= 0f ? 1f : -1f);
oy = (1f - MathF.Abs(oldOx)) * (oy >= 0f ? 1f : -1f);
}
var v = new Vector3(ox, ny, oy);
return v.LengthSquared() < 1e-6f ? Vector3.UnitY : Vector3.Normalize(v);
}
}
}

View file

@ -0,0 +1,132 @@
using System;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Threading;
using RustToDust.Core;
using RustToDust.Net;
using RustToDust.Ymir;
namespace RustToDust.Server
{
public static class Program
{
public static int Main(string[] args)
{
string bindStr = Environment.GetEnvironmentVariable("RTD_BIND") ?? "127.0.0.1";
int port = TryParseInt(Environment.GetEnvironmentVariable("RTD_PORT"), 3076);
string mapStr = Environment.GetEnvironmentVariable("RTD_MAP") ?? "desert";
int seed = TryParseInt(Environment.GetEnvironmentVariable("RTD_SEED"), 42);
int maxHumans = MatchState.ContenderCount;
double autoRestartSec = 8.0;
double durationSec = 0.0;
bool allowClientReset = false;
for (int i = 0; i < args.Length; i++)
{
string a = args[i];
if (a == "--bind" && i + 1 < args.Length) bindStr = args[++i];
else if (a.StartsWith("--bind=", StringComparison.Ordinal)) bindStr = a.Substring("--bind=".Length);
else if (a == "--port" && i + 1 < args.Length) port = TryParseInt(args[++i], port);
else if (a.StartsWith("--port=", StringComparison.Ordinal)) port = TryParseInt(a.Substring("--port=".Length), port);
else if (a == "--map" && i + 1 < args.Length) mapStr = args[++i];
else if (a.StartsWith("--map=", StringComparison.Ordinal)) mapStr = a.Substring("--map=".Length);
else if (a == "--seed" && i + 1 < args.Length) seed = TryParseInt(args[++i], seed);
else if (a.StartsWith("--seed=", StringComparison.Ordinal)) seed = TryParseInt(a.Substring("--seed=".Length), seed);
else if (a == "--max-humans" && i + 1 < args.Length) maxHumans = TryParseInt(args[++i], maxHumans);
else if (a.StartsWith("--max-humans=", StringComparison.Ordinal)) maxHumans = TryParseInt(a.Substring("--max-humans=".Length), maxHumans);
else if (a == "--auto-restart-sec" && i + 1 < args.Length) autoRestartSec = TryParseDouble(args[++i], autoRestartSec);
else if (a.StartsWith("--auto-restart-sec=", StringComparison.Ordinal)) autoRestartSec = TryParseDouble(a.Substring("--auto-restart-sec=".Length), autoRestartSec);
else if (a == "--duration-sec" && i + 1 < args.Length) durationSec = TryParseDouble(args[++i], durationSec);
else if (a.StartsWith("--duration-sec=", StringComparison.Ordinal)) durationSec = TryParseDouble(a.Substring("--duration-sec=".Length), durationSec);
else if (a == "--allow-client-reset") allowClientReset = true;
else if (a == "--assets-dir" && i + 1 < args.Length) Environment.SetEnvironmentVariable("RTD_ASSETS_DIR", args[++i]);
else if (a.StartsWith("--assets-dir=", StringComparison.Ordinal)) Environment.SetEnvironmentVariable("RTD_ASSETS_DIR", a.Substring("--assets-dir=".Length));
}
if (!IPAddress.TryParse(bindStr, out var bindIp))
{
Console.Error.WriteLine($"Invalid --bind IP address: '{bindStr}'");
return 2;
}
ArenaMapKind mapKind = string.Equals(mapStr, "sion", StringComparison.OrdinalIgnoreCase)
? ArenaMapKind.Sion
: ArenaMapKind.Desert;
using var cts = new CancellationTokenSource();
ConsoleCancelEventHandler cancelHandler = (_, e) =>
{
e.Cancel = true;
cts.Cancel();
};
EventHandler exitHandler = (_, _) => cts.Cancel();
Console.CancelKeyPress += cancelHandler;
AppDomain.CurrentDomain.ProcessExit += exitHandler;
try
{
using var host = new ServerMatchHost(
bindIp,
port,
seed,
mapKind,
maxHumans,
autoRestartSec,
allowClientReset);
Console.WriteLine($"RustToDust.Server listening on {bindIp}:{host.BoundPort} (map={mapKind}, seed={seed}, maxHumans={maxHumans})");
double tickSec = ArenaSession.FixedDt;
var sw = Stopwatch.StartNew();
double nextTickSec = sw.Elapsed.TotalSeconds;
double endSec = durationSec > 0.0 ? durationSec : double.PositiveInfinity;
while (!cts.IsCancellationRequested && sw.Elapsed.TotalSeconds < endSec)
{
double nowSec = sw.Elapsed.TotalSeconds;
if (nowSec >= nextTickSec)
{
host.StepOnce(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
nextTickSec += tickSec;
if (nowSec - nextTickSec > 0.25)
{
nextTickSec = nowSec + tickSec;
}
}
else
{
double remainingMs = (nextTickSec - nowSec) * 1000.0;
if (remainingMs > 2.0)
{
Thread.Sleep(1);
}
else
{
Thread.Yield();
}
}
}
Console.WriteLine($"RustToDust.Server shutting down cleanly after {host.SimTick} ticks.");
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"RustToDust.Server fatal error: {ex}");
return 1;
}
finally
{
Console.CancelKeyPress -= cancelHandler;
AppDomain.CurrentDomain.ProcessExit -= exitHandler;
}
}
private static int TryParseInt(string? s, int fallback) =>
int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) ? v : fallback;
private static double TryParseDouble(string? s, double fallback) =>
double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double v) ? v : fallback;
}
}

View file

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<RollForward>LatestMajor</RollForward>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\RustToDust.Core\RustToDust.Core.csproj" />
<ProjectReference Include="..\RustToDust.Ymir\RustToDust.Ymir.csproj" />
<ProjectReference Include="..\RustToDust.Net\RustToDust.Net.csproj" />
<ProjectReference Include="$(YmirRoot)/src/Ymir.Box3D/Ymir.Box3D.csproj" AdditionalProperties="YmirNativeConfiguration=$(YmirNativeConfiguration)" />
</ItemGroup>
</Project>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using RustToDust.Core;
namespace RustToDust.Ymir
{
public sealed class LocalArenaSession : IClientArenaSession
{
private readonly List<ISimEvent> _discardEvents = new();
public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null)
{
Inner = new ArenaSession(seed, mapKind, slot0Human: true);
if (!string.IsNullOrWhiteSpace(callsign))
{
Inner.SetHumanSlot(0, true, callsign);
}
}
public ArenaSession Inner { get; private set; }
public MatchState ViewState => Inner.State;
public int LocalContenderId => 0;
public ContenderState LocalContender => Inner.State.Contenders[0];
public ClientMatchOutcome LocalOutcome =>
Inner.State.Phase == MatchPhase.Active
? (LocalContender.Alive ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
: (Inner.State.WinnerContenderId == LocalContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
public int LocalDetectedByCount =>
Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.DetectedByCount : 0;
public IReadOnlyDictionary<int, PlayerContactMemory> LocalContenderContacts =>
Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.ContenderContacts : Inner.State.EmptyContacts;
public IReadOnlyDictionary<int, PlayerContactMemory> LocalSpectatorContacts =>
Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.SpectatorContacts : Inner.State.EmptyContacts;
public NetworkStatusSnapshot ConnectionStatus =>
new(NetworkMode.Solo, Connected: true, PingMs: 0, ConnectedHumans: 1, MaxHumans: 1, StateLabel: "SOLO");
public bool IsContenderVisible(int contenderId) => true;
public bool IsSpectatorVisible(int spectatorId) => true;
public void BeginRenderFrame(double dt, float physicsAlpha)
{
}
public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick)
{
if (!isPhysicsTick)
{
return;
}
Inner.SetHumanInput(0, input);
Inner.Step();
_discardEvents.Clear();
Inner.DrainStepEvents(_discardEvents);
}
public bool RequestEquipCargo(int cargoIndex, string hardpointId) =>
Inner.TryEquipCargo(0, cargoIndex, hardpointId);
public void RequestNewMatch(int seed, ArenaMapKind mapKind)
{
string? name = LocalContender.Name;
Inner.Dispose();
Inner = new ArenaSession(seed, mapKind, slot0Human: true);
if (!string.IsNullOrWhiteSpace(name))
{
Inner.SetHumanSlot(0, true, name);
}
}
public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) =>
Inner.GetInterpolatedContenderPose(contenderId, alpha);
public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha) =>
Inner.GetInterpolatedSpectatorPose(spectatorId, alpha);
public bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap) =>
Inner.TrySampleInterpolatedWalkerPose(isContender, id, alpha, out snap);
public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation)
{
var hit = Inner.World.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z));
return new ClientRayHit(
hit.Hit,
hit.StableId,
new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z),
new Vector3(hit.Normal.X, hit.Normal.Y, hit.Normal.Z),
hit.Fraction);
}
public void Dispose()
{
Inner.Dispose();
}
}
}

View file

@ -6,12 +6,6 @@ using Ymir.Box3D;
namespace RustToDust.Ymir namespace RustToDust.Ymir
{ {
[InlineArray(4)]
public struct LegArray4<T>
{
private T _element0;
}
public readonly struct WalkerLegSpec public readonly struct WalkerLegSpec
{ {
public WalkerLegSpec( public WalkerLegSpec(
@ -193,67 +187,6 @@ namespace RustToDust.Ymir
} }
} }
public struct WalkerLegAngles
{
public float HipPitch;
public float HipRoll;
public float KneeFlex;
public float HockFlex;
public float AnklePitch;
public static WalkerLegAngles Lerp(in WalkerLegAngles a, in WalkerLegAngles b, float t) => new()
{
HipPitch = a.HipPitch + (b.HipPitch - a.HipPitch) * t,
HipRoll = a.HipRoll + (b.HipRoll - a.HipRoll) * t,
KneeFlex = a.KneeFlex + (b.KneeFlex - a.KneeFlex) * t,
HockFlex = a.HockFlex + (b.HockFlex - a.HockFlex) * t,
AnklePitch = a.AnklePitch + (b.AnklePitch - a.AnklePitch) * t
};
}
public struct WalkerVisualSnapshot
{
public int LegCount;
public float GeomScale;
public bool IsDigitigrade;
public bool IsArachnidUp;
public Vector3 ComPos;
public Quaternion ComRot;
public LegArray4<WalkerLegAngles> LegAngles;
public LegArray4<Vector3> FootNormal;
public LegArray4<float> LoadG;
public static WalkerVisualSnapshot Interpolate(in WalkerVisualSnapshot prev, in WalkerVisualSnapshot curr, float alpha)
{
float t = Math.Clamp(alpha, 0f, 1f);
Quaternion q0 = prev.ComRot.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(prev.ComRot);
Quaternion q1 = curr.ComRot.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(curr.ComRot);
if (Quaternion.Dot(q0, q1) < 0f)
{
q1 = -q1;
}
WalkerVisualSnapshot res = new()
{
LegCount = curr.LegCount,
GeomScale = curr.GeomScale,
IsDigitigrade = curr.IsDigitigrade,
IsArachnidUp = curr.IsArachnidUp,
ComPos = Vector3.Lerp(prev.ComPos, curr.ComPos, t),
ComRot = Quaternion.Slerp(q0, q1, t)
};
for (int i = 0; i < curr.LegCount; i++)
{
res.LegAngles[i] = WalkerLegAngles.Lerp(prev.LegAngles[i], curr.LegAngles[i], t);
Vector3 n = Vector3.Lerp(prev.FootNormal[i], curr.FootNormal[i], t);
res.FootNormal[i] = n.LengthSquared() > 1e-6f ? Vector3.Normalize(n) : Vector3.UnitY;
res.LoadG[i] = prev.LoadG[i] + (curr.LoadG[i] - prev.LoadG[i]) * t;
}
return res;
}
}
public struct WalkerJointActuator public struct WalkerJointActuator
{ {
public WalkerLegAngles Theta; public WalkerLegAngles Theta;

View file

@ -11,8 +11,8 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void DrivingAndFiring_MovesBuggyInYmirAndBuildsWeaponHeat() public void DrivingAndFiring_MovesBuggyInYmirAndBuildsWeaponHeat()
{ {
using var session = new ArenaSession(seed: 42); using var session = new ArenaSession(seed: 42, slot0Human: true);
var player = session.State.Player; var player = session.State.Contenders[0];
float startX = player.X; float startX = player.X;
float startZ = player.Z; float startZ = player.Z;
float startYaw = player.Yaw; float startYaw = player.Yaw;
@ -20,7 +20,7 @@ namespace RustToDust.Tests
for (int tick = 0; tick < 120; tick++) for (int tick = 0; tick < 120; tick++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 1f, Throttle: 1f,
Steer: 0.45f, Steer: 0.45f,
AimWorldX: player.X + 40f, AimWorldX: player.X + 40f,
@ -28,6 +28,7 @@ namespace RustToDust.Tests
Fire: true, Fire: true,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
if (session.State.Tracers.Count > 0) if (session.State.Tracers.Count > 0)
{ {
@ -52,30 +53,30 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void ChassisSwap_ToManticoreAndRaptor_ReplacesBodyWithoutLeakingYmirLanes() public void ChassisSwap_ToManticoreAndRaptor_ReplacesBodyWithoutLeakingYmirLanes()
{ {
using var session = new ArenaSession(seed: 77); using var session = new ArenaSession(seed: 77, slot0Human: true);
var player = session.State.Player; var player = session.State.Contenders[0];
int initialFreeSlots = session.World.FreeBodySlots; int initialFreeSlots = session.World.FreeBodySlots;
// Step once to settle world // Step once to settle world
session.Step(new PlayerInput(0f, 0f, 0f, 0f, false, false, false)); session.Step();
// Spawn Manticore (Dorsal) right beside player and swap // Spawn Manticore (Dorsal) right beside player and swap
session.State.SpawnChassisDrop(player.X + 1f, player.Z + 1f, Catalog.Manticore); session.State.SpawnChassisDrop(player.X + 1f, player.Z + 1f, Catalog.Manticore);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal("manticore", player.Grid.Spec.Id); Assert.Equal("manticore", player.Grid.Spec.Id);
Assert.Equal(GridPlane.Dorsal, player.Grid.Spec.Plane); Assert.Equal(GridPlane.Dorsal, player.Grid.Spec.Plane);
// Step so Ymir reclaims old tombstone lane // Step so Ymir reclaims old tombstone lane
session.Step(new PlayerInput(0f, 0f, 0f, 0f, false, false, false)); session.Step();
Assert.Equal(initialFreeSlots, session.World.FreeBodySlots); Assert.Equal(initialFreeSlots, session.World.FreeBodySlots);
// Now spawn Raptor (Coronal) beside player and swap // Now spawn Raptor (Coronal) beside player and swap
session.State.SpawnChassisDrop(player.X + 1f, player.Z + 1f, Catalog.Raptor); session.State.SpawnChassisDrop(player.X + 1f, player.Z + 1f, Catalog.Raptor);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal("raptor", player.Grid.Spec.Id); Assert.Equal("raptor", player.Grid.Spec.Id);
Assert.Equal(GridPlane.Coronal, player.Grid.Spec.Plane); Assert.Equal(GridPlane.Coronal, player.Grid.Spec.Plane);
session.Step(new PlayerInput(0f, 0f, 0f, 0f, false, false, false)); session.Step();
Assert.Equal(initialFreeSlots, session.World.FreeBodySlots); Assert.Equal(initialFreeSlots, session.World.FreeBodySlots);
} }
@ -101,20 +102,21 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void BroadsideFire_UsesDirectionalSupportRadiusNotMaxExtent() public void BroadsideFire_UsesDirectionalSupportRadiusNotMaxExtent()
{ {
using var session = new ArenaSession(seed: 19); using var session = new ArenaSession(seed: 19, slot0Human: true);
var player = session.State.Player; var player = session.State.Contenders[0];
// Swap to Tank / Anvil (HalfWidth = 1.93m, HalfLength = 2.83m) where broadside vs forward differs by ~0.9m. // Swap to Tank / Anvil (HalfWidth = 1.93m, HalfLength = 2.83m) where broadside vs forward differs by ~0.9m.
session.State.SpawnChassisDrop(player.X + 0.5f, player.Z + 0.5f, Catalog.Tank); session.State.SpawnChassisDrop(player.X + 0.5f, player.Z + 0.5f, Catalog.Tank);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal(Catalog.Tank.Id, player.Grid.Spec.Id); Assert.Equal(Catalog.Tank.Id, player.Grid.Spec.Id);
// Step once to settle body, then aim strictly perpendicular (broadside) to player's Yaw. // Step once to settle body, then aim strictly perpendicular (broadside) to player's Yaw.
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, false)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, false));
session.Step();
float broadsideX = MathF.Cos(player.Yaw); float broadsideX = MathF.Cos(player.Yaw);
float broadsideZ = -MathF.Sin(player.Yaw); float broadsideZ = -MathF.Sin(player.Yaw);
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 0f, Throttle: 0f,
Steer: 0f, Steer: 0f,
AimWorldX: player.X + broadsideX * 30f, AimWorldX: player.X + broadsideX * 30f,
@ -122,6 +124,7 @@ namespace RustToDust.Tests
Fire: true, Fire: true,
InteractPickup: false, InteractPickup: false,
Brake: true)); Brake: true));
session.Step();
Assert.NotEmpty(session.State.Tracers); Assert.NotEmpty(session.State.Tracers);
var tracer = session.State.Tracers[^1]; var tracer = session.State.Tracers[^1];
@ -136,15 +139,16 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void TracerEvent_AssignsMonotonicId_AndPreservesAcrossAdvance() public void TracerEvent_AssignsMonotonicId_AndPreservesAcrossAdvance()
{ {
using var session = new ArenaSession(seed: 19); using var session = new ArenaSession(seed: 19, slot0Human: true);
var player = session.State.Player; var player = session.State.Contenders[0];
float aimX = player.X + MathF.Sin(player.Yaw) * 25f; float aimX = player.X + MathF.Sin(player.Yaw) * 25f;
float aimZ = player.Z + MathF.Cos(player.Yaw) * 25f; float aimZ = player.Z + MathF.Cos(player.Yaw) * 25f;
var ids = new List<int>(); var ids = new List<int>();
for (int tick = 0; tick < 30 && ids.Count < 2; tick++) for (int tick = 0; tick < 30 && ids.Count < 2; tick++)
{ {
session.Step(new PlayerInput(0f, 0f, aimX, aimZ, Fire: true, InteractPickup: false, Brake: true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, aimX, aimZ, Fire: true, InteractPickup: false, Brake: true));
session.Step();
foreach (var t in session.State.Tracers) foreach (var t in session.State.Tracers)
{ {
if (!ids.Contains(t.Id)) if (!ids.Contains(t.Id))

View file

@ -0,0 +1,357 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Numerics;
using System.Threading;
using GameCult.Mesh;
using RustToDust.Core;
using RustToDust.Net;
using RustToDust.Ymir;
using Xunit;
using Xunit.Abstractions;
namespace RustToDust.Tests
{
public sealed class CultNetMultiplayerTests
{
private readonly ITestOutputHelper _output;
public CultNetMultiplayerTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void SnapshotCodec_WorstCase12ContendersAndWalkersAndCombatSpecs_StrictlyFitsIn1152Bytes()
{
var state = new MatchState(seed: 42, ArenaMapKind.Desert);
var local = state.Contenders[0];
local.Grid.SwapChassis(Catalog.Bastion); // large 8x8 dorsal mech grid
var contenders = new List<NetContenderState>(12);
var walkers = new List<NetWalkerEntry>(12);
var specs = new List<NetSpectatorState>(10);
for (int i = 0; i < 12; i++)
{
contenders.Add(new NetContenderState
{
SlotId = (byte)i,
Alive = true,
IsHuman = true,
Fire = true,
Brake = false,
Snap = false,
Pos = new Vector3(i * 10f, 3f, -i * 5f),
Rot = Quaternion.Identity,
Vel = new Vector3(12f, 0f, 4f),
AimYaw = 0.5f,
AimPitchDeg = 10f,
Throttle = 1f,
Steer = -0.5f,
CoreHpRatio = 0.85f,
MaxThermalRatio = 0.45f
});
var ws = new WalkerVisualSnapshot { LegCount = 4 };
for (int l = 0; l < 4; l++)
{
ws.LegAngles[l] = new WalkerLegAngles { HipPitch = 0.4f, HipRoll = 0.1f, KneeFlex = -0.8f, HockFlex = 0.3f, AnklePitch = 0.2f };
ws.FootNormal[l] = Vector3.UnitY;
ws.LoadG[l] = 1.2f;
}
walkers.Add(new NetWalkerEntry { IsContender = true, EntityId = (byte)i, Snapshot = ws });
}
for (int i = 0; i < 10; i++)
{
specs.Add(new NetSpectatorState
{
Id = (byte)i,
Alive = true,
Stance = SpectatorStance.Provoked,
TargetContenderId = 0,
Pos = new Vector3(100f + i * 5f, 4f, -80f),
Rot = Quaternion.Identity,
Vel = new Vector3(2f, 0f, -3f)
});
}
byte[] p1 = SnapshotCodec.EncodeCorePvs(
1, 42, 84, 1.4f, 10, 100, 450f, MatchPhase.Active, null, 2, 0xFFF,
local, new Vector3(0.1f, 0.2f, 0.05f), contenders, walkers, specs);
byte[] w1 = SnapshotCodec.WrapLatest(p1, 1, 1);
byte[] p2 = SnapshotCodec.EncodeSpectatorOrbitHalf(1, 42, 0, Enumerable.Range(0, 28).Select(i => specs[i % specs.Count]).ToList());
byte[] w2 = SnapshotCodec.WrapLatest(p2, 1, 2);
var radarList = Enumerable.Range(0, 32).Select(i => new NetRadarContact { EntityId = (byte)i, Visible = true, LastSeenX = i * 5f, LastSeenZ = -i * 5f }).ToList();
byte[] p3 = SnapshotCodec.EncodeRadarContacts(1, 42, radarList.Take(11).ToList(), radarList);
byte[] w3 = SnapshotCodec.WrapLatest(p3, 1, 3);
byte[] pIn = SnapshotCodec.EncodeClientInput(new ClientInputPacket(1, 99, 1234, new PlayerInput(1f, -0.5f, 10f, 20f, true, true, false, 2f, 0.5f)));
byte[] wIn = SnapshotCodec.WrapLatest(pIn, 1, 4, SnapshotCodec.SchemaInputId);
_output.WriteLine($"Max wire bytes: Packet1={w1.Length}B, Packet2={w2.Length}B, Packet3={w3.Length}B, Input={wIn.Length}B");
Assert.True(w1.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet1 {w1.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B");
Assert.True(w2.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet2 {w2.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B");
Assert.True(w3.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet3 {w3.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B");
Assert.True(wIn.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Input {wIn.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B");
var decoded = SnapshotCodec.DecodeCorePvs(SnapshotCodec.Unwrap(w1).Payload.Span);
Assert.Equal(12, decoded.Contenders.Count);
Assert.Equal(42u, decoded.SnapshotSeq);
}
[Fact]
public void RealUdpLoopback_TwoClientsSion_DriveFireDamageCargoAndSimEvents()
{
using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0);
var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
using var clientA = new RemoteArenaSession(ep, "Alpha");
using var clientB = new RemoteArenaSession(ep, "Bravo");
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
Assert.True(PumpUntil(host, new[] { clientA, clientB }, () => clientA.IsJoined && clientB.IsJoined, ref nowMs, 3000),
"Both UDP clients should join ServerMatchHost");
Assert.NotEqual(clientA.LocalContenderId, clientB.LocalContenderId);
int slotA = clientA.LocalContenderId;
int slotB = clientB.LocalContenderId;
// Place A and B facing each other 28m apart in open Sion plaza
var anchor = host.Session.State.Contenders[slotA];
host.Session.SetContenderPose(slotA, anchor.X, anchor.Z, 0f);
host.Session.SetContenderPose(slotB, anchor.X, anchor.Z + 28f, MathF.PI);
// Give clientB a cargo module & equip it over reliable schema channel -> verify private cargo not leaked to A!
host.Session.State.Contenders[slotB].Grid.TryAddCargo(Catalog.Autocannon);
host.Session.State.Contenders[slotA].Grid.TryAddCargo(Catalog.CopperRad);
int cargoIdxB = host.Session.State.Contenders[slotB].Grid.Cargo.Count - 1;
Assert.True(clientB.RequestEquipCargo(cargoIdxB, "hp.weapon.roof"));
float startAz = clientA.LocalContender.Z;
float bArmorBefore = host.Session.State.Contenders[slotB].Grid.TotalArmorRatio();
// Step 90 ticks: Client A drives forward + fires at Client B
for (int t = 0; t < 90; t++)
{
var posB = host.Session.State.Contenders[slotB];
clientA.SubmitLocalInput(new PlayerInput(0.6f, 0f, posB.X, posB.Z, Fire: true, InteractPickup: false, Brake: false, AimWorldY: posB.Y), true);
clientB.SubmitLocalInput(new PlayerInput(0f, 0f, anchor.X, anchor.Z, Fire: false, InteractPickup: false, Brake: true), true);
nowMs += 16;
host.StepOnce(nowMs);
clientA.BeginRenderFrame(1.0 / 60.0, 1f);
clientB.BeginRenderFrame(1.0 / 60.0, 1f);
Thread.Sleep(1);
}
Assert.True(clientA.LocalContender.Z > startAz + 1.5f, "Client A should have advanced under Option M + server auth");
Assert.True(host.Session.State.Contenders[slotB].Grid.TotalArmorRatio() < bArmorBefore, "Client A's fire should damage Client B on server");
Assert.True(clientB.LocalContender.Grid.TotalArmorRatio() < 1.0f, "Client B should receive HitImpactEvent armor damage");
Assert.Equal(Catalog.Autocannon.Id, clientA.ViewState.Contenders[slotB].Grid.GetMountedOn("hp.weapon.roof")?.Spec.Id);
Assert.Empty(clientA.ViewState.Contenders[slotB].Grid.Cargo); // Private cargo NOT leaked!
Assert.True(clientA.ViewState.Tracers.Count > 0 || host.Session.State.Contenders[slotB].Grid.HitSequence > 0);
}
[Fact]
public void AntiWallhack_PvsPayloadAudit_OccludedRivalAndExemplarOmittedUntilPvsEnter()
{
using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 12, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0);
var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
using var clientA = new RemoteArenaSession(ep, "Alpha");
using var clientB = new RemoteArenaSession(ep, "Bravo");
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
Assert.True(PumpUntil(host, new[] { clientA, clientB }, () => clientA.IsJoined && clientB.IsJoined, ref nowMs, 3000));
int slotA = clientA.LocalContenderId;
int slotB = clientB.LocalContenderId;
// Place A and B on opposite sides of tall cover box (> 65m apart so outside proximity PVS envelope!)
var box = host.Session.State.ArenaCoverBoxes.First(b => b.HalfY >= 2.3f);
host.Session.SetContenderPose(slotA, box.X, box.Z - box.HalfZ - 40f, 0f);
host.Session.SetContenderPose(slotB, box.X, box.Z + box.HalfZ + 40f, 0f);
if (host.Session.State.ObserverStates.TryGetValue(slotA, out var obsA)) obsA.ContenderContacts.Remove(slotB);
if (host.Session.State.ObserverStates.TryGetValue(slotB, out var obsB)) obsB.ContenderContacts.Remove(slotA);
// Step 10 ticks so server recomputes PVS & snapshots while B also tries moving behind cover
float preBClientX = clientA.ViewState.Contenders[slotB].X;
float preBClientZ = clientA.ViewState.Contenders[slotB].Z;
float preBServerZ = host.Session.State.Contenders[slotB].Z;
for (int t = 0; t < 10; t++)
{
clientB.SubmitLocalInput(new PlayerInput(1f, 0f, 0f, 0f, false, false, false), true);
nowMs += 16;
host.StepOnce(nowMs);
clientA.BeginRenderFrame(1.0 / 60.0, 1f);
clientB.BeginRenderFrame(1.0 / 60.0, 1f);
Thread.Sleep(1);
}
Assert.False(host.Session.IsEntityInPeerPvs(slotA, true, slotB), "Occluded rival > 65m must NOT be in Peer A PVS");
Assert.False(clientA.IsContenderVisible(slotB), "Client A must mark occluded rival invisible");
Assert.False(clientA.LocalContenderContacts.TryGetValue(slotB, out var memB) && MatchState.IsContactOnRadar(memB));
Assert.True(MathF.Abs(host.Session.State.Contenders[slotB].Z - preBServerZ) > 0.25f, "Server B actually moved behind cover");
Assert.Equal(preBClientX, clientA.ViewState.Contenders[slotB].X);
Assert.Equal(preBClientZ, clientA.ViewState.Contenders[slotB].Z);
// Now move B into open plaza right in front of A AND swap B's chassis while occluded -> verify PvsEnter delivers chassis & pose!
host.Session.State.SpawnChassisDrop(box.X, box.Z + box.HalfZ + 40f, Catalog.Anvil);
Assert.True(host.Session.TrySwapNearbyChassis(slotB));
host.Session.SetContenderPose(slotB, box.X + 18f, box.Z - box.HalfZ - 40f, 0f);
for (int t = 0; t < 12; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.BeginRenderFrame(1.0 / 60.0, 1f);
clientB.BeginRenderFrame(1.0 / 60.0, 1f);
Thread.Sleep(1);
}
Assert.True(clientA.IsContenderVisible(slotB), "Rival entering open LOS must become PVS visible");
Assert.Equal(Catalog.Anvil.Id, clientA.ViewState.Contenders[slotB].Grid.Spec.Id);
}
[Fact]
public void OptionM_LocalPredictionMovesImmediatelyAtZeroMs_ReconcilesSmoothly_AndHardSnapsOver4m()
{
using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0);
var serverEp = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
using var client = new RemoteArenaSession(serverEp, "Predictor");
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
Assert.True(PumpUntil(host, new[] { client }, () => client.IsJoined, ref nowMs, 3000));
int slot = client.LocalContenderId;
host.Session.SetContenderPose(slot, 0f, 0f, 0f);
for (int t = 0; t < 4; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
client.BeginRenderFrame(1.0 / 60.0, 1f);
Thread.Sleep(1);
}
float initialZ = client.GetInterpolatedContenderPose(slot, 1f).Pos.Z;
// Drop ALL inbound snapshots temporarily while client drives 10 ticks -> Option M must predict movement immediately!
client.DebugInboundLatestDropFilter = _ => true;
for (int t = 0; t < 10; t++)
{
client.SubmitLocalInput(new PlayerInput(1f, 0f, 0f, 60f, false, false, false), true);
}
float predictedZ = client.GetInterpolatedContenderPose(slot, 1f).Pos.Z;
Assert.True(predictedZ > initialZ + 0.10f, $"Option M must move immediately at 0ms before snapshots arrive ({initialZ:F3} -> {predictedZ:F3})");
Assert.True(client.UnackedInputCount >= 10);
// Re-enable snapshots & let server process delayed packets -> verify reconciliation replays unacked & decays error smoothly
client.DebugInboundLatestDropFilter = null;
for (int t = 0; t < 12; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
client.BeginRenderFrame(1.0 / 60.0, 1f);
Thread.Sleep(1);
}
Assert.Equal(0, client.UnackedInputCount);
// Force > 4.0m authoritative displacement (teleport) -> Option M MUST hard-snap residual error to zero!
host.Session.SetContenderPose(slot, 45f, 45f, 0f);
bool sawTeleportSnap = false;
float errAtSnap = float.MaxValue;
for (int t = 0; t < 10; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
client.BeginRenderFrame(1.0 / 60.0, 1f);
var p = client.GetInterpolatedContenderPose(slot, 1f).Pos;
if (Vector2.Distance(new Vector2(p.X, p.Z), new Vector2(45f, 45f)) < 2.0f)
{
sawTeleportSnap = true;
errAtSnap = client.CurrentPredictionError.Length();
break;
}
Thread.Sleep(1);
}
Assert.True(sawTeleportSnap, "Client should receive >4m teleport snapshot");
Assert.True(errAtSnap < 0.001f,
$"Expected >4m teleport to hard-snap prediction error to zero, got {errAtSnap:F4}m");
var snappedPos = client.GetInterpolatedContenderPose(slot, 1f).Pos;
Assert.InRange(Vector2.Distance(new Vector2(snappedPos.X, snappedPos.Z), new Vector2(45f, 45f)), 0f, 1.5f);
}
[Fact]
public void OptionL1_DisconnectAndTimeoutHandBackToAi_AndReconnectTokenReclaimsExactSlot()
{
using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0);
var serverEp = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
var clientA = new RemoteArenaSession(serverEp, "Nomad");
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000));
int originalSlot = clientA.LocalContenderId;
Guid token = clientA.ReconnectToken;
Assert.NotEqual(Guid.Empty, token);
Assert.True(host.Session.State.Contenders[originalSlot].IsHuman);
// 1. Graceful disconnect -> IsHuman flips to false (AI takes over surviving chassis)
clientA.DisconnectGracefully("BRB");
clientA.Dispose();
for (int t = 0; t < 35; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
Thread.Sleep(1);
}
Assert.False(host.Session.State.Contenders[originalSlot].IsHuman, "Graceful disconnect must hand slot back to AI");
Assert.Equal(0, host.ConnectedHumanCount);
// 2. Reconnect presenting matching ReconnectToken -> reclaims exact same slot!
using var clientAReconnect = new RemoteArenaSession(serverEp, "Nomad", token);
Assert.True(PumpUntil(host, new[] { clientAReconnect }, () => clientAReconnect.IsJoined, ref nowMs, 3000));
Assert.Equal(originalSlot, clientAReconnect.LocalContenderId);
Assert.True(host.Session.State.Contenders[originalSlot].IsHuman);
// 3. Simulate > 5000ms silence (timeout) -> server releases slot back to AI cleanly!
nowMs += ServerMatchHost.IdleTimeoutMs + 250;
host.StepOnce(nowMs);
Assert.False(host.Session.State.Contenders[originalSlot].IsHuman, "5s silence timeout must hand slot back to AI");
Assert.Equal(0, host.ConnectedHumanCount);
}
private static bool PumpUntil(
ServerMatchHost host,
RemoteArenaSession[] clients,
Func<bool> condition,
ref long nowMs,
int timeoutMs)
{
var deadline = DateTimeOffset.UtcNow.AddMilliseconds(timeoutMs);
while (DateTimeOffset.UtcNow < deadline)
{
nowMs += 16;
host.StepOnce(nowMs);
for (int i = 0; i < clients.Length; i++)
{
clients[i].PumpNetwork();
}
if (condition()) return true;
Thread.Sleep(2);
}
return condition();
}
}
}

View file

@ -25,9 +25,9 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void MesaBetweenSpectatorAndContender_BlocksLosAndPreventsFiringThroughTerrain() public void MesaBetweenSpectatorAndContender_BlocksLosAndPreventsFiringThroughTerrain()
{ {
using var session = new ArenaSession(seed: 42); using var session = new ArenaSession(seed: 42, slot0Human: true);
var mesa = FindTallMesa(session.State.Terrain); var mesa = FindTallMesa(session.State.Terrain);
var player = session.State.Player; var player = session.State.Contenders[0];
var spec = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Patron); var spec = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Patron);
// Place player and spectator on opposite sides of the tall mesa // Place player and spectator on opposite sides of the tall mesa
@ -42,7 +42,8 @@ namespace RustToDust.Tests
for (int tick = 0; tick < 10; tick++) for (int tick = 0; tick < 10; tick++)
{ {
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.False(session.HasLineOfSight( Assert.False(session.HasLineOfSight(
spec.X, MatchRules.GetObserverEyeY(spec.Y, spec.Grid.Spec.HalfHeight), spec.Z, spec.X, MatchRules.GetObserverEyeY(spec.Y, spec.Grid.Spec.HalfHeight), spec.Z,
@ -59,9 +60,9 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void CrestingRidge_RestoresLosAndAllowsSpectatorEngagement() public void CrestingRidge_RestoresLosAndAllowsSpectatorEngagement()
{ {
using var session = new ArenaSession(seed: 42); using var session = new ArenaSession(seed: 42, slot0Human: true);
var mesa = FindTallMesa(session.State.Terrain); var mesa = FindTallMesa(session.State.Terrain);
var player = session.State.Player; var player = session.State.Contenders[0];
var spec = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Patron); var spec = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Patron);
// Start occluded across the mesa // Start occluded across the mesa
@ -69,7 +70,8 @@ namespace RustToDust.Tests
session.SetSpectatorPose(spec.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z); session.SetSpectatorPose(spec.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z);
session.State.Spectators.OnSpectatorDamaged(spec, player.Id); session.State.Spectators.OnSpectatorDamaged(spec, player.Id);
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.False(spec.HasTargetLos); Assert.False(spec.HasTargetLos);
// Now player crests onto the high mesa plateau overlooking the spectator // Now player crests onto the high mesa plateau overlooking the spectator
@ -79,7 +81,8 @@ namespace RustToDust.Tests
bool sawTracer = false; bool sawTracer = false;
for (int tick = 0; tick < 30; tick++) for (int tick = 0; tick < 30; tick++)
{ {
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
if (session.State.Tracers.Count > 0) if (session.State.Tracers.Count > 0)
{ {
sawTracer = true; sawTracer = true;
@ -95,30 +98,32 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void LowSignatureExemplar_HiddenBehindRidge_IsInvisibleOnRadar_WhileInLosContactIsVisible() public void LowSignatureExemplar_HiddenBehindRidge_IsInvisibleOnRadar_WhileInLosContactIsVisible()
{ {
using var session = new ArenaSession(seed: 42); using var session = new ArenaSession(seed: 42, slot0Human: true);
var mesa = FindTallMesa(session.State.Terrain); var mesa = FindTallMesa(session.State.Terrain);
var player = session.State.Player; var player = session.State.Contenders[0];
var exemplar = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar); var exemplar = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar);
var visibleRival = session.State.Contenders[1]; var visibleRival = session.State.Contenders[1];
Assert.True(exemplar.RadarSignature <= 0.25f); Assert.True(exemplar.RadarSignature <= 0.25f);
// Reset memory so exemplar has never been seen yet, then hide it on the far side of the mesa // Reset memory so exemplar has never been seen yet, then hide it on the far side of the mesa
session.State.SpectatorContacts[exemplar.Id] = new PlayerContactMemory(); var obs0 = session.State.GetOrCreateObserverState(0);
obs0.SpectatorContacts[exemplar.Id] = new PlayerContactMemory();
session.SetContenderPose(player.Id, mesa.X - mesa.RadiusX - 18f, mesa.Z); session.SetContenderPose(player.Id, mesa.X - mesa.RadiusX - 18f, mesa.Z);
session.SetSpectatorPose(exemplar.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z); session.SetSpectatorPose(exemplar.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z);
// Place rival contender nearby in clear open LOS on the player's side of the mesa // Place rival contender nearby in clear open LOS on the player's side of the mesa
session.SetContenderPose(visibleRival.Id, mesa.X - mesa.RadiusX - 50f, mesa.Z + 12f); session.SetContenderPose(visibleRival.Id, mesa.X - mesa.RadiusX - 50f, mesa.Z + 12f);
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
var exMem = session.State.SpectatorContacts[exemplar.Id]; var exMem = obs0.SpectatorContacts[exemplar.Id];
Assert.False(exMem.VisibleToPlayer); Assert.False(exMem.VisibleToPlayer);
Assert.False(exMem.FaintHorizonPing); Assert.False(exMem.FaintHorizonPing);
Assert.False(MatchState.IsContactOnRadar(exMem), "Hidden low-signature Exemplar must vanish off player radar"); Assert.False(MatchState.IsContactOnRadar(exMem), "Hidden low-signature Exemplar must vanish off player radar");
var rivalMem = session.State.ContenderContacts[visibleRival.Id]; var rivalMem = obs0.ContenderContacts[visibleRival.Id];
Assert.True(rivalMem.VisibleToPlayer, "In-LOS contact must be live-visible to player"); Assert.True(rivalMem.VisibleToPlayer, "In-LOS contact must be live-visible to player");
Assert.True(MatchState.IsContactOnRadar(rivalMem)); Assert.True(MatchState.IsContactOnRadar(rivalMem));
} }
@ -126,9 +131,9 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void StaticCoverWall_BlocksLineOfSight() public void StaticCoverWall_BlocksLineOfSight()
{ {
using var session = new ArenaSession(seed: 12); using var session = new ArenaSession(seed: 12, slot0Human: true);
var box = session.State.ArenaCoverBoxes[0]; var box = session.State.ArenaCoverBoxes[0];
var player = session.State.Player; var player = session.State.Contenders[0];
var rival = session.State.Contenders[1]; var rival = session.State.Contenders[1];
// Ensure rival is a low-profile ground vehicle shorter than the 4m ruin cover wall // Ensure rival is a low-profile ground vehicle shorter than the 4m ruin cover wall
@ -208,7 +213,7 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void OccludedSpectators_DoNotLeakLiveTargetAfterMemoryExpires_FiveSeconds() public void OccludedSpectators_DoNotLeakLiveTargetAfterMemoryExpires_FiveSeconds()
{ {
using var session = new ArenaSession(seed: 42); using var session = new ArenaSession(seed: 42, slot0Human: true);
// Shrink safe circle so the tall mesa perimeter is outside SafeRadius // Shrink safe circle so the tall mesa perimeter is outside SafeRadius
session.State.Time = 360f; session.State.Time = 360f;
session.State.Spectators.UpdateSafeRadius(session.State.Time); session.State.Spectators.UpdateSafeRadius(session.State.Time);
@ -230,7 +235,7 @@ namespace RustToDust.Tests
} }
Assert.True(bestMinRadius > 0f, "Expected at least one tall Mesa in generated terrain."); Assert.True(bestMinRadius > 0f, "Expected at least one tall Mesa in generated terrain.");
var player = session.State.Player; var player = session.State.Contenders[0];
var tourists = session.State.Spectators.Spectators.Where(s => s.Tier == SpectatorTier.Tourist).ToList(); var tourists = session.State.Spectators.Spectators.Where(s => s.Tier == SpectatorTier.Tourist).ToList();
var provokedSpec = tourists[0]; var provokedSpec = tourists[0];
var clearedSpec = tourists[1]; var clearedSpec = tourists[1];
@ -265,7 +270,8 @@ namespace RustToDust.Tests
session.SetContenderPose(player.Id, specSideX - (negIsFurther ? 12f : -12f), mesa.Z); session.SetContenderPose(player.Id, specSideX - (negIsFurther ? 12f : -12f), mesa.Z);
session.SetSpectatorPose(provokedSpec.Id, specSideX, mesa.Z); session.SetSpectatorPose(provokedSpec.Id, specSideX, mesa.Z);
session.State.Spectators.OnSpectatorDamaged(provokedSpec, player.Id); session.State.Spectators.OnSpectatorDamaged(provokedSpec, player.Id);
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.True(provokedSpec.HasTargetLos, "Expected initial LOS before player drops behind cover"); Assert.True(provokedSpec.HasTargetLos, "Expected initial LOS before player drops behind cover");
float provokedKnownX = provokedSpec.LastKnownTargetX; float provokedKnownX = provokedSpec.LastKnownTargetX;
@ -277,7 +283,8 @@ namespace RustToDust.Tests
session.SetSpectatorPose(clearedSpec.Id, specSideX, mesa.Z + 4f); session.SetSpectatorPose(clearedSpec.Id, specSideX, mesa.Z + 4f);
// Verify clearedSpec gets Pass-2 Cleared assignment without LOS // Verify clearedSpec gets Pass-2 Cleared assignment without LOS
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.False(provokedSpec.HasTargetLos); Assert.False(provokedSpec.HasTargetLos);
Assert.Equal(SpectatorStance.Cleared, clearedSpec.Stance); Assert.Equal(SpectatorStance.Cleared, clearedSpec.Stance);
Assert.False(clearedSpec.HasTargetLos); Assert.False(clearedSpec.HasTargetLos);
@ -294,7 +301,8 @@ namespace RustToDust.Tests
session.SetContenderPose(player.Id, occludedX, latZ); session.SetContenderPose(player.Id, occludedX, latZ);
} }
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.False(provokedSpec.HasTargetLos, $"Provoked spectator regained unexpected LOS at tick {tick}"); Assert.False(provokedSpec.HasTargetLos, $"Provoked spectator regained unexpected LOS at tick {tick}");
Assert.False(clearedSpec.HasTargetLos, $"Cleared spectator regained unexpected LOS at tick {tick}"); Assert.False(clearedSpec.HasTargetLos, $"Cleared spectator regained unexpected LOS at tick {tick}");
@ -427,9 +435,9 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void AiContender_ImmediatelyDropsTrackingAndFiring_OnExactTickLosBreaks() public void AiContender_ImmediatelyDropsTrackingAndFiring_OnExactTickLosBreaks()
{ {
using var session = new ArenaSession(seed: 12); using var session = new ArenaSession(seed: 12, slot0Human: true);
var box = session.State.ArenaCoverBoxes[0]; var box = session.State.ArenaCoverBoxes[0];
var player = session.State.Player; var player = session.State.Contenders[0];
var ai = session.State.Contenders[1]; var ai = session.State.Contenders[1];
// Move other rivals far away so only ai <-> player interaction is isolated // Move other rivals far away so only ai <-> player interaction is isolated
@ -467,7 +475,8 @@ namespace RustToDust.Tests
// Advance `phase` ticks in open LOS; open-LOS acquisition must be immediate on tick 0! // Advance `phase` ticks in open LOS; open-LOS acquisition must be immediate on tick 0!
for (int t = 0; t <= phase; t++) for (int t = 0; t <= phase; t++)
{ {
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.Equal(player.Id, ai.AiTargetContenderId); Assert.Equal(player.Id, ai.AiTargetContenderId);
Assert.True(ai.FireCmd, $"Expected AI to acquire open-LOS target and fire immediately (phase={phase}, t={t})"); Assert.True(ai.FireCmd, $"Expected AI to acquire open-LOS target and fire immediately (phase={phase}, t={t})");
} }
@ -484,7 +493,8 @@ namespace RustToDust.Tests
// Move laterally behind cover to verify AI never steers/aims toward hidden coords // Move laterally behind cover to verify AI never steers/aims toward hidden coords
session.SetContenderPose(player.Id, box.X + (occTick % 2 == 0 ? 1.5f : -1.5f), box.Z + box.HalfZ + 8f, yaw: 0f); session.SetContenderPose(player.Id, box.X + (occTick % 2 == 0 ? 1.5f : -1.5f), box.Z + box.HalfZ + 8f, yaw: 0f);
} }
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.Null(ai.AiTargetContenderId); Assert.Null(ai.AiTargetContenderId);
Assert.False(ai.FireCmd, $"AI leaked FireCmd on occluded tick {occTick} (phase={phase})"); Assert.False(ai.FireCmd, $"AI leaked FireCmd on occluded tick {occTick} (phase={phase})");
@ -497,9 +507,9 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void PlayerDetectedByCount_StaysExactZero_UnderAsymmetricCover_NoFlicker() public void PlayerDetectedByCount_StaysExactZero_UnderAsymmetricCover_NoFlicker()
{ {
using var session = new ArenaSession(seed: 12); using var session = new ArenaSession(seed: 12, slot0Human: true);
var box = session.State.ArenaCoverBoxes.First(b => b.HalfY >= 2.8f); var box = session.State.ArenaCoverBoxes.First(b => b.HalfY >= 2.8f);
var player = session.State.Player; var player = session.State.Contenders[0];
var rival = session.State.Contenders[1]; var rival = session.State.Contenders[1];
// Move all other rivals and spectators far away (> 500m) so only rival <-> player is tested // Move all other rivals and spectators far away (> 500m) so only rival <-> player is tested
@ -536,10 +546,12 @@ namespace RustToDust.Tests
// Re-pin poses each tick so drift never alters cover geometry // Re-pin poses each tick so drift never alters cover geometry
session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 4f); session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 4f);
session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 40f); session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 40f);
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.True(session.State.ContenderContacts[rival.Id].VisibleToPlayer); var obs0 = session.State.GetOrCreateObserverState(0);
Assert.Equal(0, session.State.PlayerDetectedByCount); Assert.True(obs0.ContenderContacts[rival.Id].VisibleToPlayer);
Assert.Equal(0, obs0.DetectedByCount);
} }
} }

View file

@ -50,7 +50,7 @@ namespace RustToDust.Tests
// 1. Walk, turn, and climb slopes across all 7 mechs + exemplar_frame // 1. Walk, turn, and climb slopes across all 7 mechs + exemplar_frame
foreach (var spec in specs) foreach (var spec in specs)
{ {
using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert); using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++) for (int i = 1; i < session.State.Contenders.Count; i++)
{ {
session.SetContenderPose(i, 500f + i * 16f, 500f); session.SetContenderPose(i, 500f + i * 16f, 500f);
@ -59,8 +59,8 @@ namespace RustToDust.Tests
// Phase A: start on flat/gentle ground near origin (60 ticks) to verify honest walk slip < 8cm // Phase A: start on flat/gentle ground near origin (60 ticks) to verify honest walk slip < 8cm
session.SetContenderPose(0, 0f, 0f, 0f); session.SetContenderPose(0, 0f, 0f, 0f);
session.State.SpawnChassisDrop(0f, 0f, spec); session.State.SpawnChassisDrop(0f, 0f, spec);
Assert.True(session.TrySwapNearbyChassis(), $"Failed swap to {spec.Id}"); Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id}");
var player = session.State.Player; var player = session.State.Contenders[0];
Assert.Equal(spec.Id, player.Grid.Spec.Id); Assert.Equal(spec.Id, player.Grid.Spec.Id);
var ws = session.GetWalkerState(true, player.Id); var ws = session.GetWalkerState(true, player.Id);
@ -70,7 +70,7 @@ namespace RustToDust.Tests
for (int t = 0; t < 60; t++) for (int t = 0; t < 60; t++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 0.45f, Throttle: 0.45f,
Steer: 0f, Steer: 0f,
AimWorldX: player.X, AimWorldX: player.X,
@ -78,6 +78,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
} }
Assert.True(ws.MaxFootSlipM < 0.08f, Assert.True(ws.MaxFootSlipM < 0.08f,
$"{spec.Id}: normal walk foot slip {ws.MaxFootSlipM:F4}m >= 0.08m (maxSpd={spec.MaxSpeed:F1})"); $"{spec.Id}: normal walk foot slip {ws.MaxFootSlipM:F4}m >= 0.08m (maxSpd={spec.MaxSpeed:F1})");
@ -123,7 +124,7 @@ namespace RustToDust.Tests
for (int t = 0; t < 180; t++) for (int t = 0; t < 180; t++)
{ {
float steer = MathF.Sin(t * 0.06f) * 0.65f; float steer = MathF.Sin(t * 0.06f) * 0.65f;
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 0.85f, Throttle: 0.85f,
Steer: steer, Steer: steer,
AimWorldX: player.X + 40f * MathF.Sin(player.Yaw), AimWorldX: player.X + 40f * MathF.Sin(player.Yaw),
@ -131,6 +132,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
Assert.True(float.IsFinite(player.X) && float.IsFinite(player.Y) && float.IsFinite(player.Z), Assert.True(float.IsFinite(player.X) && float.IsFinite(player.Y) && float.IsFinite(player.Z),
$"{spec.Id}: non-finite pose at tick {t}"); $"{spec.Id}: non-finite pose at tick {t}");
@ -199,7 +201,7 @@ namespace RustToDust.Tests
// 2. Benchmark 12 simultaneous mechs CPU < 1.5 ms/tick // 2. Benchmark 12 simultaneous mechs CPU < 1.5 ms/tick
{ {
using var benchSession = new ArenaSession(seed: 99, mapKind: ArenaMapKind.Desert); using var benchSession = new ArenaSession(seed: 99, mapKind: ArenaMapKind.Desert, slot0Human: true);
for (int i = 0; i < benchSession.State.Contenders.Count; i++) for (int i = 0; i < benchSession.State.Contenders.Count; i++)
{ {
var spec = specs[i % 7]; var spec = specs[i % 7];
@ -225,7 +227,8 @@ namespace RustToDust.Tests
// Warmup JIT // Warmup JIT
for (int w = 0; w < 20; w++) for (int w = 0; w < 20; w++)
{ {
benchSession.Step(new PlayerInput(0.8f, 0.2f, 0f, 100f, false, false, false)); benchSession.SetHumanInput(0, new PlayerInput(0.8f, 0.2f, 0f, 100f, false, false, false));
benchSession.Step();
} }
var view = benchSession.World.View; var view = benchSession.World.View;
@ -261,16 +264,16 @@ namespace RustToDust.Tests
Span<float> legIntegrities = stackalloc float[4]; Span<float> legIntegrities = stackalloc float[4];
foreach (var spec in new[] { Catalog.Breaker, Catalog.Bastion }) foreach (var spec in new[] { Catalog.Breaker, Catalog.Bastion })
{ {
using var session = new ArenaSession(seed: 17, mapKind: ArenaMapKind.Desert); using var session = new ArenaSession(seed: 17, mapKind: ArenaMapKind.Desert, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++) for (int i = 1; i < session.State.Contenders.Count; i++)
{ {
session.SetContenderPose(i, 450f + i * 16f, 450f); session.SetContenderPose(i, 450f + i * 16f, 450f);
} }
session.SetContenderPose(0, 0f, 0f, 0f); session.SetContenderPose(0, 0f, 0f, 0f);
session.State.SpawnChassisDrop(0f, 0f, spec); session.State.SpawnChassisDrop(0f, 0f, spec);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
var player = session.State.Player; var player = session.State.Contenders[0];
var grid = player.Grid; var grid = player.Grid;
// Strip all left-leg cells (Breaker Coronal L: y>=H-2, x<W/2; Bastion Dorsal FL: y<H/2, x<W/2) // Strip all left-leg cells (Breaker Coronal L: y>=H-2, x<W/2; Bastion Dorsal FL: y<H/2, x<W/2)
@ -310,7 +313,7 @@ namespace RustToDust.Tests
for (int t = 0; t < 180; t++) for (int t = 0; t < 180; t++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 0.9f, Throttle: 0.9f,
Steer: 0f, Steer: 0f,
AimWorldX: player.X, AimWorldX: player.X,
@ -318,6 +321,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
Assert.True(float.IsFinite(player.X) && float.IsFinite(player.Y) && float.IsFinite(player.Z)); Assert.True(float.IsFinite(player.X) && float.IsFinite(player.Y) && float.IsFinite(player.Z));
peakLeftGrf = MathF.Max(peakLeftGrf, ws.LastGrfY[0]); peakLeftGrf = MathF.Max(peakLeftGrf, ws.LastGrfY[0]);
@ -346,12 +350,12 @@ namespace RustToDust.Tests
{ {
foreach (var spec in new[] { Catalog.Breaker, Catalog.Manticore }) foreach (var spec in new[] { Catalog.Breaker, Catalog.Manticore })
{ {
using var session = new ArenaSession(seed: 7, mapKind: ArenaMapKind.Desert); using var session = new ArenaSession(seed: 7, mapKind: ArenaMapKind.Desert, slot0Human: true);
session.SetContenderPose(0, 0f, 0f, 0f); session.SetContenderPose(0, 0f, 0f, 0f);
session.State.SpawnChassisDrop(0f, 0f, spec); session.State.SpawnChassisDrop(0f, 0f, spec);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
var player = session.State.Player; var player = session.State.Contenders[0];
var body = session.GetContenderBody(player.Id)!.Value; var body = session.GetContenderBody(player.Id)!.Value;
var view = session.World.View; var view = session.World.View;
int lane = body.Lane; int lane = body.Lane;
@ -395,7 +399,8 @@ namespace RustToDust.Tests
bool sawAirborneTick = false; bool sawAirborneTick = false;
for (int t = 0; t < 20; t++) for (int t = 0; t < 20; t++)
{ {
session.Step(new PlayerInput(1f, 0f, 0f, 50f, false, false, false)); session.SetHumanInput(0, new PlayerInput(1f, 0f, 0f, 50f, false, false, false));
session.Step();
if (ws.IsAirborne) if (ws.IsAirborne)
{ {
sawAirborneTick = true; sawAirborneTick = true;
@ -427,7 +432,7 @@ namespace RustToDust.Tests
foreach (float yawDeg in yawsDeg) foreach (float yawDeg in yawsDeg)
{ {
float yawRad = yawDeg * MathF.PI / 180f; float yawRad = yawDeg * MathF.PI / 180f;
using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert); using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++) for (int i = 1; i < session.State.Contenders.Count; i++)
{ {
session.SetContenderPose(i, 500f + i * 16f, 500f); session.SetContenderPose(i, 500f + i * 16f, 500f);
@ -435,14 +440,15 @@ namespace RustToDust.Tests
session.SetContenderPose(0, 0f, 0f, yawRad); session.SetContenderPose(0, 0f, 0f, yawRad);
session.State.SpawnChassisDrop(0f, 0f, spec); session.State.SpawnChassisDrop(0f, 0f, spec);
Assert.True(session.TrySwapNearbyChassis(), $"Failed swap to {spec.Id}"); Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id}");
session.SetContenderPose(0, 0f, 0f, yawRad); session.SetContenderPose(0, 0f, 0f, yawRad);
var player = session.State.Player; var player = session.State.Contenders[0];
// Lettle -> Wait 5 idle ticks to verify zero rest creep from dead stop // Lettle -> Wait 5 idle ticks to verify zero rest creep from dead stop
for (int t = 0; t < 5; t++) for (int t = 0; t < 5; t++)
{ {
session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false));
session.Step();
} }
Vector2 cmdFwd = new(MathF.Sin(yawRad), MathF.Cos(yawRad)); Vector2 cmdFwd = new(MathF.Sin(yawRad), MathF.Cos(yawRad));
@ -452,7 +458,7 @@ namespace RustToDust.Tests
Vector2 wStart = new(player.X, player.Z); Vector2 wStart = new(player.X, player.Z);
for (int t = 0; t < 120; t++) for (int t = 0; t < 120; t++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 1f, Throttle: 1f,
Steer: 0f, Steer: 0f,
AimWorldX: player.X + cmdFwd.X * 50f, AimWorldX: player.X + cmdFwd.X * 50f,
@ -460,6 +466,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
} }
float endWSpeed = player.Speed; float endWSpeed = player.Speed;
Vector2 wDelta = new Vector2(player.X, player.Z) - wStart; Vector2 wDelta = new Vector2(player.X, player.Z) - wStart;
@ -477,7 +484,7 @@ namespace RustToDust.Tests
Vector2 finalWindowStart = Vector2.Zero; Vector2 finalWindowStart = Vector2.Zero;
for (int t = 0; t < 180; t++) for (int t = 0; t < 180; t++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 0f, Throttle: 0f,
Steer: 0f, Steer: 0f,
AimWorldX: player.X + cmdFwd.X * 50f, AimWorldX: player.X + cmdFwd.X * 50f,
@ -485,6 +492,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
if (timeToStop < 0f && player.Speed < 0.30f) if (timeToStop < 0f && player.Speed < 0.30f)
{ {
@ -515,7 +523,7 @@ namespace RustToDust.Tests
Vector2 revDir = new(MathF.Sin(player.Yaw), MathF.Cos(player.Yaw)); Vector2 revDir = new(MathF.Sin(player.Yaw), MathF.Cos(player.Yaw));
for (int t = 0; t < 90; t++) for (int t = 0; t < 90; t++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: -1f, Throttle: -1f,
Steer: 0f, Steer: 0f,
AimWorldX: player.X + revDir.X * 50f, AimWorldX: player.X + revDir.X * 50f,
@ -523,6 +531,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
} }
float revDisp = Vector2.Dot(new Vector2(player.X, player.Z) - sStart, -revDir); float revDisp = Vector2.Dot(new Vector2(player.X, player.Z) - sStart, -revDir);
Assert.True(revDisp >= 3.0f, Assert.True(revDisp >= 3.0f,
@ -531,7 +540,8 @@ namespace RustToDust.Tests
// Settle until stopped before turning test // Settle until stopped before turning test
for (int t = 0; t < 180 && (t < 20 || player.Speed > 0.05f); t++) for (int t = 0; t < 180 && (t < 20 || player.Speed > 0.05f); t++)
{ {
session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false));
session.Step();
} }
// 4. Hold D (Steer = +1, Throttle = 0) for 1.5s (90 ticks) // 4. Hold D (Steer = +1, Throttle = 0) for 1.5s (90 ticks)
@ -540,7 +550,7 @@ namespace RustToDust.Tests
float accumYaw = 0f; float accumYaw = 0f;
for (int t = 0; t < 90; t++) for (int t = 0; t < 90; t++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 0f, Throttle: 0f,
Steer: 1f, Steer: 1f,
AimWorldX: player.X, AimWorldX: player.X,
@ -548,6 +558,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
accumYaw += MatchRules.NormalizeAngle(player.Yaw - prevYaw); accumYaw += MatchRules.NormalizeAngle(player.Yaw - prevYaw);
prevYaw = player.Yaw; prevYaw = player.Yaw;
} }
@ -573,7 +584,7 @@ namespace RustToDust.Tests
{ {
foreach (var spec in new[] { Catalog.Breaker, Catalog.Bastion }) foreach (var spec in new[] { Catalog.Breaker, Catalog.Bastion })
{ {
using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion); using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++) for (int i = 1; i < session.State.Contenders.Count; i++)
{ {
session.SetContenderPose(i, 900f + i * 16f, 900f); session.SetContenderPose(i, 900f + i * 16f, 900f);
@ -581,8 +592,8 @@ namespace RustToDust.Tests
var sion = session.State.SionMap!; var sion = session.State.SionMap!;
// Find a clear sloped hillside on Sion (slope ~7-18 deg, free of buildings and low wall meshes along a +/-7m corridor) // Find a clear sloped hillside on Sion (slope ~7-18 deg, free of buildings and low wall meshes along a +/-7m corridor)
float slopeX = session.State.Player.X; float slopeX = session.State.Contenders[0].X;
float slopeZ = session.State.Player.Z; float slopeZ = session.State.Contenders[0].Z;
float slopeYaw = 0f; float slopeYaw = 0f;
bool foundSlope = false; bool foundSlope = false;
for (float r = 40f; r <= 560f && !foundSlope; r += 20f) for (float r = 40f; r <= 560f && !foundSlope; r += 20f)
@ -642,9 +653,9 @@ namespace RustToDust.Tests
session.SetContenderPose(0, slopeX, slopeZ, slopeYaw); session.SetContenderPose(0, slopeX, slopeZ, slopeYaw);
session.State.SpawnChassisDrop(slopeX, slopeZ, spec); session.State.SpawnChassisDrop(slopeX, slopeZ, spec);
Assert.True(session.TrySwapNearbyChassis(), $"Failed swap to {spec.Id} on Sion"); Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id} on Sion");
session.SetContenderPose(0, slopeX, slopeZ, slopeYaw); session.SetContenderPose(0, slopeX, slopeZ, slopeYaw);
var player = session.State.Player; var player = session.State.Contenders[0];
// 1. Drive forward up/along slope (2.0s) // 1. Drive forward up/along slope (2.0s)
Vector2 startPos = new(player.X, player.Z); Vector2 startPos = new(player.X, player.Z);
@ -654,7 +665,7 @@ namespace RustToDust.Tests
float startY = player.Y; float startY = player.Y;
for (int t = 0; t < 120; t++) for (int t = 0; t < 120; t++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 1f, Throttle: 1f,
Steer: 0f, Steer: 0f,
AimWorldX: player.X + fwdDir.X * 50f, AimWorldX: player.X + fwdDir.X * 50f,
@ -662,6 +673,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
} }
float gEnd = session.State.Terrain.SampleHeight(player.X, player.Z); float gEnd = session.State.Terrain.SampleHeight(player.X, player.Z);
float fwdDisp = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir); float fwdDisp = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir);
@ -685,7 +697,8 @@ namespace RustToDust.Tests
float accumYaw = 0f; float accumYaw = 0f;
for (int t = 0; t < 90; t++) for (int t = 0; t < 90; t++)
{ {
session.Step(new PlayerInput(0f, 1f, player.X, player.Z + 50f, false, false, false)); session.SetHumanInput(0, new PlayerInput(0f, 1f, player.X, player.Z + 50f, false, false, false));
session.Step();
accumYaw += MatchRules.NormalizeAngle(player.Yaw - prevYaw); accumYaw += MatchRules.NormalizeAngle(player.Yaw - prevYaw);
prevYaw = player.Yaw; prevYaw = player.Yaw;
} }
@ -697,7 +710,8 @@ namespace RustToDust.Tests
Vector2 finalWinStart = Vector2.Zero; Vector2 finalWinStart = Vector2.Zero;
for (int t = 0; t < 180; t++) for (int t = 0; t < 180; t++)
{ {
session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false));
session.Step();
if (timeToStop < 0f && player.Speed < 0.35f) timeToStop = (t + 1) * ArenaSession.FixedDt; if (timeToStop < 0f && player.Speed < 0.35f) timeToStop = (t + 1) * ArenaSession.FixedDt;
if (t == 71) speedAt1_2s = player.Speed; if (t == 71) speedAt1_2s = player.Speed;
if (t == 119) finalWinStart = new Vector2(player.X, player.Z); if (t == 119) finalWinStart = new Vector2(player.X, player.Z);
@ -714,7 +728,7 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void HybridB_Bastion_SteepSionHills_15To22Deg_ClimbsWithoutBeaching() public void HybridB_Bastion_SteepSionHills_15To22Deg_ClimbsWithoutBeaching()
{ {
using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion); using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++) for (int i = 1; i < session.State.Contenders.Count; i++)
{ {
session.SetContenderPose(i, 900f + i * 16f, 900f); session.SetContenderPose(i, 900f + i * 16f, 900f);
@ -775,8 +789,8 @@ namespace RustToDust.Tests
session.SetContenderPose(0, sites[0].X, sites[0].Z, sites[0].Yaw); session.SetContenderPose(0, sites[0].X, sites[0].Z, sites[0].Yaw);
session.State.SpawnChassisDrop(sites[0].X, sites[0].Z, Catalog.Bastion); session.State.SpawnChassisDrop(sites[0].X, sites[0].Z, Catalog.Bastion);
Assert.True(session.TrySwapNearbyChassis(), "Failed swap to Bastion on Sion"); Assert.True(session.TrySwapNearbyChassis(0), "Failed swap to Bastion on Sion");
var player = session.State.Player; var player = session.State.Contenders[0];
foreach (var site in sites) foreach (var site in sites)
{ {
@ -787,7 +801,7 @@ namespace RustToDust.Tests
for (int t = 0; t < 120; t++) for (int t = 0; t < 120; t++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 1f, Throttle: 1f,
Steer: 0f, Steer: 0f,
AimWorldX: player.X + fwdDir.X * 50f, AimWorldX: player.X + fwdDir.X * 50f,
@ -795,6 +809,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
} }
float disp2s = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir); float disp2s = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir);
@ -845,7 +860,7 @@ namespace RustToDust.Tests
{ {
foreach (var spec in new[] { Catalog.Bastion, Catalog.Manticore }) foreach (var spec in new[] { Catalog.Bastion, Catalog.Manticore })
{ {
using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert); using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: true);
for (int i = 2; i < session.State.Contenders.Count; i++) for (int i = 2; i < session.State.Contenders.Count; i++)
{ {
session.SetContenderPose(i, 900f + i * 16f, 900f); session.SetContenderPose(i, 900f + i * 16f, 900f);
@ -860,7 +875,8 @@ namespace RustToDust.Tests
session.SetContenderPose(0, 0f, 0f, 0f); session.SetContenderPose(0, 0f, 0f, 0f);
for (int t = 0; t < 45; t++) for (int t = 0; t < 45; t++)
{ {
session.Step(new PlayerInput(0f, 0f, 0f, 80f, false, false, false)); session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 80f, false, false, false));
session.Step();
} }
var target = session.State.Contenders[1]; var target = session.State.Contenders[1];
@ -925,7 +941,7 @@ namespace RustToDust.Tests
foreach (var spec in new[] { Catalog.Bastion, Catalog.Manticore }) foreach (var spec in new[] { Catalog.Bastion, Catalog.Manticore })
{ {
using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion); using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++) for (int i = 1; i < session.State.Contenders.Count; i++)
{ {
session.SetContenderPose(i, 900f + i * 16f, 900f); session.SetContenderPose(i, 900f + i * 16f, 900f);
@ -933,8 +949,8 @@ namespace RustToDust.Tests
session.SetContenderPose(0, failingSites[0].X, failingSites[0].Z, 0f); session.SetContenderPose(0, failingSites[0].X, failingSites[0].Z, 0f);
session.State.SpawnChassisDrop(failingSites[0].X, failingSites[0].Z, spec); session.State.SpawnChassisDrop(failingSites[0].X, failingSites[0].Z, spec);
Assert.True(session.TrySwapNearbyChassis(), $"Failed swap to {spec.Id}"); Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id}");
var player = session.State.Player; var player = session.State.Contenders[0];
foreach (var site in failingSites) foreach (var site in failingSites)
{ {
@ -948,7 +964,7 @@ namespace RustToDust.Tests
for (int t = 0; t < 120; t++) for (int t = 0; t < 120; t++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 1f, Throttle: 1f,
Steer: 0f, Steer: 0f,
AimWorldX: player.X + fwdDir.X * 50f, AimWorldX: player.X + fwdDir.X * 50f,
@ -956,6 +972,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
} }
float disp2s = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir); float disp2s = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir);
@ -973,7 +990,7 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void HybridB_Bastion_StationaryFacingHill_DoesNotHyperExtendLegs() public void HybridB_Bastion_StationaryFacingHill_DoesNotHyperExtendLegs()
{ {
using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion); using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++) for (int i = 1; i < session.State.Contenders.Count; i++)
{ {
session.SetContenderPose(i, 900f + i * 16f, 900f); session.SetContenderPose(i, 900f + i * 16f, 900f);
@ -986,10 +1003,10 @@ namespace RustToDust.Tests
session.SetContenderPose(0, siteX, siteZ, uphillYaw); session.SetContenderPose(0, siteX, siteZ, uphillYaw);
session.State.SpawnChassisDrop(siteX, siteZ, Catalog.Bastion); session.State.SpawnChassisDrop(siteX, siteZ, Catalog.Bastion);
Assert.True(session.TrySwapNearbyChassis(), "Failed swap to Bastion at Site#0"); Assert.True(session.TrySwapNearbyChassis(0), "Failed swap to Bastion at Site#0");
session.SetContenderPose(0, siteX, siteZ, uphillYaw); session.SetContenderPose(0, siteX, siteZ, uphillYaw);
var player = session.State.Player; var player = session.State.Contenders[0];
var ws = session.GetWalkerState(true, player.Id)!; var ws = session.GetWalkerState(true, player.Id)!;
float modelRide = WalkerLocomotion.GetRideHeight(Catalog.Bastion); float modelRide = WalkerLocomotion.GetRideHeight(Catalog.Bastion);
float maxRelCom = 0f; float maxRelCom = 0f;
@ -997,7 +1014,7 @@ namespace RustToDust.Tests
for (int t = 0; t < 120; t++) for (int t = 0; t < 120; t++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 0f, Throttle: 0f,
Steer: 0f, Steer: 0f,
AimWorldX: player.X + MathF.Sin(uphillYaw) * 50f, AimWorldX: player.X + MathF.Sin(uphillYaw) * 50f,
@ -1005,6 +1022,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
float groundY = session.State.Terrain.SampleHeight(player.X, player.Z); float groundY = session.State.Terrain.SampleHeight(player.X, player.Z);
float relCom = player.Y - groundY; float relCom = player.Y - groundY;

View file

@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RustToDust.Core;
using RustToDust.Ymir;
using Xunit;
namespace RustToDust.Tests
{
public sealed class MultiplayerSimulationTests
{
[Fact]
public void TwoHumanSlots_DriveFireSwapAndMatchPhaseStaysActiveUntilSoleSurvivor()
{
using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: false);
session.SetHumanSlot(0, true, "Alpha");
session.SetHumanSlot(5, true, "Bravo");
Assert.True(session.State.Contenders[0].IsHuman);
Assert.True(session.State.Contenders[5].IsHuman);
Assert.False(session.State.Contenders[1].IsHuman);
var h0 = session.State.Contenders[0];
var h5 = session.State.Contenders[5];
session.SetContenderPose(0, -30f, 0f, 0f);
session.SetContenderPose(5, 30f, 0f, 0f);
// Place Rival 2 in open LOS for h0, and behind tall mesa or far away from h5
session.SetContenderPose(2, -30f, 55f, MathF.PI);
float h0StartZ = h0.Z;
float h5StartZ = h5.Z;
var events = new List<ISimEvent>();
for (int t = 0; t < 45; t++)
{
session.SetHumanInput(0, new PlayerInput(1f, 0f, -30f, 55f, Fire: true, InteractPickup: false, Brake: false));
session.SetHumanInput(5, new PlayerInput(-1f, 0.3f, 30f, -50f, Fire: false, InteractPickup: false, Brake: false));
session.Step();
session.DrainStepEvents(events);
}
Assert.True(h0.Z > h0StartZ + 3f, $"Human 0 should drive forward independently, deltaZ={h0.Z - h0StartZ:F2}");
Assert.True(h5.Z < h5StartZ - 2f, $"Human 5 should reverse independently, deltaZ={h5.Z - h5StartZ:F2}");
Assert.Contains(events, e => e is ShotFiredEvent sf && !sf.IsSpectatorShooter && sf.ShooterId == 0);
Assert.Contains(events, e => e is HitImpactEvent hi && hi.IsContenderShooter && hi.ShooterId == 0 && hi.ArmorDamage > 0f);
// Kill slot 0 -> match MUST stay Active while multiple contenders remain!
h0.Grid.ApplyHit(0f, 0f, 0.5f, 50000f, 0f);
Assert.False(h0.Alive);
MatchRules.UpdateMatchOutcome(session.State);
Assert.Equal(MatchPhase.Active, session.State.Phase);
// Kill all contenders except slot 5 -> MatchPhase becomes Completed and WinnerContenderId == 5!
for (int i = 0; i < session.State.Contenders.Count; i++)
{
if (i != 5 && session.State.Contenders[i].Alive)
{
session.State.Contenders[i].Grid.ApplyHit(0f, 0f, 0.5f, 50000f, 0f);
}
}
MatchRules.UpdateMatchOutcome(session.State);
Assert.Equal(MatchPhase.Completed, session.State.Phase);
Assert.Equal(5, session.State.WinnerContenderId);
}
[Fact]
public void PerObserverDetectionIsolation_Human0SeesRivalWhileOccludedHuman5DoesNot()
{
using var session = new ArenaSession(seed: 12, mapKind: ArenaMapKind.Desert, slot0Human: false);
session.SetHumanSlot(0, true, "Alpha");
session.SetHumanSlot(5, true, "Bravo");
var box = session.State.ArenaCoverBoxes[0];
var h0 = session.State.Contenders[0];
var h5 = session.State.Contenders[5];
var rival = session.State.Contenders[2];
// Move others far away
for (int i = 0; i < session.State.Contenders.Count; i++)
{
if (i != 0 && i != 5 && i != 2)
{
session.SetContenderPose(i, -650f + i * 12f, -650f);
}
}
// Place h0 and rival on same open side of cover wall; place h5 behind cover wall
session.SetContenderPose(h0.Id, box.X - 10f, box.Z - box.HalfZ - 12f, 0f);
session.SetContenderPose(rival.Id, box.X + 4f, box.Z - box.HalfZ - 12f, 0f);
session.SetContenderPose(h5.Id, box.X + 4f, box.Z + box.HalfZ + 8f, 0f);
session.SetHumanInput(0, new PlayerInput(0f, 0f, rival.X, rival.Z, false, false, true));
session.SetHumanInput(5, new PlayerInput(0f, 0f, h5.X, h5.Z, false, false, true));
session.Step();
var obs0 = session.State.ObserverStates[0];
var obs5 = session.State.ObserverStates[5];
Assert.True(obs0.ContenderContacts[rival.Id].VisibleToPlayer);
Assert.False(obs5.ContenderContacts[rival.Id].VisibleToPlayer);
Assert.False(MatchState.IsContactOnRadar(obs5.ContenderContacts[rival.Id]));
Assert.Equal(0, obs5.DetectedByCount);
}
[Fact]
public void LocalArenaSession_ImplementsUnifiedClientBoundary()
{
using var local = new LocalArenaSession(seed: 42, ArenaMapKind.Desert, "TestSolo");
Assert.Equal(0, local.LocalContenderId);
Assert.Equal("TestSolo", local.LocalContender.Name);
Assert.Equal(ClientMatchOutcome.Active, local.LocalOutcome);
Assert.Equal(NetworkMode.Solo, local.ConnectionStatus.Mode);
float startZ = local.LocalContender.Z;
for (int t = 0; t < 30; t++)
{
local.SubmitLocalInput(new PlayerInput(1f, 0f, local.LocalContender.X, local.LocalContender.Z + 50f, false, false, false), isPhysicsTick: true);
}
var (pos, _, _) = local.GetInterpolatedContenderPose(0, 1f);
Assert.NotEqual(startZ, pos.Z);
}
}
}

View file

@ -92,9 +92,10 @@ namespace RustToDust.Tests
} }
// 4. Zero tick-0 spawn ambush // 4. Zero tick-0 spawn ambush
var player = state.Player; var player = state.Contenders[0];
float initialHp = player.Grid.CoreHp; float initialHp = player.Grid.CoreHp;
session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 10f, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 10f, false, false, true));
session.Step();
for (int i = 1; i < state.Contenders.Count; i++) for (int i = 1; i < state.Contenders.Count; i++)
{ {
@ -111,9 +112,9 @@ namespace RustToDust.Tests
{ {
// Part A: AI Jackal (950 kg) must pick up Hornet (820 kg) via GetChassisUpgradeScore (> 0) // Part A: AI Jackal (950 kg) must pick up Hornet (820 kg) via GetChassisUpgradeScore (> 0)
{ {
using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert); using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true);
IsolateContenders(session, 0, 1); IsolateContenders(session, 0, 1);
var player = session.State.Player; var player = session.State.Contenders[0];
var ai = session.State.Contenders[1]; var ai = session.State.Contenders[1];
// Clear unrelated drops so Hornet is the clean target // Clear unrelated drops so Hornet is the clean target
@ -131,7 +132,8 @@ namespace RustToDust.Tests
for (int tick = 0; tick < 240 && ai.Grid.Spec.Id == Catalog.Jackal.Id; tick++) for (int tick = 0; tick < 240 && ai.Grid.Spec.Id == Catalog.Jackal.Id; tick++)
{ {
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
} }
Assert.Equal(Catalog.Hornet.Id, ai.Grid.Spec.Id); Assert.Equal(Catalog.Hornet.Id, ai.Grid.Spec.Id);
@ -139,9 +141,9 @@ namespace RustToDust.Tests
// Part B: AI Jackal picks up heavy mech drop (Breaker) // Part B: AI Jackal picks up heavy mech drop (Breaker)
{ {
using var session = new ArenaSession(seed: 77, ArenaMapKind.Desert); using var session = new ArenaSession(seed: 77, ArenaMapKind.Desert, slot0Human: true);
IsolateContenders(session, 0, 1); IsolateContenders(session, 0, 1);
var player = session.State.Player; var player = session.State.Contenders[0];
var ai = session.State.Contenders[1]; var ai = session.State.Contenders[1];
foreach (var d in session.State.GroundDrops) foreach (var d in session.State.GroundDrops)
@ -156,7 +158,8 @@ namespace RustToDust.Tests
session.State.SpawnChassisDrop(0f, 48f, Catalog.Breaker); session.State.SpawnChassisDrop(0f, 48f, Catalog.Breaker);
for (int tick = 0; tick < 240 && ai.Grid.Spec.Id == Catalog.Jackal.Id; tick++) for (int tick = 0; tick < 240 && ai.Grid.Spec.Id == Catalog.Jackal.Id; tick++)
{ {
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
} }
Assert.Equal(Catalog.Breaker.Id, ai.Grid.Spec.Id); Assert.Equal(Catalog.Breaker.Id, ai.Grid.Spec.Id);
@ -167,10 +170,10 @@ namespace RustToDust.Tests
public void NaturalizedBotAim_OffAxisSlewAndJinkOvershoot_ZeroOccludedLeak() public void NaturalizedBotAim_OffAxisSlewAndJinkOvershoot_ZeroOccludedLeak()
{ {
// 1. 90-degree off-axis slew delay // 1. 90-degree off-axis slew delay
using (var session = new ArenaSession(seed: 42, ArenaMapKind.Desert)) using (var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true))
{ {
IsolateContenders(session, 0, 1); IsolateContenders(session, 0, 1);
var player = session.State.Player; var player = session.State.Contenders[0];
var ai = session.State.Contenders[1]; var ai = session.State.Contenders[1];
// Place AI facing +Z (yaw = 0) and player 60m due +X (90 degrees off-axis) in open LOS // Place AI facing +Z (yaw = 0) and player 60m due +X (90 degrees off-axis) in open LOS
@ -178,7 +181,8 @@ namespace RustToDust.Tests
session.SetContenderPose(player.Id, 60f, 0f, yaw: 0f); session.SetContenderPose(player.Id, 60f, 0f, yaw: 0f);
ai.AiScavengeCooldown = 999f; ai.AiScavengeCooldown = 999f;
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.Equal(player.Id, ai.AiTargetContenderId); Assert.Equal(player.Id, ai.AiTargetContenderId);
Assert.False(ai.FireCmd, "90-degree off-axis AI must not snap-fire on tick 0 before slewing into cone"); Assert.False(ai.FireCmd, "90-degree off-axis AI must not snap-fire on tick 0 before slewing into cone");
@ -186,7 +190,8 @@ namespace RustToDust.Tests
for (int t = 0; t < 75; t++) for (int t = 0; t < 75; t++)
{ {
session.SetContenderPose(player.Id, 60f, 0f, yaw: 0f); session.SetContenderPose(player.Id, 60f, 0f, yaw: 0f);
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
if (ai.FireCmd) if (ai.FireCmd)
{ {
eventuallyFired = true; eventuallyFired = true;
@ -249,11 +254,11 @@ namespace RustToDust.Tests
} }
// 3. Zero occluded fire / target leak when LOS breaks behind cover // 3. Zero occluded fire / target leak when LOS breaks behind cover
using (var session = new ArenaSession(seed: 12, ArenaMapKind.Desert)) using (var session = new ArenaSession(seed: 12, ArenaMapKind.Desert, slot0Human: true))
{ {
IsolateContenders(session, 0, 1); IsolateContenders(session, 0, 1);
var box = session.State.ArenaCoverBoxes[0]; var box = session.State.ArenaCoverBoxes[0];
var player = session.State.Player; var player = session.State.Contenders[0];
var ai = session.State.Contenders[1]; var ai = session.State.Contenders[1];
float aiX = box.X; float aiX = box.X;
@ -262,7 +267,8 @@ namespace RustToDust.Tests
float pz = box.Z - box.HalfZ - 14f; float pz = box.Z - box.HalfZ - 14f;
session.SetContenderPose(ai.Id, aiX, aiZ, MathF.Atan2(px - aiX, pz - aiZ)); session.SetContenderPose(ai.Id, aiX, aiZ, MathF.Atan2(px - aiX, pz - aiZ));
session.SetContenderPose(player.Id, px, pz, 0f); session.SetContenderPose(player.Id, px, pz, 0f);
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.Equal(player.Id, ai.AiTargetContenderId); Assert.Equal(player.Id, ai.AiTargetContenderId);
Assert.True(ai.AimTracker.HasTarget); Assert.True(ai.AimTracker.HasTarget);
@ -272,7 +278,8 @@ namespace RustToDust.Tests
for (int t = 0; t < 10; t++) for (int t = 0; t < 10; t++)
{ {
session.SetContenderPose(player.Id, box.X + (t % 2 == 0 ? 2f : -2f), box.Z + box.HalfZ + 8f, 0f); session.SetContenderPose(player.Id, box.X + (t % 2 == 0 ? 2f : -2f), box.Z + box.HalfZ + 8f, 0f);
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.Null(ai.AiTargetContenderId); Assert.Null(ai.AiTargetContenderId);
Assert.False(ai.FireCmd); Assert.False(ai.FireCmd);
@ -286,14 +293,14 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void RenderInterpolation_CameraAnchorAndContenderPose_ZeroHorizPhaseMismatchAcrossAlpha() public void RenderInterpolation_CameraAnchorAndContenderPose_ZeroHorizPhaseMismatchAcrossAlpha()
{ {
using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert); using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true);
IsolateContenders(session, 0); IsolateContenders(session, 0);
var player = session.State.Player; var player = session.State.Contenders[0];
// Accelerate player forward for 30 ticks so Prev != Curr with genuine horizontal displacement & rotation // Accelerate player forward for 30 ticks so Prev != Curr with genuine horizontal displacement & rotation
for (int t = 0; t < 30; t++) for (int t = 0; t < 30; t++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 1f, Throttle: 1f,
Steer: 0.35f, Steer: 0.35f,
AimWorldX: player.X + MathF.Sin(player.Yaw) * 40f, AimWorldX: player.X + MathF.Sin(player.Yaw) * 40f,
@ -301,6 +308,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
} }
float stepHoriz = MathF.Sqrt( float stepHoriz = MathF.Sqrt(
@ -337,15 +345,15 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void PointBlankConvergence_LargeChassis_NeverFiresBackward() public void PointBlankConvergence_LargeChassis_NeverFiresBackward()
{ {
using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert); using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true);
IsolateContenders(session, 0, 1); IsolateContenders(session, 0, 1);
var player = session.State.Player; var player = session.State.Contenders[0];
var target = session.State.Contenders[1]; var target = session.State.Contenders[1];
// Swap player to Bastion (largest heavy chassis) and target to Raptor (tall mech, small 0.8m footprint) // Swap player to Bastion (largest heavy chassis) and target to Raptor (tall mech, small 0.8m footprint)
session.SetContenderPose(player.Id, 0f, 0f, yaw: 0f); session.SetContenderPose(player.Id, 0f, 0f, yaw: 0f);
session.State.SpawnChassisDrop(0f, 0f, Catalog.Bastion); session.State.SpawnChassisDrop(0f, 0f, Catalog.Bastion);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal(Catalog.Bastion.Id, player.Grid.Spec.Id); Assert.Equal(Catalog.Bastion.Id, player.Grid.Spec.Id);
session.SetContenderPose(target.Id, 0f, 4.5f, yaw: MathF.PI); session.SetContenderPose(target.Id, 0f, 4.5f, yaw: MathF.PI);
@ -356,14 +364,15 @@ namespace RustToDust.Tests
// Step 1 tick to seat bodies, re-pin poses, then fire point-blank 4.5m in front (+Z) // Step 1 tick to seat bodies, re-pin poses, then fire point-blank 4.5m in front (+Z)
float aimY = player.Y + player.Grid.Spec.HalfHeight * 0.25f; float aimY = player.Y + player.Grid.Spec.HalfHeight * 0.25f;
session.Step(new PlayerInput(0f, 0f, target.X, target.Z, false, false, true, AimWorldY: aimY)); session.SetHumanInput(0, new PlayerInput(0f, 0f, target.X, target.Z, false, false, true, AimWorldY: aimY));
session.Step();
session.SetContenderPose(player.Id, 0f, 0f, yaw: 0f); session.SetContenderPose(player.Id, 0f, 0f, yaw: 0f);
session.SetContenderPose(target.Id, 0f, 4.5f, yaw: MathF.PI); session.SetContenderPose(target.Id, 0f, 4.5f, yaw: MathF.PI);
session.State.Tracers.Clear(); session.State.Tracers.Clear();
aimY = player.Y + player.Grid.Spec.HalfHeight * 0.25f; aimY = player.Y + player.Grid.Spec.HalfHeight * 0.25f;
float targetArmorBefore = target.Grid.TotalArmorRatio(); float targetArmorBefore = target.Grid.TotalArmorRatio();
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 0f, Throttle: 0f,
Steer: 0f, Steer: 0f,
AimWorldX: target.X, AimWorldX: target.X,
@ -372,6 +381,7 @@ namespace RustToDust.Tests
InteractPickup: false, InteractPickup: false,
Brake: true, Brake: true,
AimWorldY: aimY)); AimWorldY: aimY));
session.Step();
float bastionMuzzleY = player.Y + player.Grid.Spec.HalfHeight * 0.25f; float bastionMuzzleY = player.Y + player.Grid.Spec.HalfHeight * 0.25f;
var playerTracers1 = session.State.Tracers var playerTracers1 = session.State.Tracers
@ -396,7 +406,7 @@ namespace RustToDust.Tests
{ {
m.Cooldown = 0f; m.Cooldown = 0f;
} }
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 0f, Throttle: 0f,
Steer: 0f, Steer: 0f,
AimWorldX: target.X, AimWorldX: target.X,
@ -405,6 +415,7 @@ namespace RustToDust.Tests
InteractPickup: false, InteractPickup: false,
Brake: true, Brake: true,
AimWorldY: aimY)); AimWorldY: aimY));
session.Step();
bastionMuzzleY = player.Y + player.Grid.Spec.HalfHeight * 0.25f; bastionMuzzleY = player.Y + player.Grid.Spec.HalfHeight * 0.25f;
var playerTracersFront = session.State.Tracers var playerTracersFront = session.State.Tracers
@ -429,7 +440,7 @@ namespace RustToDust.Tests
{ {
m.Cooldown = 0f; m.Cooldown = 0f;
} }
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 0f, Throttle: 0f,
Steer: 0f, Steer: 0f,
AimWorldX: target.X, AimWorldX: target.X,
@ -438,6 +449,7 @@ namespace RustToDust.Tests
InteractPickup: false, InteractPickup: false,
Brake: true, Brake: true,
AimWorldY: aimY)); AimWorldY: aimY));
session.Step();
bastionMuzzleY = player.Y + player.Grid.Spec.HalfHeight * 0.25f; bastionMuzzleY = player.Y + player.Grid.Spec.HalfHeight * 0.25f;
var playerTracers2 = session.State.Tracers var playerTracers2 = session.State.Tracers
@ -490,9 +502,9 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void AiScavenge_PrefersBetterUpgradeInPickupRange_OverCloserInferiorWreck() public void AiScavenge_PrefersBetterUpgradeInPickupRange_OverCloserInferiorWreck()
{ {
using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert); using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true);
IsolateContenders(session, 0, 1); IsolateContenders(session, 0, 1);
var player = session.State.Player; var player = session.State.Contenders[0];
var ai = session.State.Contenders[1]; var ai = session.State.Contenders[1];
foreach (var d in session.State.GroundDrops) foreach (var d in session.State.GroundDrops)
@ -508,7 +520,8 @@ namespace RustToDust.Tests
session.State.SpawnChassisDrop(0f, 1.5f, Catalog.Jackal); session.State.SpawnChassisDrop(0f, 1.5f, Catalog.Jackal);
session.State.SpawnChassisDrop(0f, 5.5f, Catalog.Hornet); session.State.SpawnChassisDrop(0f, 5.5f, Catalog.Hornet);
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.Equal(Catalog.Hornet.Id, ai.Grid.Spec.Id); Assert.Equal(Catalog.Hornet.Id, ai.Grid.Spec.Id);
} }

View file

@ -16,6 +16,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\src\RustToDust.Core\RustToDust.Core.csproj" /> <ProjectReference Include="..\..\src\RustToDust.Core\RustToDust.Core.csproj" />
<ProjectReference Include="..\..\src\RustToDust.Ymir\RustToDust.Ymir.csproj" /> <ProjectReference Include="..\..\src\RustToDust.Ymir\RustToDust.Ymir.csproj" />
<ProjectReference Include="..\..\src\RustToDust.Net\RustToDust.Net.csproj" />
<ProjectReference Include="$(YmirRoot)/src/Ymir.Box3D/Ymir.Box3D.csproj" AdditionalProperties="YmirNativeConfiguration=$(YmirNativeConfiguration)" /> <ProjectReference Include="$(YmirRoot)/src/Ymir.Box3D/Ymir.Box3D.csproj" AdditionalProperties="YmirNativeConfiguration=$(YmirNativeConfiguration)" />
</ItemGroup> </ItemGroup>

View file

@ -121,9 +121,9 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void Sion_Contenders_ZeroOccludedRadarLeaks_UnderAndOver350m_EveryTick() public void Sion_Contenders_ZeroOccludedRadarLeaks_UnderAndOver350m_EveryTick()
{ {
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion); using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true);
var sion = session.State.SionMap!; var sion = session.State.SionMap!;
var player = session.State.Player; var player = session.State.Contenders[0];
var nearRival = session.State.Contenders[1]; var nearRival = session.State.Contenders[1];
var farRival = session.State.Contenders[2]; var farRival = session.State.Contenders[2];
@ -145,7 +145,8 @@ namespace RustToDust.Tests
var (tempFarX, tempFarZ) = FindClearBuildingAdjacentSpot(sion, -1300f, 1300f); var (tempFarX, tempFarZ) = FindClearBuildingAdjacentSpot(sion, -1300f, 1300f);
SwapToChassis(session, farRival, Catalog.Jackal, tempFarX, tempFarZ); SwapToChassis(session, farRival, Catalog.Jackal, tempFarX, tempFarZ);
session.State.ContenderContacts[nearRival.Id] = new PlayerContactMemory(); var obs0 = session.State.GetOrCreateObserverState(0);
obs0.ContenderContacts[nearRival.Id] = new PlayerContactMemory();
for (int tick = 0; tick < 8; tick++) for (int tick = 0; tick < 8; tick++)
{ {
session.SetContenderPose(player.Id, bldg.CenterX, z1); session.SetContenderPose(player.Id, bldg.CenterX, z1);
@ -154,9 +155,10 @@ namespace RustToDust.Tests
player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z, player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z,
nearRival.X, MatchRules.GetTargetAimY(nearRival.Y, nearRival.Grid.Spec.HalfHeight), nearRival.Z)); nearRival.X, MatchRules.GetTargetAimY(nearRival.Y, nearRival.Grid.Spec.HalfHeight), nearRival.Z));
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
var mem = session.State.ContenderContacts[nearRival.Id]; var mem = obs0.ContenderContacts[nearRival.Id];
Assert.False(mem.VisibleToPlayer, $"Occluded <350m Sion contender leaked VisibleToPlayer on tick {tick}"); Assert.False(mem.VisibleToPlayer, $"Occluded <350m Sion contender leaked VisibleToPlayer on tick {tick}");
Assert.False(mem.HasEverBeenSeen, $"Occluded <350m Sion contender leaked HasEverBeenSeen on tick {tick}"); Assert.False(mem.HasEverBeenSeen, $"Occluded <350m Sion contender leaked HasEverBeenSeen on tick {tick}");
Assert.False(MatchState.IsContactOnRadar(mem), $"Occluded <350m Sion contender leaked onto radar on tick {tick}"); Assert.False(MatchState.IsContactOnRadar(mem), $"Occluded <350m Sion contender leaked onto radar on tick {tick}");
@ -170,7 +172,7 @@ namespace RustToDust.Tests
session.SetContenderPose(player.Id, northX, northZ); session.SetContenderPose(player.Id, northX, northZ);
session.SetContenderPose(farRival.Id, southX, southZ); session.SetContenderPose(farRival.Id, southX, southZ);
session.State.ContenderContacts[farRival.Id] = new PlayerContactMemory(); obs0.ContenderContacts[farRival.Id] = new PlayerContactMemory();
for (int tick = 0; tick < 8; tick++) for (int tick = 0; tick < 8; tick++)
{ {
@ -180,9 +182,10 @@ namespace RustToDust.Tests
player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z, player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z,
farRival.X, MatchRules.GetTargetAimY(farRival.Y, farRival.Grid.Spec.HalfHeight), farRival.Z)); farRival.X, MatchRules.GetTargetAimY(farRival.Y, farRival.Grid.Spec.HalfHeight), farRival.Z));
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
var mem = session.State.ContenderContacts[farRival.Id]; var mem = obs0.ContenderContacts[farRival.Id];
Assert.False(mem.VisibleToPlayer, $"Occluded >350m Sion contender leaked VisibleToPlayer on tick {tick}"); Assert.False(mem.VisibleToPlayer, $"Occluded >350m Sion contender leaked VisibleToPlayer on tick {tick}");
Assert.False(mem.HasEverBeenSeen, $"Occluded >350m Sion contender leaked HasEverBeenSeen on tick {tick}"); Assert.False(mem.HasEverBeenSeen, $"Occluded >350m Sion contender leaked HasEverBeenSeen on tick {tick}");
Assert.False(MatchState.IsContactOnRadar(mem), $"Occluded >350m Sion contender leaked onto radar on tick {tick}"); Assert.False(MatchState.IsContactOnRadar(mem), $"Occluded >350m Sion contender leaked onto radar on tick {tick}");
@ -193,9 +196,9 @@ namespace RustToDust.Tests
public void Sion_Contenders_Over350m_OpenLosDetectedImmediatelyOnEveryTickPhase() public void Sion_Contenders_Over350m_OpenLosDetectedImmediatelyOnEveryTickPhase()
{ {
// Verify >350m contenders with open LOS are never delayed by mod-4 staggering across contenders 1..4 on tick 0. // Verify >350m contenders with open LOS are never delayed by mod-4 staggering across contenders 1..4 on tick 0.
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion); using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true);
var sion = session.State.SionMap!; var sion = session.State.SionMap!;
var player = session.State.Player; var player = session.State.Contenders[0];
var (px, pz) = FindClearBuildingAdjacentSpot(sion, 113f, -211f); var (px, pz) = FindClearBuildingAdjacentSpot(sion, 113f, -211f);
SwapToChassis(session, player, Catalog.Condor, px, pz); SwapToChassis(session, player, Catalog.Condor, px, pz);
@ -226,15 +229,18 @@ namespace RustToDust.Tests
c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z), c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z),
$"Expected clear elevated LOS to contender {c.Id}"); $"Expected clear elevated LOS to contender {c.Id}");
session.State.ContenderContacts[c.Id] = new PlayerContactMemory(); var obs0 = session.State.GetOrCreateObserverState(0);
obs0.ContenderContacts[c.Id] = new PlayerContactMemory();
tested.Add(c); tested.Add(c);
} }
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
var obs0After = session.State.GetOrCreateObserverState(0);
foreach (var c in tested) foreach (var c in tested)
{ {
var mem = session.State.ContenderContacts[c.Id]; var mem = obs0After.ContenderContacts[c.Id];
Assert.True(mem.VisibleToPlayer, $"Contender {c.Id} >350m with open LOS missed tick-0 detection (staggering leak)"); Assert.True(mem.VisibleToPlayer, $"Contender {c.Id} >350m with open LOS missed tick-0 detection (staggering leak)");
Assert.True(MatchState.IsContactOnRadar(mem)); Assert.True(MatchState.IsContactOnRadar(mem));
} }
@ -243,9 +249,9 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void Sion_Spectators_ZeroOccludedLeaks_ZeroTick0Blindspots_AndNo950mHardCull() public void Sion_Spectators_ZeroOccludedLeaks_ZeroTick0Blindspots_AndNo950mHardCull()
{ {
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion); using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true);
var sion = session.State.SionMap!; var sion = session.State.SionMap!;
var player = session.State.Player; var player = session.State.Contenders[0];
// Part 1: Occluded low-signature Exemplar across Valere hill (>450m) never leaks on any tick (0..9) // Part 1: Occluded low-signature Exemplar across Valere hill (>450m) never leaks on any tick (0..9)
var exemplar = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar); var exemplar = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar);
@ -256,7 +262,8 @@ namespace RustToDust.Tests
SwapToChassis(session, player, Catalog.Jackal, northX, northZ); SwapToChassis(session, player, Catalog.Jackal, northX, northZ);
session.SetSpectatorPose(exemplar.Id, southX, southZ); session.SetSpectatorPose(exemplar.Id, southX, southZ);
session.State.SpectatorContacts[exemplar.Id] = new PlayerContactMemory(); var obs0 = session.State.GetOrCreateObserverState(0);
obs0.SpectatorContacts[exemplar.Id] = new PlayerContactMemory();
for (int tick = 0; tick < 10; tick++) for (int tick = 0; tick < 10; tick++)
{ {
@ -266,9 +273,10 @@ namespace RustToDust.Tests
player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z, player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z,
exemplar.X, MatchRules.GetTargetAimY(exemplar.Y, exemplar.Grid.Spec.HalfHeight), exemplar.Z)); exemplar.X, MatchRules.GetTargetAimY(exemplar.Y, exemplar.Grid.Spec.HalfHeight), exemplar.Z));
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
var mem = session.State.SpectatorContacts[exemplar.Id]; var mem = obs0.SpectatorContacts[exemplar.Id];
Assert.False(mem.VisibleToPlayer, $"Occluded Sion Exemplar leaked VisibleToPlayer on tick {tick}"); Assert.False(mem.VisibleToPlayer, $"Occluded Sion Exemplar leaked VisibleToPlayer on tick {tick}");
Assert.False(mem.FaintHorizonPing, $"Occluded Sion Exemplar leaked FaintHorizonPing on tick {tick}"); Assert.False(mem.FaintHorizonPing, $"Occluded Sion Exemplar leaked FaintHorizonPing on tick {tick}");
Assert.False(MatchState.IsContactOnRadar(mem), $"Occluded Sion Exemplar leaked onto radar on tick {tick}"); Assert.False(MatchState.IsContactOnRadar(mem), $"Occluded Sion Exemplar leaked onto radar on tick {tick}");
@ -309,16 +317,17 @@ namespace RustToDust.Tests
s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z), s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z),
$"Expected open elevated LOS to spectator {s.Id} at dist={actualDist:F1}m"); $"Expected open elevated LOS to spectator {s.Id} at dist={actualDist:F1}m");
session.State.SpectatorContacts[s.Id] = new PlayerContactMemory(); obs0.SpectatorContacts[s.Id] = new PlayerContactMemory();
openSpecs.Add(s); openSpecs.Add(s);
} }
// Step ONE tick: all 8 spectators (covering all %4 and %8 phases and >950m) must be visible immediately. // Step ONE tick: all 8 spectators (covering all %4 and %8 phases and >950m) must be visible immediately.
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
foreach (var s in openSpecs) foreach (var s in openSpecs)
{ {
var mem = session.State.SpectatorContacts[s.Id]; var mem = obs0.SpectatorContacts[s.Id];
float d = MathF.Sqrt((s.X - player.X) * (s.X - player.X) + (s.Z - player.Z) * (s.Z - player.Z)); float d = MathF.Sqrt((s.X - player.X) * (s.X - player.X) + (s.Z - player.Z) * (s.Z - player.Z));
Assert.True(mem.VisibleToPlayer, Assert.True(mem.VisibleToPlayer,
$"Open-LOS Sion spectator {s.Id} at {d:F1}m missed tick-0 detection (blindspot or >950m hard cull)"); $"Open-LOS Sion spectator {s.Id} at {d:F1}m missed tick-0 detection (blindspot or >950m hard cull)");
@ -329,9 +338,9 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void Sion_AiContender_NoOddTickTargetDropOrTunnelVision() public void Sion_AiContender_NoOddTickTargetDropOrTunnelVision()
{ {
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion); using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true);
var sion = session.State.SionMap!; var sion = session.State.SionMap!;
var player = session.State.Player; var player = session.State.Contenders[0];
var ai = session.State.Contenders[1]; var ai = session.State.Contenders[1];
var closerRival = session.State.Contenders[2]; var closerRival = session.State.Contenders[2];
@ -357,7 +366,8 @@ namespace RustToDust.Tests
player.X, MatchRules.GetTargetAimY(player.Y, player.Grid.Spec.HalfHeight), player.Z)); player.X, MatchRules.GetTargetAimY(player.Y, player.Grid.Spec.HalfHeight), player.Z));
// Advance 1 tick so ai locks onto player on tick 1 // Advance 1 tick so ai locks onto player on tick 1
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.Equal(player.Id, ai.AiTargetContenderId); Assert.Equal(player.Id, ai.AiTargetContenderId);
// On the next tick (even/odd opposite phase), bring closerRival into open LOS closer than player // On the next tick (even/odd opposite phase), bring closerRival into open LOS closer than player
@ -368,7 +378,8 @@ namespace RustToDust.Tests
ai.X, MatchRules.GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight), ai.Z, ai.X, MatchRules.GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight), ai.Z,
closerRival.X, MatchRules.GetTargetAimY(closerRival.Y, closerRival.Grid.Spec.HalfHeight), closerRival.Z)); closerRival.X, MatchRules.GetTargetAimY(closerRival.Y, closerRival.Grid.Spec.HalfHeight), closerRival.Z));
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.Equal(closerRival.Id, ai.AiTargetContenderId); Assert.Equal(closerRival.Id, ai.AiTargetContenderId);
// 2. Immediate target drop and FireCmd=false across consecutive ticks when LOS breaks behind a Sion building // 2. Immediate target drop and FireCmd=false across consecutive ticks when LOS breaks behind a Sion building
@ -392,7 +403,8 @@ namespace RustToDust.Tests
for (int t = 0; t <= phase; t++) for (int t = 0; t <= phase; t++)
{ {
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.Equal(player.Id, ai.AiTargetContenderId); Assert.Equal(player.Id, ai.AiTargetContenderId);
Assert.True(ai.FireCmd, $"Expected AI to acquire and fire immediately on Sion (phase={phase}, t={t})"); Assert.True(ai.FireCmd, $"Expected AI to acquire and fire immediately on Sion (phase={phase}, t={t})");
} }
@ -404,7 +416,8 @@ namespace RustToDust.Tests
{ {
session.SetContenderPose(ai.Id, bldg.CenterX, z1, yaw: 0f); session.SetContenderPose(ai.Id, bldg.CenterX, z1, yaw: 0f);
session.SetContenderPose(player.Id, bldg.CenterX, z2, yaw: 0f); session.SetContenderPose(player.Id, bldg.CenterX, z2, yaw: 0f);
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
session.Step();
Assert.Null(ai.AiTargetContenderId); Assert.Null(ai.AiTargetContenderId);
Assert.False(ai.FireCmd, $"AI leaked FireCmd through Sion building on occluded tick {occTick} (phase={phase})"); Assert.False(ai.FireCmd, $"AI leaked FireCmd through Sion building on occluded tick {occTick} (phase={phase})");

View file

@ -118,7 +118,7 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void ArenaSession_SionLoadsHeightfieldAndMeshesSpawnsClearBlocksLosAndStepsCleanly() public void ArenaSession_SionLoadsHeightfieldAndMeshesSpawnsClearBlocksLosAndStepsCleanly()
{ {
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion); using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true);
var state = session.State; var state = session.State;
var sion = state.SionMap!; var sion = state.SionMap!;
@ -186,12 +186,12 @@ namespace RustToDust.Tests
$"Expected HasLineOfSight above Sion building {tb.Id} roof ({tb.RoofY:F1}m) to be clear"); $"Expected HasLineOfSight above Sion building {tb.Id} roof ({tb.RoofY:F1}m) to be clear");
// Step 180 ticks (3 seconds) driving & firing: zero NaNs, zero underground falls, player moves cleanly // Step 180 ticks (3 seconds) driving & firing: zero NaNs, zero underground falls, player moves cleanly
var player = state.Player; var player = state.Contenders[0];
float pStartX = player.X; float pStartX = player.X;
float pStartZ = player.Z; float pStartZ = player.Z;
for (int tick = 0; tick < 180; tick++) for (int tick = 0; tick < 180; tick++)
{ {
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 1f, Throttle: 1f,
Steer: MathF.Sin(tick * 0.04f) * 0.25f, Steer: MathF.Sin(tick * 0.04f) * 0.25f,
AimWorldX: player.X + MathF.Sin(player.Yaw) * 60f, AimWorldX: player.X + MathF.Sin(player.Yaw) * 60f,
@ -199,6 +199,7 @@ namespace RustToDust.Tests
Fire: tick % 10 == 0, Fire: tick % 10 == 0,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
for (int cIdx = 0; cIdx < state.Contenders.Count; cIdx++) for (int cIdx = 0; cIdx < state.Contenders.Count; cIdx++)
{ {

View file

@ -151,8 +151,8 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void ArenaSession_BuggyDrivesAcrossDunesWithoutNanAndTracksElevation() public void ArenaSession_BuggyDrivesAcrossDunesWithoutNanAndTracksElevation()
{ {
using var session = new ArenaSession(seed: 42); using var session = new ArenaSession(seed: 42, slot0Human: true);
var player = session.State.Player; var player = session.State.Contenders[0];
int initialBrushes = session.State.Terrain.Brushes.Count; int initialBrushes = session.State.Terrain.Brushes.Count;
float minGround = float.PositiveInfinity; float minGround = float.PositiveInfinity;
@ -161,7 +161,7 @@ namespace RustToDust.Tests
for (int tick = 0; tick < 360; tick++) for (int tick = 0; tick < 360; tick++)
{ {
float steer = MathF.Sin(tick * 0.025f) * 0.45f; float steer = MathF.Sin(tick * 0.025f) * 0.45f;
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 1f, Throttle: 1f,
Steer: steer, Steer: steer,
AimWorldX: player.X + 30f, AimWorldX: player.X + 30f,
@ -169,6 +169,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
Assert.False(float.IsNaN(player.X) || float.IsNaN(player.Y) || float.IsNaN(player.Z), Assert.False(float.IsNaN(player.X) || float.IsNaN(player.Y) || float.IsNaN(player.Z),
$"NaN pose at tick {tick}"); $"NaN pose at tick {tick}");
@ -272,8 +273,8 @@ namespace RustToDust.Tests
private static void RunSteepTerrainStress(int seed, ChassisSpec chassis, bool testDune) private static void RunSteepTerrainStress(int seed, ChassisSpec chassis, bool testDune)
{ {
using var session = new ArenaSession(seed); using var session = new ArenaSession(seed, slot0Human: true);
var player = session.State.Player; var player = session.State.Contenders[0];
TerrainBrush targetBrush = default; TerrainBrush targetBrush = default;
float startX = 0f; float startX = 0f;
@ -335,7 +336,7 @@ namespace RustToDust.Tests
if (chassis.Id != player.Grid.Spec.Id) if (chassis.Id != player.Grid.Spec.Id)
{ {
session.State.SpawnChassisDrop(player.X, player.Z, chassis); session.State.SpawnChassisDrop(player.X, player.Z, chassis);
Assert.True(session.TrySwapNearbyChassis(), $"Expected swap to {chassis.Id} to succeed"); Assert.True(session.TrySwapNearbyChassis(0), $"Expected swap to {chassis.Id} to succeed");
Assert.Equal(chassis.Id, player.Grid.Spec.Id); Assert.Equal(chassis.Id, player.Grid.Spec.Id);
} }
@ -348,7 +349,7 @@ namespace RustToDust.Tests
for (int tick = 0; tick < 600; tick++) for (int tick = 0; tick < 600; tick++)
{ {
float steer = MathF.Sin(tick * 0.03f) * 0.15f; float steer = MathF.Sin(tick * 0.03f) * 0.15f;
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 1f, Throttle: 1f,
Steer: steer, Steer: steer,
AimWorldX: targetBrush.X, AimWorldX: targetBrush.X,
@ -356,6 +357,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: false)); Brake: false));
session.Step();
Assert.False( Assert.False(
float.IsNaN(player.X) || float.IsNaN(player.Y) || float.IsNaN(player.Z), float.IsNaN(player.X) || float.IsNaN(player.Y) || float.IsNaN(player.Z),

View file

@ -31,13 +31,13 @@ namespace RustToDust.Tests
{ {
foreach (var vtolSpec in new[] { Catalog.Hornet, Catalog.Condor }) foreach (var vtolSpec in new[] { Catalog.Hornet, Catalog.Condor })
{ {
using var session = new ArenaSession(seed: 42); using var session = new ArenaSession(seed: 42, slot0Human: true);
IsolateContenders(session, 0); IsolateContenders(session, 0);
var player = session.State.Player; var player = session.State.Contenders[0];
session.SetContenderPose(player.Id, 0f, 0f, 0f); session.SetContenderPose(player.Id, 0f, 0f, 0f);
session.State.SpawnChassisDrop(player.X, player.Z, vtolSpec); session.State.SpawnChassisDrop(player.X, player.Z, vtolSpec);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal(vtolSpec.Id, player.Grid.Spec.Id); Assert.Equal(vtolSpec.Id, player.Grid.Spec.Id);
Assert.True(player.Grid.Spec.IsVtol); Assert.True(player.Grid.Spec.IsVtol);
@ -47,7 +47,8 @@ namespace RustToDust.Tests
// Climb with VerticalThrottle = +1 for 2.5s (150 ticks) // Climb with VerticalThrottle = +1 for 2.5s (150 ticks)
for (int t = 0; t < 150; t++) for (int t = 0; t < 150; t++)
{ {
session.Step(new PlayerInput(0.4f, 0.1f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 1f)); session.SetHumanInput(0, new PlayerInput(0.4f, 0.1f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 1f));
session.Step();
} }
float ghClimbed = session.State.Terrain.SampleHeight(player.X, player.Z); float ghClimbed = session.State.Terrain.SampleHeight(player.X, player.Z);
@ -60,13 +61,15 @@ namespace RustToDust.Tests
// Hold hover with VerticalThrottle = 0 for 2.0s (120 ticks) -> settles to TargetHoverAltAgl and holds steady // Hold hover with VerticalThrottle = 0 for 2.0s (120 ticks) -> settles to TargetHoverAltAgl and holds steady
for (int t = 0; t < 60; t++) for (int t = 0; t < 60; t++)
{ {
session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 0f)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 0f));
session.Step();
} }
float ghSettled = session.State.Terrain.SampleHeight(player.X, player.Z); float ghSettled = session.State.Terrain.SampleHeight(player.X, player.Z);
float settledAgl = player.Y - vtolSpec.HalfHeight - ghSettled; float settledAgl = player.Y - vtolSpec.HalfHeight - ghSettled;
for (int t = 0; t < 60; t++) for (int t = 0; t < 60; t++)
{ {
session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 0f)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 0f));
session.Step();
} }
float ghHeld = session.State.Terrain.SampleHeight(player.X, player.Z); float ghHeld = session.State.Terrain.SampleHeight(player.X, player.Z);
float heldAgl = player.Y - vtolSpec.HalfHeight - ghHeld; float heldAgl = player.Y - vtolSpec.HalfHeight - ghHeld;
@ -76,7 +79,8 @@ namespace RustToDust.Tests
// Descend with VerticalThrottle = -1 for 3s (180 ticks) - should settle smoothly near 2.5m clearance // Descend with VerticalThrottle = -1 for 3s (180 ticks) - should settle smoothly near 2.5m clearance
for (int t = 0; t < 180; t++) for (int t = 0; t < 180; t++)
{ {
session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: -1f)); session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: -1f));
session.Step();
} }
float ghDesc = session.State.Terrain.SampleHeight(player.X, player.Z); float ghDesc = session.State.Terrain.SampleHeight(player.X, player.Z);
float descAgl = player.Y - vtolSpec.HalfHeight - ghDesc; float descAgl = player.Y - vtolSpec.HalfHeight - ghDesc;
@ -88,8 +92,8 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void MwllTriangle_ZenithBlindSpot_MainCannonBlocked_WideArcPdAndDistantGroundRigHit() public void MwllTriangle_ZenithBlindSpot_MainCannonBlocked_WideArcPdAndDistantGroundRigHit()
{ {
using var session = new ArenaSession(seed: 42); using var session = new ArenaSession(seed: 42, slot0Human: true);
var player = session.State.Player; var player = session.State.Contenders[0];
var overheadVtol = session.State.Contenders[1]; var overheadVtol = session.State.Contenders[1];
var distantGroundRig = session.State.Contenders[2]; var distantGroundRig = session.State.Contenders[2];
IsolateContenders(session, player.Id, overheadVtol.Id); IsolateContenders(session, player.Id, overheadVtol.Id);
@ -97,7 +101,7 @@ namespace RustToDust.Tests
// Swap player to Anvil (heavy tracked tank, weapons capped at +30 deg pitch) // Swap player to Anvil (heavy tracked tank, weapons capped at +30 deg pitch)
session.SetContenderPose(player.Id, 0f, 0f, 0f); session.SetContenderPose(player.Id, 0f, 0f, 0f);
session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal("anvil", player.Grid.Spec.Id); Assert.Equal("anvil", player.Grid.Spec.Id);
// Swap contender 1 to Hornet and position it high overhead (~14m horizontal, ~38m above player => ~+69 deg pitch!) // Swap contender 1 to Hornet and position it high overhead (~14m horizontal, ~38m above player => ~+69 deg pitch!)
@ -109,7 +113,8 @@ namespace RustToDust.Tests
overheadVtol.TargetHoverAltAgl = 38f; overheadVtol.TargetHoverAltAgl = 38f;
session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f); session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f);
// Step once to seat bodies cleanly // Step once to seat bodies cleanly
session.Step(new PlayerInput(0f, 0f, overheadVtol.X, overheadVtol.Z, false, false, true, AimWorldY: overheadVtol.Y)); session.SetHumanInput(0, new PlayerInput(0f, 0f, overheadVtol.X, overheadVtol.Z, false, false, true, AimWorldY: overheadVtol.Y));
session.Step();
float vtolArmorBefore = overheadVtol.Grid.TotalArmorRatio(); float vtolArmorBefore = overheadVtol.Grid.TotalArmorRatio();
@ -118,13 +123,14 @@ namespace RustToDust.Tests
{ {
overheadVtol.TargetHoverAltAgl = 38f; overheadVtol.TargetHoverAltAgl = 38f;
session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f); session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f);
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
0f, 0f, 0f, 0f,
overheadVtol.X, overheadVtol.Z, overheadVtol.X, overheadVtol.Z,
Fire: true, Fire: true,
InteractPickup: false, InteractPickup: false,
Brake: true, Brake: true,
AimWorldY: overheadVtol.Y)); AimWorldY: overheadVtol.Y));
session.Step();
} }
Assert.True(player.AllWeaponsOutOfArc, Assert.True(player.AllWeaponsOutOfArc,
$"Expected Anvil main cannons to report AllWeaponsOutOfArc (in={player.InArcWeaponCount}, out={player.OutOfArcWeaponCount}, pY={player.Y:F1}, vY={overheadVtol.Y:F1}, vSpec={overheadVtol.Grid.Spec.Id}, vAlt={overheadVtol.TargetHoverAltAgl:F1}, vAlive={overheadVtol.Alive}, vPos=({overheadVtol.X:F1},{overheadVtol.Z:F1}))"); $"Expected Anvil main cannons to report AllWeaponsOutOfArc (in={player.InArcWeaponCount}, out={player.OutOfArcWeaponCount}, pY={player.Y:F1}, vY={overheadVtol.Y:F1}, vSpec={overheadVtol.Grid.Spec.Id}, vAlt={overheadVtol.TargetHoverAltAgl:F1}, vAlive={overheadVtol.Alive}, vPos=({overheadVtol.X:F1},{overheadVtol.Z:F1}))");
@ -138,13 +144,14 @@ namespace RustToDust.Tests
{ {
overheadVtol.TargetHoverAltAgl = 38f; overheadVtol.TargetHoverAltAgl = 38f;
session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f); session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f);
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
0f, 0f, 0f, 0f,
overheadVtol.X, overheadVtol.Z, overheadVtol.X, overheadVtol.Z,
Fire: true, Fire: true,
InteractPickup: false, InteractPickup: false,
Brake: true, Brake: true,
AimWorldY: overheadVtol.Y)); AimWorldY: overheadVtol.Y));
session.Step();
pdTracers += session.State.Tracers.Count; pdTracers += session.State.Tracers.Count;
} }
Assert.False(player.AllWeaponsOutOfArc, "Expected Wide-Arc PD module to clear overhead out-of-arc block"); Assert.False(player.AllWeaponsOutOfArc, "Expected Wide-Arc PD module to clear overhead out-of-arc block");
@ -164,7 +171,8 @@ namespace RustToDust.Tests
float vtolArmorBeforeDistant = overheadVtol.Grid.TotalArmorRatio(); float vtolArmorBeforeDistant = overheadVtol.Grid.TotalArmorRatio();
for (int t = 0; t < 90; t++) for (int t = 0; t < 90; t++)
{ {
session.Step(new PlayerInput(0f, 0f, 0f, -20f, false, false, true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, -20f, false, false, true));
session.Step();
} }
Assert.True(overheadVtol.Grid.TotalArmorRatio() < vtolArmorBeforeDistant, Assert.True(overheadVtol.Grid.TotalArmorRatio() < vtolArmorBeforeDistant,
"Expected distant ground rig 140m away (~15 deg pitch) to hit the hovering Hornet inside its 30 deg cannon arc"); "Expected distant ground rig 140m away (~15 deg pitch) to hit the hovering Hornet inside its 30 deg cannon arc");
@ -173,8 +181,8 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void GroundRigWithWideArcPd_AutoTracksNearbyAirborneVtolWithoutManualFire() public void GroundRigWithWideArcPd_AutoTracksNearbyAirborneVtolWithoutManualFire()
{ {
using var session = new ArenaSession(seed: 42); using var session = new ArenaSession(seed: 42, slot0Human: true);
var player = session.State.Player; var player = session.State.Contenders[0];
var overheadVtol = session.State.Contenders[1]; var overheadVtol = session.State.Contenders[1];
IsolateContenders(session, player.Id, overheadVtol.Id); IsolateContenders(session, player.Id, overheadVtol.Id);
@ -196,7 +204,7 @@ namespace RustToDust.Tests
{ {
overheadVtol.TargetHoverAltAgl = 28f; overheadVtol.TargetHoverAltAgl = 28f;
session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f);
session.Step(new PlayerInput( session.SetHumanInput(0, new PlayerInput(
Throttle: 0f, Throttle: 0f,
Steer: 0f, Steer: 0f,
AimWorldX: 0f, AimWorldX: 0f,
@ -204,6 +212,7 @@ namespace RustToDust.Tests
Fire: false, Fire: false,
InteractPickup: false, InteractPickup: false,
Brake: true)); Brake: true));
session.Step();
if (session.State.Tracers.Count > 0) if (session.State.Tracers.Count > 0)
{ {
sawAutoTracer = true; sawAutoTracer = true;
@ -219,17 +228,18 @@ namespace RustToDust.Tests
public void QuickBolt_MountsScavengedModuleIntoEmptyMatchingHardpointBeforeCargo() public void QuickBolt_MountsScavengedModuleIntoEmptyMatchingHardpointBeforeCargo()
{ {
var state = new MatchState(seed: 42); var state = new MatchState(seed: 42);
var player = state.Player; var player = state.Contenders[0];
player.IsHuman = true;
// Swap to Anvil (starter Jackal transfers 1 weapon into hp.weapon.sponson_l, leaving hp.weapon.siege_l, hp.weapon.siege_r, hp.weapon.sponson_r empty!) // Swap to Anvil (starter Jackal transfers 1 weapon into hp.weapon.sponson_l, leaving hp.weapon.siege_l, hp.weapon.siege_r, hp.weapon.sponson_r empty!)
state.SpawnChassisDrop(player.X, player.Z, Catalog.Anvil); state.SpawnChassisDrop(player.X, player.Z, Catalog.Anvil);
Assert.True(state.TrySwapNearbyChassis()); Assert.True(state.TrySwapNearbyChassis(0));
Assert.Null(player.Grid.GetMountedOn("hp.weapon.siege_l")); Assert.Null(player.Grid.GetMountedOn("hp.weapon.siege_l"));
int cargoBefore = player.Grid.Cargo.Count; int cargoBefore = player.Grid.Cargo.Count;
// Drop 1x1 PointDefenseFlak right at player and press [E] // Drop 1x1 PointDefenseFlak right at player and press [E]
state.SpawnModuleDrop(player.X + 0.5f, player.Z, Catalog.PointDefenseFlak); state.SpawnModuleDrop(player.X + 0.5f, player.Z, Catalog.PointDefenseFlak);
MatchRules.ApplyPlayerInput(state, new PlayerInput( MatchRules.ApplyHumanInput(state, 0, new PlayerInput(
0f, 0f, player.X, player.Z + 10f, 0f, 0f, player.X, player.Z + 10f,
Fire: false, Fire: false,
InteractPickup: true, InteractPickup: true,
@ -246,7 +256,7 @@ namespace RustToDust.Tests
Assert.True(player.Grid.TryMount(Catalog.Autocannon, "hp.weapon.siege_r")); Assert.True(player.Grid.TryMount(Catalog.Autocannon, "hp.weapon.siege_r"));
Assert.True(player.Grid.TryMount(Catalog.Mg762, "hp.weapon.sponson_r")); Assert.True(player.Grid.TryMount(Catalog.Mg762, "hp.weapon.sponson_r"));
state.SpawnModuleDrop(player.X + 0.5f, player.Z, Catalog.Flak); state.SpawnModuleDrop(player.X + 0.5f, player.Z, Catalog.Flak);
MatchRules.ApplyPlayerInput(state, new PlayerInput( MatchRules.ApplyHumanInput(state, 0, new PlayerInput(
0f, 0f, player.X, player.Z + 10f, 0f, 0f, player.X, player.Z + 10f,
Fire: false, Fire: false,
InteractPickup: true, InteractPickup: true,
@ -259,8 +269,8 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void Vtol_ReverseIntoTallMesaAndCliffDrop_ZeroUndergroundTicks() public void Vtol_ReverseIntoTallMesaAndCliffDrop_ZeroUndergroundTicks()
{ {
using var session = new ArenaSession(seed: 42); using var session = new ArenaSession(seed: 42, slot0Human: true);
var player = session.State.Player; var player = session.State.Contenders[0];
IsolateContenders(session, player.Id); IsolateContenders(session, player.Id);
// Pick the tallest Mesa in generated terrain // Pick the tallest Mesa in generated terrain
@ -278,7 +288,7 @@ namespace RustToDust.Tests
Assert.True(bestHeight >= 22f, "Expected a tall Mesa in seed 42"); Assert.True(bestHeight >= 22f, "Expected a tall Mesa in seed 42");
session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Hornet); session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Hornet);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal("hornet", player.Grid.Spec.Id); Assert.Equal("hornet", player.Grid.Spec.Id);
// 1. Reverse (-Z/+X away from yaw) straight into the tall Mesa cliff face // 1. Reverse (-Z/+X away from yaw) straight into the tall Mesa cliff face
@ -290,7 +300,8 @@ namespace RustToDust.Tests
int undergroundReverseTicks = 0; int undergroundReverseTicks = 0;
for (int t = 0; t < 240; t++) for (int t = 0; t < 240; t++)
{ {
session.Step(new PlayerInput(-1f, 0f, player.X - 30f, player.Z, false, false, false)); session.SetHumanInput(0, new PlayerInput(-1f, 0f, player.X - 30f, player.Z, false, false, false));
session.Step();
float gh = session.State.Terrain.SampleHeight(player.X, player.Z); float gh = session.State.Terrain.SampleHeight(player.X, player.Z);
float agl = (player.Y - player.Grid.Spec.HalfHeight) - gh; float agl = (player.Y - player.Grid.Spec.HalfHeight) - gh;
if (agl < minReverseAgl) minReverseAgl = agl; if (agl < minReverseAgl) minReverseAgl = agl;
@ -312,7 +323,8 @@ namespace RustToDust.Tests
int undergroundDropTicks = 0; int undergroundDropTicks = 0;
for (int t = 0; t < 240; t++) for (int t = 0; t < 240; t++)
{ {
session.Step(new PlayerInput(1f, 0f, player.X + 30f, player.Z, false, false, false)); session.SetHumanInput(0, new PlayerInput(1f, 0f, player.X + 30f, player.Z, false, false, false));
session.Step();
float gh = session.State.Terrain.SampleHeight(player.X, player.Z); float gh = session.State.Terrain.SampleHeight(player.X, player.Z);
float agl = (player.Y - player.Grid.Spec.HalfHeight) - gh; float agl = (player.Y - player.Grid.Spec.HalfHeight) - gh;
if (agl < minDropAgl) minDropAgl = agl; if (agl < minDropAgl) minDropAgl = agl;
@ -326,20 +338,21 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void Vtol_OverheatedEngineToZeroPerf_LosesClimbAuthorityAndSinksTowardMinClearance() public void Vtol_OverheatedEngineToZeroPerf_LosesClimbAuthorityAndSinksTowardMinClearance()
{ {
using var session = new ArenaSession(seed: 42); using var session = new ArenaSession(seed: 42, slot0Human: true);
var player = session.State.Player; var player = session.State.Contenders[0];
IsolateContenders(session, player.Id); IsolateContenders(session, player.Id);
session.SetContenderPose(player.Id, 0f, 0f, 0f); session.SetContenderPose(player.Id, 0f, 0f, 0f);
session.State.SpawnChassisDrop(0f, 0f, Catalog.Hornet); session.State.SpawnChassisDrop(0f, 0f, Catalog.Hornet);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
// Establish steady 20m hover // Establish steady 20m hover
player.TargetHoverAltAgl = 20f; player.TargetHoverAltAgl = 20f;
session.SetContenderPose(player.Id, 0f, 0f, 0f); session.SetContenderPose(player.Id, 0f, 0f, 0f);
for (int t = 0; t < 45; t++) for (int t = 0; t < 45; t++)
{ {
session.Step(new PlayerInput(0f, 0f, 0f, 30f, false, false, false)); session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 30f, false, false, false));
session.Step();
} }
float hoverAglBefore = (player.Y - player.Grid.Spec.HalfHeight) - session.State.Terrain.SampleHeight(player.X, player.Z); float hoverAglBefore = (player.Y - player.Grid.Spec.HalfHeight) - session.State.Terrain.SampleHeight(player.X, player.Z);
Assert.InRange(hoverAglBefore, 17.5f, 22.5f); Assert.InRange(hoverAglBefore, 17.5f, 22.5f);
@ -348,7 +361,8 @@ namespace RustToDust.Tests
for (int t = 0; t < 150; t++) for (int t = 0; t < 150; t++)
{ {
player.Grid.InjectHardpointHeat("hp.engine.core", 15000f); player.Grid.InjectHardpointHeat("hp.engine.core", 15000f);
session.Step(new PlayerInput(0f, 0f, 0f, 30f, false, false, false, VerticalThrottle: 1f)); session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 30f, false, false, false, VerticalThrottle: 1f));
session.Step();
} }
float hoverAglAfter = (player.Y - player.Grid.Spec.HalfHeight) - session.State.Terrain.SampleHeight(player.X, player.Z); float hoverAglAfter = (player.Y - player.Grid.Spec.HalfHeight) - session.State.Terrain.SampleHeight(player.X, player.Z);
@ -362,9 +376,9 @@ namespace RustToDust.Tests
public void StrippedZeroArmorHardpoint_DisablesManualFireAndAutoPointDefense() public void StrippedZeroArmorHardpoint_DisablesManualFireAndAutoPointDefense()
{ {
// 1. Manual FireMountedWeapons disabled when hardpoint armor == 0 // 1. Manual FireMountedWeapons disabled when hardpoint armor == 0
using (var session = new ArenaSession(seed: 42)) using (var session = new ArenaSession(seed: 42, slot0Human: true))
{ {
var player = session.State.Player; var player = session.State.Contenders[0];
var target = session.State.Contenders[1]; var target = session.State.Contenders[1];
IsolateContenders(session, player.Id, target.Id); IsolateContenders(session, player.Id, target.Id);
@ -390,7 +404,8 @@ namespace RustToDust.Tests
int tracersFired = 0; int tracersFired = 0;
for (int t = 0; t < 20; t++) for (int t = 0; t < 20; t++)
{ {
session.Step(new PlayerInput(0f, 0f, target.X, target.Z, Fire: true, InteractPickup: false, Brake: true, AimWorldY: target.Y)); session.SetHumanInput(0, new PlayerInput(0f, 0f, target.X, target.Z, Fire: true, InteractPickup: false, Brake: true, AimWorldY: target.Y));
session.Step();
tracersFired += session.State.Tracers.Count(tr => tracersFired += session.State.Tracers.Count(tr =>
MathF.Abs(tr.StartX - player.X) < 10f && MathF.Abs(tr.StartZ - player.Z) < 10f); MathF.Abs(tr.StartX - player.X) < 10f && MathF.Abs(tr.StartZ - player.Z) < 10f);
} }
@ -402,9 +417,9 @@ namespace RustToDust.Tests
} }
// 2. Auto-PD TryAutoPointDefenseFire disabled when PD hardpoint armor == 0 // 2. Auto-PD TryAutoPointDefenseFire disabled when PD hardpoint armor == 0
using (var session = new ArenaSession(seed: 42)) using (var session = new ArenaSession(seed: 42, slot0Human: true))
{ {
var player = session.State.Player; var player = session.State.Contenders[0];
var overheadVtol = session.State.Contenders[1]; var overheadVtol = session.State.Contenders[1];
IsolateContenders(session, player.Id, overheadVtol.Id); IsolateContenders(session, player.Id, overheadVtol.Id);
@ -434,7 +449,8 @@ namespace RustToDust.Tests
{ {
overheadVtol.TargetHoverAltAgl = 28f; overheadVtol.TargetHoverAltAgl = 28f;
session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f);
session.Step(new PlayerInput(0f, 0f, 0f, -50f, Fire: false, InteractPickup: false, Brake: true)); session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, -50f, Fire: false, InteractPickup: false, Brake: true));
session.Step();
pdTracers += session.State.Tracers.Count(tr => pdTracers += session.State.Tracers.Count(tr =>
MathF.Abs(tr.StartX - player.X) < 10f && MathF.Abs(tr.StartZ - player.Z) < 10f); MathF.Abs(tr.StartX - player.X) < 10f && MathF.Abs(tr.StartZ - player.Z) < 10f);
} }
@ -447,13 +463,13 @@ namespace RustToDust.Tests
[Fact] [Fact]
public void SwapChassis_VtolToGroundToVtol_ResetsTargetHoverAltAgl() public void SwapChassis_VtolToGroundToVtol_ResetsTargetHoverAltAgl()
{ {
using var session = new ArenaSession(seed: 42); using var session = new ArenaSession(seed: 42, slot0Human: true);
var player = session.State.Player; var player = session.State.Contenders[0];
IsolateContenders(session, player.Id); IsolateContenders(session, player.Id);
session.SetContenderPose(player.Id, 0f, 0f, 0f); session.SetContenderPose(player.Id, 0f, 0f, 0f);
session.State.SpawnChassisDrop(0f, 0f, Catalog.Hornet); session.State.SpawnChassisDrop(0f, 0f, Catalog.Hornet);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal(10f, player.TargetHoverAltAgl); Assert.Equal(10f, player.TargetHoverAltAgl);
player.TargetHoverAltAgl = 42f; player.TargetHoverAltAgl = 42f;
@ -461,13 +477,13 @@ namespace RustToDust.Tests
// Swap to ground rig // Swap to ground rig
session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Jackal); session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Jackal);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal(3.0f, player.TargetHoverAltAgl); Assert.Equal(3.0f, player.TargetHoverAltAgl);
Assert.Equal(0f, player.VerticalThrottleCmd); Assert.Equal(0f, player.VerticalThrottleCmd);
// Swap back to VTOL -> must spawn cleanly at 10m hover, NOT stale 42m // Swap back to VTOL -> must spawn cleanly at 10m hover, NOT stale 42m
session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Condor); session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Condor);
Assert.True(session.TrySwapNearbyChassis()); Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal(10.0f, player.TargetHoverAltAgl); Assert.Equal(10.0f, player.TargetHoverAltAgl);
Assert.Equal(0f, player.VerticalThrottleCmd); Assert.Equal(0f, player.VerticalThrottleCmd);
float gh = session.State.Terrain.SampleHeight(player.X, player.Z); float gh = session.State.Terrain.SampleHeight(player.X, player.Z);
@ -479,7 +495,8 @@ namespace RustToDust.Tests
public void InteractPickup_UsesUnifiedNearestDropPriority_ChassisCloserThanModule() public void InteractPickup_UsesUnifiedNearestDropPriority_ChassisCloserThanModule()
{ {
var state = new MatchState(seed: 42); var state = new MatchState(seed: 42);
var player = state.Player; var player = state.Contenders[0];
player.IsHuman = true;
// Remove pre-scattered drops near player to keep test deterministic // Remove pre-scattered drops near player to keep test deterministic
state.GroundDrops.Clear(); state.GroundDrops.Clear();
@ -490,7 +507,7 @@ namespace RustToDust.Tests
var nearest = state.FindNearestInteractableDrop(0); var nearest = state.FindNearestInteractableDrop(0);
Assert.Same(chassisDrop, nearest); Assert.Same(chassisDrop, nearest);
MatchRules.ApplyPlayerInput(state, new PlayerInput( MatchRules.ApplyHumanInput(state, 0, new PlayerInput(
0f, 0f, player.X, player.Z + 10f, 0f, 0f, player.X, player.Z + 10f,
Fire: false, Fire: false,
InteractPickup: true, InteractPickup: true,