Cut 1: 1536m desert relief, terrain/cover LOS detection, tier positioning, 3P shoulder cam

This commit is contained in:
Meta Vens 2026-12-04 15:14:00 +01:00
commit 3221ca1d0c
19 changed files with 1558 additions and 316 deletions

View file

@ -173,8 +173,8 @@ public partial class ArenaRenderer : Node3D
_safeRingImm.ClearSurfaces();
_safeRingImm.SurfaceBegin(Mesh.PrimitiveType.Triangles);
const int segments = 96;
const float halfThick = 0.65f;
const int segments = 160;
const float halfThick = 1.1f;
float rInner = MathF.Max(2f, safeRadius - halfThick);
float rOuter = safeRadius + halfThick;
@ -353,7 +353,7 @@ public partial class ArenaRenderer : Node3D
? session.State.Contenders[s.TargetContenderId.Value]
: null;
if (s.Stance != SpectatorStance.Neutral && target is { Alive: true })
if (s.Stance != SpectatorStance.Neutral && s.HasTargetLos && target is { Alive: true })
{
Vector3 start = specPos + new Vector3(0f, s.Grid.Spec.HalfHeight * 0.7f, 0f);
Vector3 end = new Vector3(target.X, target.Y + target.Grid.Spec.HalfHeight * 0.3f, target.Z);

View file

@ -28,6 +28,7 @@ public partial class Hud : CanvasLayer
private readonly Func<ArenaSession?> _getSession;
private readonly Action<int, string> _onEquipCargo;
private readonly Func<float> _getCameraYaw;
private Label _chassisHeader = null!;
private Label _planeBadge = null!;
@ -35,10 +36,12 @@ public partial class Hud : CanvasLayer
private Label _coreHpLabel = null!;
private Label _statsLabel = null!;
private Label _safeLabel = null!;
private Label _detectionLabel = null!;
private Label _promptLabel = null!;
private Label _controlsHint = null!;
private RadarWidget _radar = null!;
private CrosshairOverlay _crosshair = null!;
private SchematicPanel _schematic = null!;
private VBoxContainer _cargoList = null!;
private Label _cargoHeader = null!;
@ -56,10 +59,11 @@ public partial class Hud : CanvasLayer
private int _lastCargoHash = -1;
private bool _garageExpanded;
public Hud(Func<ArenaSession?> getSession, Action<int, string> onEquipCargo)
public Hud(Func<ArenaSession?> getSession, Action<int, string> onEquipCargo, Func<float>? getCameraYaw = null)
{
_getSession = getSession;
_onEquipCargo = onEquipCargo;
_getCameraYaw = getCameraYaw ?? (() => 0f);
Layer = 10;
}
@ -75,6 +79,7 @@ public partial class Hud : CanvasLayer
public override void _Ready()
{
BuildCrosshair();
BuildTopLeft();
BuildTopRightRadar();
BuildBottomLeftSchematic();
@ -125,11 +130,26 @@ public partial class Hud : CanvasLayer
_safeLabel.Modulate = RedCol;
}
if (state.PlayerDetectedByCount > 0)
{
_detectionLabel.Text = $"DETECTED BY {state.PlayerDetectedByCount}";
_detectionLabel.Modulate = RedCol;
}
else
{
_detectionLabel.Text = "CONCEALED (TERRAIN)";
_detectionLabel.Modulate = OliveCol;
}
_promptLabel.Text = BuildInteractionPrompt(state, player);
_promptLabel.Visible = !string.IsNullOrEmpty(_promptLabel.Text);
// Radar
_radar.SetState(state);
// Crosshair + Heat Arc
_crosshair.SetState(player);
_crosshair.QueueRedraw();
// Radar (heading-up with camera yaw)
_radar.SetState(state, _getCameraYaw());
_radar.QueueRedraw();
// Schematic + Cargo
@ -164,6 +184,14 @@ public partial class Hud : CanvasLayer
}
}
private void BuildCrosshair()
{
_crosshair = new CrosshairOverlay { Name = "Crosshair" };
_crosshair.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_crosshair.MouseFilter = Control.MouseFilterEnum.Ignore;
AddChild(_crosshair);
}
private void BuildTopLeft()
{
var panel = CreateStyledPanel();
@ -222,12 +250,16 @@ public partial class Hud : CanvasLayer
_safeLabel.AddThemeFontSizeOverride("font_size", 13);
vbox.AddChild(_safeLabel);
_detectionLabel = new Label { Text = "CONCEALED (TERRAIN)" };
_detectionLabel.AddThemeFontSizeOverride("font_size", 13);
vbox.AddChild(_detectionLabel);
_promptLabel = new Label { Text = "", Visible = false };
_promptLabel.AddThemeColorOverride("font_color", CyanCol);
_promptLabel.AddThemeFontSizeOverride("font_size", 14);
vbox.AddChild(_promptLabel);
_controlsHint = new Label { Text = "WASD Drive | LMB Fire | E Loot/Swap | Tab Garage | R Reset" };
_controlsHint = new Label { Text = "WASD Drive | Mouse Aim | LMB Fire | E Loot/Swap | Tab Garage | Wheel Zoom" };
_controlsHint.AddThemeColorOverride("font_color", TextMuted);
_controlsHint.AddThemeFontSizeOverride("font_size", 11);
vbox.AddChild(_controlsHint);
@ -566,15 +598,86 @@ public partial class Hud : CanvasLayer
return panel;
}
private sealed partial class CrosshairOverlay : Control
{
private ContenderState? _player;
public void SetState(ContenderState player) => _player = player;
public override void _Draw()
{
Vector2 center = Size * 0.5f;
float gap = 6f;
float tick = 10f;
Color retCol = new Color(TextLight.R, TextLight.G, TextLight.B, 0.88f);
// Clean 4-tick center crosshair + center pip
DrawCircle(center, 1.8f, retCol);
DrawLine(center + new Vector2(-gap - tick, 0f), center + new Vector2(-gap, 0f), retCol, 1.6f);
DrawLine(center + new Vector2(gap, 0f), center + new Vector2(gap + tick, 0f), retCol, 1.6f);
DrawLine(center + new Vector2(0f, -gap - tick), center + new Vector2(0f, -gap), retCol, 1.6f);
DrawLine(center + new Vector2(0f, gap), center + new Vector2(0f, gap + tick), retCol, 1.6f);
if (_player is null || !_player.Alive)
{
return;
}
// Thermal heat-arc indicator around crosshair
float heatRatio = 0f;
bool overPlateau = false;
var mounted = _player.Grid.Mounted;
for (int i = 0; i < mounted.Count; i++)
{
var m = mounted[i];
if (m.Spec.Kind == HardpointKind.Weapon)
{
float r = Math.Clamp(
(m.CurrentTemp - ChassisGrid.AmbientTemp) / MathF.Max(1f, m.Spec.MaxTemp - ChassisGrid.AmbientTemp),
0f, 1f);
if (r > heatRatio) heatRatio = r;
if (m.CurrentTemp > m.Spec.OptimalTemp + m.Spec.PlateauWidth * 0.5f)
{
overPlateau = true;
}
}
}
float arcRadius = 21f;
float startAngle = -MathF.PI * 0.75f;
float maxSweep = MathF.PI * 1.5f;
DrawArc(center, arcRadius, startAngle, startAngle + maxSweep, 24, new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.4f), 2.0f);
if (heatRatio > 0.01f)
{
Color heatCol = overPlateau
? RedCol
: (heatRatio > 0.65f ? OrangeCol : OliveCol);
DrawArc(center, arcRadius, startAngle, startAngle + maxSweep * heatRatio, 24, heatCol, 2.4f);
}
}
}
private sealed partial class RadarWidget : Control
{
private MatchState? _state;
private float _cameraYaw;
public void SetState(MatchState state) => _state = state;
public void SetState(MatchState state, float cameraYaw)
{
_state = state;
_cameraYaw = cameraYaw;
}
private static Vector2 WorldToRadar(Vector2 center, float scale, float wx, float wz) =>
// Match chase camera orientation: screen-up = +Z, screen-right = -X.
center + new Vector2(-wx, -wz) * scale;
private static Vector2 WorldToRadar(Vector2 center, float scale, float wx, float wz, float camYaw)
{
// Heading-up 3P radar: camera forward (sinY, cosY) is always UP (-screenY), camera right (-cosY, sinY) is RIGHT (+screenX).
float sinY = MathF.Sin(camYaw);
float cosY = MathF.Cos(camYaw);
float rx = -wx * cosY + wz * sinY;
float fy = wx * sinY + wz * cosY;
return center + new Vector2(rx, -fy) * scale;
}
public override void _Draw()
{
@ -584,19 +687,21 @@ public partial class Hud : CanvasLayer
DrawCircle(center, radius, BgInner);
DrawArc(center, radius, 0f, MathF.Tau, 48, BorderCol, 1.5f);
// Forward-up indicator tick at top of radar
DrawLine(center + new Vector2(0f, -radius), center + new Vector2(0f, -radius + 6f), CyanCol, 2.0f);
if (_state is null) return;
// Safe Circle
float safePx = _state.Spectators.SafeRadius * scale;
DrawArc(center, safePx, 0f, MathF.Tau, 56, OrangeCol, 1.6f);
DrawArc(center, safePx, 0f, MathF.Tau, 64, OrangeCol, 1.6f);
// Ground drops
for (int i = 0; i < _state.GroundDrops.Count; i++)
{
var d = _state.GroundDrops[i];
if (d.PickedUp) continue;
var p = WorldToRadar(center, scale, d.X, d.Z);
var p = WorldToRadar(center, scale, d.X, d.Z, _cameraYaw);
if (d.Chassis is not null)
{
DrawRect(new Rect2(p - new Vector2(2.5f, 2.5f), new Vector2(5f, 5f)), CyanCol);
@ -607,13 +712,23 @@ public partial class Hud : CanvasLayer
}
}
// Spectator Wall (scaled by RadarSignature) + red target lock lines
// Spectator Wall (LOS / Tourist horizon rule / 5s ghost memory; hidden Exemplars vanish!)
var specs = _state.Spectators.Spectators;
for (int i = 0; i < specs.Count; i++)
{
var s = specs[i];
if (!s.Alive) continue;
var p = WorldToRadar(center, scale, s.X, s.Z);
_state.SpectatorContacts.TryGetValue(s.Id, out var mem);
if (!MatchState.IsContactOnRadar(mem))
{
continue;
}
bool live = mem!.VisibleToPlayer;
float drawX = live || mem.FaintHorizonPing ? s.X : mem.LastSeenX;
float drawZ = live || mem.FaintHorizonPing ? s.Z : mem.LastSeenZ;
var p = WorldToRadar(center, scale, drawX, drawZ, _cameraYaw);
float blipR = 1.6f + s.RadarSignature * 3.1f;
Color col = s.Tier switch
@ -623,30 +738,46 @@ public partial class Hud : CanvasLayer
_ => RedCol
};
if (s.Stance != SpectatorStance.Neutral && s.TargetContenderId.HasValue)
if (live && s.Stance != SpectatorStance.Neutral && s.HasTargetLos && s.TargetContenderId.HasValue)
{
int tid = s.TargetContenderId.Value;
if (tid >= 0 && tid < _state.Contenders.Count && _state.Contenders[tid].Alive)
{
var tgt = _state.Contenders[tid];
var tp = WorldToRadar(center, scale, tgt.X, tgt.Z);
var tp = WorldToRadar(center, scale, tgt.X, tgt.Z, _cameraYaw);
DrawLine(p, tp, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f), 1.3f);
}
col = RedCol;
}
DrawCircle(p, blipR, col);
if (!live)
{
float alpha = mem.FaintHorizonPing
? 0.42f
: Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f);
Color ghostCol = mem.FaintHorizonPing ? GoldCol : col;
DrawCircle(p, blipR, new Color(ghostCol.R, ghostCol.G, ghostCol.B, alpha));
}
else
{
DrawCircle(p, blipR, col);
}
}
// Contenders
// Contenders (player always live; rivals obey LOS + 5s ghost memory)
float sinY = MathF.Sin(_cameraYaw);
float cosY = MathF.Cos(_cameraYaw);
for (int i = 0; i < _state.Contenders.Count; i++)
{
var c = _state.Contenders[i];
if (!c.Alive) continue;
var p = WorldToRadar(center, scale, c.X, c.Z);
if (c.IsPlayer)
{
var dir = new Vector2(-MathF.Sin(c.Yaw), -MathF.Cos(c.Yaw));
var p = WorldToRadar(center, scale, c.X, c.Z, _cameraYaw);
var dir = new Vector2(
-MathF.Sin(c.Yaw) * cosY + MathF.Cos(c.Yaw) * sinY,
-(MathF.Sin(c.Yaw) * sinY + MathF.Cos(c.Yaw) * cosY));
var perp = new Vector2(-dir.Y, dir.X);
var pts = new[]
{
@ -655,10 +786,25 @@ public partial class Hud : CanvasLayer
p - dir * 4.5f - perp * 4.2f
};
DrawColoredPolygon(pts, OliveCol);
continue;
}
_state.ContenderContacts.TryGetValue(c.Id, out var mem);
if (!MatchState.IsContactOnRadar(mem))
{
continue;
}
if (mem!.VisibleToPlayer)
{
var p = WorldToRadar(center, scale, c.X, c.Z, _cameraYaw);
DrawCircle(p, 3.3f, OrangeCol);
}
else
{
DrawCircle(p, 3.3f, OrangeCol);
var p = WorldToRadar(center, scale, mem.LastSeenX, mem.LastSeenZ, _cameraYaw);
float alpha = Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f);
DrawCircle(p, 2.8f, new Color(OrangeCol.R, OrangeCol.G, OrangeCol.B, alpha));
}
}
}

View file

