using System;
using System.Collections.Generic;
using System.Diagnostics;
using Godot;
using RustToDust.Core;
using RustToDust.Ymir;
namespace RustToDust.Client;
///
/// Root Godot node for Rust to Dust.
/// Godot physics is Dummy; owns 100% of vehicle, thermal, spectator, and terrain physics at 60 Hz.
///
public partial class Main : Node3D
{
private TerrainRenderer _terrain = null!;
private ArenaRenderer _arena = null!;
private Camera3D _camera = null!;
private Hud _hud = null!;
private ArenaSession? _session;
private PlayerInput? _scriptedInput;
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;
// Temporary Step 1/Step 3 perf probe (enabled only when RTD_PERF_FRAMES is set)
private int _perfTargetFrames;
private int _perfFrameCount;
private int _perfPhysicsTicks;
private long _perfLastFrameTick;
private int _perfLastDirtyRebakes;
private readonly List _perfFrameMs = new();
private readonly List _perfPhysicsStepMs = new();
private readonly List _perfTerrainSyncMs = new();
private readonly List _perfArenaSyncMs = new();
private readonly List _perfHudMs = new();
private readonly List _perfDirtyRebakeDelta = new();
private readonly List _perfDrawCalls = new();
private readonly List _perfPrimitives = new();
private readonly List _perfObjects = new();
private readonly List _perfNodeCount = new();
private readonly List _perfTimeProcess = new();
private readonly List _perfTimePhysicsProcess = new();
private double _perfPendingStepMs;
private double _perfPendingTerrainMs;
private double _perfPendingArenaMs;
private double _perfCamMsSum;
public ArenaSession Session => _session ?? throw new InvalidOperationException($"No active ArenaSession ({Failure ?? "uninitialized"})");
public TerrainRenderer Terrain => _terrain;
public ArenaRenderer Arena => _arena;
public Hud Hud => _hud;
public string? Failure { get; private set; }
public int Seed => _seed;
public float CameraYaw => _cameraYaw;
public override void _Ready()
{
SetupLightingAndSky();
_terrain = new TerrainRenderer { Name = "Terrain" };
AddChild(_terrain);
_arena = new ArenaRenderer { Name = "Arena" };
AddChild(_arena);
_camera = new Camera3D
{
Name = "ShoulderCamera",
Current = true,
Fov = 58f,
Far = 1800f
};
AddChild(_camera);
_hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw) { Name = "Hud" };
AddChild(_hud);
if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"), out int perfFrames) && perfFrames > 0)
{
_perfTargetFrames = perfFrames;
ArenaSession.PerfEnabled = true;
}
Reset(_seed);
_perfLastFrameTick = Stopwatch.GetTimestamp();
_perfLastDirtyRebakes = _terrain.DirtyRebakes;
}
public override void _ExitTree()
{
_session?.Dispose();
_session = null;
}
public void Reset(int seed)
{
_seed = seed;
_session?.Dispose();
_session = null;
Failure = null;
try
{
_session = new ArenaSession(seed);
var p = _session.State.Player;
_cameraYaw = p.Yaw;
_cameraPitch = Mathf.DegToRad(12f);
_cameraZoom = 1.0f;
_cameraSmoothedAnchor = ComputeTargetAnchor(p);
_terrain.InvalidateAll();
_terrain.Sync(_session.State.Terrain);
_arena.Sync(_session, _elapsedSeconds, 0f);
UpdateCamera(1f);
_hud.Sync(_session);
if (DisplayServer.GetName() != "headless" && !_hud.GarageExpanded && _perfTargetFrames == 0)
{
Input.MouseMode = Input.MouseModeEnum.Captured;
}
}
catch (Exception ex)
{
Failure = ex.Message;
GD.PushError("ArenaSession startup failed: " + ex);
}
}
public void SetScriptedInput(PlayerInput? input) => _scriptedInput = input;
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(-78f),
Mathf.DegToRad(62f));
return;
}
if (@event is InputEventKey key && key.Pressed && !key.Echo)
{
switch (key.Keycode)
{
case Key.E:
_interactQueued = true;
break;
case Key.Tab:
_hud.ToggleGarage();
if (DisplayServer.GetName() != "headless")
{
Input.MouseMode = _hud.GarageExpanded
? Input.MouseModeEnum.Visible
: Input.MouseModeEnum.Captured;
}
break;
case Key.T:
_hud.ToggleThermal();
break;
case Key.R:
Reset(_seed + 1);
break;
case Key.Escape:
if (_hud.GarageExpanded)
{
_hud.ToggleGarage();
if (DisplayServer.GetName() != "headless")
{
Input.MouseMode = Input.MouseModeEnum.Visible;
}
}
else if (DisplayServer.GetName() != "headless")
{
Input.MouseMode = Input.MouseMode == Input.MouseModeEnum.Captured
? Input.MouseModeEnum.Visible
: Input.MouseModeEnum.Captured;
}
break;
}
}
else if (@event is InputEventMouseButton mb && mb.Pressed)
{
if (mb.ButtonIndex == MouseButton.WheelUp)
{
_cameraZoom = Math.Clamp(_cameraZoom - 0.08f, 0.75f, 1.6f);
}
else if (mb.ButtonIndex == MouseButton.WheelDown)
{
_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;
}
}
}
public override void _PhysicsProcess(double delta)
{
if (_session is null)
{
return;
}
_elapsedSeconds += (float)delta;
var input = _scriptedInput ?? GatherPlayerInput();
_interactQueued = false;
if (_perfTargetFrames > 0)
{
long t0 = Stopwatch.GetTimestamp();
_session.Step(input);
long t1 = Stopwatch.GetTimestamp();
_terrain.Sync(_session.State.Terrain);
long t2 = Stopwatch.GetTimestamp();
_arena.Sync(_session, _elapsedSeconds, (float)delta);
long t3 = Stopwatch.GetTimestamp();
double toMs = 1000.0 / Stopwatch.Frequency;
_perfPendingStepMs += (t1 - t0) * toMs;
_perfPendingTerrainMs += (t2 - t1) * toMs;
_perfPendingArenaMs += (t3 - t2) * toMs;
_perfPhysicsTicks++;
}
else
{
_session.Step(input);
_terrain.Sync(_session.State.Terrain);
_arena.Sync(_session, _elapsedSeconds, (float)delta);
}
}
public override void _Process(double delta)
{
if (_session is null)
{
return;
}
if (_perfTargetFrames > 0)
{
long tc0 = Stopwatch.GetTimestamp();
UpdateCamera((float)delta);
_terrain.UpdateTileLod(_camera.GlobalPosition);
long th0 = Stopwatch.GetTimestamp();
_hud.Sync(_session);
long th1 = Stopwatch.GetTimestamp();
_perfCamMsSum += (th0 - tc0) * 1000.0 / Stopwatch.Frequency;
double hudMs = (th1 - th0) * 1000.0 / Stopwatch.Frequency;
long now = Stopwatch.GetTimestamp();
double frameMs = (now - _perfLastFrameTick) * 1000.0 / Stopwatch.Frequency;
_perfLastFrameTick = now;
_perfFrameMs.Add(frameMs);
_perfPhysicsStepMs.Add(_perfPendingStepMs);
_perfTerrainSyncMs.Add(_perfPendingTerrainMs);
_perfArenaSyncMs.Add(_perfPendingArenaMs);
_perfHudMs.Add(hudMs);
_perfPendingStepMs = 0;
_perfPendingTerrainMs = 0;
_perfPendingArenaMs = 0;
int rebakesNow = _terrain.DirtyRebakes;
_perfDirtyRebakeDelta.Add(rebakesNow - _perfLastDirtyRebakes);
_perfLastDirtyRebakes = rebakesNow;
_perfDrawCalls.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalDrawCallsInFrame));
_perfPrimitives.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalPrimitivesInFrame));
_perfObjects.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalObjectsInFrame));
_perfNodeCount.Add(Performance.GetMonitor(Performance.Monitor.ObjectNodeCount));
_perfTimeProcess.Add(Performance.GetMonitor(Performance.Monitor.TimeProcess) * 1000.0);
_perfTimePhysicsProcess.Add(Performance.GetMonitor(Performance.Monitor.TimePhysicsProcess) * 1000.0);
_perfFrameCount++;
if (_perfFrameCount >= _perfTargetFrames)
{
PrintPerfSummaryAndQuit();
}
}
else
{
UpdateCamera((float)delta);
_terrain.UpdateTileLod(_camera.GlobalPosition);
_hud.Sync(_session);
}
}
private void PrintPerfSummaryAndQuit()
{
static double Avg(List v)
{
if (v.Count == 0) return 0;
double s = 0;
foreach (double x in v) s += x;
return s / v.Count;
}
static double P95(List v)
{
if (v.Count == 0) return 0;
var sorted = new List(v);
sorted.Sort();
int idx = Math.Clamp((int)Math.Ceiling(sorted.Count * 0.95) - 1, 0, sorted.Count - 1);
return sorted[idx];
}
double totalMs = 0;
foreach (double x in _perfFrameMs) totalMs += x;
double fps = totalMs > 0 ? (_perfFrameMs.Count * 1000.0 / totalMs) : 0;
double rebakeAvg = 0;
int rebakeTotal = 0;
foreach (int r in _perfDirtyRebakeDelta) rebakeTotal += r;
rebakeAvg = _perfDirtyRebakeDelta.Count > 0 ? (double)rebakeTotal / _perfDirtyRebakeDelta.Count : 0;
double steadyMs = 0;
int steadyCount = Math.Max(0, _perfFrameMs.Count - 10);
for (int i = 10; i < _perfFrameMs.Count; i++) steadyMs += _perfFrameMs[i];
double steadyAvgMs = steadyCount > 0 ? steadyMs / steadyCount : 0;
double steadyFps = steadyAvgMs > 0 ? 1000.0 / steadyAvgMs : 0;
GD.Print("=== PERF BENCHMARK SUMMARY ===");
GD.Print($"Frames={_perfFrameMs.Count} PhysicsTicks={_perfPhysicsTicks} AvgFPS={fps:F2} SteadyFPS(10..59)={steadyFps:F2} EngineFPS={Engine.GetFramesPerSecond():F1}");
GD.Print($"frameMs: avg={Avg(_perfFrameMs):F2} steadyAvg={steadyAvgMs:F2} p95={P95(_perfFrameMs):F2}");
GD.Print($"physicsStepMs/frame: avg={Avg(_perfPhysicsStepMs):F2} p95={P95(_perfPhysicsStepMs):F2}");
GD.Print($"terrainSyncMs/frame: avg={Avg(_perfTerrainSyncMs):F2} p95={P95(_perfTerrainSyncMs):F2} dirtyRebakesTotal={rebakeTotal} dirtyRebakesAvg={rebakeAvg:F2}");
GD.Print($"arenaSyncMs/frame: avg={Avg(_perfArenaSyncMs):F2} p95={P95(_perfArenaSyncMs):F2}");
GD.Print($"hudMs/frame: avg={Avg(_perfHudMs):F2} p95={P95(_perfHudMs):F2}");
GD.Print($"RenderTotalDrawCallsInFrame: avg={Avg(_perfDrawCalls):F0} max={P95(_perfDrawCalls):F0}");
GD.Print($"RenderTotalPrimitivesInFrame: avg={Avg(_perfPrimitives):F0}");
GD.Print($"RenderTotalObjectsInFrame: avg={Avg(_perfObjects):F0}");
GD.Print($"ObjectNodeCount: avg={Avg(_perfNodeCount):F0}");
GD.Print($"TimeProcessMs: avg={Avg(_perfTimeProcess):F2}");
GD.Print($"TimePhysicsProcessMs: avg={Avg(_perfTimePhysicsProcess):F2}");
GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}");
GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / _perfPhysicsTicks:F2} ai={ArenaSession.PerfAiMs / _perfPhysicsTicks:F2} drive={ArenaSession.PerfDriveMs / _perfPhysicsTicks:F2} world={ArenaSession.PerfWorldMs / _perfPhysicsTicks:F2} sync={ArenaSession.PerfBodySyncMs / _perfPhysicsTicks:F2} detect={ArenaSession.PerfDetectMs / _perfPhysicsTicks:F2} weapons={ArenaSession.PerfWeaponsMs / _perfPhysicsTicks:F2}");
foreach (var kv in _arena.AssetCache.Vehicles)
{
int tris = 0;
var bm = kv.Value.BakedStaticMesh;
for (int s = 0; s < bm.GetSurfaceCount(); s++)
{
var arr = bm.SurfaceGetArrays(s);
if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array)
tris += arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length / 3;
}
int farTris = 0;
var fm = kv.Value.BakedLodFarMesh;
for (int s = 0; s < fm.GetSurfaceCount(); s++)
{
var arr = fm.SurfaceGetArrays(s);
if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array)
farTris += arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length / 3;
}
int nodes = CountSubtreeNodes(kv.Value.SceneTemplate);
GD.Print($" Vehicle '{kv.Key}': nodes={nodes} bakedTris={tris} farTris={farTris} surfs={bm.GetSurfaceCount()} farSurfs={fm.GetSurfaceCount()} detachChunks={kv.Value.DetachableParts.Count}");
}
if (_arena.AssetCache.Vehicles.TryGetValue("paladin", out var palTpl))
{
var names = new List();
CollectNodeNames(palTpl.SceneTemplate, names, 40);
GD.Print($" Paladin sample nodes: {string.Join(", ", names)}");
}
GD.Print("=== END PERF BENCHMARK ===");
GetTree().Quit(0);
}
private static void CollectNodeNames(Node cur, List outNames, int limit)
{
if (outNames.Count >= limit) return;
outNames.Add($"{cur.Name}({cur.GetType().Name})");
for (int i = 0; i < cur.GetChildCount(); i++) CollectNodeNames(cur.GetChild(i), outNames, limit);
}
private static int CountSubtreeNodes(Node cur)
{
int n = 1;
for (int i = 0; i < cur.GetChildCount(); i++) n += CountSubtreeNodes(cur.GetChild(i));
return n;
}
private PlayerInput GatherPlayerInput()
{
float throttle = 0f;
if (Input.IsKeyPressed(Key.W) || Input.IsKeyPressed(Key.Up)) throttle += 1f;
if (Input.IsKeyPressed(Key.S) || Input.IsKeyPressed(Key.Down)) throttle -= 1f;
float steer = 0f;
if (Input.IsKeyPressed(Key.D) || Input.IsKeyPressed(Key.Right)) steer += 1f;
if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) steer -= 1f;
bool isVtol = Session.State.Player.Grid.Spec.IsVtol;
float verticalThrottle = 0f;
if (Input.IsKeyPressed(Key.Space)) verticalThrottle += 1f;
if (Input.IsKeyPressed(Key.C) || Input.IsKeyPressed(Key.Ctrl)) verticalThrottle -= 1f;
bool brake = isVtol ? Input.IsKeyPressed(Key.Shift) : Input.IsKeyPressed(Key.Space);
bool pointerOnHud = Input.MouseMode != Input.MouseModeEnum.Captured &&
_hud.IsPointerOverInteractiveHud(GetViewport().GetMousePosition());
bool fire = !pointerOnHud && Input.IsMouseButtonPressed(MouseButton.Left);
var (aimX, aimY, aimZ) = ComputeCenterScreenAim();
return new PlayerInput(
Throttle: throttle,
Steer: steer,
AimWorldX: aimX,
AimWorldZ: aimZ,
Fire: fire,
InteractPickup: _interactQueued,
Brake: brake,
AimWorldY: aimY,
VerticalThrottle: verticalThrottle);
}
private (float AimX, float AimY, float AimZ) ComputeCenterScreenAim()
{
var player = Session.State.Player;
Vector2 screenSize = GetViewport().GetVisibleRect().Size;
if (screenSize.X < 2f || screenSize.Y < 2f)
{
return (
player.X + MathF.Sin(_cameraYaw) * 40f,
player.Y,
player.Z + MathF.Cos(_cameraYaw) * 40f);
}
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++)
{
var hit = Session.World.CastRayClosest(
(castOrigin.X, castOrigin.Y, castOrigin.Z),
(rayDir.X * remainingDist, rayDir.Y * remainingDist, rayDir.Z * remainingDist));
if (!hit.Hit)
{
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;
}
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 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;
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.Up * 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)
{
_session?.TryEquipCargo(cargoIndex, hardpointId);
}
private void SetupLightingAndSky()
{
var sun = new DirectionalLight3D
{
Name = "DesertSun",
LightColor = new Color(1.0f, 0.92f, 0.78f),
LightEnergy = 1.45f,
ShadowEnabled = true,
DirectionalShadowMode = DirectionalLight3D.ShadowMode.Parallel2Splits,
DirectionalShadowMaxDistance = 145f,
RotationDegrees = new Vector3(-48f, 32f, 0f)
};
AddChild(sun);
var skyMat = new ProceduralSkyMaterial
{
SkyTopColor = new Color(0.24f, 0.34f, 0.44f),
SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f),
GroundBottomColor = new Color(0.32f, 0.22f, 0.14f),
GroundHorizonColor = new Color(0.70f, 0.50f, 0.33f)
};
var env = new Godot.Environment
{
BackgroundMode = Godot.Environment.BGMode.Sky,
Sky = new Sky { SkyMaterial = skyMat },
AmbientLightSource = Godot.Environment.AmbientSource.Sky,
AmbientLightEnergy = 0.55f,
FogEnabled = true,
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 });
}
}