Merge nibu/rtd-cut9-menu-lobby into integrated Cut 7+8+9

This commit is contained in:
Meta Vens 2026-12-05 18:49:36 +01:00
commit 42b17c168e
25 changed files with 5150 additions and 90 deletions

View file

@ -11,6 +11,15 @@ using RustToDust.Ymir;
namespace RustToDust.Client;
public enum ClientScreenMode
{
MainMenu,
ServerBrowser,
Lobby,
InMatch,
PauseOverlay
}
/// <summary>
/// Root Godot node for Rust to Dust.
/// Godot physics is Dummy; <see cref="IClientArenaSession"/> drives Solo (<see cref="LocalArenaSession"/>),
@ -28,9 +37,28 @@ public partial class Main : Node3D
private Camera3D _camera = null!;
private Hud _hud = null!;
private AtmosphereSystem _atmosphere = null!;
private MainMenu _mainMenu = null!;
private ServerBrowser _serverBrowser = null!;
private LobbyScreen _lobbyScreen = null!;
private IClientArenaSession? _session;
private MatchState? _boundViewState;
private bool _wasNetConnected;
private ClientScreenMode _screenMode = ClientScreenMode.MainMenu;
private DirectoryReporter? _directoryReporter;
private string _directoryUrl = ServerBrowser.DefaultDirectoryUrl;
private string _publicHostOverride = "auto";
private string _serverName = "Rust to Dust";
private DirectoryHeartbeatSnapshot _cachedDirectorySnapshot;
private readonly object _dirSnapGate = new();
private int _lastDirHumans = -1;
private MatchPhase _lastDirPhase = (MatchPhase)(-1);
private ArenaMapKind _lastDirMap = (ArenaMapKind)(-1);
private int _lastDirSeed;
private SionMapData? _menuSionData;
private TerrainField? _menuSionTerrain;
private int _menuPreviewTargetFrames;
private int _menuPreviewFrames;
private string? _menuPreviewOut;
private readonly WalkerFootstepTracker _footsteps = new();
private readonly CameraJuiceState _camJuice = new();
private readonly List<ISimEvent> _frameEvents = new(128);
@ -80,6 +108,8 @@ public partial class Main : Node3D
private double _perfCamMsSum;
public IClientArenaSession Session => _session ?? throw new InvalidOperationException($"No active IClientArenaSession ({Failure ?? "uninitialized"})");
public bool HasActiveSession => _session is not null;
public ClientScreenMode ScreenMode => _screenMode;
public TerrainRenderer Terrain => _terrain;
public SionMapRenderer SionMap => _sionMap;
public ArenaRenderer Arena => _arena;
@ -89,9 +119,13 @@ public partial class Main : Node3D
public Camera3D Camera => _camera;
public Hud Hud => _hud;
public AtmosphereSystem Atmosphere => _atmosphere;
public MainMenu MainMenuOverlay => _mainMenu;
public ServerBrowser ServerBrowserOverlay => _serverBrowser;
public LobbyScreen LobbyOverlay => _lobbyScreen;
public ArenaMapKind MapKind => _mapKind;
public ArenaMapKind? InitialMapKindOverride { get; set; }
public bool InitialSkipDropOverride { get; set; }
public bool InitialSkipMenuOverride { get; set; }
public string? Failure { get; private set; }
public int Seed => _seed;
public float CameraYaw => _cameraYaw;
@ -135,6 +169,40 @@ public partial class Main : Node3D
_hud.NetworkPanelToggled += _ => SyncMouseMode();
AddChild(_hud);
_mainMenu = new MainMenu { Name = "MainMenu" };
_mainMenu.PlaySoloRequested += OnMainMenuPlaySolo;
_mainMenu.ServerBrowserRequested += OnMainMenuServerBrowser;
_mainMenu.HostLobbyRequested += OnMainMenuHostLobby;
_mainMenu.CallsignChanged += cs =>
{
_callsign = cs;
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
};
_mainMenu.QuitRequested += () => GetTree().Quit(0);
_mainMenu.ResumeRequested += () =>
{
if (_screenMode == ClientScreenMode.PauseOverlay)
{
SetScreenMode(ClientScreenMode.InMatch);
}
};
_mainMenu.ReturnToMainMenuRequested += ReturnToMainMenu;
AddChild(_mainMenu);
_serverBrowser = new ServerBrowser { Name = "ServerBrowser" };
_serverBrowser.JoinRequested += OnBrowserJoinRequested;
_serverBrowser.HostRequested += () =>
{
SetScreenMode(ClientScreenMode.MainMenu);
_mainMenu.SetHostPanelOpen(true);
};
_serverBrowser.BackRequested += () => SetScreenMode(ClientScreenMode.MainMenu);
AddChild(_serverBrowser);
_lobbyScreen = new LobbyScreen { Name = "LobbyScreen" };
_lobbyScreen.LeaveRequested += ReturnToMainMenu;
AddChild(_lobbyScreen);
var reticleMat = new StandardMaterial3D
{
ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded,
@ -158,6 +226,25 @@ public partial class Main : Node3D
string? cliName = GetCliArg("--name");
string? cliMap = GetCliArg("--map");
string? cliSeed = GetCliArg("--seed");
bool cliSolo = GetCliArg("--solo", allowBareFlag: true) is not null
|| System.Environment.GetEnvironmentVariable("RTD_SOLO") == "1";
bool cliLobby = GetCliArg("--lobby", allowBareFlag: true) is not null
|| System.Environment.GetEnvironmentVariable("RTD_LOBBY") == "1";
string? cliDirUrl = GetCliArg("--directory-url");
string? envDirUrl = System.Environment.GetEnvironmentVariable("RTD_DIRECTORY_URL");
_directoryUrl = cliDirUrl ?? envDirUrl ?? ServerBrowser.DefaultDirectoryUrl;
string? cliPublicHost = GetCliArg("--public-host");
string? envPublicHost = System.Environment.GetEnvironmentVariable("RTD_PUBLIC_HOST");
if ((cliPublicHost ?? envPublicHost) is { Length: > 0 } ph)
{
_publicHostOverride = ph.Trim();
}
string? cliServerName = GetCliArg("--server-name");
string? envServerName = System.Environment.GetEnvironmentVariable("RTD_SERVER_NAME");
if ((cliServerName ?? envServerName) is { Length: > 0 } sn)
{
_serverName = sn.Trim();
}
if (!string.IsNullOrWhiteSpace(cliName))
{
@ -204,6 +291,8 @@ public partial class Main : Node3D
: $"127.0.0.1:{hostTarget.Trim()}";
}
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort);
_serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint);
if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"), out int perfFrames) && perfFrames > 0)
{
@ -215,20 +304,44 @@ public partial class Main : Node3D
_perfTargetFrames = autoExitFrames;
}
if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_MENU_EXIT_FRAMES"), out int menuExitFrames) && menuExitFrames > 0)
{
_menuPreviewTargetFrames = menuExitFrames;
}
_menuPreviewOut = System.Environment.GetEnvironmentVariable("RTD_MENU_PREVIEW_OUT");
bool perfCombat = _perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1";
bool skipInitialDrop = InitialSkipDropOverride || perfCombat;
bool autoBypassMenu = InitialMapKindOverride.HasValue
|| InitialSkipDropOverride
|| InitialSkipMenuOverride
|| _perfTargetFrames > 0
|| !string.IsNullOrWhiteSpace(connectTarget)
|| hostTarget is not null
|| cliSolo;
if (!string.IsNullOrWhiteSpace(connectTarget))
{
StartRemoteSession(connectTarget, _callsign);
StartRemoteSession(connectTarget, _callsign, fromBrowser: false);
}
else if (hostTarget is not null)
{
StartListenHostSession(hostTarget, _callsign);
StartListenHostSession(
hostTarget,
_callsign,
_mapKind,
_serverName,
startInLobby: cliLobby,
listOnPublicDirectory: false,
fallbackToLocalOnFailure: true);
}
else if (autoBypassMenu)
{
Reset(_seed, _mapKind, skipInitialDrop);
}
else
{
Reset(_seed, _mapKind, skipInitialDrop);
EnterMainMenuBackdrop();
}
if (perfCombat && _session is not null)
@ -303,9 +416,7 @@ public partial class Main : Node3D
public override void _ExitTree()
{
_session?.Dispose();
_session = null;
_boundViewState = null;
DisposeSessionAndDirectory();
}
public void Reset(int seed, ArenaMapKind? mapKind = null, bool skipInitialDrop = false)
@ -316,16 +427,14 @@ public partial class Main : Node3D
_mapKind = mapKind.Value;
}
_session?.Dispose();
_session = null;
_boundViewState = null;
_wasNetConnected = false;
DisposeSessionAndDirectory();
Failure = null;
_hud.SetNetworkError(null);
try
{
_session = new LocalArenaSession(seed, _mapKind, _callsign, skipInitialDrop);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: true);
}
catch (Exception ex)
@ -335,46 +444,219 @@ public partial class Main : Node3D
}
}
private void StartListenHostSession(string hostArg, string callsign)
private void EnterMainMenuBackdrop()
{
string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Host" : callsign.Trim();
DisposeSessionAndDirectory();
Failure = null;
_hud.SetNetworkError(null);
EnsureMenuSionBackdrop();
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort);
_mainMenu.SetHostPanelOpen(false);
SetScreenMode(ClientScreenMode.MainMenu);
}
private void ReturnToMainMenu()
{
_mainMenu.SetStatus(null);
EnterMainMenuBackdrop();
}
private void DisposeSessionAndDirectory()
{
_directoryReporter?.Dispose();
_directoryReporter = null;
_lastDirHumans = -1;
_lastDirPhase = (MatchPhase)(-1);
_lastDirMap = (ArenaMapKind)(-1);
_lastDirSeed = 0;
if (_session is RemoteArenaSession remote)
{
remote.DisconnectGracefully("Leave");
}
_session?.Dispose();
_session = null;
_boundViewState = null;
_wasNetConnected = false;
}
private void EnsureMenuSionBackdrop()
{
_menuSionData ??= SionMapLoader.Load();
_menuSionTerrain ??= TerrainField.LoadHeightmap(
_menuSionData.Metadata.SizeMeters,
_menuSionData.Metadata.GridRes,
_menuSionData.Heights,
_menuSionData.Metadata.MinY,
_menuSionData.Metadata.MaxY,
42UL);
_terrain.Visible = false;
_sionMap.Visible = true;
_arena.Visible = false;
_dropReticleMesh.Visible = false;
_camera.Far = 4200f;
_atmosphere.ApplyMap(ArenaMapKind.Sion);
_sionMap.EnsureBuilt(_menuSionData, _menuSionTerrain);
UpdateLobbyOrMenuOrbitCamera(ArenaMapKind.Sion, _menuSionTerrain);
_sionMap.UpdateLod(_camera.GlobalPosition);
}
private void UpdateLobbyOrMenuOrbitCamera(ArenaMapKind mapKind, TerrainField terrain)
{
float orbitRadius = mapKind == ArenaMapKind.Sion ? 460f : 210f;
float speed = mapKind == ArenaMapKind.Sion ? 0.055f : 0.08f;
float angle = _elapsedSeconds * speed + 0.65f;
float ox = MathF.Cos(angle) * orbitRadius;
float oz = MathF.Sin(angle) * orbitRadius;
float groundY = terrain.SampleHeight(ox, oz);
float targetY = terrain.SampleHeight(0f, 0f) + (mapKind == ArenaMapKind.Sion ? 42f : 14f);
float camY = mapKind == ArenaMapKind.Sion
? MathF.Max(groundY + 115f, targetY + 135f)
: MathF.Max(groundY + 55f, 85f);
_camera.Fov = 58f;
_camera.GlobalPosition = new Vector3(ox, camY, oz);
_camera.LookAt(new Vector3(0f, targetY, 0f), Vector3.Up);
}
private void SetScreenMode(ClientScreenMode mode)
{
_screenMode = mode;
switch (mode)
{
case ClientScreenMode.MainMenu:
_hud.SetMatchHudActive(false);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.MainMenu);
_arena.Visible = false;
_dropReticleMesh.Visible = false;
break;
case ClientScreenMode.ServerBrowser:
_hud.SetMatchHudActive(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_lobbyScreen.SetLobbyVisible(false);
_serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint);
_serverBrowser.SetBrowserVisible(true, autoRefresh: true);
_arena.Visible = false;
_dropReticleMesh.Visible = false;
break;
case ClientScreenMode.Lobby:
_hud.SetMatchHudActive(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(true);
_arena.Visible = false;
_dropReticleMesh.Visible = false;
break;
case ClientScreenMode.InMatch:
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_arena.Visible = true;
_hud.SetMatchHudActive(true);
break;
case ClientScreenMode.PauseOverlay:
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_arena.Visible = true;
_hud.SetMatchHudActive(true);
_mainMenu.SetPauseContext(BuildPauseContextLine());
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.PauseOverlay);
break;
}
SyncMouseMode();
}
private string BuildPauseContextLine()
{
string mapLabel = _mapKind == ArenaMapKind.Sion ? "SION 3KM" : "DESERT RING";
if (_session is null) return mapLabel;
var net = _session.ConnectionStatus;
return net.Mode switch
{
NetworkMode.ListenHost => $"{mapLabel} • {net.StateLabel}",
NetworkMode.RemoteClient => $"{mapLabel} • {net.StateLabel}",
_ => $"SOLO • {mapLabel} • SEED {_seed}"
};
}
private void StartListenHostSession(
string hostArg,
string callsign,
ArenaMapKind mapKind,
string serverName,
bool startInLobby,
bool listOnPublicDirectory,
bool fallbackToLocalOnFailure)
{
string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Host" : callsign.Trim();
string cleanServerName = string.IsNullOrWhiteSpace(serverName) ? "Rust to Dust" : serverName.Trim();
Failure = null;
_hud.SetNetworkError(null);
_mainMenu.SetHostError(null);
try
{
ParseBindAndPort(hostArg, IPAddress.Loopback, DefaultNetPort, out IPAddress bindIp, out int port);
var hostSession = new ListenHostArenaSession(bindIp, port, _seed, _mapKind);
IPAddress defaultBind = listOnPublicDirectory || !fallbackToLocalOnFailure ? IPAddress.Any : IPAddress.Loopback;
ParseBindAndPort(hostArg, defaultBind, DefaultNetPort, out IPAddress bindIp, out int port);
var hostSession = new ListenHostArenaSession(
bindIp,
port,
_seed,
mapKind,
startInLobby: startInLobby,
serverName: cleanServerName,
minHumansToStart: 1);
hostSession.Host.Session.SetHumanSlot(0, true, nextCallsign);
var oldSession = _session;
DisposeSessionAndDirectory();
_session = hostSession;
_callsign = nextCallsign;
_boundViewState = null;
_wasNetConnected = false;
_lastEndpoint = $"{bindIp}:{hostSession.Host.BoundPort}";
_mapKind = mapKind;
_serverName = cleanServerName;
_lastEndpoint = $"{(bindIp.Equals(IPAddress.Any) ? IPAddress.Loopback : bindIp)}:{hostSession.Host.BoundPort}";
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
if (listOnPublicDirectory)
{
string normDir = DirectoryBrowserClient.NormalizeBaseUrl(_directoryUrl);
if (!string.IsNullOrEmpty(normDir))
{
UpdateCachedDirectorySnapshot(hostSession);
_directoryReporter = new DirectoryReporter(normDir, ReadCachedDirectorySnapshot);
}
}
SetScreenMode(startInLobby ? ClientScreenMode.Lobby : ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: true);
oldSession?.Dispose();
}
catch (Exception ex)
{
Failure = ex.Message;
if (_session is null)
if (fallbackToLocalOnFailure && _session is null)
{
_session = new LocalArenaSession(_seed, _mapKind, _callsign);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: false);
}
_hud.SetNetworkError(ex.Message);
_mainMenu.SetHostError(ex.Message);
GD.PushError("ListenHostArenaSession startup failed: " + ex);
}
}
private void StartRemoteSession(string endpointText, string callsign)
private void StartRemoteSession(string endpointText, string callsign, bool fromBrowser)
{
string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim();
Failure = null;
_hud.SetNetworkError(null);
_serverBrowser.SetError(null);
try
{
@ -382,29 +664,112 @@ public partial class Main : Node3D
var remote = new RemoteArenaSession(ep, nextCallsign);
remote.PumpNetwork();
var oldSession = _session;
DisposeSessionAndDirectory();
_session = remote;
_callsign = nextCallsign;
_boundViewState = null;
_wasNetConnected = false;
_lastEndpoint = endpointText.Trim();
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
SetScreenMode(fromBrowser ? ClientScreenMode.Lobby : ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: true);
oldSession?.Dispose();
}
catch (Exception ex)
{
Failure = ex.Message;
if (_session is null)
if (!fromBrowser && _session is null && _screenMode == ClientScreenMode.InMatch)
{
_session = new LocalArenaSession(_seed, _mapKind, _callsign);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: false);
}
_hud.SetNetworkError(ex.Message);
_serverBrowser.SetError(ex.Message);
GD.PushError("RemoteArenaSession startup failed: " + ex);
}
}
private DirectoryHeartbeatSnapshot ReadCachedDirectorySnapshot()
{
lock (_dirSnapGate)
{
return _cachedDirectorySnapshot;
}
}
private void UpdateCachedDirectorySnapshot(ListenHostArenaSession hostSession)
{
var state = hostSession.ViewState;
int humans = hostSession.Host.ConnectedHumanCount;
string phaseStr = state.Phase switch
{
MatchPhase.Lobby => "Lobby",
MatchPhase.Completed => "Completed",
_ => "Active"
};
string mapStr = state.MapKind == ArenaMapKind.Sion ? "sion" : "desert";
int wave = hostSession.DropWaveState.CurrentWaveIndex;
bool changed = humans != _lastDirHumans
|| state.Phase != _lastDirPhase
|| state.MapKind != _lastDirMap
|| state.Seed != _lastDirSeed;
lock (_dirSnapGate)
{
_cachedDirectorySnapshot = new DirectoryHeartbeatSnapshot(
Name: _serverName,
PublicHost: _publicHostOverride,
UdpPort: hostSession.Host.BoundPort,
Map: mapStr,
Seed: state.Seed,
Humans: humans,
MaxHumans: MatchState.ContenderCount,
Phase: phaseStr,
Wave: wave);
}
if (changed)
{
_lastDirHumans = humans;
_lastDirPhase = state.Phase;
_lastDirMap = state.MapKind;
_lastDirSeed = state.Seed;
_directoryReporter?.NotifyChanged();
}
}
private void OnMainMenuPlaySolo(ArenaMapKind mapKind, string callsign)
{
_callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim();
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
Reset(_seed, mapKind, skipInitialDrop: false);
}
private void OnMainMenuServerBrowser(string callsign)
{
_callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim();
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
SetScreenMode(ClientScreenMode.ServerBrowser);
}
private void OnMainMenuHostLobby(int port, string serverName, ArenaMapKind mapKind, bool listOnPublicDirectory, string callsign)
{
string? envBind = System.Environment.GetEnvironmentVariable("RTD_BIND");
string hostArg = !string.IsNullOrWhiteSpace(envBind) ? $"{envBind.Trim()}:{port}" : port.ToString(CultureInfo.InvariantCulture);
StartListenHostSession(
hostArg,
callsign,
mapKind,
serverName,
startInLobby: true,
listOnPublicDirectory: listOnPublicDirectory,
fallbackToLocalOnFailure: false);
}
private void OnBrowserJoinRequested(string endpointText, string callsign)
{
StartRemoteSession(endpointText, callsign, fromBrowser: true);
}
private void OnSoloRequested()
{
Reset(_seed, _mapKind);
@ -414,12 +779,19 @@ public partial class Main : Node3D
{
string? envBind = System.Environment.GetEnvironmentVariable("RTD_BIND");
string hostArg = !string.IsNullOrWhiteSpace(envBind) ? $"{envBind.Trim()}:{port}" : port.ToString(CultureInfo.InvariantCulture);
StartListenHostSession(hostArg, callsign);
StartListenHostSession(
hostArg,
callsign,
_mapKind,
_serverName,
startInLobby: false,
listOnPublicDirectory: false,
fallbackToLocalOnFailure: true);
}
private void OnJoinRequested(string endpointText, string callsign)
{
StartRemoteSession(endpointText, callsign);
StartRemoteSession(endpointText, callsign, fromBrowser: false);
}
private void BindSessionPresentation(bool resetCamera)
@ -464,13 +836,22 @@ public partial class Main : Node3D
_camera.Far = _mapKind == ArenaMapKind.Sion ? 4200f : 1800f;
_atmosphere.ApplyMap(_mapKind);
bool inLobby = _screenMode == ClientScreenMode.Lobby || state.Phase == MatchPhase.Lobby;
if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null)
{
_terrain.Visible = false;
_sionMap.Visible = true;
_sionMap.EnsureBuilt(state.SionMap, state.Terrain);
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
UpdateCamera(1f, 1f);
if (!inLobby)
{
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
UpdateCamera(1f, 1f);
}
else
{
UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain);
}
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
@ -479,18 +860,31 @@ public partial class Main : Node3D
_terrain.Visible = true;
_terrain.InvalidateAll();
_terrain.Sync(state.Terrain);
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
UpdateCamera(1f, 1f);
if (!inLobby)
{
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
UpdateCamera(1f, 1f);
}
else
{
UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain);
}
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
var localStart = _session.LocalContender;
Vector3 startVec = new(localStart.X, localStart.Y, localStart.Z);
Vector3 startFwd = new(MathF.Sin(localStart.Yaw), 0f, MathF.Cos(localStart.Yaw));
_arena.Particles.PrewarmFlashLights(startVec, startFwd);
_arena.PomDecals.PrewarmShader(startVec);
_hud.Sync(_session);
if (!inLobby)
{
var localStart = _session.LocalContender;
Vector3 startVec = new(localStart.X, localStart.Y, localStart.Z);
Vector3 startFwd = new(MathF.Sin(localStart.Yaw), 0f, MathF.Cos(localStart.Yaw));
_arena.Particles.PrewarmFlashLights(startVec, startFwd);
_arena.PomDecals.PrewarmShader(startVec);
_hud.Sync(_session);
}
else
{
_lobbyScreen.Sync(_session);
}
SyncMouseMode();
}
@ -500,6 +894,11 @@ public partial class Main : Node3D
{
return;
}
if (_screenMode != ClientScreenMode.InMatch)
{
Input.MouseMode = Input.MouseModeEnum.Visible;
return;
}
bool uiOpen = _hud.GarageExpanded || _hud.NetworkPanelOpen;
Input.MouseMode = uiOpen ? Input.MouseModeEnum.Visible : Input.MouseModeEnum.Captured;
}
@ -616,18 +1015,37 @@ 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(-78f),
Mathf.DegToRad(62f));
return;
}
if (@event is InputEventKey key && key.Pressed && !key.Echo)
{
if (_screenMode == ClientScreenMode.MainMenu)
{
if (key.Keycode == Key.Escape && _mainMenu.IsHostPanelOpen)
{
_mainMenu.SetHostPanelOpen(false);
}
return;
}
if (_screenMode == ClientScreenMode.ServerBrowser)
{
if (key.Keycode == Key.Escape)
{
SetScreenMode(ClientScreenMode.MainMenu);
}
return;
}
if (_screenMode == ClientScreenMode.Lobby)
{
return;
}
if (_screenMode == ClientScreenMode.PauseOverlay)
{
if (key.Keycode == Key.Escape)
{
SetScreenMode(ClientScreenMode.InMatch);
}
return;
}
if (key.Keycode == Key.F9)
{
_hud.ToggleNetworkPanel();
@ -647,11 +1065,9 @@ public partial class Main : Node3D
_hud.ToggleGarage();
SyncMouseMode();
}
else if (DisplayServer.GetName() != "headless")
else
{
Input.MouseMode = Input.MouseMode == Input.MouseModeEnum.Captured
? Input.MouseModeEnum.Visible
: Input.MouseModeEnum.Captured;
SetScreenMode(ClientScreenMode.PauseOverlay);
}
return;
}
@ -677,8 +1093,25 @@ public partial class Main : Node3D
_session?.RequestNewMatch(_seed, _mapKind == ArenaMapKind.Sion ? ArenaMapKind.Desert : ArenaMapKind.Sion);
break;
}
return;
}
else if (@event is InputEventMouseButton mb && mb.Pressed)
if (_screenMode != ClientScreenMode.InMatch)
{
return;
}
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 InputEventMouseButton mb && mb.Pressed)
{
if (mb.ButtonIndex == MouseButton.WheelUp)
{
@ -708,7 +1141,15 @@ public partial class Main : Node3D
}
_elapsedSeconds += (float)delta;
var input = _scriptedInput ?? GatherPlayerInput();
PlayerInput input;
if (_screenMode == ClientScreenMode.InMatch)
{
input = _scriptedInput ?? GatherPlayerInput();
}
else
{
input = new PlayerInput(0f, 0f, 0f, 0f, false, false, false);
}
_interactQueued = false;
if (_perfTargetFrames > 0)
@ -730,13 +1171,43 @@ public partial class Main : Node3D
{
if (_session is null)
{
_elapsedSeconds += (float)delta;
EnsureMenuSionBackdrop();
if (_menuPreviewTargetFrames > 0)
{
_menuPreviewFrames++;
if (_menuPreviewFrames >= _menuPreviewTargetFrames)
{
SaveMenuPreviewAndQuit();
}
}
return;
}
float alpha = Math.Clamp((float)Engine.GetPhysicsInterpolationFraction(), 0f, 1f);
_session.BeginRenderFrame(delta, alpha);
if (_session is ListenHostArenaSession liveHost && _directoryReporter is not null)
{
UpdateCachedDirectorySnapshot(liveHost);
}
bool nowConnected = _session.ConnectionStatus.Connected;
bool sessionReadyForPhaseRouting = _session is not RemoteArenaSession || nowConnected;
if (sessionReadyForPhaseRouting)
{
if (_session.ViewState.Phase == MatchPhase.Lobby && _screenMode != ClientScreenMode.Lobby)
{
SetScreenMode(ClientScreenMode.Lobby);
BindSessionPresentation(resetCamera: true);
}
else if (_session.ViewState.Phase != MatchPhase.Lobby && _screenMode == ClientScreenMode.Lobby)
{
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: true);
}
}
if (!ReferenceEquals(_boundViewState, _session.ViewState) || (!_wasNetConnected && nowConnected))
{
BindSessionPresentation(resetCamera: true);
@ -762,6 +1233,27 @@ public partial class Main : Node3D
}
_wasNetConnected = nowConnected;
if (_screenMode == ClientScreenMode.Lobby)
{
_frameEvents.Clear();
_session.DrainSimEvents(_frameEvents);
if (_mapKind == ArenaMapKind.Desert)
{
_terrain.Sync(_session.ViewState.Terrain);
}
UpdateLobbyOrMenuOrbitCamera(_mapKind, _session.ViewState.Terrain);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
_lobbyScreen.Sync(_session);
return;
}
if (_perfTargetFrames > 0)
{
if (_session.ConnectionStatus.Mode == NetworkMode.RemoteClient && !nowConnected && _perfWaitConnectFrames < 300)
@ -858,6 +1350,20 @@ public partial class Main : Node3D
}
}
private void SaveMenuPreviewAndQuit()
{
if (!string.IsNullOrWhiteSpace(_menuPreviewOut) && DisplayServer.GetName() != "headless")
{
var img = GetViewport().GetTexture()?.GetImage();
if (img is not null)
{
var err = img.SavePng(_menuPreviewOut);
GD.Print($"MENU PREVIEW SAVED: {_menuPreviewOut} ({img.GetWidth()}x{img.GetHeight()}, err={err})");
}
}
GetTree().Quit(0);
}
private void DrainAndFanSimEvents(float dt, float alpha)
{
if (_session is null)