@ -18,8 +18,10 @@ public partial class Main : Node3D
private ArenaSession? _session;
private PlayerInput? _scriptedInput;
private float _cameraDistance = 30f;
private Vector3 _cameraSmoothedTarget = Vector3.Zero;
private float _cameraYaw;
private float _cameraPitch = Mathf.DegToRad(12f);
private float _cameraZoom = 1.0f;
private Vector3 _cameraSmoothedAnchor = Vector3.Zero;
private float _elapsedSeconds;
private bool _interactQueued;
private int _seed = 42;
@ -30,6 +32,7 @@ public partial class Main : Node3D
public Hud Hud => _hud;
public string? Failure { get; private set; }
public int Seed => _seed;
public float CameraYaw => _cameraYaw;
public override void _Ready()
{
@ -43,14 +46,14 @@ public partial class Main : Node3D
_camera = new Camera3D
{
Name = "TacticalCamera",
Name = "ShoulderCamera",
Current = true,
Fov = 48f,
Far = 520f
Fov = 58f,
Far = 1800f
};
AddChild(_camera);
_hud = new Hud(() => _session, OnEquipCargo) { Name = "Hud" };
_hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw) { Name = "Hud" };
AddChild(_hud);
Reset(_seed);
@ -73,11 +76,21 @@ public partial class Main : Node3D
{
_session = new ArenaSession(seed);
var p = _session.State.Player;
_cameraSmoothedTarget = new Vector3(p.X, p.Y, p.Z);
_cameraYaw = p.Yaw;
_cameraPitch = Mathf.DegToRad(12f);
_cameraZoom = 1.0f;
_cameraSmoothedAnchor = ComputeTargetAnchor(p);
_terrain.InvalidateAll();
_terrain.Sync(_session.State.Terrain);
_arena.Sync(_session, _elapsedSeconds);
UpdateCamera(1f);
_hud.Sync(_session);
if (DisplayServer.GetName() != "headless" && !_hud.GarageExpanded)
{
Input.MouseMode = Input.MouseModeEnum.Captured;
}
}
catch (Exception ex)
{
@ -90,6 +103,16 @@ public partial class Main : Node3D
public override void _UnhandledInput(InputEvent @event)
{
if (@event is InputEventMouseMotion mm && Input.MouseMode == Input.MouseModeEnum.Captured)
{
_cameraYaw -= mm.Relative.X * 0.0028f;
_cameraPitch = Math.Clamp(
_cameraPitch + mm.Relative.Y * 0.0024f,
Mathf.DegToRad(-18f),
Mathf.DegToRad(38f));
return;
}
if (@event is InputEventKey key && key.Pressed && !key.Echo)
{
switch (key.Keycode)
@ -99,14 +122,23 @@ public partial class Main : Node3D
break;
case Key.Tab:
_hud.ToggleGarage();
if (DisplayServer.GetName() != "headless")
{
Input.MouseMode = _hud.GarageExpanded
? Input.MouseModeEnum.Visible
: Input.MouseModeEnum.Captured;
}
break;
case Key.R:
Reset(_seed + 1);
break;
case Key.Escape:
Input.MouseMode = Input.MouseMode == Input.MouseModeEnum.Confined
? Input.MouseModeEnum.Visible
: Input.MouseModeEnum.Confined;
if (DisplayServer.GetName() != "headless")
{
Input.MouseMode = Input.MouseMode == Input.MouseModeEnum.Captured
? Input.MouseModeEnum.Visible
: Input.MouseModeEnum.Captured;
}
break;
}
}
@ -114,11 +146,19 @@ public partial class Main : Node3D
{
if (mb.ButtonIndex == MouseButton.WheelUp)
{
_cameraDistance = Math.Clamp(_cameraDistance - 2.5f, 16f, 58f);
_cameraZoom = Math.Clamp(_cameraZoom - 0.08f, 0.75f, 1.6f);
}
else if (mb.ButtonIndex == MouseButton.WheelDown)
{
_cameraDistance = Math.Clamp(_cameraDistance + 2.5f, 16f, 58f);
_cameraZoom = Math.Clamp(_cameraZoom + 0.08f, 0.75f, 1.6f);
}
else if (mb.ButtonIndex == MouseButton.Left &&
Input.MouseMode == Input.MouseModeEnum.Visible &&
!_hud.GarageExpanded &&
!_hud.IsPointerOverInteractiveHud(mb.Position) &&
DisplayServer.GetName() != "headless")
{
Input.MouseMode = Input.MouseModeEnum.Captured;
}
}
}
@ -161,11 +201,11 @@ public partial class Main : Node3D
if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) steer -= 1f;
bool brake = Input.IsKeyPressed(Key.Space);
Vector2 mousePos = GetViewport().GetMousePosition();
bool pointerOnHud = _hud.IsPointerOverInteractiveHud(mousePos);
bool pointerOnHud = Input.MouseMode != Input.MouseModeEnum.Captured &&
_hud.IsPointerOverInteractiveHud(GetViewport().GetMousePosition());
bool fire = !pointerOnHud && Input.IsMouseButtonPressed(MouseButton.Left);
var (aimX, aimZ) = ComputeMouseTerrainAim(mousePos);
var (aimX, aimY, aimZ) = ComputeCenterScreenAim();
return new PlayerInput(
Throttle: throttle,
Steer: steer,
@ -173,48 +213,135 @@ public partial class Main : Node3D
AimWorldZ: aimZ,
Fire: fire,
InteractPickup: _interactQueued,
Brake: brake);
Brake: brake,
AimWorldY: aimY);
}
private (float AimX, float AimZ) ComputeMouseTerrainAim(Vector2 mousePos)
private (float AimX, float AimY, float AimZ) ComputeCenterScreenAim()
{
var player = Session.State.Player;
Vector3 rayOrigin = _camera.ProjectRayOrigin(mousePos);
Vector3 rayDir = _camera.ProjectRayNormal(mousePos);
if (Session.State.Terrain.Raycast(
rayOrigin.X, rayOrigin.Y, rayOrigin.Z,
rayDir.X, rayDir.Y, rayDir.Z,
maxDistance: 320f,
out float hx, out _, out float hz, out _))
Vector2 screenSize = GetViewport().GetVisibleRect().Size;
if (screenSize.X < 2f || screenSize.Y < 2f)
{
return (hx, hz);
return (
player.X + MathF.Sin(_cameraYaw) * 40f,
player.Y,
player.Z + MathF.Cos(_cameraYaw) * 40f);
}
if (MathF.Abs(rayDir.Y) > 1e-4f)
Vector2 center = screenSize * 0.5f;
Vector3 rayOrigin = _camera.ProjectRayOrigin(center);
Vector3 rayDir = _camera.ProjectRayNormal(center);
const float maxAimDist = 450f;
ulong playerStableId = ArenaSession.ContenderStableIdBase + (ulong)player.Id;
Vector3 castOrigin = rayOrigin;
float remainingDist = maxAimDist;
float boxDist = maxAimDist;
Vector3 boxHitPt = Vector3.Zero;
bool hasBoxHit = false;
// Cast against Ymir world, skipping the player's own chassis if hit along the shoulder ray.
for (int attempt = 0; attempt < 2; attempt++)
{
float t = (player.Y - rayOrigin.Y) / rayDir.Y;
if (t > 0f)
var hit = Session.World.CastRayClosest(
(castOrigin.X, castOrigin.Y, castOrigin.Z),
(rayDir.X * remainingDist, rayDir.Y * remainingDist, rayDir.Z * remainingDist));
if (!hit.Hit)
{
Vector3 p = rayOrigin + rayDir * t;
return (p.X, p.Z);
break;
}
var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z);
if (hit.StableId == playerStableId)
{
float skip = rayOrigin.DistanceTo(pt) + 0.4f;
castOrigin = rayOrigin + rayDir * skip;
remainingDist = MathF.Max(1f, maxAimDist - skip);
continue;
}
boxHitPt = pt;
boxDist = rayOrigin.DistanceTo(pt);
hasBoxHit = true;
break;
}
return (player.X + MathF.Sin(player.Yaw) * 25f, player.Z + MathF.Cos(player.Yaw) * 25f);
bool hasTerrainHit = Session.State.Terrain.Raycast(
rayOrigin.X, rayOrigin.Y, rayOrigin.Z,
rayDir.X, rayDir.Y, rayDir.Z,
maxDistance: boxDist,
out float tx, out float ty, out float tz, out float terrainDist);
if (hasTerrainHit && terrainDist <= boxDist)
{
return (tx, ty, tz);
}
if (hasBoxHit)
{
return (boxHitPt.X, boxHitPt.Y, boxHitPt.Z);
}
Vector3 farPt = rayOrigin + rayDir * 320f;
return (farPt.X, farPt.Y, farPt.Z);
}
private Vector3 ComputeTargetAnchor(ContenderState p)
{
var spec = p.Grid.Spec;
float heightT = Math.Clamp((spec.HalfHeight - 0.75f) / (2.35f - 0.75f), 0f, 1.2f);
float upOffset = Mathf.Lerp(3.2f, 6.5f, heightT);
float rightOffset = Mathf.Lerp(1.6f, 2.8f, heightT);
var camRight = new Vector3(-MathF.Cos(_cameraYaw), 0f, MathF.Sin(_cameraYaw));
return new Vector3(p.X, p.Y + (upOffset - spec.HalfHeight), p.Z) + camRight * rightOffset;
}
private void UpdateCamera(float dt)
{
var p = Session.State.Player;
var target = new Vector3(p.X, p.Y + 1.0f, p.Z);
float blend = 1f - MathF.Exp(-dt * 9f);
_cameraSmoothedTarget = _cameraSmoothedTarget.Lerp(target, blend);
var spec = p.Grid.Spec;
float heightT = Math.Clamp((spec.HalfHeight - 0.75f) / (2.35f - 0.75f), 0f, 1.2f);
float backDist = Mathf.Lerp(7.5f, 12.5f, heightT) * _cameraZoom;
// Angled tactical 3rd-person desert chase view
Vector3 offset = new Vector3(0f, _cameraDistance * 0.78f, -_cameraDistance * 0.72f);
_camera.GlobalPosition = _cameraSmoothedTarget + offset;
_camera.LookAt(_cameraSmoothedTarget, Vector3.Up);
Vector3 targetAnchor = ComputeTargetAnchor(p);
float blend = dt >= 1f ? 1f : 1f - MathF.Exp(-dt * 16f);
_cameraSmoothedAnchor = _cameraSmoothedAnchor.Lerp(targetAnchor, blend);
var camFwdHoriz = new Vector3(MathF.Sin(_cameraYaw), 0f, MathF.Cos(_cameraYaw));
var lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.UnitY * MathF.Sin(_cameraPitch)).Normalized();
// Pull camera forward along arm if terrain or static cover blocks the shoulder-to-camera ray
float effectiveBack = backDist;
if (Session.State.Terrain.Raycast(
_cameraSmoothedAnchor.X, _cameraSmoothedAnchor.Y, _cameraSmoothedAnchor.Z,
-lookDir.X, -lookDir.Y, -lookDir.Z,
backDist,
out _, out _, out _, out float terrainDist))
{
effectiveBack = MathF.Min(effectiveBack, MathF.Max(1.6f, terrainDist - 0.6f));
}
var boxHit = Session.World.CastRayClosest(
(_cameraSmoothedAnchor.X, _cameraSmoothedAnchor.Y, _cameraSmoothedAnchor.Z),
(-lookDir.X * effectiveBack, -lookDir.Y * effectiveBack, -lookDir.Z * effectiveBack));
if (boxHit.Hit && boxHit.StableId < ArenaSession.ContenderStableIdBase)
{
var pt = new Vector3(boxHit.Point.X, boxHit.Point.Y, boxHit.Point.Z);
effectiveBack = MathF.Min(effectiveBack, MathF.Max(1.6f, _cameraSmoothedAnchor.DistanceTo(pt) - 0.5f));
}
Vector3 camPos = _cameraSmoothedAnchor - lookDir * effectiveBack;
float minTerrainY = Session.State.Terrain.SampleHeight(camPos.X, camPos.Z) + 1.2f;
if (camPos.Y < minTerrainY)
{
camPos.Y = minTerrainY;
}
_camera.GlobalPosition = camPos;
_camera.LookAt(camPos + lookDir * 60f, Vector3.Up);
}
private void OnEquipCargo(int cargoIndex, string hardpointId)
@ -248,8 +375,11 @@ public partial class Main : Node3D
AmbientLightSource = Godot.Environment.AmbientSource.Sky,
AmbientLightEnergy = 0.55f,
FogEnabled = true,
FogLightColor = new Color(0.74f, 0.55f, 0.38f),
FogDensity = 0.0022f
FogMode = Godot.Environment.FogModeEnum.Depth,
FogLightColor = new Color(0.76f, 0.57f, 0.39f),
FogDensity = 0.72f,
FogDepthBegin = 380f,
FogDepthEnd = 1100f
};
AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = env });
}

View file

@ -7,13 +7,13 @@ namespace RustToDust.Client;
/// <summary>
/// Top-down orthographic SubViewport brush-to-tile PBR + displacement terrain baker.
/// Maintains a 4x4 grid of 96m x 96m terrain tiles covering [-192, +192] in X and Z.
/// Maintains an 8x8 grid of 192m x 192m terrain tiles covering [-768, +768] in X and Z.
/// Only tiles whose <see cref="TerrainField.TileVersions"/> changed are re-baked.
/// </summary>
public partial class TerrainRenderer : Node3D
{
private const int ViewportSize = 256;
private const float InnerTexelSpan = 253.0f; // texel 1 center (1.5) .. texel 254 center (254.5)
private const int ViewportSize = 128;
private const float InnerTexelSpan = 125.0f; // texel 1 center (1.5) .. texel 126 center (126.5)
private const float GutterCenterOffset = 1.5f;
private const float PixelsPerMeter = InnerTexelSpan / TerrainField.TileSize;
private const float HeightSpan = TerrainField.MaxWorldHeight - TerrainField.MinWorldHeight;
@ -162,8 +162,8 @@ public partial class TerrainRenderer : Node3D
var plane = new PlaneMesh
{
Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize),
SubdivideWidth = 48,
SubdivideDepth = 48
SubdivideWidth = 40,
SubdivideDepth = 40
};
var mat = new ShaderMaterial { Shader = _surfaceShader };
@ -172,6 +172,9 @@ public partial class TerrainRenderer : Node3D
mat.SetShaderParameter("height_min", TerrainField.MinWorldHeight);
mat.SetShaderParameter("height_max", TerrainField.MaxWorldHeight);
mat.SetShaderParameter("tile_size", TerrainField.TileSize);
mat.SetShaderParameter("inner_span", InnerTexelSpan);
mat.SetShaderParameter("tex_size", (float)ViewportSize);
mat.SetShaderParameter("gutter_offset", GutterCenterOffset);
float centerX = -TerrainField.HalfExtent + (tx + 0.5f) * TerrainField.TileSize;
float centerZ = -TerrainField.HalfExtent + (tz + 0.5f) * TerrainField.TileSize;

View file

@ -1,12 +1,12 @@
shader_type canvas_item;
render_mode blend_add;
// Encodes positive height deltas into R ([-12m, +16m] => span 28m),
// Encodes positive height deltas into R ([-18m, +52m] => span 70m),
// roughness delta into G, scorch/track wear into B, and ALWAYS A = 1.0
// (required for gl_compatibility TransparentBg=false blend equations).
uniform int brush_kind = 0;
uniform float height_delta = 0.0;
uniform float height_span = 28.0;
uniform float height_span = 70.0;
void fragment() {
vec2 uv_local = UV * 2.0 - 1.0;

View file

@ -4,7 +4,7 @@ render_mode blend_sub;
// Encodes negative height deltas (crater pits, dry washes, road ruts, tire ruts) into R.
uniform int brush_kind = 0;
uniform float height_delta = 0.0;
uniform float height_span = 28.0;
uniform float height_span = 70.0;
void fragment() {
vec2 uv_local = UV * 2.0 - 1.0;

View file

@ -3,9 +3,12 @@ render_mode cull_back, depth_draw_opaque;
uniform sampler2D height_tex : filter_linear, repeat_disable;
uniform sampler2D albedo_tex : filter_linear, repeat_disable;
uniform float height_min = -12.0;
uniform float height_max = 16.0;
uniform float tile_size = 96.0;
uniform float height_min = -18.0;
uniform float height_max = 52.0;
uniform float tile_size = 192.0;
uniform float inner_span = 125.0;
uniform float tex_size = 128.0;
uniform float gutter_offset = 1.5;
float decode_height(float h_norm) {
return mix(height_min, height_max, clamp(h_norm, 0.0, 1.0));
@ -18,7 +21,7 @@ float hash21(vec2 p) {
}
vec2 to_baked_uv(vec2 mesh_uv) {
return (mesh_uv * 253.0 + 1.5) / 256.0;
return (mesh_uv * inner_span + gutter_offset) / tex_size;
}
void vertex() {
@ -28,8 +31,8 @@ void vertex() {
void fragment() {
vec2 uv_baked = to_baked_uv(UV);
const float texel_step = 1.0 / 256.0;
float world_step = tile_size / 253.0;
float texel_step = 1.0 / tex_size;
float world_step = tile_size / inner_span;
float hL = decode_height(texture(height_tex, uv_baked - vec2(texel_step, 0.0)).r);
float hR = decode_height(texture(height_tex, uv_baked + vec2(texel_step, 0.0)).r);

View file

@ -59,7 +59,7 @@ public partial class Smoke : Node
Check(Engine.PhysicsTicksPerSecond == 60, $"Expected 60 physics ticks/sec, got {Engine.PhysicsTicksPerSecond}");
Check((string)ProjectSettings.GetSetting("physics/3d/physics_engine") == "Dummy", "Godot 3D physics_engine is not Dummy");
Check(!_main.GetWorld3D().Space.IsValid, "Godot should have no active 3D physics space");
Check(_main.Terrain.BakedTileCount == 16, $"Expected 16 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;
float startX = player.X;
@ -97,11 +97,11 @@ public partial class Smoke : Node
bool isHeadless = DisplayServer.GetName() == "headless";
int rebakesBefore = _main.Terrain.DirtyRebakes;
float cpuBefore = _main.Session.State.Terrain.SampleHeight(-48f, -48f);
float cpuBefore = _main.Session.State.Terrain.SampleHeight(-96f, -96f);
float gpuBefore = 0f;
if (!isHeadless)
{
bool hasGpuBefore = _main.Terrain.TrySampleBakedHeight(-48f, -48f, out gpuBefore);
bool hasGpuBefore = _main.Terrain.TrySampleBakedHeight(-96f, -96f, out gpuBefore);
Check(hasGpuBefore, "Expected GPU HeightViewport readback to succeed before crater");
if (hasGpuBefore)
{
@ -110,12 +110,12 @@ public partial class Smoke : Node
}
}
_main.Session.State.Terrain.StampCrater(-48f, -48f, radius: 5f, depth: 1.4f);
_main.Session.State.Terrain.StampCrater(-96f, -96f, radius: 5f, depth: 1.4f);
_main.Terrain.Sync(_main.Session.State.Terrain);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
float cpuAfter = _main.Session.State.Terrain.SampleHeight(-48f, -48f);
float cpuAfter = _main.Session.State.Terrain.SampleHeight(-96f, -96f);
Check(cpuAfter < cpuBefore - 0.8f,
$"Expected CPU terrain height to drop after crater stamp (before {cpuBefore:F2}m, after {cpuAfter:F2}m)");
Check(_main.Terrain.DirtyRebakes == rebakesBefore + 1,
@ -123,7 +123,7 @@ public partial class Smoke : Node
if (!isHeadless)
{
bool hasGpuAfter = _main.Terrain.TrySampleBakedHeight(-48f, -48f, out float gpuAfter);
bool hasGpuAfter = _main.Terrain.TrySampleBakedHeight(-96f, -96f, out float gpuAfter);
Check(hasGpuAfter, "Expected GPU HeightViewport readback to succeed after crater");
if (hasGpuAfter)
{

View file

@ -37,7 +37,7 @@ namespace RustToDust.Core
public void EmitMatchStart(float timestamp) =>
Emit(timestamp, BroadcastKind.MatchStart,
"Imperial Broadcast opens the desert ring. Eight unvarnished rigs enter for the gallery's amusement.");
"Imperial Broadcast opens the desert ring. Twelve unvarnished rigs enter for the gallery's amusement.");
public void EmitTouristPull(float timestamp, int contenderId) =>
Emit(timestamp, BroadcastKind.TouristPull,

View file

@ -43,9 +43,9 @@ namespace RustToDust.Core
BaseCellThermalMass: 10f,
BaseCellArmor: 24f,
MassKg: 950f,
BaseThrust: 13500f,
BaseThrust: 14500f,
BaseTurnRate: 4.2f,
MaxSpeed: 32f,
MaxSpeed: 34f,
HalfWidth: 1.05f,
HalfHeight: 0.75f,
HalfLength: 1.65f,
@ -75,9 +75,9 @@ namespace RustToDust.Core
BaseCellThermalMass: 13f,
BaseCellArmor: 34f,
MassKg: 1850f,
BaseThrust: 22000f,
BaseThrust: 23500f,
BaseTurnRate: 3.3f,
MaxSpeed: 27f,
MaxSpeed: 29f,
HalfWidth: 1.25f,
HalfHeight: 0.95f,
HalfLength: 2.3f,
@ -142,9 +142,9 @@ namespace RustToDust.Core
BaseCellThermalMass: 15f,
BaseCellArmor: 46f,
MassKg: 2800f,
BaseThrust: 33000f,
BaseThrust: 34500f,
BaseTurnRate: 3.6f,
MaxSpeed: 25f,
MaxSpeed: 26f,
HalfWidth: 1.6f,
HalfHeight: 1.35f,
HalfLength: 2.1f,
@ -175,9 +175,9 @@ namespace RustToDust.Core
BaseCellThermalMass: 14f,
BaseCellArmor: 42f,
MassKg: 2300f,
BaseThrust: 30000f,
BaseThrust: 33000f,
BaseTurnRate: 4.1f,
MaxSpeed: 26f,
MaxSpeed: 30f,
HalfWidth: 1.35f,
HalfHeight: 1.95f,
HalfLength: 1.15f,
@ -213,9 +213,9 @@ namespace RustToDust.Core
BaseCellThermalMass: 18f,
BaseCellArmor: 58f,
MassKg: 4100f,
BaseThrust: 41000f,
BaseThrust: 43000f,
BaseTurnRate: 2.7f,
MaxSpeed: 21f,
MaxSpeed: 22f,
HalfWidth: 1.75f,
HalfHeight: 2.35f,
HalfLength: 1.4f,
@ -247,7 +247,7 @@ namespace RustToDust.Core
TurnBonus: 0f,
ArmorBonus: 0f,
WeaponDamage: 12f,
WeaponRange: 75f,
WeaponRange: 165f,
FireCooldown: 0.22f,
ProjectileSpeed: 220f,
SpreadRad: 0.035f,
@ -272,7 +272,7 @@ namespace RustToDust.Core
TurnBonus: 0f,
ArmorBonus: 0f,
WeaponDamage: 22f,
WeaponRange: 95f,
WeaponRange: 210f,
FireCooldown: 0.34f,
ProjectileSpeed: 250f,
SpreadRad: 0.025f,
@ -297,7 +297,7 @@ namespace RustToDust.Core
TurnBonus: 0f,
ArmorBonus: 0f,
WeaponDamage: 8.5f,
WeaponRange: 48f,
WeaponRange: 105f,
FireCooldown: 0.65f,
ProjectileSpeed: 185f,
SpreadRad: 0.14f,
@ -322,7 +322,7 @@ namespace RustToDust.Core
TurnBonus: 0f,
ArmorBonus: 0f,
WeaponDamage: 85f,
WeaponRange: 120f,
WeaponRange: 265f,
FireCooldown: 1.45f,
ProjectileSpeed: 280f,
SpreadRad: 0.01f,
@ -449,7 +449,7 @@ namespace RustToDust.Core
TurnBonus: 0f,
ArmorBonus: 0f,
WeaponDamage: 54f,
WeaponRange: 130f,
WeaponRange: 285f,
FireCooldown: 0.55f,
ProjectileSpeed: 400f,
SpreadRad: 0.004f,
@ -474,7 +474,7 @@ namespace RustToDust.Core
TurnBonus: 0f,
ArmorBonus: 0f,
WeaponDamage: 26f,
WeaponRange: 95f,
WeaponRange: 210f,
FireCooldown: 0.18f,
ProjectileSpeed: 310f,
SpreadRad: 0.02f,

View file

@ -2,8 +2,13 @@ using System;
namespace RustToDust.Core
{
public delegate bool LineOfSightCheck(float ax, float ay, float az, float bx, float by, float bz);
public static class MatchRules
{
public static float GetObserverEyeY(float y, float halfHeight) => y + halfHeight * 1.4f;
public static float GetTargetAimY(float y, float halfHeight) => y + halfHeight * 1.1f;
public static float NormalizeAngle(float rad)
{
while (rad > MathF.PI) rad -= MathF.Tau;
@ -26,6 +31,7 @@ namespace RustToDust.Core
player.ThrottleCmd = Math.Clamp(input.Throttle, -1f, 1f);
player.SteerCmd = Math.Clamp(input.Steer, -1f, 1f);
player.AimX = input.AimWorldX;
player.AimY = input.AimWorldY;
player.AimZ = input.AimWorldZ;
player.FireCmd = input.Fire;
player.BrakeCmd = input.Brake;
@ -39,9 +45,9 @@ namespace RustToDust.Core
}
}
public static void UpdateAiContenders(MatchState state, float dt)
public static void UpdateAiContenders(MatchState state, float dt, LineOfSightCheck? hasLos = null)
{
float safeLimit = MathF.Max(15f, state.Spectators.SafeRadius - 10f);
float safeLimit = MathF.Max(30f, state.Spectators.SafeRadius - 25f);
for (int i = 0; i < state.Contenders.Count; i++)
{
@ -59,8 +65,8 @@ namespace RustToDust.Core
float goalZ = 0f;
bool hasGoal = false;
bool wantFire = false;
float aimX = ai.X + MathF.Sin(ai.Yaw) * 20f;
float aimZ = ai.Z + MathF.Cos(ai.Yaw) * 20f;
float aimX = ai.X + MathF.Sin(ai.Yaw) * 25f;
float aimZ = ai.Z + MathF.Cos(ai.Yaw) * 25f;
// 1. Stay inside the shrinking Safe Circle
if (distFromCenter > safeLimit)
@ -70,9 +76,10 @@ namespace RustToDust.Core
hasGoal = true;
}
// 2. Find nearest hostile contender
// 2. Find nearest hostile contender with actual line-of-sight
ContenderState? target = null;
float bestEnemyDistSq = 90f * 90f;
float bestEnemyDistSq = 215f * 215f;
float aiEyeY = GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight);
for (int j = 0; j < state.Contenders.Count; j++)
{
var other = state.Contenders[j];
@ -84,18 +91,26 @@ namespace RustToDust.Core
float dx = other.X - ai.X;
float dz = other.Z - ai.Z;
float d2 = dx * dx + dz * dz;
if (d2 < bestEnemyDistSq)
if (d2 >= bestEnemyDistSq)
{
bestEnemyDistSq = d2;
target = other;
continue;
}
if (hasLos is not null &&
!hasLos(ai.X, aiEyeY, ai.Z, other.X, GetTargetAimY(other.Y, other.Grid.Spec.HalfHeight), other.Z))
{
continue;
}
bestEnemyDistSq = d2;
target = other;
}
// 3. Scavenge nearby upgrades when safe
if (!hasGoal && ai.AiScavengeCooldown <= 0f)
{
GroundDrop? bestDrop = null;
float bestDropDistSq = 34f * 34f;
float bestDropDistSq = 85f * 85f;
for (int d = 0; d < state.GroundDrops.Count; d++)
{
var drop = state.GroundDrops[d];
@ -146,11 +161,11 @@ namespace RustToDust.Core
aimX = target.X;
aimZ = target.Z;
float dist = MathF.Sqrt(bestEnemyDistSq);
wantFire = dist <= 72f;
wantFire = dist <= 165f;
if (!hasGoal)
{
if (dist > 34f)
if (dist > 75f)
{
goalX = target.X;
goalZ = target.Z;
@ -159,23 +174,29 @@ namespace RustToDust.Core
{
// Orbit target instead of ramming headlong
float tangentAngle = MathF.Atan2(ai.Z - target.Z, ai.X - target.X) + 0.7f;
goalX = target.X + MathF.Cos(tangentAngle) * 26f;
goalZ = target.Z + MathF.Sin(tangentAngle) * 26f;
goalX = target.X + MathF.Cos(tangentAngle) * 52f;
goalZ = target.Z + MathF.Sin(tangentAngle) * 52f;
}
hasGoal = true;
}
}
else if (!hasGoal && state.LastGunfireX.HasValue && state.LastGunfireZ.HasValue &&
state.Time - state.LastGunfireTime < 8f)
state.Time - state.LastGunfireTime < 12f)
{
goalX = state.LastGunfireX.Value;
goalZ = state.LastGunfireZ.Value;
hasGoal = true;
float gdx = state.LastGunfireX.Value - ai.X;
float gdz = state.LastGunfireZ.Value - ai.Z;
if (gdx * gdx + gdz * gdz <= 340f * 340f)
{
goalX = state.LastGunfireX.Value;
goalZ = state.LastGunfireZ.Value;
hasGoal = true;
}
}
else if (!hasGoal)
if (!hasGoal)
{
float patrolAngle = ai.Id * 0.9f + state.Time * 0.15f;
float r = MathF.Min(safeLimit * 0.65f, 45f);
float patrolAngle = ai.Id * 0.9f + state.Time * 0.12f;
float r = MathF.Min(safeLimit * 0.65f, 190f);
goalX = MathF.Cos(patrolAngle) * r;
goalZ = MathF.Sin(patrolAngle) * r;
}
@ -189,6 +210,7 @@ namespace RustToDust.Core
ai.ThrottleCmd = MathF.Abs(yawError) > 1.25f ? 0.35f : 0.85f;
ai.BrakeCmd = false;
ai.AimX = aimX;
ai.AimY = target is not null ? GetTargetAimY(target.Y, target.Grid.Spec.HalfHeight) : float.NaN;
ai.AimZ = aimZ;
ai.FireCmd = wantFire;
}
@ -205,7 +227,7 @@ namespace RustToDust.Core
{
if (spec.Stance == SpectatorStance.Neutral || !spec.TargetContenderId.HasValue)
{
(goalX, goalZ) = state.Spectators.GetPerimeterSlot(spec);
(goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes);
aimX = 0f;
aimZ = 0f;
shouldFire = false;
@ -221,13 +243,62 @@ namespace RustToDust.Core
if (target is null || !target.Alive)
{
(goalX, goalZ) = state.Spectators.GetPerimeterSlot(spec);
(goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes);
aimX = 0f;
aimZ = 0f;
shouldFire = false;
return;
}
// Occluded behind terrain/cover: never shoot through rock! Maneuver around ridge / to higher ground.
if (!spec.HasTargetLos)
{
shouldFire = false;
bool hasMemory = spec.TimeSinceLastSeen < SpectatorRing.TargetMemoryDuration;
float focusX = hasMemory ? spec.LastKnownTargetX : target.X;
float focusZ = hasMemory ? spec.LastKnownTargetZ : target.Z;
aimX = focusX;
aimZ = focusZ;
float fdx = focusX - spec.X;
float fdz = focusZ - spec.Z;
float fLen = MathF.Sqrt(fdx * fdx + fdz * fdz);
if (fLen < 1f)
{
(goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes);
return;
}
float dirX = fdx / fLen;
float dirZ = fdz / fLen;
float perpX = -dirZ;
float perpZ = dirX;
float sideSign = (spec.Id & 1) == 0 ? 1f : -1f;
// Evaluate flanking steps (left flank, right flank, crest-climb toward last-known position)
float step = MathF.Min(42f, fLen * 0.65f);
float cand1X = spec.X + (dirX * 0.65f + perpX * 0.76f * sideSign) * step;
float cand1Z = spec.Z + (dirZ * 0.65f + perpZ * 0.76f * sideSign) * step;
float cand2X = spec.X + (dirX * 0.65f - perpX * 0.76f * sideSign) * step;
float cand2Z = spec.Z + (dirZ * 0.65f - perpZ * 0.76f * sideSign) * step;
float h1 = state.Terrain.SampleHeight(cand1X, cand1Z);
float h2 = state.Terrain.SampleHeight(cand2X, cand2Z);
// Prefer the flanking shoulder that gets higher ground (sightline over ridge) unless it is a steep cliff
if (h1 >= h2)
{
goalX = cand1X;
goalZ = cand1Z;
}
else
{
goalX = cand2X;
goalZ = cand2Z;
}
return;
}
aimX = target.X;
aimZ = target.Z;
@ -247,7 +318,7 @@ namespace RustToDust.Core
goalZ = target.Z + MathF.Sin(angle) * (spec.PreferredRange * 0.85f);
}
shouldFire = dist <= 115f;
shouldFire = dist <= 255f;
// Tourists self-throttle when their Imperial weapons run hot
if (shouldFire && spec.Tier == SpectatorTier.Tourist)

View file

@ -17,7 +17,8 @@ namespace RustToDust.Core
float AimWorldZ,
bool Fire,
bool InteractPickup,
bool Brake);
bool Brake,
float AimWorldY = float.NaN);
public readonly record struct TracerEvent(
float StartX,
@ -38,6 +39,16 @@ namespace RustToDust.Core
float HalfZ,
bool IsBoundary);
public sealed class PlayerContactMemory
{
public bool VisibleToPlayer { get; set; }
public float LastSeenAge { get; set; } = float.PositiveInfinity;
public float LastSeenX { get; set; }
public float LastSeenZ { get; set; }
public bool HasEverBeenSeen { get; set; }
public bool FaintHorizonPing { get; set; }
}
public sealed class GroundDrop
{
public GroundDrop(int id, float x, float z, ChassisSpec? chassis, ModuleSpec? module)
@ -70,6 +81,7 @@ namespace RustToDust.Core
Z = z;
Yaw = yaw;
AimX = x + MathF.Sin(yaw) * 20f;
AimY = Y;
AimZ = z + MathF.Cos(yaw) * 20f;
}
@ -82,6 +94,7 @@ namespace RustToDust.Core
public float Z { get; set; }
public float Yaw { get; set; }
public float AimX { get; set; }
public float AimY { get; set; }
public float AimZ { get; set; }
public float Speed { get; set; }
public int Kills { get; set; }
@ -98,9 +111,11 @@ namespace RustToDust.Core
public sealed class MatchState
{
public const int ContenderCount = 8;
public const float ArenaHalfExtent = 195f;
public const float PickupRadius = 6.5f;
public const int ContenderCount = 12;
public const float ArenaHalfExtent = 772f;
public const float PickupRadius = 7.0f;
public const float ContactGhostDuration = 5.0f;
public const float TouristHorizonMaxRange = 420f;
private int _nextDropId = 1;
@ -134,6 +149,10 @@ namespace RustToDust.Core
public IReadOnlyList<ArenaBoxSpec> ArenaCoverBoxes { get; }
public IReadOnlyList<ArenaBoxSpec> ArenaBoundaryBoxes { get; }
public Dictionary<int, PlayerContactMemory> ContenderContacts { get; } = new();
public Dictionary<int, PlayerContactMemory> SpectatorContacts { get; } = new();
public int PlayerDetectedByCount { get; set; }
public float? LastGunfireX { get; set; }
public float? LastGunfireZ { get; set; }
public float LastGunfireTime { get; set; } = -100f;
@ -142,6 +161,35 @@ namespace RustToDust.Core
public event Action<ContenderState>? ChassisSwapped;
public static bool IsContactOnRadar(PlayerContactMemory? mem)
{
if (mem is null)
{
return false;
}
return mem.VisibleToPlayer || mem.FaintHorizonPing || (mem.HasEverBeenSeen && mem.LastSeenAge <= ContactGhostDuration);
}
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 GroundDrop SpawnModuleDrop(float x, float z, ModuleSpec module)
{
var drop = new GroundDrop(_nextDropId++, x, z, null, module);
@ -277,7 +325,6 @@ namespace RustToDust.Core
var overflow = contender.Grid.SwapChassis(nearest.Chassis);
nearest.PickedUp = true;
// Leave old hull behind and drop overflow modules around the swap site
SpawnChassisDrop(contender.X - 2.2f, contender.Z - 2.2f, oldChassis);
for (int i = 0; i < overflow.Count; i++)
{
@ -292,78 +339,132 @@ namespace RustToDust.Core
private void SpawnContenders()
{
// Spawn 8 contenders evenly around an inner ring (radius 95m, well inside SafeRadius = 150m)
const float spawnRadius = 95f;
// Spawn 12 contenders (player + 11 AI) spread across r ~ 240..460m (well inside SafeRadius = 560m)
for (int i = 0; i < ContenderCount; i++)
{
float angle = (i / (float)ContenderCount) * MathF.Tau;
float x = MathF.Cos(angle) * spawnRadius;
float z = MathF.Sin(angle) * spawnRadius;
float angle = (i / (float)ContenderCount) * MathF.Tau + (float)(Rng.NextDouble() - 0.5) * 0.16f;
float baseR = 250f + (float)Rng.NextDouble() * 195f;
float x = MathF.Cos(angle) * baseR;
float z = MathF.Sin(angle) * baseR;
// Nudge radially inside [240, 460] if landing on a steep mesa cliff edge
for (int step = 0; step < 8; step++)
{
var (_, ny, _) = Terrain.SampleNormal(x, z);
if (ny >= 0.88f)
{
break;
}
float r = 245f + ((baseR - 245f + step * 28f) % 210f);
x = MathF.Cos(angle) * r;
z = MathF.Sin(angle) * r;
}
float yaw = MathF.Atan2(-x, -z);
string name = i == 0 ? "Contender 01 (You)" : $"Contender {i + 1:00}";
var contender = new ContenderState(i, name, i == 0, Catalog.CreateStarterBuggy(), x, z, yaw);
contender.Y = Terrain.SampleHeight(x, z) + contender.Grid.Spec.HalfHeight + 0.15f;
contender.AimY = contender.Y;
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();
}
}
private void ScatterInitialLoot()
{
// Deterministic chassis wrecks across arena ruins
(ChassisSpec Spec, float X, float Z)[] chassisPlacements =
// 10 deterministic salvageable chassis wrecks scattered across canyons, passes, and salvage pads
ChassisSpec[] chassisPool =
{
(Catalog.Technical, 45f, 35f),
(Catalog.Technical, -52f, -28f),
(Catalog.Tank, 12f, -68f),
(Catalog.Manticore, -42f, 54f),
(Catalog.Raptor, 64f, -40f),
(Catalog.Paladin, 0f, 18f)
Catalog.Technical, Catalog.Technical,
Catalog.Tank, Catalog.Tank,
Catalog.Manticore, Catalog.Manticore,
Catalog.Raptor, Catalog.Raptor,
Catalog.Paladin, Catalog.Paladin
};
foreach (var (spec, x, z) in chassisPlacements)
for (int i = 0; i < chassisPool.Length; i++)
{
SpawnChassisDrop(x, z, spec);
float angle = (i / (float)chassisPool.Length) * MathF.Tau + 0.35f;
float r = i >= 8 ? (55f + i * 10f) : (145f + (i % 4) * 90f);
SpawnChassisDrop(MathF.Cos(angle) * r, MathF.Sin(angle) * r, chassisPool[i]);
}
// Deterministic salvage module crates
// 24 ground salvage module drops spread across canyons, passes, and ruins
ModuleSpec[] salvagePool =
{
Catalog.Autocannon, Catalog.Flak, Catalog.Recoilless,
Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate,
Catalog.Autocannon, Catalog.Flak, Catalog.TurboCore,
Catalog.WeldedPlate, Catalog.CopperRad, Catalog.Mg762
Catalog.Autocannon, Catalog.Flak, Catalog.Recoilless, Catalog.TurboCore,
Catalog.CopperRad, Catalog.WeldedPlate, Catalog.Mg762, Catalog.DieselCore,
Catalog.Autocannon, Catalog.Flak, Catalog.Recoilless, Catalog.TurboCore,
Catalog.CopperRad, Catalog.WeldedPlate, Catalog.Autocannon, Catalog.Recoilless,
Catalog.Flak, Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate,
Catalog.Mg762, Catalog.Autocannon, Catalog.DieselCore, Catalog.CopperRad
};
for (int i = 0; i < salvagePool.Length; i++)
{
float angle = (i / (float)salvagePool.Length) * MathF.Tau + 0.25f;
float r = 24f + (i % 3) * 26f;
float angle = (i / (float)salvagePool.Length) * MathF.Tau + 0.19f;
float r = 75f + (i % 5) * 95f;
SpawnModuleDrop(MathF.Cos(angle) * r, MathF.Sin(angle) * r, salvagePool[i]);
}
}
private static IReadOnlyList<ArenaBoxSpec> BuildCoverBoxes()
{
// 16 deterministic ruin walls / cover blocks placed clear of the 95m spawn ring and (0,0) center wreck
return new ArenaBoxSpec[]
// 36 deterministic ruin walls / cover blocks spaced >= 90m apart across the 1.5km valley
var boxes = new List<ArenaBoxSpec>(36);
// Inner plaza ring (4 blocks at r = 68m)
for (int i = 0; i < 4; i++)
{
new(28f, 1.8f, 16f, 4.5f, 1.8f, 1.4f, false),
new(-28f, 1.8f, -16f, 4.5f, 1.8f, 1.4f, false),
new(16f, 1.8f, -32f, 1.4f, 1.8f, 4.5f, false),
new(-16f, 1.8f, 32f, 1.4f, 1.8f, 4.5f, false),
new(58f, 2.2f, 18f, 3.2f, 2.2f, 3.2f, false),
new(-58f, 2.2f, -18f, 3.2f, 2.2f, 3.2f, false),
new(22f, 2.2f, 62f, 5.0f, 2.2f, 1.6f, false),
new(-22f, 2.2f, -62f, 5.0f, 2.2f, 1.6f, false),
new(72f, 1.6f, -52f, 2.8f, 1.6f, 2.8f, false),
new(-72f, 1.6f, 52f, 2.8f, 1.6f, 2.8f, false),
new(46f, 2.0f, -72f, 4.0f, 2.0f, 1.5f, false),
new(-46f, 2.0f, 72f, 4.0f, 2.0f, 1.5f, false),
new(118f, 2.4f, 24f, 3.5f, 2.4f, 3.5f, false),
new(-118f, 2.4f, -24f, 3.5f, 2.4f, 3.5f, false),
new(24f, 2.4f, -118f, 3.5f, 2.4f, 3.5f, false),
new(-24f, 2.4f, 118f, 3.5f, 2.4f, 3.5f, false)
};
float a = (i / 4f) * MathF.Tau + 0.35f;
bool rot = i % 2 == 0;
boxes.Add(new ArenaBoxSpec(
MathF.Cos(a) * 68f, 2.0f, MathF.Sin(a) * 68f,
rot ? 5.2f : 1.6f, 2.0f, rot ? 1.6f : 5.2f, false));
}
// Inner-mid ruins (8 blocks at r = 175m)
for (int i = 0; i < 8; i++)
{
float a = (i / 8f) * MathF.Tau + 0.15f;
bool bunker = i % 3 == 0;
boxes.Add(new ArenaBoxSpec(
MathF.Cos(a) * 175f, 2.3f, MathF.Sin(a) * 175f,
bunker ? 3.8f : (i % 2 == 0 ? 5.8f : 1.8f),
2.3f,
bunker ? 3.8f : (i % 2 == 0 ? 1.8f : 5.8f),
false));
}
// Mid-valley pass ruins (12 blocks at r = 335m)
for (int i = 0; i < 12; i++)
{
float a = (i / 12f) * MathF.Tau + 0.22f;
bool bunker = i % 2 == 0;
boxes.Add(new ArenaBoxSpec(
MathF.Cos(a) * 335f, 2.4f, MathF.Sin(a) * 335f,
bunker ? 4.0f : 6.0f, 2.4f, bunker ? 4.0f : 1.8f, false));
}
// Outer rim ruins (12 blocks at r = 515m)
for (int i = 0; i < 12; i++)
{
float a = (i / 12f) * MathF.Tau + 0.08f;
bool tall = i % 3 == 0;
boxes.Add(new ArenaBoxSpec(
MathF.Cos(a) * 515f, tall ? 2.8f : 2.2f, MathF.Sin(a) * 515f,
tall ? 3.6f : 5.6f, tall ? 2.8f : 2.2f, tall ? 3.6f : 1.8f, false));
}
return boxes;
}
private static IReadOnlyList<ArenaBoxSpec> SeatBoxesOnTerrain(IReadOnlyList<ArenaBoxSpec> raw, TerrainField terrain)
@ -384,9 +485,9 @@ namespace RustToDust.Core
private static IReadOnlyList<ArenaBoxSpec> BuildBoundaryBoxes()
{
const float wallY = 2f;
const float wallHalfH = 10f;
const float wallHalfThick = 2f;
const float wallY = 12f;
const float wallHalfH = 60f;
const float wallHalfThick = 4f;
const float span = ArenaHalfExtent + wallHalfThick;
return new ArenaBoxSpec[]
{

View file

@ -17,7 +17,7 @@ namespace RustToDust.Core
Provoked
}
public readonly record struct RingContact(int Id, float X, float Z, bool Alive);
public readonly record struct RingContact(int Id, float X, float Z, bool Alive, float Y = 0f, float HalfHeight = 1f);
public sealed class SpectatorState
{
@ -57,6 +57,17 @@ namespace RustToDust.Core
public int? TargetContenderId { get; set; }
public bool BroadcastWakeupEmitted { get; set; }
public bool HasTargetLos { get; set; }
public float LastKnownTargetX { get; set; }
public float LastKnownTargetY { get; set; }
public float LastKnownTargetZ { get; set; }
public float TimeSinceLastSeen { get; set; } = float.PositiveInfinity;
public bool HasNeutralAnchor { get; set; }
public float NeutralAnchorX { get; set; }
public float NeutralAnchorZ { get; set; }
public float NeutralAnchorSafeRadius { get; set; }
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
@ -66,11 +77,12 @@ namespace RustToDust.Core
public sealed class SpectatorRing
{
public const float InitialRadius = 150f;
public const float MinRadius = 35f;
public const float GraceDuration = 20f;
public const float ShrinkDuration = 240f;
public const int DefaultSpectatorCount = 40;
public const float InitialRadius = 560f;
public const float MinRadius = 85f;
public const float GraceDuration = 30f;
public const float ShrinkDuration = 360f;
public const int DefaultSpectatorCount = 56;
public const float TargetMemoryDuration = 4.0f;
private readonly List<SpectatorState> _spectators = new();
private readonly Dictionary<int, bool> _aliveById = new();
@ -97,7 +109,13 @@ namespace RustToDust.Core
SafeRadius = InitialRadius + (MinRadius - InitialRadius) * t;
}
public void UpdateClearance(ReadOnlySpan<RingContact> contenders)
public void UpdateClearance(ReadOnlySpan<RingContact> contenders) =>
UpdateClearance(contenders, 0f, null);
public void UpdateClearance(
ReadOnlySpan<RingContact> contenders,
float dt,
Func<SpectatorState, RingContact, bool>? hasLos)
{
_aliveById.Clear();
for (int i = 0; i < contenders.Length; i++)
@ -105,13 +123,20 @@ namespace RustToDust.Core
_aliveById[contenders[i].Id] = contenders[i].Alive;
}
Span<int> prevTargets = _spectators.Count <= 256
? stackalloc int[_spectators.Count]
: new int[_spectators.Count];
// Keep Provoked lock while target is alive; reset Cleared to Neutral for clean re-evaluation.
for (int i = 0; i < _spectators.Count; i++)
{
var spec = _spectators[i];
prevTargets[i] = spec.TargetContenderId ?? -1;
if (!spec.Alive)
{
spec.TargetContenderId = null;
spec.HasTargetLos = false;
continue;
}
@ -123,16 +148,37 @@ namespace RustToDust.Core
{
spec.Stance = SpectatorStance.Neutral;
spec.TargetContenderId = null;
spec.HasTargetLos = false;
spec.TimeSinceLastSeen = float.PositiveInfinity;
}
else
{
var contact = FindContact(contenders, spec.TargetContenderId.Value);
bool los = hasLos is null || hasLos(spec, contact);
if (los)
{
spec.HasTargetLos = true;
spec.LastKnownTargetX = contact.X;
spec.LastKnownTargetY = contact.Y;
spec.LastKnownTargetZ = contact.Z;
spec.TimeSinceLastSeen = 0f;
}
else
{
spec.HasTargetLos = false;
spec.TimeSinceLastSeen += dt;
}
}
}
else
{
spec.Stance = SpectatorStance.Neutral;
spec.TargetContenderId = null;
spec.HasTargetLos = false;
}
}
// Assign Cleared spectators to contenders outside the Safe Circle.
// Assign Cleared spectators to contenders outside the Safe Circle, prioritizing spectators with LOS.
for (int c = 0; c < contenders.Length; c++)
{
var contender = contenders[c];
@ -149,12 +195,60 @@ namespace RustToDust.Core
}
int allowedCleared = Math.Min(8, 1 + (int)(outsideDist / 12f));
int assigned = 0;
for (int k = 0; k < allowedCleared; k++)
// Pass 1: Spectators with direct LOS to the offender.
while (assigned < allowedCleared)
{
SpectatorState? nearest = null;
int bestIdx = -1;
float bestDistSq = float.PositiveInfinity;
for (int i = 0; i < _spectators.Count; i++)
{
var spec = _spectators[i];
if (!spec.Alive || spec.Stance != SpectatorStance.Neutral)
{
continue;
}
if (hasLos is not null && !hasLos(spec, contender))
{
continue;
}
float dx = spec.X - contender.X;
float dz = spec.Z - contender.Z;
float d2 = dx * dx + dz * dz;
if (d2 < bestDistSq)
{
bestDistSq = d2;
bestIdx = i;
}
}
if (bestIdx < 0)
{
break;
}
var chosen = _spectators[bestIdx];
chosen.Stance = SpectatorStance.Cleared;
chosen.TargetContenderId = contender.Id;
chosen.HasTargetLos = true;
chosen.LastKnownTargetX = contender.X;
chosen.LastKnownTargetY = contender.Y;
chosen.LastKnownTargetZ = contender.Z;
chosen.TimeSinceLastSeen = 0f;
assigned++;
}
// Pass 2: If fewer than allowedCleared have LOS (e.g. offender ducked behind a ridge),
// clear nearby spectators with recent memory or closest flanking interceptors so they maneuver over the ridge.
while (assigned < allowedCleared && hasLos is not null)
{
int bestIdx = -1;
float bestScore = float.PositiveInfinity;
for (int i = 0; i < _spectators.Count; i++)
{
var spec = _spectators[i];
@ -166,20 +260,36 @@ namespace RustToDust.Core
float dx = spec.X - contender.X;
float dz = spec.Z - contender.Z;
float d2 = dx * dx + dz * dz;
if (d2 < bestDistSq)
bool hasMemory = prevTargets[i] == contender.Id && spec.TimeSinceLastSeen < TargetMemoryDuration;
float score = hasMemory ? d2 * 0.25f : d2;
if (score < bestScore)
{
bestDistSq = d2;
nearest = spec;
bestScore = score;
bestIdx = i;
}
}
if (nearest is null)
if (bestIdx < 0)
{
break;
}
nearest.Stance = SpectatorStance.Cleared;
nearest.TargetContenderId = contender.Id;
var chosen = _spectators[bestIdx];
chosen.Stance = SpectatorStance.Cleared;
chosen.TargetContenderId = contender.Id;
chosen.HasTargetLos = false;
if (prevTargets[bestIdx] == contender.Id && chosen.TimeSinceLastSeen < TargetMemoryDuration)
{
chosen.TimeSinceLastSeen += dt;
}
else
{
chosen.LastKnownTargetX = contender.X;
chosen.LastKnownTargetY = contender.Y;
chosen.LastKnownTargetZ = contender.Z;
chosen.TimeSinceLastSeen = 0f;
}
assigned++;
}
}
}
@ -211,8 +321,12 @@ namespace RustToDust.Core
continue;
}
float angularSpeed = spec.Tier == SpectatorTier.Exemplar ? 0.045f : 0.02f;
spec.RingAngle += angularSpeed * dt;
// Only ostentatious Tourists orbit continuously in plain sight;
// Patrons and Exemplars hold their chosen high-ground / ambush positions.
if (spec.Tier == SpectatorTier.Tourist)
{
spec.RingAngle += 0.02f * dt;
}
}
}
@ -222,6 +336,96 @@ namespace RustToDust.Core
return (MathF.Cos(spec.RingAngle) * r, MathF.Sin(spec.RingAngle) * r);
}
public (float X, float Z) GetNeutralGoal(
SpectatorState spec,
TerrainField? terrain,
IReadOnlyList<ArenaBoxSpec>? coverBoxes)
{
if (spec.Tier == SpectatorTier.Tourist || terrain is null)
{
return GetPerimeterSlot(spec);
}
if (spec.HasNeutralAnchor && MathF.Abs(SafeRadius - spec.NeutralAnchorSafeRadius) < 8f)
{
return (spec.NeutralAnchorX, spec.NeutralAnchorZ);
}
float bestX = MathF.Cos(spec.RingAngle) * (SafeRadius + spec.RingOffset);
float bestZ = MathF.Sin(spec.RingAngle) * (SafeRadius + spec.RingOffset);
float bestScore = float.NegativeInfinity;
float maxBound = TerrainField.HalfExtent - 18f;
for (int ai = -3; ai <= 3; ai++)
{
float angle = spec.RingAngle + ai * 0.075f;
float cosA = MathF.Cos(angle);
float sinA = MathF.Sin(angle);
for (int ri = 0; ri < 3; ri++)
{
float r = SafeRadius + 18f + ri * 26f;
float cx = Math.Clamp(cosA * r, -maxBound, maxBound);
float cz = Math.Clamp(sinA * r, -maxBound, maxBound);
float distLen = MathF.Sqrt(cx * cx + cz * cz);
float inX = distLen > 1f ? -cx / distLen : 0f;
float inZ = distLen > 1f ? -cz / distLen : -1f;
float hHere = terrain.SampleHeight(cx, cz);
float hInward = terrain.SampleHeight(cx + inX * 26f, cz + inZ * 26f);
float score;
if (spec.Tier == SpectatorTier.Patron)
{
// Patrons claim elevated vantage points overlooking the arena interior
score = hHere * 2.0f + MathF.Max(0f, hHere - hInward) * 1.1f;
}
else
{
// Exemplars seek reverse-slope / low-profile / cover-adjacent ambush spots
float reverseSlope = MathF.Max(0f, hInward - hHere) * 3.0f;
float lowProfile = -hHere * 0.8f;
float coverBonus = 0f;
if (coverBoxes is not null)
{
for (int b = 0; b < coverBoxes.Count; b++)
{
var box = coverBoxes[b];
float bx = box.X - cx;
float bz = box.Z - cz;
float bDist2 = bx * bx + bz * bz;
if (bDist2 < 28f * 28f && bDist2 > 4f * 4f)
{
// Prefer cover standing between the exemplar and the interior
float forwardDot = bx * inX + bz * inZ;
if (forwardDot > 2f)
{
coverBonus = 14f;
break;
}
}
}
}
score = reverseSlope + lowProfile + coverBonus;
}
if (score > bestScore)
{
bestScore = score;
bestX = cx;
bestZ = cz;
}
}
}
spec.NeutralAnchorX = bestX;
spec.NeutralAnchorZ = bestZ;
spec.NeutralAnchorSafeRadius = SafeRadius;
spec.HasNeutralAnchor = true;
return (bestX, bestZ);
}
public int CountClearedFor(int contenderId)
{
int count = 0;
@ -257,7 +461,6 @@ namespace RustToDust.Core
{
case SpectatorTier.Tourist:
{
// Guaranteed 1-2 Imperial high-end modules
int count = rng.Next(1, 3);
for (int i = 0; i < count; i++)
{
@ -267,7 +470,6 @@ namespace RustToDust.Core
}
case SpectatorTier.Patron:
{
// Mixed salvage: 1 module (50% imperial, 50% human upgraded)
if (rng.NextDouble() < 0.5)
{
drops.Add(Catalog.ImperialModules[rng.Next(Catalog.ImperialModules.Count)]);
@ -280,7 +482,6 @@ namespace RustToDust.Core
}
case SpectatorTier.Exemplar:
{
// Minimal/no high-end loot: only an occasional modest scrap trophy (never IsImperial)
if (rng.NextDouble() < 0.4)
{
drops.Add(Catalog.WeldedPlate);
@ -291,9 +492,20 @@ namespace RustToDust.Core
return drops;
}
private static RingContact FindContact(ReadOnlySpan<RingContact> contenders, int id)
{
for (int i = 0; i < contenders.Length; i++)
{
if (contenders[i].Id == id)
{
return contenders[i];
}
}
return default;
}
private void SpawnRing(Random rng, int count)
{
// ~45% Tourists, ~35% Patrons, ~20% Exemplars
int touristCount = (int)MathF.Round(count * 0.45f);
int patronCount = (int)MathF.Round(count * 0.35f);
@ -305,7 +517,6 @@ namespace RustToDust.Core
else tiers.Add(SpectatorTier.Exemplar);
}
// Deterministic shuffle so tiers are evenly distributed around the perimeter
for (int i = tiers.Count - 1; i > 0; i--)
{
int j = rng.Next(i + 1);
@ -315,7 +526,7 @@ namespace RustToDust.Core
for (int i = 0; i < count; i++)
{
float angle = (i / (float)count) * MathF.Tau;
float ringOffset = 10f + (float)rng.NextDouble() * 16f;
float ringOffset = 25f + (float)rng.NextDouble() * 50f;
var tier = tiers[i];
var spec = CreateSpectator(1000 + i, tier, angle, ringOffset);
@ -353,8 +564,8 @@ namespace RustToDust.Core
id, tier, grid, angle, ringOffset,
radarSignature: 1.0f,
aimSpreadRad: 0.14f,
maxSpeed: 16f,
preferredRange: 42f);
maxSpeed: 18f,
preferredRange: 95f);
}
case SpectatorTier.Patron:
{
@ -367,12 +578,11 @@ namespace RustToDust.Core
id, tier, grid, angle, ringOffset,
radarSignature: 0.6f,
aimSpreadRad: 0.055f,
maxSpeed: 24f,
preferredRange: 36f);
maxSpeed: 26f,
preferredRange: 82f);
}
default: // Exemplar
{
// Lightly armored, lethal precision, blazing speed
var exemplarSpec = Catalog.Raptor with
{
Id = "exemplar_frame",
@ -381,7 +591,7 @@ namespace RustToDust.Core
MassKg = 1150f,
BaseThrust = 26000f,
BaseTurnRate = 6.2f,
MaxSpeed = 38f,
MaxSpeed = 40f,
HalfWidth = 0.8f,
HalfHeight = 1.55f,
HalfLength = 0.8f
@ -394,10 +604,10 @@ namespace RustToDust.Core
MountRequired(grid, Catalog.GoldRadiator, "rad_rsh");
return new SpectatorState(
id, tier, grid, angle, ringOffset,
radarSignature: 0.22f,
radarSignature: 0.18f,
aimSpreadRad: 0.006f,
maxSpeed: 38f,
preferredRange: 24f);
maxSpeed: 40f,
preferredRange: 58f);
}
}
}

View file

@ -32,12 +32,13 @@ namespace RustToDust.Core
public sealed class TerrainField
{
public const float ArenaSize = 384f;
public const float HalfExtent = 192f;
public const int TileGridCount = 4;
public const float TileSize = ArenaSize / TileGridCount; // 96m
public const float MinWorldHeight = -12f;
public const float MaxWorldHeight = 16f;
public const float ArenaSize = 1536f;
public const float HalfExtent = 768f;
public const int TileGridCount = 8;
public const float TileSize = ArenaSize / TileGridCount; // 192m
public const float MinWorldHeight = -18f;
public const float MaxWorldHeight = 52f;
public const float HeightSpan = MaxWorldHeight - MinWorldHeight; // 70m
public const int MaxDynamicDecals = 256;
private readonly List<TerrainBrush> _brushes = new();
@ -53,7 +54,7 @@ namespace RustToDust.Core
{
for (int tx = 0; tx < TileGridCount; tx++)
{
_tileBrushIndices[tx, tz] = new List<int>(24);
_tileBrushIndices[tx, tz] = new List<int>(32);
}
}
}
@ -61,9 +62,9 @@ namespace RustToDust.Core
public ulong Seed { get; }
public IReadOnlyList<TerrainBrush> Brushes => _brushes;
public int[,] TileVersions { get; }
public uint DirtyTileMask { get; private set; }
public ulong DirtyTileMask { get; private set; }
public void ClearDirtyMask() => DirtyTileMask = 0u;
public void ClearDirtyMask() => DirtyTileMask = 0UL;
public IReadOnlyList<int> GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz];
@ -79,9 +80,9 @@ namespace RustToDust.Core
X: 0f,
Z: 0f,
RotationRad: 0f,
RadiusX: 16f,
RadiusZ: 16f,
HeightDelta: 0.15f,
RadiusX: 28f,
RadiusZ: 28f,
HeightDelta: 0.20f,
Roughness: 0.90f,
Metallic: 0.05f,
AlbedoR: 0.44f,
@ -92,7 +93,7 @@ namespace RustToDust.Core
for (int i = 0; i < coverBoxes.Count; i++)
{
var box = coverBoxes[i];
float padR = MathF.Max(box.HalfX, box.HalfZ) + 7.5f;
float padR = MathF.Max(box.HalfX, box.HalfZ) + 12f;
field.AddBrush(new TerrainBrush(
Id: 0,
Kind: TerrainBrushKind.SalvagePad,
@ -101,7 +102,7 @@ namespace RustToDust.Core
RotationRad: 0f,
RadiusX: padR,
RadiusZ: padR,
HeightDelta: 0.1f + (float)rng.NextDouble() * 0.25f,
HeightDelta: 0.10f + (float)rng.NextDouble() * 0.25f,
Roughness: 0.92f,
Metallic: 0.04f,
AlbedoR: 0.42f,
@ -110,12 +111,12 @@ namespace RustToDust.Core
Dynamic: false));
}
// 2. Dirt track ring segments around the mid-arena loop (r ~ 76..92m)
const int roadCount = 8;
// 2. Dirt track ring segments around the mid-valley loop (r ~ 260..290m)
const int roadCount = 16;
for (int i = 0; i < roadCount; i++)
{
float angle = (i / (float)roadCount) * MathF.Tau + 0.18f;
float r = 82f + (float)(rng.NextDouble() * 8.0 - 4.0);
float angle = (i / (float)roadCount) * MathF.Tau + 0.14f;
float r = 275f + (float)(rng.NextDouble() * 20.0 - 10.0);
float rx = MathF.Cos(angle) * r;
float rz = MathF.Sin(angle) * r;
float tangentRot = angle + MathF.PI * 0.5f;
@ -125,9 +126,9 @@ namespace RustToDust.Core
X: rx,
Z: rz,
RotationRad: tangentRot,
RadiusX: 34f,
RadiusZ: 9f,
HeightDelta: -0.18f,
RadiusX: 64f,
RadiusZ: 11f,
HeightDelta: -0.22f,
Roughness: 0.94f,
Metallic: 0.02f,
AlbedoR: 0.56f,
@ -136,68 +137,20 @@ namespace RustToDust.Core
Dynamic: false));
}
// 3. Sweeping desert dune ridges (~20 ridges + 2 dry-wash troughs), kept clear of cover box pads
int duneCount = 0;
int attempts = 0;
while (duneCount < 20 && attempts < 360)
{
attempts++;
float x = (float)(rng.NextDouble() * 300.0 - 150.0);
float z = (float)(rng.NextDouble() * 300.0 - 150.0);
float radiusX = 12f + (float)rng.NextDouble() * 11f;
float radiusZ = 24f + (float)rng.NextDouble() * 22f;
if (MathF.Abs(field.SampleHeight(x, z)) > 1.8f)
{
continue;
}
bool dryWash = duneCount is 5 or 13;
float heightDelta = dryWash
? -(1.2f + (float)rng.NextDouble() * 0.9f)
: 1.6f + (float)rng.NextDouble() * 2.0f;
float rot = (float)(rng.NextDouble() * MathF.PI);
var candidate = new TerrainBrush(
Id: 0,
Kind: TerrainBrushKind.DuneRidge,
X: x,
Z: z,
RotationRad: rot,
RadiusX: radiusX,
RadiusZ: radiusZ,
HeightDelta: heightDelta,
Roughness: dryWash ? 0.96f : 0.89f,
Metallic: 0.02f,
AlbedoR: dryWash ? 0.58f : 0.78f,
AlbedoG: dryWash ? 0.41f : 0.56f,
AlbedoB: dryWash ? 0.27f : 0.34f,
Dynamic: false);
if (!IsBrushClearOfCover(in candidate, coverBoxes))
{
continue;
}
field.AddBrush(candidate);
duneCount++;
}
// 4. Terraced rust-mesa hills (~7 mesas), mainly mid/outer desert away from spawns & cover
// 3. Tall flat-topped rust mesas & buttes (+22m..+44m, radius 45..110m) for huge landmarks and full hull-down cover
int mesaCount = 0;
attempts = 0;
while (mesaCount < 7 && attempts < 200)
int attempts = 0;
while (mesaCount < 14 && attempts < 500)
{
attempts++;
float angle = (float)(rng.NextDouble() * MathF.Tau);
float dist = 54f + (float)rng.NextDouble() * 116f;
float dist = 125f + (float)rng.NextDouble() * 520f;
float x = MathF.Cos(angle) * dist;
float z = MathF.Sin(angle) * dist;
float rx = 14f + (float)rng.NextDouble() * 10f;
float rz = 13f + (float)rng.NextDouble() * 10f;
float rx = 45f + (float)rng.NextDouble() * 65f;
float rz = 45f + (float)rng.NextDouble() * 65f;
if (OverlapsSpawnRing(x, z, MathF.Max(rx, rz) + 5f) ||
MathF.Abs(field.SampleHeight(x, z)) > 1.6f)
if (MathF.Abs(field.SampleHeight(x, z)) > 4.0f)
{
continue;
}
@ -210,7 +163,7 @@ namespace RustToDust.Core
RotationRad: (float)(rng.NextDouble() * MathF.PI),
RadiusX: rx,
RadiusZ: rz,
HeightDelta: 3.1f + (float)rng.NextDouble() * 2.4f,
HeightDelta: 22f + (float)rng.NextDouble() * 22f,
Roughness: 0.86f,
Metallic: 0.08f,
AlbedoR: 0.48f,
@ -227,13 +180,100 @@ namespace RustToDust.Core
mesaCount++;
}
// 4. Sweeping high sand dune ridges (+10m..+26m, RadiusX 90..180m, RadiusZ 30..65m) forming blind crests
int duneCount = 0;
attempts = 0;
while (duneCount < 30 && attempts < 700)
{
attempts++;
float x = (float)(rng.NextDouble() * 1280.0 - 640.0);
float z = (float)(rng.NextDouble() * 1280.0 - 640.0);
float radiusX = 90f + (float)rng.NextDouble() * 90f;
float radiusZ = 30f + (float)rng.NextDouble() * 35f;
if (field.SampleHeight(x, z) > 15f)
{
continue;
}
float heightDelta = 10f + (float)rng.NextDouble() * 16f;
float rot = (float)(rng.NextDouble() * MathF.PI);
var candidate = new TerrainBrush(
Id: 0,
Kind: TerrainBrushKind.DuneRidge,
X: x,
Z: z,
RotationRad: rot,
RadiusX: radiusX,
RadiusZ: radiusZ,
HeightDelta: heightDelta,
Roughness: 0.89f,
Metallic: 0.02f,
AlbedoR: 0.78f,
AlbedoG: 0.56f,
AlbedoB: 0.34f,
Dynamic: false);
if (!IsBrushClearOfCover(in candidate, coverBoxes))
{
continue;
}
field.AddBrush(candidate);
duneCount++;
}
// 5. Deep dry canyons / arroyos (-8m..-16m carved washes) letting buggies run concealed below the skyline
int canyonCount = 0;
attempts = 0;
while (canyonCount < 12 && attempts < 450)
{
attempts++;
float x = (float)(rng.NextDouble() * 1160.0 - 580.0);
float z = (float)(rng.NextDouble() * 1160.0 - 580.0);
float radiusX = 42f + (float)rng.NextDouble() * 34f;
float radiusZ = 115f + (float)rng.NextDouble() * 85f;
float curH = field.SampleHeight(x, z);
if (curH < -2.5f || curH > 12f)
{
continue;
}
float heightDelta = -(8f + (float)rng.NextDouble() * 7.5f);
float rot = (float)(rng.NextDouble() * MathF.PI);
var candidate = new TerrainBrush(
Id: 0,
Kind: TerrainBrushKind.DuneRidge,
X: x,
Z: z,
RotationRad: rot,
RadiusX: radiusX,
RadiusZ: radiusZ,
HeightDelta: heightDelta,
Roughness: 0.96f,
Metallic: 0.02f,
AlbedoR: 0.54f,
AlbedoG: 0.38f,
AlbedoB: 0.25f,
Dynamic: false);
if (!IsBrushClearOfCover(in candidate, coverBoxes))
{
continue;
}
field.AddBrush(candidate);
canyonCount++;
}
// Bump all initial tile versions to 1 so clients detect initial bake needed
for (int tz = 0; tz < TileGridCount; tz++)
{
for (int tx = 0; tx < TileGridCount; tx++)
{
field.TileVersions[tx, tz] = 1;
field.DirtyTileMask |= 1u << (tz * TileGridCount + tx);
field.DirtyTileMask |= 1UL << (tz * TileGridCount + tx);
}
}
@ -263,7 +303,7 @@ namespace RustToDust.Core
public void StampTrack(float x, float z, float yaw, float width, float length)
{
var brush = SetDynamicDecal(new TerrainBrush(
SetDynamicDecal(new TerrainBrush(
Id: 0,
Kind: TerrainBrushKind.Track,
X: x,
@ -278,7 +318,6 @@ namespace RustToDust.Core
AlbedoG: 0.29f,
AlbedoB: 0.18f,
Dynamic: true));
_ = brush;
}
public void StampScorch(float x, float z, float radius)
@ -347,7 +386,6 @@ namespace RustToDust.Core
float maxDistance,
out float hitX, out float hitY, out float hitZ, out float hitDist)
{
const float stepSize = 1.5f;
float prevT = 0f;
float prevDiff = oy - SampleHeight(ox, oz);
if (prevDiff <= 0f)
@ -359,7 +397,8 @@ namespace RustToDust.Core
return true;
}
for (float t = stepSize; t <= maxDistance + stepSize; t += stepSize)
float t = 1.5f;
while (prevT < maxDistance)
{
float ct = MathF.Min(t, maxDistance);
float px = ox + dx * ct;
@ -401,6 +440,8 @@ namespace RustToDust.Core
{
break;
}
t = ct + (ct < 160f ? 1.5f : 2.5f);
}
hitX = 0f;
@ -507,7 +548,7 @@ namespace RustToDust.Core
if (incrementTileVersion)
{
TileVersions[tx, tz]++;
DirtyTileMask |= 1u << (tz * TileGridCount + tx);
DirtyTileMask |= 1UL << (tz * TileGridCount + tx);
}
}
}
@ -522,14 +563,14 @@ namespace RustToDust.Core
{
_tileBrushIndices[tx, tz].Remove(index);
TileVersions[tx, tz]++;
DirtyTileMask |= 1u << (tz * TileGridCount + tx);
DirtyTileMask |= 1UL << (tz * TileGridCount + tx);
}
}
}
private static void GetBrushTileBounds(in TerrainBrush brush, out int minTx, out int maxTx, out int minTz, out int maxTz)
{
const float gutterPaddingMeters = 1.0f;
const float gutterPaddingMeters = 3.5f;
float extent = MathF.Sqrt(brush.RadiusX * brush.RadiusX + brush.RadiusZ * brush.RadiusZ) + gutterPaddingMeters;
float minX = brush.X - extent;
float maxX = brush.X + extent;
@ -550,34 +591,28 @@ namespace RustToDust.Core
private static bool IsBrushClearOfCover(in TerrainBrush candidate, IReadOnlyList<ArenaBoxSpec> coverBoxes)
{
if (MathF.Abs(EvaluateBrushHeight(in candidate, 0f, 0f)) > 0.35f)
if (MathF.Abs(EvaluateBrushHeight(in candidate, 0f, 0f)) > 0.25f)
{
return false;
}
const float margin = 1.5f;
const float margin = 2.0f;
for (int i = 0; i < coverBoxes.Count; i++)
{
var c = coverBoxes[i];
float hx = c.HalfX + margin;
float hz = c.HalfZ + margin;
if (MathF.Abs(EvaluateBrushHeight(in candidate, c.X, c.Z)) > 0.35f ||
MathF.Abs(EvaluateBrushHeight(in candidate, c.X - hx, c.Z - hz)) > 0.35f ||
MathF.Abs(EvaluateBrushHeight(in candidate, c.X + hx, c.Z - hz)) > 0.35f ||
MathF.Abs(EvaluateBrushHeight(in candidate, c.X - hx, c.Z + hz)) > 0.35f ||
MathF.Abs(EvaluateBrushHeight(in candidate, c.X + hx, c.Z + hz)) > 0.35f)
if (MathF.Abs(EvaluateBrushHeight(in candidate, c.X, c.Z)) > 0.25f ||
MathF.Abs(EvaluateBrushHeight(in candidate, c.X - hx, c.Z - hz)) > 0.25f ||
MathF.Abs(EvaluateBrushHeight(in candidate, c.X + hx, c.Z - hz)) > 0.25f ||
MathF.Abs(EvaluateBrushHeight(in candidate, c.X - hx, c.Z + hz)) > 0.25f ||
MathF.Abs(EvaluateBrushHeight(in candidate, c.X + hx, c.Z + hz)) > 0.25f)
{
return false;
}
}
return true;
}
private static bool OverlapsSpawnRing(float x, float z, float radius)
{
float dist = MathF.Sqrt(x * x + z * z);
return MathF.Abs(dist - 95f) < radius + 6f;
}
}
}

View file

@ -10,11 +10,11 @@ namespace RustToDust.Ymir
{
public const float FixedDt = 1f / 60f;
public const int SubStepCount = 4;
public const int WorldBodyCapacity = 256;
public const int WorldBodyCapacity = 384;
private const ulong GroundStableId = 1;
private const ulong StaticBoxStableIdBase = 10;
private const ulong ContenderStableIdBase = 1000;
public const ulong ContenderStableIdBase = 1000;
private const ulong SpectatorStableIdBase = 3000;
private readonly Box3DSoaWorld _world;
@ -38,6 +38,7 @@ namespace RustToDust.Ymir
BuildStaticArena();
SpawnContenderBodies();
SpawnSpectatorBodies();
UpdatePlayerDetectionMemory();
}
public MatchState State { get; }
@ -55,6 +56,161 @@ namespace RustToDust.Ymir
public Box3DSoaBodyHandle? GetSpectatorBody(int spectatorId) =>
_spectatorBodies.TryGetValue(spectatorId, out var h) ? h : null;
public void SetContenderPose(int contenderId, float x, float z, float? yaw = null)
{
if (contenderId < 0 || contenderId >= State.Contenders.Count)
{
return;
}
var c = State.Contenders[contenderId];
float y = State.Terrain.SampleHeight(x, z) + c.Grid.Spec.HalfHeight + 0.15f;
c.X = x;
c.Y = y;
c.Z = z;
if (yaw.HasValue) c.Yaw = yaw.Value;
if (_contenderBodies.TryGetValue(contenderId, out var handle))
{
var view = _world.View;
int lane = handle.Lane;
view.PositionX[lane] = x;
view.PositionY[lane] = y;
view.PositionZ[lane] = z;
view.VelocityX[lane] = 0f;
view.VelocityY[lane] = 0f;
view.VelocityZ[lane] = 0f;
if (yaw.HasValue)
{
var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw.Value);
view.RotationX[lane] = q.X;
view.RotationY[lane] = q.Y;
view.RotationZ[lane] = q.Z;
view.RotationW[lane] = q.W;
}
}
}
public void SetSpectatorPose(int spectatorId, float x, float z, float? yaw = null)
{
SpectatorState? spec = null;
for (int i = 0; i < State.Spectators.Spectators.Count; i++)
{
if (State.Spectators.Spectators[i].Id == spectatorId)
{
spec = State.Spectators.Spectators[i];
break;
}
}
if (spec is null)
{
return;
}
float y = State.Terrain.SampleHeight(x, z) + spec.Grid.Spec.HalfHeight + 0.15f;
spec.X = x;
spec.Y = y;
spec.Z = z;
if (yaw.HasValue) spec.Yaw = yaw.Value;
if (_spectatorBodies.TryGetValue(spectatorId, out var handle))
{
var view = _world.View;
int lane = handle.Lane;
view.PositionX[lane] = x;
view.PositionY[lane] = y;
view.PositionZ[lane] = z;
view.VelocityX[lane] = 0f;
view.VelocityY[lane] = 0f;
view.VelocityZ[lane] = 0f;
if (yaw.HasValue)
{
var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw.Value);
view.RotationX[lane] = q.X;
view.RotationY[lane] = q.Y;
view.RotationZ[lane] = q.Z;
view.RotationW[lane] = q.W;
}
}
}
public bool HasLineOfSight(float ax, float ay, float az, float bx, float by, float bz)
{
var delta = new Vector3(bx - ax, by - ay, bz - az);
float dist = delta.Length();
if (dist <= 0.25f)
{
return true;
}
Vector3 dir = delta / dist;
if (State.Terrain.Raycast(
ax, ay, az,
dir.X, dir.Y, dir.Z,
MathF.Max(0.1f, dist - 0.5f),
out _, out _, out _, out _))
{
return false;
}
var hit = _world.CastRayClosest((ax, ay, az), (delta.X, delta.Y, delta.Z));
if (!hit.Hit)
{
return true;
}
if (hit.StableId >= StaticBoxStableIdBase && hit.StableId < ContenderStableIdBase)
{
return false;
}
// If a dynamic body caught the single closest ray, verify no static cover wall lies along the segment.
return !IntersectsAnyCoverBox(ax, ay, az, dir.X, dir.Y, dir.Z, dist);
}
private bool IntersectsAnyCoverBox(float ox, float oy, float oz, float dx, float dy, float dz, float maxDist)
{
var boxes = State.ArenaCoverBoxes;
for (int i = 0; i < boxes.Count; i++)
{
var b = boxes[i];
if (RayIntersectsAabb(ox, oy, oz, dx, dy, dz, maxDist, b))
{
return true;
}
}
return false;
}
private static bool RayIntersectsAabb(
float ox, float oy, float oz,
float dx, float dy, float dz,
float maxDist,
in ArenaBoxSpec box)
{
float tMin = 0f;
float tMax = maxDist;
if (!SlabTest(ox, dx, box.X - box.HalfX, box.X + box.HalfX, ref tMin, ref tMax)) return false;
if (!SlabTest(oy, dy, box.Y - box.HalfY, box.Y + box.HalfY, ref tMin, ref tMax)) return false;
if (!SlabTest(oz, dz, box.Z - box.HalfZ, box.Z + box.HalfZ, ref tMin, ref tMax)) return false;
return tMax >= tMin;
}
private static bool SlabTest(float o, float d, float minB, float maxB, ref float tMin, ref float tMax)
{
if (MathF.Abs(d) < 1e-6f)
{
return o >= minB && o <= maxB;
}
float invD = 1f / d;
float t1 = (minB - o) * invD;
float t2 = (maxB - o) * invD;
if (t1 > t2) (t1, t2) = (t2, t1);
tMin = MathF.Max(tMin, t1);
tMax = MathF.Min(tMax, t2);
return tMax >= tMin;
}
public void Step(PlayerInput input)
{
ObjectDisposedException.ThrowIf(_disposed, this);
@ -66,12 +222,13 @@ namespace RustToDust.Ymir
UpdateRingClearance();
MatchRules.ApplyPlayerInput(State, input);
MatchRules.UpdateAiContenders(State, FixedDt);
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight);
ApplyPhysicsDrives();
_world.Step(FixedDt, SubStepCount);
SyncBodiesFromWorld();
UpdatePlayerDetectionMemory();
StepThermalAndCooldowns();
ProcessWeapons();
MatchRules.UpdateMatchOutcome(State);
@ -79,12 +236,12 @@ namespace RustToDust.Ymir
private void BuildStaticArena()
{
// Safety floor slab at y = -12m below the lowest possible terrain valley;
// Safety floor slab at y = -20m below the lowest possible terrain valley (-18m);
// primary terrain support comes from 4-corner spring-damper sampling of State.Terrain.
_world.AddStaticBox(
GroundStableId,
(0f, -13f, 0f),
(210f, 1f, 210f),
(0f, -20f, 0f),
(800f, 1f, 800f),
friction: 0.25f,
restitution: 0.05f);
@ -190,9 +347,9 @@ namespace RustToDust.Ymir
for (int i = 0; i < State.Contenders.Count; i++)
{
var c = State.Contenders[i];
contacts[i] = new RingContact(c.Id, c.X, c.Z, c.Alive);
contacts[i] = new RingContact(c.Id, c.X, c.Z, c.Alive, c.Y, c.Grid.Spec.HalfHeight);
}
State.Spectators.UpdateClearance(contacts);
State.Spectators.UpdateClearance(contacts, FixedDt, HasSpectatorLos);
for (int i = 0; i < State.Spectators.Spectators.Count; i++)
{
@ -223,6 +380,13 @@ namespace RustToDust.Ymir
}
}
private bool HasSpectatorLos(SpectatorState spec, RingContact target)
{
return HasLineOfSight(
spec.X, MatchRules.GetObserverEyeY(spec.Y, spec.Grid.Spec.HalfHeight), spec.Z,
target.X, MatchRules.GetTargetAimY(target.Y, target.HalfHeight), target.Z);
}
private void ApplyPhysicsDrives()
{
var view = _world.View;
@ -493,6 +657,129 @@ namespace RustToDust.Ymir
}
}
private void UpdatePlayerDetectionMemory()
{
var p = State.Player;
if (!p.Alive)
{
State.PlayerDetectedByCount = 0;
return;
}
float pEyeY = MatchRules.GetObserverEyeY(p.Y, p.Grid.Spec.HalfHeight);
float pTargetY = MatchRules.GetTargetAimY(p.Y, p.Grid.Spec.HalfHeight);
int detectedBy = 0;
for (int i = 0; i < State.Contenders.Count; i++)
{
var c = State.Contenders[i];
if (c.IsPlayer)
{
continue;
}
var mem = State.GetOrCreateContenderContact(c.Id);
if (!c.Alive)
{
mem.VisibleToPlayer = false;
mem.FaintHorizonPing = false;
mem.LastSeenAge = float.PositiveInfinity;
continue;
}
bool playerSees = HasLineOfSight(
p.X, pEyeY, p.Z,
c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z);
if (playerSees)
{
mem.VisibleToPlayer = true;
mem.FaintHorizonPing = false;
mem.LastSeenAge = 0f;
mem.LastSeenX = c.X;
mem.LastSeenZ = c.Z;
mem.HasEverBeenSeen = true;
float dx = c.X - p.X;
float dz = c.Z - p.Z;
if (dx * dx + dz * dz <= 240f * 240f &&
HasLineOfSight(c.X, MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight), c.Z, p.X, pTargetY, p.Z))
{
detectedBy++;
}
}
else
{
mem.VisibleToPlayer = false;
mem.FaintHorizonPing = false;
if (mem.HasEverBeenSeen)
{
mem.LastSeenAge += FixedDt;
}
}
}
for (int i = 0; i < State.Spectators.Spectators.Count; i++)
{
var s = State.Spectators.Spectators[i];
var mem = State.GetOrCreateSpectatorContact(s.Id);
if (!s.Alive)
{
mem.VisibleToPlayer = false;
mem.FaintHorizonPing = false;
mem.LastSeenAge = float.PositiveInfinity;
continue;
}
bool playerSees = HasLineOfSight(
p.X, pEyeY, p.Z,
s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z);
if (playerSees)
{
mem.VisibleToPlayer = true;
mem.FaintHorizonPing = false;
mem.LastSeenAge = 0f;
mem.LastSeenX = s.X;
mem.LastSeenZ = s.Z;
mem.HasEverBeenSeen = true;
}
else
{
mem.VisibleToPlayer = false;
if (mem.HasEverBeenSeen)
{
mem.LastSeenAge += FixedDt;
}
// Spectator wall horizon rule: gaudy Tourists (RadarSignature >= 0.9) ping faintly over moderate crests at medium range;
// low-signature Exemplars vanish completely when terrain-occluded.
bool horizonPing = false;
if (s.RadarSignature >= 0.9f)
{
float dx = s.X - p.X;
float dz = s.Z - p.Z;
if (dx * dx + dz * dz <= MatchState.TouristHorizonMaxRange * MatchState.TouristHorizonMaxRange)
{
horizonPing = HasLineOfSight(
p.X, pEyeY + 14f, p.Z,
s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight) + 14f, s.Z);
}
}
mem.FaintHorizonPing = horizonPing;
}
if (s.Stance != SpectatorStance.Neutral &&
s.TargetContenderId == p.Id &&
s.HasTargetLos)
{
detectedBy++;
}
}
State.PlayerDetectedByCount = detectedBy;
}
private void StepThermalAndCooldowns()
{
for (int i = 0; i < State.Contenders.Count; i++)
@ -570,6 +857,7 @@ namespace RustToDust.Ymir
shooterPos: new Vector3(c.X, c.Y, c.Z),
shooterYaw: c.Yaw,
aimX: c.AimX,
aimY: c.AimY,
aimZ: c.AimZ,
extraSpread: 0f,
view: view);
@ -599,6 +887,7 @@ namespace RustToDust.Ymir
shooterPos: new Vector3(s.X, s.Y, s.Z),
shooterYaw: s.Yaw,
aimX: aimX,
aimY: float.NaN,
aimZ: aimZ,
extraSpread: s.AimSpreadRad,
view: view);
@ -614,11 +903,12 @@ namespace RustToDust.Ymir
Vector3 shooterPos,
float shooterYaw,
float aimX,
float aimY,
float aimZ,
float extraSpread,
Box3DSoaView view)
{
float targetY = ResolveAimTargetY(aimX, aimZ, shooterStableId);
float targetY = !float.IsNaN(aimY) ? aimY : ResolveAimTargetY(aimX, aimZ, shooterStableId);
for (int m = 0; m < shooterGrid.Mounted.Count; m++)
{

View file

@ -82,15 +82,18 @@ namespace RustToDust.Tests
public void Raycast_RespectsStaticCoverWalls()
{
using var session = new ArenaSession(seed: 12);
// Cover block #0 sits at (28, 1.8, 16) with half-extents (4.5, 1.8, 1.4).
// A ray from one side (28, 1.0, 10) to the other side (28, 1.0, 22) must hit the static cover wall!
var blockedHit = session.World.CastRayClosest((28f, 1.0f, 10f), (0f, 0f, 15f));
var c0 = session.State.ArenaCoverBoxes[0];
float rayStartZ = c0.Z - c0.HalfZ - 5f;
float raySpanZ = c0.HalfZ * 2f + 10f;
// A ray from one side of cover block #0 to the other must hit the static cover wall!
var blockedHit = session.World.CastRayClosest((c0.X, c0.Y, rayStartZ), (0f, 0f, raySpanZ));
Assert.True(blockedHit.Hit);
Assert.True(blockedHit.Point.Z < 16f, $"Expected cover hit before z=16, got z={blockedHit.Point.Z:F2}");
Assert.True(blockedHit.Point.Z < c0.Z, $"Expected cover hit before z={c0.Z:F2}, got z={blockedHit.Point.Z:F2}");
Assert.InRange(blockedHit.StableId, 10UL, 99UL); // Static cover StableId range
// Ray high above the cover block (y = 5.0 > 3.6 top) passes unobstructed
var clearHit = session.World.CastRayClosest((28f, 5.0f, 10f), (0f, 0f, 15f));
// Ray high above the cover block passes unobstructed
var clearHit = session.World.CastRayClosest((c0.X, c0.Y + c0.HalfY + 2.0f, rayStartZ), (0f, 0f, raySpanZ));
Assert.False(clearHit.Hit);
}

View file

@ -0,0 +1,200 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RustToDust.Core;
using RustToDust.Ymir;
using Xunit;
namespace RustToDust.Tests
{
public sealed class DetectionLosTests
{
private static TerrainBrush FindTallMesa(TerrainField terrain)
{
for (int i = 0; i < terrain.Brushes.Count; i++)
{
var b = terrain.Brushes[i];
if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f)
{
return b;
}
}
throw new InvalidOperationException("Expected at least one tall Mesa in generated terrain.");
}
[Fact]
public void MesaBetweenSpectatorAndContender_BlocksLosAndPreventsFiringThroughTerrain()
{
using var session = new ArenaSession(seed: 42);
var mesa = FindTallMesa(session.State.Terrain);
var player = session.State.Player;
var spec = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Patron);
// Place player and spectator on opposite sides of the tall mesa
float playerX = mesa.X - mesa.RadiusX - 18f;
float specX = mesa.X + mesa.RadiusX + 18f;
session.SetContenderPose(player.Id, playerX, mesa.Z);
session.SetSpectatorPose(spec.Id, specX, mesa.Z);
// Provoke this spectator onto the player so it actively hunts, while terrain blocks sightline
session.State.Spectators.OnSpectatorDamaged(spec, player.Id);
float initialCoreHp = player.Grid.CoreHp;
for (int tick = 0; tick < 10; tick++)
{
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
Assert.False(session.HasLineOfSight(
spec.X, MatchRules.GetObserverEyeY(spec.Y, spec.Grid.Spec.HalfHeight), spec.Z,
player.X, MatchRules.GetTargetAimY(player.Y, player.Grid.Spec.HalfHeight), player.Z));
Assert.False(spec.HasTargetLos);
MatchRules.ComputeSpectatorBehavior(spec, session.State, out _, out _, out _, out _, out bool shouldFire);
Assert.False(shouldFire, "Occluded spectator must NOT fire through a mesa");
}
Assert.Equal(initialCoreHp, player.Grid.CoreHp);
}
[Fact]
public void CrestingRidge_RestoresLosAndAllowsSpectatorEngagement()
{
using var session = new ArenaSession(seed: 42);
var mesa = FindTallMesa(session.State.Terrain);
var player = session.State.Player;
var spec = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Patron);
// Start occluded across the mesa
session.SetContenderPose(player.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.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
Assert.False(spec.HasTargetLos);
// Now player crests onto the high mesa plateau overlooking the spectator
session.SetContenderPose(player.Id, mesa.X + mesa.RadiusX * 0.25f, mesa.Z);
session.SetSpectatorPose(spec.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z);
bool sawTracer = false;
for (int tick = 0; tick < 30; tick++)
{
session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
if (session.State.Tracers.Count > 0)
{
sawTracer = true;
}
}
Assert.True(spec.HasTargetLos, "Cresting the mesa must restore spectator LOS");
MatchRules.ComputeSpectatorBehavior(spec, session.State, out _, out _, out _, out _, out bool shouldFire);
Assert.True(shouldFire, "Spectator with restored LOS within range should be cleared to fire");
Assert.True(sawTracer, "Expected spectator to fire weapons once LOS was restored");
}
[Fact]
public void LowSignatureExemplar_HiddenBehindRidge_IsInvisibleOnRadar_WhileInLosContactIsVisible()
{
using var session = new ArenaSession(seed: 42);
var mesa = FindTallMesa(session.State.Terrain);
var player = session.State.Player;
var exemplar = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar);
var visibleRival = session.State.Contenders[1];
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
session.State.SpectatorContacts[exemplar.Id] = new PlayerContactMemory();
session.SetContenderPose(player.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
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));
var exMem = session.State.SpectatorContacts[exemplar.Id];
Assert.False(exMem.VisibleToPlayer);
Assert.False(exMem.FaintHorizonPing);
Assert.False(MatchState.IsContactOnRadar(exMem), "Hidden low-signature Exemplar must vanish off player radar");
var rivalMem = session.State.ContenderContacts[visibleRival.Id];
Assert.True(rivalMem.VisibleToPlayer, "In-LOS contact must be live-visible to player");
Assert.True(MatchState.IsContactOnRadar(rivalMem));
}
[Fact]
public void StaticCoverWall_BlocksLineOfSight()
{
using var session = new ArenaSession(seed: 12);
var box = session.State.ArenaCoverBoxes[0];
var player = session.State.Player;
var rival = session.State.Contenders[1];
session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 4f);
session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 4f);
bool los = session.HasLineOfSight(
player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z,
rival.X, MatchRules.GetTargetAimY(rival.Y, rival.Grid.Spec.HalfHeight), rival.Z);
Assert.False(los, "Static cover ruin wall between two vehicles must block HasLineOfSight");
}
[Fact]
public void NeutralTierPositioning_PatronsClaimHigherGroundThanTouristsAndExemplars_AndHoldSpots()
{
var state = new MatchState(seed: 42);
var ring = state.Spectators;
var touristHeights = new List<float>();
var patronHeights = new List<float>();
var exemplarHeights = new List<float>();
var initialGoals = new Dictionary<int, (float X, float Z)>();
for (int i = 0; i < ring.Spectators.Count; i++)
{
var s = ring.Spectators[i];
var (gx, gz) = ring.GetNeutralGoal(s, state.Terrain, state.ArenaCoverBoxes);
initialGoals[s.Id] = (gx, gz);
float h = state.Terrain.SampleHeight(gx, gz);
switch (s.Tier)
{
case SpectatorTier.Tourist: touristHeights.Add(h); break;
case SpectatorTier.Patron: patronHeights.Add(h); break;
case SpectatorTier.Exemplar: exemplarHeights.Add(h); break;
}
}
float avgPatronH = patronHeights.Average();
float avgTouristH = touristHeights.Average();
float avgExemplarH = exemplarHeights.Average();
Assert.True(avgPatronH > avgTouristH + 1.0f,
$"Expected Patrons ({avgPatronH:F2}m) to claim higher ground than Tourists ({avgTouristH:F2}m)");
Assert.True(avgPatronH > avgExemplarH + 1.0f,
$"Expected Patrons ({avgPatronH:F2}m) to claim higher ground than Exemplars ({avgExemplarH:F2}m)");
// Advance perimeter orbits while SafeRadius is within grace period: Tourists orbit, Patrons & Exemplars hold!
ring.AdvancePerimeterOrbits(15f);
for (int i = 0; i < ring.Spectators.Count; i++)
{
var s = ring.Spectators[i];
var (gx, gz) = ring.GetNeutralGoal(s, state.Terrain, state.ArenaCoverBoxes);
var prev = initialGoals[s.Id];
float moved = MathF.Sqrt((gx - prev.X) * (gx - prev.X) + (gz - prev.Z) * (gz - prev.Z));
if (s.Tier == SpectatorTier.Tourist)
{
Assert.True(moved > 10f, "Expected Neutral Tourists to continue orbiting perimeter");
}
else
{
Assert.True(moved < 0.01f, $"Expected Neutral {s.Tier} to hold chosen vantage/ambush spot, moved {moved:F2}m");
}
}
}
}
}

View file

@ -11,7 +11,8 @@ namespace RustToDust.Tests
public void Clearance_ZeroInsideSafeCircle_MonotonicOutside()
{
var ring = new SpectatorRing(seed: 101);
float r = ring.SafeRadius; // 150f
float r = ring.SafeRadius; // 560f
Assert.Equal(56, ring.Spectators.Count);
// Inside safe circle -> 0 cleared
ring.UpdateClearance(new[] { new RingContact(0, r - 20f, 0f, true) });

View file

@ -11,6 +11,12 @@ namespace RustToDust.Tests
[Fact]
public void Generate_ProducesDeterministicNonFlatReliefWithinBounds()
{
Assert.Equal(1536f, TerrainField.ArenaSize);
Assert.Equal(8, TerrainField.TileGridCount);
Assert.Equal(192f, TerrainField.TileSize);
Assert.Equal(-18f, TerrainField.MinWorldHeight);
Assert.Equal(52f, TerrainField.MaxWorldHeight);
var emptyCover = Array.Empty<ArenaBoxSpec>();
var a = TerrainField.Generate(42UL, emptyCover);
var b = TerrainField.Generate(42UL, emptyCover);
@ -20,9 +26,9 @@ namespace RustToDust.Tests
float maxH = float.NegativeInfinity;
bool anyDifferentSeed = false;
for (int gx = -160; gx <= 160; gx += 16)
for (int gx = -700; gx <= 700; gx += 50)
{
for (int gz = -160; gz <= 160; gz += 16)
for (int gz = -700; gz <= 700; gz += 50)
{
float ha = a.SampleHeight(gx, gz);
float hb = b.SampleHeight(gx, gz);
@ -39,9 +45,9 @@ namespace RustToDust.Tests
}
}
Assert.True(maxH - minH > 2.5f, $"Expected non-flat dune/mesa relief > 2.5m span, got [{minH:F2}, {maxH:F2}]");
Assert.InRange(minH, -4.5f, 1.0f);
Assert.InRange(maxH, 2.0f, 9.5f);
Assert.True(maxH - minH >= 25f, $"Expected dramatic mesa/dune/canyon relief >= 25m span, got [{minH:F2}, {maxH:F2}]");
Assert.InRange(minH, TerrainField.MinWorldHeight, -3.0f);
Assert.InRange(maxH, 18.0f, TerrainField.MaxWorldHeight);
Assert.True(anyDifferentSeed, "Different seeds should generate distinct desert relief");
}
@ -51,10 +57,10 @@ namespace RustToDust.Tests
var terrain = TerrainField.Generate(42UL, Array.Empty<ArenaBoxSpec>());
terrain.ClearDirtyMask();
// Tile (1, 1) spans X in [-96, 0), Z in [-96, 0).
// Point (-48, -48) with radius 6m is strictly inside tile (1, 1) and nowhere else.
const float cx = -48f;
const float cz = -48f;
// Tile (3, 3) spans X in [-192, 0), Z in [-192, 0).
// Point (-96, -96) with radius 6m is strictly inside tile (3, 3) and nowhere else.
const float cx = -96f;
const float cz = -96f;
const float radius = 6f;
const float depth = 1.6f;
@ -71,16 +77,58 @@ namespace RustToDust.Tests
Assert.True(afterRim > beforeRim + 0.2f,
$"Expected crater ejecta rim to rise >0.2m (before {beforeRim:F2}, after {afterRim:F2})");
// Only tile (1, 1) should have incremented from version 1 to 2
// Only tile (3, 3) should have incremented from version 1 to 2
for (int tz = 0; tz < TerrainField.TileGridCount; tz++)
{
for (int tx = 0; tx < TerrainField.TileGridCount; tx++)
{
int expected = (tx == 1 && tz == 1) ? 2 : 1;
int expected = (tx == 3 && tz == 3) ? 2 : 1;
Assert.Equal(expected, terrain.TileVersions[tx, tz]);
}
}
Assert.Equal(1u << (1 * TerrainField.TileGridCount + 1), terrain.DirtyTileMask);
Assert.Equal(1UL << (3 * TerrainField.TileGridCount + 3), terrain.DirtyTileMask);
}
[Fact]
public void Raycast_DetectsBlockingMesaAndClearsAboveCrest()
{
var terrain = TerrainField.Generate(42UL, Array.Empty<ArenaBoxSpec>());
TerrainBrush? tallMesa = null;
for (int i = 0; i < terrain.Brushes.Count; i++)
{
var b = terrain.Brushes[i];
if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f)
{
tallMesa = b;
break;
}
}
Assert.NotNull(tallMesa);
var mesa = tallMesa!.Value;
float startX = mesa.X - mesa.RadiusX - 25f;
float endX = mesa.X + mesa.RadiusX + 25f;
float span = endX - startX;
float lowY = terrain.SampleHeight(startX, mesa.Z) + 4f;
bool blocked = terrain.Raycast(
startX, lowY, mesa.Z,
1f, 0f, 0f,
span,
out float hx, out _, out _, out _);
Assert.True(blocked, "Expected low ray across tall mesa to be blocked by terrain");
Assert.InRange(hx, startX, endX);
float highY = terrain.SampleHeight(mesa.X, mesa.Z) + 6f;
bool clear = terrain.Raycast(
startX, highY, mesa.Z,
1f, 0f, 0f,
span,
out _, out _, out _, out _);
Assert.False(clear, "Expected ray above mesa plateau to pass unobstructed");
}
[Fact]
@ -173,8 +221,9 @@ namespace RustToDust.Tests
$"Cover box at ({box.X}, {box.Z}) bottom {boxBottom:F2}m floats above corner height {minH:F2}m");
}
Assert.True(maxCoverCornerDelta <= 0.5f,
$"Expected MaxCoverCornerDelta <= 0.5m for seed {seed}, got {maxCoverCornerDelta:F3}m");
Assert.Equal(36, state.ArenaCoverBoxes.Count);
Assert.True(maxCoverCornerDelta <= 0.6f,
$"Expected MaxCoverCornerDelta <= 0.6m for seed {seed}, got {maxCoverCornerDelta:F3}m");
}
[Fact]
@ -190,7 +239,7 @@ namespace RustToDust.Tests
}
}
Assert.Equal(8, roads.Count);
Assert.Equal(16, roads.Count);
foreach (var road in roads)
{
Assert.True(road.RadiusX > road.RadiusZ,