diff --git a/RustToDust.slnx b/RustToDust.slnx
index 28d4f8b..cf1fca2 100644
--- a/RustToDust.slnx
+++ b/RustToDust.slnx
@@ -4,6 +4,7 @@
+
diff --git a/client/Hud.cs b/client/Hud.cs
index 6c2c789..40d4312 100644
--- a/client/Hud.cs
+++ b/client/Hud.cs
@@ -180,8 +180,31 @@ public partial class Hud : CanvasLayer
_schematic.QueueRedraw();
}
+ public void SetMatchHudActive(bool active)
+ {
+ Visible = active;
+ if (!active)
+ {
+ if (_netPanel.Visible)
+ {
+ _netPanel.Visible = false;
+ _callsignEdit.ReleaseFocus();
+ _endpointEdit.ReleaseFocus();
+ }
+ if (_garageExpanded)
+ {
+ ToggleGarage();
+ }
+ ResetFeedback();
+ }
+ }
+
public override void _Process(double delta)
{
+ if (!Visible)
+ {
+ return;
+ }
float dt = (float)delta;
_crosshair?.Advance(dt);
diff --git a/client/ImperialChrome.cs b/client/ImperialChrome.cs
new file mode 100644
index 0000000..39896a0
--- /dev/null
+++ b/client/ImperialChrome.cs
@@ -0,0 +1,213 @@
+using Godot;
+
+namespace RustToDust.Client;
+
+///
+/// Shared Industrial Imperial palette and beveled panel_chrome.gdshader panel/control
+/// helpers for pre-match UI layers (, ,
+/// ). Kept separate from so Hud.GetChromeMaterials()
+/// preserves its exact 6-panel contract.
+///
+public static class ImperialChrome
+{
+ public static readonly Color BgDark = Color.FromHtml("#131613");
+ public static readonly Color BgInner = Color.FromHtml("#1b1f1b");
+ public static readonly Color BgHover = Color.FromHtml("#242b23");
+ public static readonly Color BgPressed = Color.FromHtml("#2e372c");
+ public static readonly Color BorderCol = Color.FromHtml("#3e4638");
+ public static readonly Color OliveCol = Color.FromHtml("#9bb06a");
+ public static readonly Color OrangeCol = Color.FromHtml("#e08a4a");
+ public static readonly Color TextLight = Color.FromHtml("#e4dfd2");
+ public static readonly Color TextMuted = Color.FromHtml("#989487");
+ public static readonly Color CyanCol = Color.FromHtml("#44d9e8");
+ public static readonly Color GoldCol = Color.FromHtml("#e6b838");
+ public static readonly Color RedCol = Color.FromHtml("#d93829");
+ public static readonly Color ScrimCol = new(0.03f, 0.04f, 0.03f, 0.56f);
+
+ private static Shader? _sharedChromeShader;
+ private static ImageTexture? _sharedWhiteTex;
+
+ internal static Shader? ChromeShader => _sharedChromeShader ??= GD.Load("res://panel_chrome.gdshader");
+
+ internal static ImageTexture WhiteTexture
+ {
+ get
+ {
+ if (_sharedWhiteTex is null)
+ {
+ var img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8);
+ img.SetPixel(0, 0, Colors.White);
+ _sharedWhiteTex = ImageTexture.CreateFromImage(img);
+ }
+ return _sharedWhiteTex;
+ }
+ }
+
+ public static ImperialChromePanel CreatePanel(
+ Color accentColor,
+ float cornerLen = 14f,
+ float borderPx = 1.5f,
+ float bgAlpha = 0.90f,
+ int padH = 14,
+ int padV = 12)
+ {
+ return new ImperialChromePanel(accentColor, cornerLen, borderPx, bgAlpha, padH, padV);
+ }
+
+ public static Label CreateLabel(string text, int fontSize, Color color, HorizontalAlignment align = HorizontalAlignment.Left)
+ {
+ var lbl = new Label
+ {
+ Text = text,
+ HorizontalAlignment = align
+ };
+ lbl.AddThemeFontSizeOverride("font_size", fontSize);
+ lbl.AddThemeColorOverride("font_color", color);
+ return lbl;
+ }
+
+ public static Button CreateButton(string text, Color accentColor, int fontSize = 13, float minHeight = 32f)
+ {
+ var btn = new Button
+ {
+ Text = text,
+ FocusMode = Control.FocusModeEnum.None,
+ CustomMinimumSize = new Vector2(0f, minHeight)
+ };
+ StyleButton(btn, accentColor, fontSize);
+ return btn;
+ }
+
+ public static void StyleButton(Button btn, Color accentColor, int fontSize = 13)
+ {
+ btn.AddThemeFontSizeOverride("font_size", fontSize);
+ btn.AddThemeColorOverride("font_color", TextLight);
+ btn.AddThemeColorOverride("font_hover_color", Colors.White);
+ btn.AddThemeColorOverride("font_pressed_color", accentColor);
+ btn.AddThemeColorOverride("font_disabled_color", new Color(TextMuted.R, TextMuted.G, TextMuted.B, 0.45f));
+
+ var normal = MakeBox(BgInner, new Color(accentColor.R, accentColor.G, accentColor.B, 0.55f), 1);
+ var hover = MakeBox(BgHover, accentColor, 1);
+ var pressed = MakeBox(BgPressed, accentColor, 2);
+ var disabled = MakeBox(new Color(BgDark.R, BgDark.G, BgDark.B, 0.65f), new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.4f), 1);
+
+ btn.AddThemeStyleboxOverride("normal", normal);
+ btn.AddThemeStyleboxOverride("hover", hover);
+ btn.AddThemeStyleboxOverride("pressed", pressed);
+ btn.AddThemeStyleboxOverride("disabled", disabled);
+ btn.AddThemeStyleboxOverride("focus", hover);
+ }
+
+ public static void StyleLineEdit(LineEdit edit, Color accentColor, int fontSize = 13)
+ {
+ edit.AddThemeFontSizeOverride("font_size", fontSize);
+ edit.AddThemeColorOverride("font_color", TextLight);
+ edit.AddThemeColorOverride("font_placeholder_color", new Color(TextMuted.R, TextMuted.G, TextMuted.B, 0.65f));
+ edit.AddThemeColorOverride("font_uneditable_color", TextMuted);
+ edit.AddThemeColorOverride("caret_color", accentColor);
+
+ var normal = MakeBox(BgInner, BorderCol, 1, padH: 8, padV: 4);
+ var focus = MakeBox(BgHover, accentColor, 1, padH: 8, padV: 4);
+ var readOnly = MakeBox(new Color(BgDark.R, BgDark.G, BgDark.B, 0.72f), new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.45f), 1, padH: 8, padV: 4);
+
+ edit.AddThemeStyleboxOverride("normal", normal);
+ edit.AddThemeStyleboxOverride("focus", focus);
+ edit.AddThemeStyleboxOverride("read_only", readOnly);
+ }
+
+ public static void StyleOptionButton(OptionButton opt, Color accentColor, int fontSize = 13)
+ {
+ StyleButton(opt, accentColor, fontSize);
+ }
+
+ public static void StyleCheckBox(CheckBox chk, Color accentColor, int fontSize = 12)
+ {
+ chk.FocusMode = Control.FocusModeEnum.None;
+ chk.AddThemeFontSizeOverride("font_size", fontSize);
+ chk.AddThemeColorOverride("font_color", TextLight);
+ chk.AddThemeColorOverride("font_hover_color", Colors.White);
+ chk.AddThemeColorOverride("font_pressed_color", accentColor);
+ chk.AddThemeColorOverride("font_disabled_color", TextMuted);
+ }
+
+ public static HSeparator MakeRule(Color? color = null)
+ {
+ var sep = new HSeparator();
+ var line = new StyleBoxLine
+ {
+ Color = color ?? new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.75f),
+ Thickness = 1
+ };
+ sep.AddThemeStyleboxOverride("separator", line);
+ return sep;
+ }
+
+ private static StyleBoxFlat MakeBox(Color bg, Color border, int borderW, int padH = 10, int padV = 6)
+ {
+ var box = new StyleBoxFlat
+ {
+ BgColor = bg,
+ BorderColor = border,
+ ContentMarginLeft = padH,
+ ContentMarginRight = padH,
+ ContentMarginTop = padV,
+ ContentMarginBottom = padV
+ };
+ box.SetBorderWidthAll(borderW);
+ return box;
+ }
+}
+
+public sealed partial class ImperialChromePanel : PanelContainer
+{
+ private readonly ShaderMaterial _material;
+
+ public ImperialChromePanel(
+ Color accentColor,
+ float cornerLen = 14f,
+ float borderPx = 1.5f,
+ float bgAlpha = 0.90f,
+ int padH = 14,
+ int padV = 12)
+ {
+ _material = new ShaderMaterial { Shader = ImperialChrome.ChromeShader };
+ _material.SetShaderParameter("bg_color", new Color(ImperialChrome.BgDark.R, ImperialChrome.BgDark.G, ImperialChrome.BgDark.B, bgAlpha));
+ _material.SetShaderParameter("border_color", ImperialChrome.BorderCol);
+ _material.SetShaderParameter("accent_color", accentColor);
+ _material.SetShaderParameter("corner_len", cornerLen);
+ _material.SetShaderParameter("border_px", borderPx);
+ Material = _material;
+
+ var empty = new StyleBoxEmpty
+ {
+ ContentMarginLeft = padH,
+ ContentMarginRight = padH,
+ ContentMarginTop = padV,
+ ContentMarginBottom = padV
+ };
+ AddThemeStyleboxOverride("panel", empty);
+ }
+
+ public ShaderMaterial ChromeMaterial => _material;
+
+ public void SetAccentColor(Color accentColor)
+ {
+ _material.SetShaderParameter("accent_color", accentColor);
+ }
+
+ public override void _Notification(int what)
+ {
+ if (what == NotificationResized)
+ {
+ _material.SetShaderParameter("rect_size", Size);
+ QueueRedraw();
+ }
+ }
+
+ public override void _Draw()
+ {
+ if (Size.X < 2f || Size.Y < 2f) return;
+ _material.SetShaderParameter("rect_size", Size);
+ DrawTextureRect(ImperialChrome.WhiteTexture, new Rect2(Vector2.Zero, Size), false, Colors.White);
+ }
+}
diff --git a/client/LobbyScreen.cs b/client/LobbyScreen.cs
new file mode 100644
index 0000000..7a64842
--- /dev/null
+++ b/client/LobbyScreen.cs
@@ -0,0 +1,474 @@
+using System;
+using System.Globalization;
+using Godot;
+using RustToDust.Core;
+
+namespace RustToDust.Client;
+
+///
+/// Authoritative pre-match orbital lobby overlay ().
+/// Displays the 12 contender slots, ready states, host-only map/seed controls,
+/// live 5-second orbital insertion countdown banner, and launch/leave actions.
+///
+public sealed partial class LobbyScreen : CanvasLayer
+{
+ private sealed class SlotRowView
+ {
+ public required PanelContainer Frame;
+ public required Label IndexLabel;
+ public required Label NameLabel;
+ public required Label RoleBadge;
+ public required Label ReadyBadge;
+ }
+
+ private readonly SlotRowView[] _slotViews = new SlotRowView[MatchState.ContenderCount];
+
+ private Control _root = null!;
+ private ImperialChromePanel _panel = null!;
+ private Label _modeBadge = null!;
+ private PanelContainer _countdownBanner = null!;
+ private Label _countdownLabel = null!;
+ private Label _rosterSummaryLabel = null!;
+
+ private OptionButton _mapOption = null!;
+ private LineEdit _seedEdit = null!;
+ private Button _applyConfigBtn = null!;
+ private Button _randomSeedBtn = null!;
+ private Label _authorityNoteLabel = null!;
+ private Label _netStatusLabel = null!;
+
+ private Button _readyBtn = null!;
+ private Button _launchBtn = null!;
+ private Button _leaveBtn = null!;
+
+ private IClientArenaSession? _activeSession;
+ private int? _lastSyncedSeed;
+ private byte? _lastSyncedMap;
+
+ public LobbyScreen()
+ {
+ Layer = 20;
+ }
+
+ public event Action? LeaveRequested;
+
+ public bool IsTextInputFocused => Visible && _seedEdit is not null && _seedEdit.HasFocus();
+
+ public override void _Ready()
+ {
+ BuildUi();
+ SetLobbyVisible(false);
+ }
+
+ public void SetLobbyVisible(bool visible)
+ {
+ Visible = visible;
+ if (_root is not null)
+ {
+ _root.Visible = visible;
+ }
+ if (!visible)
+ {
+ _activeSession = null;
+ _lastSyncedSeed = null;
+ _lastSyncedMap = null;
+ _seedEdit?.ReleaseFocus();
+ }
+ }
+
+ public void Sync(IClientArenaSession session)
+ {
+ _activeSession = session;
+ var net = session.ConnectionStatus;
+ var lobby = session.LobbyState;
+
+ _modeBadge.Text = net.Mode switch
+ {
+ NetworkMode.ListenHost => net.StateLabel,
+ NetworkMode.RemoteClient => net.Connected
+ ? $"CONNECTED • PING {net.PingMs} ms"
+ : (net.LastError is not null ? $"DISCONNECTED: {net.LastError}" : "CONNECTING TO LOBBY..."),
+ _ => "SOLO"
+ };
+ _modeBadge.AddThemeColorOverride("font_color",
+ net.LastError is not null ? ImperialChrome.RedCol : (net.Connected ? ImperialChrome.CyanCol : ImperialChrome.OrangeCol));
+
+ if (lobby is null)
+ {
+ _countdownLabel.Text = net.LastError is not null
+ ? $"CONNECTION LOST — {net.LastError}"
+ : "ESTABLISHING RUDP UPLINK TO SERVER LOBBY...";
+ _countdownLabel.AddThemeColorOverride("font_color", net.LastError is not null ? ImperialChrome.RedCol : ImperialChrome.OrangeCol);
+ _rosterSummaryLabel.Text = "Awaiting authoritative lobby roster...";
+ _readyBtn.Disabled = true;
+ _launchBtn.Visible = false;
+ _mapOption.Disabled = true;
+ _seedEdit.Editable = false;
+ _applyConfigBtn.Disabled = true;
+ _randomSeedBtn.Disabled = true;
+ _authorityNoteLabel.Text = "Waiting for server snapshot...";
+ _netStatusLabel.Text = net.StateLabel;
+ return;
+ }
+
+ int localId = session.LocalContenderId;
+ bool isHost = lobby.HostSlotId.HasValue && lobby.HostSlotId.Value == localId;
+ bool localReady = false;
+ int humanCount = 0;
+ int readyCount = 0;
+ int aiCount = 0;
+
+ for (int i = 0; i < _slotViews.Length; i++)
+ {
+ var view = _slotViews[i];
+ if (i < lobby.Slots.Count)
+ {
+ var slot = lobby.Slots[i];
+ bool isLocalSlot = slot.SlotId == localId;
+ bool isHostSlot = lobby.HostSlotId.HasValue && slot.SlotId == lobby.HostSlotId.Value;
+
+ view.IndexLabel.Text = $"SLOT {slot.SlotId + 1:00}";
+ if (slot.IsHuman)
+ {
+ humanCount++;
+ if (slot.IsReady) readyCount++;
+ if (isLocalSlot) localReady = slot.IsReady;
+
+ view.NameLabel.Text = string.IsNullOrWhiteSpace(slot.Callsign) ? $"Pilot {slot.SlotId + 1}" : slot.Callsign;
+ view.NameLabel.AddThemeColorOverride("font_color", isLocalSlot ? ImperialChrome.TextLight : Colors.White);
+
+ view.RoleBadge.Text = isHostSlot
+ ? (isLocalSlot ? "[HOST / YOU]" : "[HOST]")
+ : (isLocalSlot ? "[YOU]" : "[PILOT]");
+ view.RoleBadge.AddThemeColorOverride("font_color", isHostSlot ? ImperialChrome.GoldCol : ImperialChrome.CyanCol);
+
+ view.ReadyBadge.Text = slot.IsReady ? "[READY]" : "[WAIT]";
+ view.ReadyBadge.AddThemeColorOverride("font_color", slot.IsReady ? ImperialChrome.OliveCol : ImperialChrome.OrangeCol);
+
+ ApplyRowFrame(view.Frame, isLocalSlot ? ImperialChrome.CyanCol : ImperialChrome.BorderCol, highlighted: isLocalSlot);
+ }
+ else
+ {
+ aiCount++;
+ view.NameLabel.Text = "AI BACKFILL";
+ view.NameLabel.AddThemeColorOverride("font_color", ImperialChrome.TextMuted);
+ view.RoleBadge.Text = "[BOT]";
+ view.RoleBadge.AddThemeColorOverride("font_color", ImperialChrome.TextMuted);
+ view.ReadyBadge.Text = "[ARMED]";
+ view.ReadyBadge.AddThemeColorOverride("font_color", ImperialChrome.TextMuted);
+ ApplyRowFrame(view.Frame, new Color(ImperialChrome.BorderCol.R, ImperialChrome.BorderCol.G, ImperialChrome.BorderCol.B, 0.45f), highlighted: false);
+ }
+ }
+ }
+
+ _rosterSummaryLabel.Text = $"HUMANS: {humanCount}/{MatchState.ContenderCount} • READY: {readyCount}/{Math.Max(1, humanCount)} • AI BACKFILL: {aiCount}";
+
+ // Countdown banner
+ if (lobby.CountdownSeconds is float cd)
+ {
+ int ceilSec = Math.Max(1, (int)MathF.Ceiling(cd));
+ _countdownLabel.Text = $"ORBITAL INSERTION IN {ceilSec}...";
+ _countdownLabel.AddThemeColorOverride("font_color", ceilSec <= 2 ? ImperialChrome.OrangeCol : ImperialChrome.GoldCol);
+ _panel.SetAccentColor(ImperialChrome.GoldCol);
+ }
+ else
+ {
+ string readyHint = humanCount < lobby.MinHumansToAutoStart
+ ? $"NEED {lobby.MinHumansToAutoStart} HUMANS FOR AUTO-LAUNCH"
+ : "ALL PILOTS READY UP TO BEGIN DROP";
+ _countdownLabel.Text = isHost
+ ? $"PRE-MATCH STANDBY • {readyHint} (OR LAUNCH DROP)"
+ : $"PRE-MATCH STANDBY • {readyHint}";
+ _countdownLabel.AddThemeColorOverride("font_color", ImperialChrome.CyanCol);
+ _panel.SetAccentColor(ImperialChrome.CyanCol);
+ }
+
+ // Sync Map & Seed without clobbering active typing by host
+ if (_lastSyncedMap != lobby.SelectedMap)
+ {
+ _lastSyncedMap = lobby.SelectedMap;
+ _mapOption.Select((ArenaMapKind)lobby.SelectedMap == ArenaMapKind.Desert ? 1 : 0);
+ }
+ if (_lastSyncedSeed != lobby.SelectedSeed && (!_seedEdit.HasFocus() || !isHost))
+ {
+ _lastSyncedSeed = lobby.SelectedSeed;
+ _seedEdit.Text = lobby.SelectedSeed.ToString(CultureInfo.InvariantCulture);
+ }
+
+ // Strict host authority gating
+ _mapOption.Disabled = !isHost;
+ _seedEdit.Editable = isHost;
+ _applyConfigBtn.Disabled = !isHost;
+ _randomSeedBtn.Disabled = !isHost;
+ _authorityNoteLabel.Text = isHost
+ ? "HOST AUTHORITY: You control drop zone, seed, and forced launch."
+ : "READ-ONLY: Only the match host can edit map, seed, or force launch.";
+ _authorityNoteLabel.AddThemeColorOverride("font_color", isHost ? ImperialChrome.GoldCol : ImperialChrome.TextMuted);
+
+ _readyBtn.Disabled = false;
+ _readyBtn.Text = localReady ? "READY [ON] — CLICK TO UNREADY" : "READY UP";
+ ImperialChrome.StyleButton(_readyBtn, localReady ? ImperialChrome.OliveCol : ImperialChrome.CyanCol, 14);
+
+ _launchBtn.Visible = isHost;
+ _launchBtn.Disabled = !isHost;
+ _launchBtn.Text = lobby.ForceLaunched ? "LAUNCHING NOW..." : "LAUNCH DROP";
+
+ _netStatusLabel.Text = $"{net.StateLabel} • MAP: {((ArenaMapKind)lobby.SelectedMap == ArenaMapKind.Sion ? "SION 3KM" : "DESERT RING")} • SEED {lobby.SelectedSeed}";
+ }
+
+ private void BuildUi()
+ {
+ _root = new Control
+ {
+ Name = "LobbyScreenRoot",
+ MouseFilter = Control.MouseFilterEnum.Stop
+ };
+ _root.SetAnchorsPreset(Control.LayoutPreset.FullRect);
+ AddChild(_root);
+
+ var scrim = new ColorRect
+ {
+ Color = new Color(0.03f, 0.04f, 0.03f, 0.36f),
+ MouseFilter = Control.MouseFilterEnum.Stop
+ };
+ scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect);
+ _root.AddChild(scrim);
+
+ _panel = ImperialChrome.CreatePanel(ImperialChrome.CyanCol, cornerLen: 18f, borderPx: 2f, bgAlpha: 0.92f, padH: 18, padV: 16);
+ _panel.Name = "LobbyScreenPanel";
+ _panel.AnchorLeft = 0.5f;
+ _panel.AnchorRight = 0.5f;
+ _panel.AnchorTop = 0.5f;
+ _panel.AnchorBottom = 0.5f;
+ _panel.OffsetLeft = -500f;
+ _panel.OffsetRight = 500f;
+ _panel.OffsetTop = -305f;
+ _panel.OffsetBottom = 305f;
+ _root.AddChild(_panel);
+
+ var vbox = new VBoxContainer();
+ vbox.AddThemeConstantOverride("separation", 10);
+ _panel.AddChild(vbox);
+
+ // Header row
+ var headerRow = new HBoxContainer();
+ headerRow.AddThemeConstantOverride("separation", 12);
+ vbox.AddChild(headerRow);
+
+ var titleLbl = ImperialChrome.CreateLabel("PRE-MATCH ORBITAL LOBBY", 20, ImperialChrome.TextLight);
+ titleLbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
+ headerRow.AddChild(titleLbl);
+
+ _modeBadge = ImperialChrome.CreateLabel("HOST :3076", 12, ImperialChrome.CyanCol, HorizontalAlignment.Right);
+ headerRow.AddChild(_modeBadge);
+
+ // Countdown Banner
+ _countdownBanner = new PanelContainer();
+ var cdStyle = new StyleBoxFlat
+ {
+ BgColor = ImperialChrome.BgInner,
+ BorderColor = ImperialChrome.GoldCol,
+ ContentMarginLeft = 12,
+ ContentMarginRight = 12,
+ ContentMarginTop = 8,
+ ContentMarginBottom = 8
+ };
+ cdStyle.SetBorderWidthAll(1);
+ _countdownBanner.AddThemeStyleboxOverride("panel", cdStyle);
+ vbox.AddChild(_countdownBanner);
+
+ _countdownLabel = ImperialChrome.CreateLabel("PRE-MATCH STANDBY", 15, ImperialChrome.CyanCol, HorizontalAlignment.Center);
+ _countdownBanner.AddChild(_countdownLabel);
+
+ // Body: Two columns (Left Roster | Right Config & Actions)
+ var bodyRow = new HBoxContainer
+ {
+ SizeFlagsVertical = Control.SizeFlags.ExpandFill
+ };
+ bodyRow.AddThemeConstantOverride("separation", 16);
+ vbox.AddChild(bodyRow);
+
+ // Left Column: Roster (Slot 01..12)
+ var leftCol = new VBoxContainer
+ {
+ SizeFlagsHorizontal = Control.SizeFlags.ExpandFill,
+ SizeFlagsStretchRatio = 1.35f
+ };
+ leftCol.AddThemeConstantOverride("separation", 4);
+ bodyRow.AddChild(leftCol);
+
+ leftCol.AddChild(ImperialChrome.CreateLabel("CONTENDER ROSTER (SLOTS 01 – 12)", 12, ImperialChrome.OrangeCol));
+
+ for (int i = 0; i < _slotViews.Length; i++)
+ {
+ var frame = new PanelContainer();
+ ApplyRowFrame(frame, ImperialChrome.BorderCol, highlighted: false);
+
+ var row = new HBoxContainer();
+ row.AddThemeConstantOverride("separation", 8);
+ frame.AddChild(row);
+
+ var idxLbl = ImperialChrome.CreateLabel($"SLOT {i + 1:00}", 11, ImperialChrome.TextMuted);
+ idxLbl.CustomMinimumSize = new Vector2(64f, 0f);
+ row.AddChild(idxLbl);
+
+ var nameLbl = ImperialChrome.CreateLabel("AI BACKFILL", 12, ImperialChrome.TextMuted);
+ nameLbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
+ nameLbl.ClipText = true;
+ row.AddChild(nameLbl);
+
+ var roleLbl = ImperialChrome.CreateLabel("[BOT]", 11, ImperialChrome.TextMuted);
+ roleLbl.CustomMinimumSize = new Vector2(92f, 0f);
+ roleLbl.HorizontalAlignment = HorizontalAlignment.Right;
+ row.AddChild(roleLbl);
+
+ var readyLbl = ImperialChrome.CreateLabel("[ARMED]", 11, ImperialChrome.TextMuted);
+ readyLbl.CustomMinimumSize = new Vector2(72f, 0f);
+ readyLbl.HorizontalAlignment = HorizontalAlignment.Right;
+ row.AddChild(readyLbl);
+
+ leftCol.AddChild(frame);
+ _slotViews[i] = new SlotRowView
+ {
+ Frame = frame,
+ IndexLabel = idxLbl,
+ NameLabel = nameLbl,
+ RoleBadge = roleLbl,
+ ReadyBadge = readyLbl
+ };
+ }
+
+ _rosterSummaryLabel = ImperialChrome.CreateLabel("HUMANS: 1/12 • READY: 0/1 • AI BACKFILL: 11", 11, ImperialChrome.OliveCol);
+ leftCol.AddChild(_rosterSummaryLabel);
+
+ // Right Column: Drop Zone Config & Launch Actions
+ var rightCol = new VBoxContainer
+ {
+ SizeFlagsHorizontal = Control.SizeFlags.ExpandFill,
+ SizeFlagsStretchRatio = 1.0f
+ };
+ rightCol.AddThemeConstantOverride("separation", 10);
+ bodyRow.AddChild(rightCol);
+
+ rightCol.AddChild(ImperialChrome.CreateLabel("DROP ZONE CONFIGURATION", 12, ImperialChrome.GoldCol));
+ rightCol.AddChild(ImperialChrome.MakeRule());
+
+ var mapRow = new HBoxContainer();
+ mapRow.AddThemeConstantOverride("separation", 8);
+ rightCol.AddChild(mapRow);
+ var mapLbl = ImperialChrome.CreateLabel("MAP", 12, ImperialChrome.TextMuted);
+ mapLbl.CustomMinimumSize = new Vector2(68f, 0f);
+ mapRow.AddChild(mapLbl);
+ _mapOption = new OptionButton { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
+ _mapOption.AddItem("SION (3KM ALPINE)", 0);
+ _mapOption.AddItem("DESERT RING", 1);
+ ImperialChrome.StyleOptionButton(_mapOption, ImperialChrome.OliveCol, 13);
+ _mapOption.ItemSelected += _ => ApplyConfigFromUi();
+ mapRow.AddChild(_mapOption);
+
+ var seedRow = new HBoxContainer();
+ seedRow.AddThemeConstantOverride("separation", 8);
+ rightCol.AddChild(seedRow);
+ var seedLbl = ImperialChrome.CreateLabel("SEED", 12, ImperialChrome.TextMuted);
+ seedLbl.CustomMinimumSize = new Vector2(68f, 0f);
+ seedRow.AddChild(seedLbl);
+ _seedEdit = new LineEdit
+ {
+ Text = "42",
+ MaxLength = 12,
+ SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
+ };
+ ImperialChrome.StyleLineEdit(_seedEdit, ImperialChrome.GoldCol, 13);
+ _seedEdit.TextSubmitted += _ => ApplyConfigFromUi();
+ seedRow.AddChild(_seedEdit);
+
+ _randomSeedBtn = ImperialChrome.CreateButton("RND", ImperialChrome.BorderCol, 12, 30f);
+ _randomSeedBtn.CustomMinimumSize = new Vector2(54f, 30f);
+ _randomSeedBtn.Pressed += () =>
+ {
+ int nextSeed = Random.Shared.Next(1, 999999);
+ _seedEdit.Text = nextSeed.ToString(CultureInfo.InvariantCulture);
+ ApplyConfigFromUi();
+ };
+ seedRow.AddChild(_randomSeedBtn);
+
+ _applyConfigBtn = ImperialChrome.CreateButton("APPLY MAP & SEED", ImperialChrome.GoldCol, 12, 32f);
+ _applyConfigBtn.Pressed += ApplyConfigFromUi;
+ rightCol.AddChild(_applyConfigBtn);
+
+ _authorityNoteLabel = ImperialChrome.CreateLabel("HOST AUTHORITY", 11, ImperialChrome.TextMuted);
+ _authorityNoteLabel.AutowrapMode = TextServer.AutowrapMode.Word;
+ rightCol.AddChild(_authorityNoteLabel);
+
+ rightCol.AddChild(ImperialChrome.MakeRule());
+
+ var spacer = new Control { SizeFlagsVertical = Control.SizeFlags.ExpandFill };
+ rightCol.AddChild(spacer);
+
+ _readyBtn = ImperialChrome.CreateButton("READY UP", ImperialChrome.CyanCol, 14, 42f);
+ _readyBtn.Pressed += OnReadyPressed;
+ rightCol.AddChild(_readyBtn);
+
+ _launchBtn = ImperialChrome.CreateButton("LAUNCH DROP", ImperialChrome.OliveCol, 14, 42f);
+ _launchBtn.Pressed += OnLaunchPressed;
+ rightCol.AddChild(_launchBtn);
+
+ _leaveBtn = ImperialChrome.CreateButton("LEAVE TO MENU", ImperialChrome.RedCol, 13, 36f);
+ _leaveBtn.Pressed += () => LeaveRequested?.Invoke();
+ rightCol.AddChild(_leaveBtn);
+
+ _netStatusLabel = ImperialChrome.CreateLabel(string.Empty, 11, ImperialChrome.TextMuted);
+ _netStatusLabel.AutowrapMode = TextServer.AutowrapMode.Word;
+ vbox.AddChild(_netStatusLabel);
+ }
+
+ private void OnReadyPressed()
+ {
+ if (_activeSession is null || _activeSession.LobbyState is not { } lobby) return;
+ int localId = _activeSession.LocalContenderId;
+ bool currentReady = false;
+ for (int i = 0; i < lobby.Slots.Count; i++)
+ {
+ if (lobby.Slots[i].SlotId == localId)
+ {
+ currentReady = lobby.Slots[i].IsReady;
+ break;
+ }
+ }
+ _activeSession.SetLobbyReady(!currentReady);
+ }
+
+ private void OnLaunchPressed()
+ {
+ _activeSession?.RequestLobbyStart();
+ }
+
+ private void ApplyConfigFromUi()
+ {
+ if (_activeSession is null || _activeSession.LobbyState is not { } lobby) return;
+ if (!lobby.HostSlotId.HasValue || lobby.HostSlotId.Value != _activeSession.LocalContenderId) return;
+
+ var mapKind = _mapOption.Selected == 1 ? ArenaMapKind.Desert : ArenaMapKind.Sion;
+ int seed = int.TryParse(_seedEdit.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed)
+ ? parsed
+ : lobby.SelectedSeed;
+
+ _seedEdit.ReleaseFocus();
+ _activeSession.RequestLobbyConfig(seed, mapKind);
+ }
+
+ private static void ApplyRowFrame(PanelContainer frame, Color borderColor, bool highlighted)
+ {
+ var style = new StyleBoxFlat
+ {
+ BgColor = highlighted ? ImperialChrome.BgHover : ImperialChrome.BgInner,
+ BorderColor = borderColor,
+ ContentMarginLeft = 8,
+ ContentMarginRight = 8,
+ ContentMarginTop = 4,
+ ContentMarginBottom = 4
+ };
+ style.SetBorderWidthAll(1);
+ frame.AddThemeStyleboxOverride("panel", style);
+ }
+}
diff --git a/client/Main.cs b/client/Main.cs
index 2beeea3..9d76e57 100644
--- a/client/Main.cs
+++ b/client/Main.cs
@@ -11,6 +11,15 @@ using RustToDust.Ymir;
namespace RustToDust.Client;
+public enum ClientScreenMode
+{
+ MainMenu,
+ ServerBrowser,
+ Lobby,
+ InMatch,
+ PauseOverlay
+}
+
///
/// Root Godot node for Rust to Dust.
/// Godot physics is Dummy; drives Solo (),
@@ -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 _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)
diff --git a/client/MainMenu.cs b/client/MainMenu.cs
new file mode 100644
index 0000000..15c8da9
--- /dev/null
+++ b/client/MainMenu.cs
@@ -0,0 +1,425 @@
+using System;
+using System.Globalization;
+using Godot;
+using RustToDust.Core;
+
+namespace RustToDust.Client;
+
+///
+/// Industrial Imperial main menu overlay over the live Sion 3D orbit backdrop,
+/// plus the in-match [ESC] pause overlay.
+///
+public sealed partial class MainMenu : CanvasLayer
+{
+ public enum OverlayKind
+ {
+ Hidden,
+ MainMenu,
+ PauseOverlay
+ }
+
+ private Control _mainRoot = null!;
+ private ImperialChromePanel _menuPanel = null!;
+ private ImperialChromePanel _hostPanel = null!;
+ private LineEdit _callsignEdit = null!;
+ private Label _statusLabel = null!;
+
+ private LineEdit _serverNameEdit = null!;
+ private LineEdit _portEdit = null!;
+ private OptionButton _hostMapOption = null!;
+ private CheckBox _listPublicCheck = null!;
+ private Label _directoryHintLabel = null!;
+ private Label _hostErrorLabel = null!;
+
+ private Control _pauseRoot = null!;
+ private Label _pauseContextLabel = null!;
+
+ private OverlayKind _overlayKind = OverlayKind.Hidden;
+ private string _directoryUrl = string.Empty;
+
+ public MainMenu()
+ {
+ Layer = 20;
+ }
+
+ public event Action? PlaySoloRequested;
+ public event Action? ServerBrowserRequested;
+ public event Action? HostLobbyRequested;
+ public event Action? CallsignChanged;
+ public event Action? QuitRequested;
+ public event Action? ResumeRequested;
+ public event Action? ReturnToMainMenuRequested;
+
+ public bool IsHostPanelOpen => _hostPanel is not null && _hostPanel.Visible;
+ public bool IsTextInputFocused =>
+ Visible && _overlayKind == OverlayKind.MainMenu &&
+ (_callsignEdit.HasFocus() || _serverNameEdit.HasFocus() || _portEdit.HasFocus());
+ public string Callsign => SanitizeCallsign(_callsignEdit?.Text);
+
+ public override void _Ready()
+ {
+ BuildMainRoot();
+ BuildPauseRoot();
+ SetOverlayKind(OverlayKind.Hidden);
+ }
+
+ public void SetOverlayKind(OverlayKind kind)
+ {
+ _overlayKind = kind;
+ Visible = kind != OverlayKind.Hidden;
+ if (_mainRoot is not null)
+ {
+ _mainRoot.Visible = kind == OverlayKind.MainMenu;
+ }
+ if (_pauseRoot is not null)
+ {
+ _pauseRoot.Visible = kind == OverlayKind.PauseOverlay;
+ }
+ if (kind != OverlayKind.MainMenu)
+ {
+ ReleaseTextFocus();
+ }
+ }
+
+ public void SetHostPanelOpen(bool open)
+ {
+ if (_hostPanel is null) return;
+ _hostPanel.Visible = open;
+ if (open)
+ {
+ _hostErrorLabel.Text = string.Empty;
+ _hostErrorLabel.Visible = false;
+ }
+ else
+ {
+ _serverNameEdit.ReleaseFocus();
+ _portEdit.ReleaseFocus();
+ }
+ }
+
+ public void SetDefaults(string callsign, string directoryUrl, ArenaMapKind defaultMap = ArenaMapKind.Sion, int defaultPort = 3076)
+ {
+ _directoryUrl = directoryUrl ?? string.Empty;
+ if (_callsignEdit is not null)
+ {
+ _callsignEdit.Text = SanitizeCallsign(callsign);
+ }
+ if (_portEdit is not null)
+ {
+ _portEdit.Text = defaultPort.ToString(CultureInfo.InvariantCulture);
+ }
+ if (_hostMapOption is not null)
+ {
+ _hostMapOption.Select(defaultMap == ArenaMapKind.Desert ? 1 : 0);
+ }
+ if (_directoryHintLabel is not null)
+ {
+ _directoryHintLabel.Text = string.IsNullOrWhiteSpace(_directoryUrl)
+ ? "Public directory disabled (empty URL)"
+ : $"Directory: {_directoryUrl}";
+ }
+ }
+
+ public void SetStatus(string? message, bool isError = false)
+ {
+ if (_statusLabel is null) return;
+ if (string.IsNullOrWhiteSpace(message))
+ {
+ _statusLabel.Visible = false;
+ _statusLabel.Text = string.Empty;
+ return;
+ }
+ _statusLabel.Text = message.Trim();
+ _statusLabel.AddThemeColorOverride("font_color", isError ? ImperialChrome.RedCol : ImperialChrome.CyanCol);
+ _statusLabel.Visible = true;
+ }
+
+ public void SetHostError(string? message)
+ {
+ if (_hostErrorLabel is null) return;
+ if (string.IsNullOrWhiteSpace(message))
+ {
+ _hostErrorLabel.Visible = false;
+ _hostErrorLabel.Text = string.Empty;
+ return;
+ }
+ _hostErrorLabel.Text = message.Trim();
+ _hostErrorLabel.Visible = true;
+ }
+
+ public void SetPauseContext(string contextLine)
+ {
+ if (_pauseContextLabel is not null)
+ {
+ _pauseContextLabel.Text = contextLine;
+ }
+ }
+
+ private void ReleaseTextFocus()
+ {
+ _callsignEdit?.ReleaseFocus();
+ _serverNameEdit?.ReleaseFocus();
+ _portEdit?.ReleaseFocus();
+ }
+
+ private void BuildMainRoot()
+ {
+ _mainRoot = new Control
+ {
+ Name = "MainMenuRoot",
+ MouseFilter = Control.MouseFilterEnum.Ignore
+ };
+ _mainRoot.SetAnchorsPreset(Control.LayoutPreset.FullRect);
+ AddChild(_mainRoot);
+
+ _menuPanel = ImperialChrome.CreatePanel(ImperialChrome.OrangeCol, cornerLen: 18f, borderPx: 2f, bgAlpha: 0.91f, padH: 20, padV: 18);
+ _menuPanel.Name = "MainMenuPanel";
+ _menuPanel.AnchorLeft = 0f;
+ _menuPanel.AnchorTop = 0f;
+ _menuPanel.OffsetLeft = 48f;
+ _menuPanel.OffsetTop = 52f;
+ _menuPanel.OffsetRight = 458f;
+ _mainRoot.AddChild(_menuPanel);
+
+ var vbox = new VBoxContainer();
+ vbox.AddThemeConstantOverride("separation", 10);
+ _menuPanel.AddChild(vbox);
+
+ vbox.AddChild(ImperialChrome.CreateLabel("IMPERIAL ORBITAL INSERTION • SECTOR 01", 11, ImperialChrome.GoldCol));
+
+ var title = ImperialChrome.CreateLabel("RUST TO DUST", 32, ImperialChrome.TextLight);
+ vbox.AddChild(title);
+
+ vbox.AddChild(ImperialChrome.CreateLabel("SION 3KM ALPINE ARENA • BROKKR COMBAT CHASSIS", 11, ImperialChrome.TextMuted));
+ vbox.AddChild(ImperialChrome.MakeRule());
+
+ // Callsign row
+ var callRow = new HBoxContainer();
+ callRow.AddThemeConstantOverride("separation", 10);
+ vbox.AddChild(callRow);
+
+ var callLbl = ImperialChrome.CreateLabel("CALLSIGN", 12, ImperialChrome.TextMuted);
+ callLbl.CustomMinimumSize = new Vector2(82f, 0f);
+ callRow.AddChild(callLbl);
+
+ _callsignEdit = new LineEdit
+ {
+ Text = "Pilot",
+ MaxLength = 24,
+ PlaceholderText = "Pilot",
+ SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
+ };
+ ImperialChrome.StyleLineEdit(_callsignEdit, ImperialChrome.CyanCol, 13);
+ _callsignEdit.TextChanged += txt => CallsignChanged?.Invoke(SanitizeCallsign(txt));
+ callRow.AddChild(_callsignEdit);
+
+ vbox.AddChild(ImperialChrome.MakeRule());
+
+ var playSionBtn = ImperialChrome.CreateButton("PLAY SOLO — SION", ImperialChrome.OliveCol, 14, 38f);
+ playSionBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Sion, Callsign);
+ vbox.AddChild(playSionBtn);
+
+ var playDesertBtn = ImperialChrome.CreateButton("PLAY SOLO — DESERT", ImperialChrome.OrangeCol, 14, 38f);
+ playDesertBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Desert, Callsign);
+ vbox.AddChild(playDesertBtn);
+
+ var browserBtn = ImperialChrome.CreateButton("SERVER BROWSER", ImperialChrome.CyanCol, 14, 38f);
+ browserBtn.Pressed += () => ServerBrowserRequested?.Invoke(Callsign);
+ vbox.AddChild(browserBtn);
+
+ var hostBtn = ImperialChrome.CreateButton("HOST MATCH", ImperialChrome.GoldCol, 14, 38f);
+ hostBtn.Pressed += () => SetHostPanelOpen(!IsHostPanelOpen);
+ vbox.AddChild(hostBtn);
+
+ vbox.AddChild(ImperialChrome.MakeRule());
+
+ var quitBtn = ImperialChrome.CreateButton("QUIT", ImperialChrome.RedCol, 13, 34f);
+ quitBtn.Pressed += () => QuitRequested?.Invoke();
+ vbox.AddChild(quitBtn);
+
+ _statusLabel = ImperialChrome.CreateLabel(string.Empty, 11, ImperialChrome.CyanCol);
+ _statusLabel.AutowrapMode = TextServer.AutowrapMode.Word;
+ _statusLabel.Visible = false;
+ vbox.AddChild(_statusLabel);
+
+ vbox.AddChild(ImperialChrome.CreateLabel("Data: swisstopo 3km Sion | CultNet UDP 3076", 10, ImperialChrome.TextMuted));
+
+ BuildHostPanel();
+ }
+
+ private void BuildHostPanel()
+ {
+ _hostPanel = ImperialChrome.CreatePanel(ImperialChrome.GoldCol, cornerLen: 16f, borderPx: 1.5f, bgAlpha: 0.93f, padH: 18, padV: 16);
+ _hostPanel.Name = "HostConfigPanel";
+ _hostPanel.AnchorLeft = 0f;
+ _hostPanel.AnchorTop = 0f;
+ _hostPanel.OffsetLeft = 480f;
+ _hostPanel.OffsetTop = 132f;
+ _hostPanel.OffsetRight = 900f;
+ _hostPanel.Visible = false;
+ _mainRoot.AddChild(_hostPanel);
+
+ var vbox = new VBoxContainer();
+ vbox.AddThemeConstantOverride("separation", 10);
+ _hostPanel.AddChild(vbox);
+
+ vbox.AddChild(ImperialChrome.CreateLabel("HOST PRE-MATCH LOBBY", 14, ImperialChrome.GoldCol));
+ vbox.AddChild(ImperialChrome.MakeRule());
+
+ var nameRow = new HBoxContainer();
+ nameRow.AddThemeConstantOverride("separation", 8);
+ vbox.AddChild(nameRow);
+ var srvLbl = ImperialChrome.CreateLabel("SERVER NAME", 11, ImperialChrome.TextMuted);
+ srvLbl.CustomMinimumSize = new Vector2(106f, 0f);
+ nameRow.AddChild(srvLbl);
+ _serverNameEdit = new LineEdit
+ {
+ Text = "Rust to Dust",
+ MaxLength = 48,
+ PlaceholderText = "Server Name",
+ SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
+ };
+ ImperialChrome.StyleLineEdit(_serverNameEdit, ImperialChrome.GoldCol, 13);
+ nameRow.AddChild(_serverNameEdit);
+
+ var portRow = new HBoxContainer();
+ portRow.AddThemeConstantOverride("separation", 8);
+ vbox.AddChild(portRow);
+ var portLbl = ImperialChrome.CreateLabel("UDP PORT", 11, ImperialChrome.TextMuted);
+ portLbl.CustomMinimumSize = new Vector2(106f, 0f);
+ portRow.AddChild(portLbl);
+ _portEdit = new LineEdit
+ {
+ Text = "3076",
+ MaxLength = 5,
+ PlaceholderText = "3076",
+ SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
+ };
+ ImperialChrome.StyleLineEdit(_portEdit, ImperialChrome.GoldCol, 13);
+ portRow.AddChild(_portEdit);
+
+ var mapRow = new HBoxContainer();
+ mapRow.AddThemeConstantOverride("separation", 8);
+ vbox.AddChild(mapRow);
+ var mapLbl = ImperialChrome.CreateLabel("DROP ZONE", 11, ImperialChrome.TextMuted);
+ mapLbl.CustomMinimumSize = new Vector2(106f, 0f);
+ mapRow.AddChild(mapLbl);
+ _hostMapOption = new OptionButton
+ {
+ SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
+ };
+ _hostMapOption.AddItem("SION (3KM ALPINE)", 0);
+ _hostMapOption.AddItem("DESERT RING", 1);
+ _hostMapOption.Select(0);
+ ImperialChrome.StyleOptionButton(_hostMapOption, ImperialChrome.OliveCol, 13);
+ mapRow.AddChild(_hostMapOption);
+
+ _listPublicCheck = new CheckBox
+ {
+ Text = "List on Public Directory",
+ ButtonPressed = false
+ };
+ ImperialChrome.StyleCheckBox(_listPublicCheck, ImperialChrome.CyanCol, 12);
+ vbox.AddChild(_listPublicCheck);
+
+ _directoryHintLabel = ImperialChrome.CreateLabel("Directory: https://eureka.gamecult.org/rtd-directory", 10, ImperialChrome.TextMuted);
+ _directoryHintLabel.AutowrapMode = TextServer.AutowrapMode.Word;
+ vbox.AddChild(_directoryHintLabel);
+
+ _hostErrorLabel = ImperialChrome.CreateLabel(string.Empty, 11, ImperialChrome.RedCol);
+ _hostErrorLabel.AutowrapMode = TextServer.AutowrapMode.Word;
+ _hostErrorLabel.Visible = false;
+ vbox.AddChild(_hostErrorLabel);
+
+ var btnRow = new HBoxContainer();
+ btnRow.AddThemeConstantOverride("separation", 8);
+ vbox.AddChild(btnRow);
+
+ var launchBtn = ImperialChrome.CreateButton("LAUNCH LOBBY", ImperialChrome.OliveCol, 13, 34f);
+ launchBtn.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
+ launchBtn.Pressed += OnHostLaunchPressed;
+ btnRow.AddChild(launchBtn);
+
+ var cancelBtn = ImperialChrome.CreateButton("CANCEL", ImperialChrome.BorderCol, 13, 34f);
+ cancelBtn.Pressed += () => SetHostPanelOpen(false);
+ btnRow.AddChild(cancelBtn);
+ }
+
+ private void OnHostLaunchPressed()
+ {
+ if (!int.TryParse(_portEdit.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int port) ||
+ port is < 1 or > 65535)
+ {
+ SetHostError("UDP port must be between 1 and 65535.");
+ return;
+ }
+
+ string serverName = string.IsNullOrWhiteSpace(_serverNameEdit.Text)
+ ? "Rust to Dust"
+ : _serverNameEdit.Text.Trim();
+ var mapKind = _hostMapOption.Selected == 1 ? ArenaMapKind.Desert : ArenaMapKind.Sion;
+ bool listPublic = _listPublicCheck.ButtonPressed;
+
+ SetHostError(null);
+ HostLobbyRequested?.Invoke(port, serverName, mapKind, listPublic, Callsign);
+ }
+
+ private void BuildPauseRoot()
+ {
+ _pauseRoot = new Control
+ {
+ Name = "PauseOverlayRoot",
+ MouseFilter = Control.MouseFilterEnum.Stop
+ };
+ _pauseRoot.SetAnchorsPreset(Control.LayoutPreset.FullRect);
+ AddChild(_pauseRoot);
+
+ var scrim = new ColorRect
+ {
+ Color = ImperialChrome.ScrimCol,
+ MouseFilter = Control.MouseFilterEnum.Stop
+ };
+ scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect);
+ _pauseRoot.AddChild(scrim);
+
+ var panel = ImperialChrome.CreatePanel(ImperialChrome.OrangeCol, cornerLen: 16f, borderPx: 2f, bgAlpha: 0.94f, padH: 20, padV: 18);
+ panel.Name = "PauseOverlayPanel";
+ panel.AnchorLeft = 0.5f;
+ panel.AnchorRight = 0.5f;
+ panel.AnchorTop = 0.5f;
+ panel.AnchorBottom = 0.5f;
+ panel.OffsetLeft = -190f;
+ panel.OffsetRight = 190f;
+ panel.OffsetTop = -132f;
+ panel.OffsetBottom = 132f;
+ _pauseRoot.AddChild(panel);
+
+ var vbox = new VBoxContainer();
+ vbox.AddThemeConstantOverride("separation", 10);
+ panel.AddChild(vbox);
+
+ vbox.AddChild(ImperialChrome.CreateLabel("TACTICAL PAUSE • [ESC]", 16, ImperialChrome.OrangeCol, HorizontalAlignment.Center));
+
+ _pauseContextLabel = ImperialChrome.CreateLabel("COMBAT ACTIVE", 11, ImperialChrome.TextMuted, HorizontalAlignment.Center);
+ vbox.AddChild(_pauseContextLabel);
+ vbox.AddChild(ImperialChrome.MakeRule());
+
+ var resumeBtn = ImperialChrome.CreateButton("RESUME", ImperialChrome.OliveCol, 14, 36f);
+ resumeBtn.Pressed += () => ResumeRequested?.Invoke();
+ vbox.AddChild(resumeBtn);
+
+ var menuBtn = ImperialChrome.CreateButton("RETURN TO MAIN MENU", ImperialChrome.OrangeCol, 14, 36f);
+ menuBtn.Pressed += () => ReturnToMainMenuRequested?.Invoke();
+ vbox.AddChild(menuBtn);
+
+ var quitBtn = ImperialChrome.CreateButton("QUIT", ImperialChrome.RedCol, 13, 34f);
+ quitBtn.Pressed += () => QuitRequested?.Invoke();
+ vbox.AddChild(quitBtn);
+ }
+
+ private static string SanitizeCallsign(string? raw)
+ {
+ string trimmed = (raw ?? string.Empty).Trim();
+ return string.IsNullOrEmpty(trimmed) ? "Pilot" : trimmed;
+ }
+}
diff --git a/client/ServerBrowser.cs b/client/ServerBrowser.cs
new file mode 100644
index 0000000..eda6536
--- /dev/null
+++ b/client/ServerBrowser.cs
@@ -0,0 +1,738 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Threading;
+using System.Threading.Tasks;
+using Godot;
+using RustToDust.Net;
+
+namespace RustToDust.Client;
+
+///
+/// Public Yggdrasil directory server browser with live non-blocking UDP RTDP
+/// ping probes, optional 127.0.0.1:3076 localhost probe, and direct IP:Port join.
+///
+public sealed partial class ServerBrowser : CanvasLayer
+{
+ public const string DefaultDirectoryUrl = "https://eureka.gamecult.org/rtd-directory";
+
+ private sealed class ServerRowModel
+ {
+ public required string Key;
+ public required string Host;
+ public required int Port;
+ public required string Name;
+ public required string Map;
+ public required int Humans;
+ public required int MaxHumans;
+ public required string Phase;
+ public required bool IsLocalProbe;
+ public int? PingMs;
+ public bool TimedOut;
+ public bool Probing = true;
+ public bool Disposed;
+
+ public Button? RowButton;
+ public Label? NameLabel;
+ public Label? MapLabel;
+ public Label? PlayersLabel;
+ public Label? PhaseLabel;
+ public Label? PingLabel;
+ public Label? AddressLabel;
+ }
+
+ private readonly ConcurrentQueue _mainThreadQueue = new();
+ private readonly List _rows = new();
+
+ private Control _root = null!;
+ private Label _dirStatusLabel = null!;
+ private Label _dirUrlLabel = null!;
+ private VBoxContainer _rowsContainer = null!;
+ private CheckBox _probeLocalhostCheck = null!;
+ private LineEdit _directEndpointEdit = null!;
+ private Button _refreshBtn = null!;
+ private Button _joinBtn = null!;
+ private Label _footerErrorLabel = null!;
+
+ private CancellationTokenSource? _refreshCts;
+ private int _refreshSeq;
+ private string _directoryUrl = DefaultDirectoryUrl;
+ private string _callsign = "Pilot";
+ private string? _selectedKey;
+
+ public ServerBrowser()
+ {
+ Layer = 20;
+ }
+
+ public event Action? JoinRequested;
+ public event Action? HostRequested;
+ public event Action? BackRequested;
+
+ public bool IsTextInputFocused => Visible && _directEndpointEdit is not null && _directEndpointEdit.HasFocus();
+ public int RowCount => _rows.Count;
+
+ public override void _Ready()
+ {
+ BuildUi();
+ SetBrowserVisible(false);
+ }
+
+ public override void _ExitTree()
+ {
+ CancelPendingRefresh();
+ }
+
+ public override void _Process(double delta)
+ {
+ while (_mainThreadQueue.TryDequeue(out var action))
+ {
+ action();
+ }
+ }
+
+ public void Configure(string directoryUrl, string callsign, string? defaultDirectEndpoint = null)
+ {
+ _directoryUrl = directoryUrl ?? string.Empty;
+ _callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim();
+ if (_dirUrlLabel is not null)
+ {
+ _dirUrlLabel.Text = string.IsNullOrWhiteSpace(_directoryUrl)
+ ? "DIRECTORY: DISABLED"
+ : $"DIRECTORY: {_directoryUrl}";
+ }
+ if (_directEndpointEdit is not null && !string.IsNullOrWhiteSpace(defaultDirectEndpoint))
+ {
+ _directEndpointEdit.Text = defaultDirectEndpoint.Trim();
+ }
+ }
+
+ public void SetBrowserVisible(bool visible, bool autoRefresh = true)
+ {
+ Visible = visible;
+ if (_root is not null)
+ {
+ _root.Visible = visible;
+ }
+ if (visible)
+ {
+ SetError(null);
+ if (autoRefresh)
+ {
+ Refresh();
+ }
+ }
+ else
+ {
+ CancelPendingRefresh();
+ _directEndpointEdit?.ReleaseFocus();
+ }
+ }
+
+ public void SetError(string? message)
+ {
+ if (_footerErrorLabel is null) return;
+ if (string.IsNullOrWhiteSpace(message))
+ {
+ _footerErrorLabel.Visible = false;
+ _footerErrorLabel.Text = string.Empty;
+ return;
+ }
+ _footerErrorLabel.Text = message.Trim();
+ _footerErrorLabel.Visible = true;
+ }
+
+ public void Refresh()
+ {
+ CancelPendingRefresh();
+ int seq = ++_refreshSeq;
+ _refreshCts = new CancellationTokenSource();
+ CancellationToken ct = _refreshCts.Token;
+
+ ClearRows();
+ _selectedKey = null;
+ UpdateJoinButtonState();
+ SetError(null);
+
+ bool probeLocal = _probeLocalhostCheck is null || _probeLocalhostCheck.ButtonPressed;
+ if (probeLocal)
+ {
+ var localRow = new ServerRowModel
+ {
+ Key = "local:127.0.0.1:3076",
+ Host = "127.0.0.1",
+ Port = 3076,
+ Name = "LOCALHOST (127.0.0.1:3076)",
+ Map = "-",
+ Humans = 0,
+ MaxHumans = 12,
+ Phase = "PROBING",
+ IsLocalProbe = true,
+ Probing = true
+ };
+ AddRowWidget(localRow);
+ _ = ProbeRowAsync(localRow, seq, ct);
+ }
+
+ string dirUrl = DirectoryBrowserClient.NormalizeBaseUrl(_directoryUrl);
+ if (string.IsNullOrEmpty(dirUrl))
+ {
+ SetDirectoryStatus("Directory URL not configured — local/direct connect ready.", isWarning: true);
+ return;
+ }
+
+ SetDirectoryStatus("Querying public Yggdrasil directory...", isWarning: false);
+
+ _ = Task.Run(async () =>
+ {
+ try
+ {
+ var servers = await DirectoryBrowserClient.FetchServersAsync(dirUrl, ct).ConfigureAwait(false);
+ _mainThreadQueue.Enqueue(() =>
+ {
+ if (!IsInsideTree() || seq != _refreshSeq) return;
+ OnDirectoryFetched(servers, seq, ct);
+ });
+ }
+ catch (OperationCanceledException)
+ {
+ }
+ catch (Exception ex)
+ {
+ _mainThreadQueue.Enqueue(() =>
+ {
+ if (!IsInsideTree() || seq != _refreshSeq) return;
+ SetDirectoryStatus($"Directory offline ({ShortError(ex.Message)}) — direct IP:Port connect available.", isWarning: true);
+ });
+ }
+ }, ct);
+ }
+
+ private void OnDirectoryFetched(IReadOnlyList servers, int seq, CancellationToken ct)
+ {
+ if (servers.Count == 0)
+ {
+ SetDirectoryStatus("Directory online — 0 public servers listed.", isWarning: false);
+ return;
+ }
+
+ SetDirectoryStatus($"Directory online — {servers.Count} {(servers.Count == 1 ? "server" : "servers")} listed. Pinging...", isWarning: false);
+
+ for (int i = 0; i < servers.Count; i++)
+ {
+ var s = servers[i];
+ if (string.IsNullOrWhiteSpace(s.PublicHost) || s.UdpPort is < 1 or > 65535)
+ {
+ continue;
+ }
+
+ // Avoid duplicating localhost row if directory explicitly lists 127.0.0.1:3076
+ bool isLoopbackDefault = string.Equals(s.PublicHost, "127.0.0.1", StringComparison.Ordinal) && s.UdpPort == 3076;
+ if (isLoopbackDefault)
+ {
+ RemoveLocalProbeRowIfPresent();
+ }
+
+ var row = new ServerRowModel
+ {
+ Key = $"dir:{s.ServerId:N}:{s.PublicHost}:{s.UdpPort}",
+ Host = s.PublicHost,
+ Port = s.UdpPort,
+ Name = string.IsNullOrWhiteSpace(s.Name) ? $"{s.PublicHost}:{s.UdpPort}" : s.Name.Trim(),
+ Map = FormatMap(s.Map),
+ Humans = s.Humans,
+ MaxHumans = s.MaxHumans > 0 ? s.MaxHumans : 12,
+ Phase = FormatPhase(s.Phase),
+ IsLocalProbe = false,
+ Probing = true
+ };
+ AddRowWidget(row);
+ _ = ProbeRowAsync(row, seq, ct);
+ }
+ }
+
+ private async Task ProbeRowAsync(ServerRowModel row, int seq, CancellationToken ct)
+ {
+ try
+ {
+ var result = await ServerPingProbe.ProbeAsync(row.Host, row.Port, TimeSpan.FromMilliseconds(1400), ct).ConfigureAwait(false);
+ _mainThreadQueue.Enqueue(() =>
+ {
+ if (!IsInsideTree() || seq != _refreshSeq || row.Disposed || !_rows.Contains(row) || row.RowButton is null || !IsInstanceValid(row.RowButton)) return;
+ row.Probing = false;
+ if (result.Success && result.Summary is { } summary)
+ {
+ row.PingMs = result.RttMs;
+ row.TimedOut = false;
+ if (!string.IsNullOrWhiteSpace(summary.ServerName))
+ {
+ row.Name = row.IsLocalProbe
+ ? $"[LOCAL] {summary.ServerName.Trim()}"
+ : summary.ServerName.Trim();
+ }
+ row.Map = summary.MapKind == RustToDust.Core.ArenaMapKind.Sion ? "SION" : "DESERT";
+ row.Humans = summary.Humans;
+ row.MaxHumans = summary.MaxHumans > 0 ? summary.MaxHumans : 12;
+ row.Phase = summary.Phase switch
+ {
+ RustToDust.Core.MatchPhase.Lobby => "LOBBY",
+ RustToDust.Core.MatchPhase.Completed => "COMPLETE",
+ _ => "IN-MATCH"
+ };
+ }
+ else
+ {
+ row.PingMs = null;
+ row.TimedOut = true;
+ if (row.IsLocalProbe)
+ {
+ row.Phase = "OFFLINE";
+ }
+ }
+ SyncRowVisual(row);
+ });
+ }
+ catch (OperationCanceledException)
+ {
+ }
+ catch
+ {
+ _mainThreadQueue.Enqueue(() =>
+ {
+ if (!IsInsideTree() || seq != _refreshSeq || row.Disposed || !_rows.Contains(row) || row.RowButton is null || !IsInstanceValid(row.RowButton)) return;
+ row.Probing = false;
+ row.PingMs = null;
+ row.TimedOut = true;
+ SyncRowVisual(row);
+ });
+ }
+ }
+
+ private void CancelPendingRefresh()
+ {
+ _refreshSeq++;
+ if (_refreshCts is not null)
+ {
+ try { _refreshCts.Cancel(); } catch { }
+ _refreshCts.Dispose();
+ _refreshCts = null;
+ }
+ while (_mainThreadQueue.TryDequeue(out _)) { }
+ }
+
+ private void BuildUi()
+ {
+ _root = new Control
+ {
+ Name = "ServerBrowserRoot",
+ MouseFilter = Control.MouseFilterEnum.Stop
+ };
+ _root.SetAnchorsPreset(Control.LayoutPreset.FullRect);
+ AddChild(_root);
+
+ var scrim = new ColorRect
+ {
+ Color = new Color(0.03f, 0.04f, 0.03f, 0.42f),
+ MouseFilter = Control.MouseFilterEnum.Stop
+ };
+ scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect);
+ _root.AddChild(scrim);
+
+ var panel = ImperialChrome.CreatePanel(ImperialChrome.CyanCol, cornerLen: 18f, borderPx: 2f, bgAlpha: 0.93f, padH: 18, padV: 16);
+ panel.Name = "ServerBrowserPanel";
+ panel.AnchorLeft = 0.5f;
+ panel.AnchorRight = 0.5f;
+ panel.AnchorTop = 0.5f;
+ panel.AnchorBottom = 0.5f;
+ panel.OffsetLeft = -530f;
+ panel.OffsetRight = 530f;
+ panel.OffsetTop = -290f;
+ panel.OffsetBottom = 290f;
+ _root.AddChild(panel);
+
+ var vbox = new VBoxContainer();
+ vbox.AddThemeConstantOverride("separation", 10);
+ panel.AddChild(vbox);
+
+ // Header bar
+ var headerRow = new HBoxContainer();
+ headerRow.AddThemeConstantOverride("separation", 10);
+ vbox.AddChild(headerRow);
+
+ var titleCol = new VBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
+ titleCol.AddThemeConstantOverride("separation", 2);
+ headerRow.AddChild(titleCol);
+ titleCol.AddChild(ImperialChrome.CreateLabel("PUBLIC YGGDRASIL SERVER BROWSER", 20, ImperialChrome.CyanCol));
+ _dirUrlLabel = ImperialChrome.CreateLabel($"DIRECTORY: {_directoryUrl}", 11, ImperialChrome.TextMuted);
+ titleCol.AddChild(_dirUrlLabel);
+
+ _refreshBtn = ImperialChrome.CreateButton("REFRESH", ImperialChrome.CyanCol, 13, 34f);
+ _refreshBtn.CustomMinimumSize = new Vector2(108f, 34f);
+ _refreshBtn.Pressed += Refresh;
+ headerRow.AddChild(_refreshBtn);
+
+ var hostBtn = ImperialChrome.CreateButton("HOST", ImperialChrome.GoldCol, 13, 34f);
+ hostBtn.CustomMinimumSize = new Vector2(92f, 34f);
+ hostBtn.Pressed += () => HostRequested?.Invoke();
+ headerRow.AddChild(hostBtn);
+
+ var backBtn = ImperialChrome.CreateButton("BACK", ImperialChrome.OrangeCol, 13, 34f);
+ backBtn.CustomMinimumSize = new Vector2(92f, 34f);
+ backBtn.Pressed += () => BackRequested?.Invoke();
+ headerRow.AddChild(backBtn);
+
+ // Status + Localhost toggle row
+ var subRow = new HBoxContainer();
+ subRow.AddThemeConstantOverride("separation", 12);
+ vbox.AddChild(subRow);
+
+ _dirStatusLabel = ImperialChrome.CreateLabel("Ready.", 12, ImperialChrome.TextMuted);
+ _dirStatusLabel.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
+ _dirStatusLabel.ClipText = true;
+ subRow.AddChild(_dirStatusLabel);
+
+ _probeLocalhostCheck = new CheckBox
+ {
+ Text = "Probe Localhost (127.0.0.1:3076)",
+ ButtonPressed = true
+ };
+ ImperialChrome.StyleCheckBox(_probeLocalhostCheck, ImperialChrome.OliveCol, 12);
+ _probeLocalhostCheck.Toggled += _ => Refresh();
+ subRow.AddChild(_probeLocalhostCheck);
+
+ vbox.AddChild(ImperialChrome.MakeRule());
+
+ // Column headers
+ var colHeader = new HBoxContainer();
+ colHeader.AddThemeConstantOverride("separation", 8);
+ vbox.AddChild(colHeader);
+ AddHeaderCell(colHeader, "SERVER NAME", expand: true, width: 0f);
+ AddHeaderCell(colHeader, "MAP", expand: false, width: 96f);
+ AddHeaderCell(colHeader, "PLAYERS", expand: false, width: 90f);
+ AddHeaderCell(colHeader, "PHASE", expand: false, width: 112f);
+ AddHeaderCell(colHeader, "PING", expand: false, width: 100f);
+ AddHeaderCell(colHeader, "ENDPOINT", expand: false, width: 175f);
+
+ // Scrollable rows
+ var listFrame = new PanelContainer
+ {
+ SizeFlagsVertical = Control.SizeFlags.ExpandFill
+ };
+ var frameStyle = new StyleBoxFlat
+ {
+ BgColor = new Color(ImperialChrome.BgDark.R, ImperialChrome.BgDark.G, ImperialChrome.BgDark.B, 0.72f),
+ BorderColor = ImperialChrome.BorderCol,
+ ContentMarginLeft = 6,
+ ContentMarginRight = 6,
+ ContentMarginTop = 6,
+ ContentMarginBottom = 6
+ };
+ frameStyle.SetBorderWidthAll(1);
+ listFrame.AddThemeStyleboxOverride("panel", frameStyle);
+ vbox.AddChild(listFrame);
+
+ var scroll = new ScrollContainer
+ {
+ SizeFlagsHorizontal = Control.SizeFlags.ExpandFill,
+ SizeFlagsVertical = Control.SizeFlags.ExpandFill,
+ HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled
+ };
+ listFrame.AddChild(scroll);
+
+ _rowsContainer = new VBoxContainer
+ {
+ SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
+ };
+ _rowsContainer.AddThemeConstantOverride("separation", 4);
+ scroll.AddChild(_rowsContainer);
+
+ vbox.AddChild(ImperialChrome.MakeRule());
+
+ // Footer: direct IP:Port + Join Selected
+ var footerRow = new HBoxContainer();
+ footerRow.AddThemeConstantOverride("separation", 10);
+ vbox.AddChild(footerRow);
+
+ footerRow.AddChild(ImperialChrome.CreateLabel("DIRECT IP:PORT", 12, ImperialChrome.TextMuted));
+
+ _directEndpointEdit = new LineEdit
+ {
+ Text = "127.0.0.1:3076",
+ PlaceholderText = "127.0.0.1:3076",
+ MaxLength = 96,
+ CustomMinimumSize = new Vector2(240f, 34f)
+ };
+ ImperialChrome.StyleLineEdit(_directEndpointEdit, ImperialChrome.CyanCol, 13);
+ _directEndpointEdit.TextSubmitted += _ => JoinDirect();
+ footerRow.AddChild(_directEndpointEdit);
+
+ var directBtn = ImperialChrome.CreateButton("DIRECT CONNECT", ImperialChrome.OrangeCol, 13, 34f);
+ directBtn.CustomMinimumSize = new Vector2(150f, 34f);
+ directBtn.Pressed += JoinDirect;
+ footerRow.AddChild(directBtn);
+
+ var spacer = new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
+ footerRow.AddChild(spacer);
+
+ _joinBtn = ImperialChrome.CreateButton("JOIN SELECTED", ImperialChrome.OliveCol, 14, 34f);
+ _joinBtn.CustomMinimumSize = new Vector2(170f, 34f);
+ _joinBtn.Disabled = true;
+ _joinBtn.Pressed += JoinSelected;
+ footerRow.AddChild(_joinBtn);
+
+ _footerErrorLabel = ImperialChrome.CreateLabel(string.Empty, 12, ImperialChrome.RedCol);
+ _footerErrorLabel.AutowrapMode = TextServer.AutowrapMode.Word;
+ _footerErrorLabel.Visible = false;
+ vbox.AddChild(_footerErrorLabel);
+ }
+
+ private static void AddHeaderCell(HBoxContainer parent, string text, bool expand, float width)
+ {
+ var lbl = ImperialChrome.CreateLabel(text, 11, ImperialChrome.TextMuted);
+ if (expand)
+ {
+ lbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
+ }
+ else
+ {
+ lbl.CustomMinimumSize = new Vector2(width, 0f);
+ }
+ parent.AddChild(lbl);
+ }
+
+ private void ClearRows()
+ {
+ for (int i = 0; i < _rows.Count; i++)
+ {
+ _rows[i].Disposed = true;
+ }
+ _rows.Clear();
+ if (_rowsContainer is null) return;
+ for (int i = _rowsContainer.GetChildCount() - 1; i >= 0; i--)
+ {
+ var c = _rowsContainer.GetChild(i);
+ _rowsContainer.RemoveChild(c);
+ c.QueueFree();
+ }
+ }
+
+ private void RemoveLocalProbeRowIfPresent()
+ {
+ for (int i = _rows.Count - 1; i >= 0; i--)
+ {
+ if (!_rows[i].IsLocalProbe) continue;
+ var row = _rows[i];
+ row.Disposed = true;
+ var btn = row.RowButton;
+ _rows.RemoveAt(i);
+ if (btn is not null && IsInstanceValid(btn))
+ {
+ _rowsContainer.RemoveChild(btn);
+ btn.QueueFree();
+ }
+ }
+ }
+
+ private void AddRowWidget(ServerRowModel row)
+ {
+ _rows.Add(row);
+
+ var btn = new Button
+ {
+ FocusMode = Control.FocusModeEnum.None,
+ CustomMinimumSize = new Vector2(0f, 34f),
+ SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
+ };
+ row.RowButton = btn;
+
+ var hbox = new HBoxContainer
+ {
+ MouseFilter = Control.MouseFilterEnum.Ignore
+ };
+ hbox.SetAnchorsPreset(Control.LayoutPreset.FullRect);
+ hbox.OffsetLeft = 10f;
+ hbox.OffsetRight = -10f;
+ hbox.AddThemeConstantOverride("separation", 8);
+ btn.AddChild(hbox);
+
+ row.NameLabel = MakeRowCell(row.Name, 13, ImperialChrome.TextLight, expand: true, width: 0f);
+ row.MapLabel = MakeRowCell(row.Map, 12, ImperialChrome.OliveCol, expand: false, width: 96f);
+ row.PlayersLabel = MakeRowCell($"{row.Humans}/{row.MaxHumans}", 12, ImperialChrome.TextLight, expand: false, width: 90f);
+ row.PhaseLabel = MakeRowCell(row.Phase, 12, ImperialChrome.CyanCol, expand: false, width: 112f);
+ row.PingLabel = MakeRowCell("...", 12, ImperialChrome.TextMuted, expand: false, width: 100f);
+ row.AddressLabel = MakeRowCell($"{row.Host}:{row.Port}", 11, ImperialChrome.TextMuted, expand: false, width: 175f);
+
+ hbox.AddChild(row.NameLabel);
+ hbox.AddChild(row.MapLabel);
+ hbox.AddChild(row.PlayersLabel);
+ hbox.AddChild(row.PhaseLabel);
+ hbox.AddChild(row.PingLabel);
+ hbox.AddChild(row.AddressLabel);
+
+ btn.Pressed += () => SelectRow(row);
+ btn.GuiInput += ev =>
+ {
+ if (ev is InputEventMouseButton mb && mb.Pressed && mb.DoubleClick && mb.ButtonIndex == MouseButton.Left)
+ {
+ SelectRow(row);
+ JoinSelected();
+ }
+ };
+
+ _rowsContainer.AddChild(btn);
+ SyncRowVisual(row);
+ }
+
+ private static Label MakeRowCell(string text, int fontSize, Color color, bool expand, float width)
+ {
+ var lbl = new Label
+ {
+ Text = text,
+ VerticalAlignment = VerticalAlignment.Center,
+ ClipText = true,
+ MouseFilter = Control.MouseFilterEnum.Ignore
+ };
+ lbl.AddThemeFontSizeOverride("font_size", fontSize);
+ lbl.AddThemeColorOverride("font_color", color);
+ if (expand)
+ {
+ lbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
+ }
+ else
+ {
+ lbl.CustomMinimumSize = new Vector2(width, 0f);
+ }
+ return lbl;
+ }
+
+ private void SelectRow(ServerRowModel row)
+ {
+ _selectedKey = row.Key;
+ if (_directEndpointEdit is not null && !_directEndpointEdit.HasFocus())
+ {
+ _directEndpointEdit.Text = $"{row.Host}:{row.Port}";
+ }
+ for (int i = 0; i < _rows.Count; i++)
+ {
+ SyncRowVisual(_rows[i]);
+ }
+ UpdateJoinButtonState();
+ }
+
+ private void SyncRowVisual(ServerRowModel row)
+ {
+ if (row.Disposed || !_rows.Contains(row) || row.RowButton is null || !IsInstanceValid(row.RowButton)) return;
+ bool selected = string.Equals(_selectedKey, row.Key, StringComparison.Ordinal);
+
+ Color accent = selected
+ ? ImperialChrome.OliveCol
+ : (row.TimedOut ? ImperialChrome.BorderCol : ImperialChrome.CyanCol);
+ var normal = new StyleBoxFlat
+ {
+ BgColor = selected ? ImperialChrome.BgPressed : ImperialChrome.BgInner,
+ BorderColor = selected ? ImperialChrome.OliveCol : new Color(ImperialChrome.BorderCol.R, ImperialChrome.BorderCol.G, ImperialChrome.BorderCol.B, 0.7f)
+ };
+ normal.SetBorderWidthAll(selected ? 2 : 1);
+ var hover = new StyleBoxFlat
+ {
+ BgColor = ImperialChrome.BgHover,
+ BorderColor = accent
+ };
+ hover.SetBorderWidthAll(1);
+
+ row.RowButton.AddThemeStyleboxOverride("normal", normal);
+ row.RowButton.AddThemeStyleboxOverride("hover", hover);
+ row.RowButton.AddThemeStyleboxOverride("pressed", hover);
+ row.RowButton.AddThemeStyleboxOverride("focus", hover);
+
+ row.NameLabel!.Text = row.Name;
+ row.NameLabel.AddThemeColorOverride("font_color", row.TimedOut && row.IsLocalProbe ? ImperialChrome.TextMuted : ImperialChrome.TextLight);
+ row.MapLabel!.Text = row.Map;
+ row.PlayersLabel!.Text = $"{row.Humans}/{row.MaxHumans}";
+ row.PhaseLabel!.Text = row.Phase;
+
+ Color phaseCol = row.Phase switch
+ {
+ "LOBBY" => ImperialChrome.OliveCol,
+ "IN-MATCH" => ImperialChrome.GoldCol,
+ "OFFLINE" => ImperialChrome.TextMuted,
+ _ => ImperialChrome.CyanCol
+ };
+ row.PhaseLabel.AddThemeColorOverride("font_color", phaseCol);
+
+ if (row.Probing)
+ {
+ row.PingLabel!.Text = "...";
+ row.PingLabel.AddThemeColorOverride("font_color", ImperialChrome.TextMuted);
+ }
+ else if (row.PingMs is int ms)
+ {
+ row.PingLabel!.Text = $"{ms} ms";
+ Color pingCol = ms < 70 ? ImperialChrome.OliveCol : (ms < 150 ? ImperialChrome.GoldCol : ImperialChrome.OrangeCol);
+ row.PingLabel.AddThemeColorOverride("font_color", pingCol);
+ }
+ else
+ {
+ row.PingLabel!.Text = "TIMEOUT";
+ row.PingLabel.AddThemeColorOverride("font_color", ImperialChrome.RedCol);
+ }
+
+ row.AddressLabel!.Text = $"{row.Host}:{row.Port}";
+ }
+
+ private void UpdateJoinButtonState()
+ {
+ if (_joinBtn is null) return;
+ _joinBtn.Disabled = string.IsNullOrEmpty(_selectedKey);
+ }
+
+ private void JoinSelected()
+ {
+ for (int i = 0; i < _rows.Count; i++)
+ {
+ if (string.Equals(_rows[i].Key, _selectedKey, StringComparison.Ordinal))
+ {
+ string ep = $"{_rows[i].Host}:{_rows[i].Port}";
+ JoinRequested?.Invoke(ep, _callsign);
+ return;
+ }
+ }
+ }
+
+ private void JoinDirect()
+ {
+ string ep = (_directEndpointEdit?.Text ?? string.Empty).Trim();
+ if (string.IsNullOrEmpty(ep))
+ {
+ SetError("Enter host:port to connect directly.");
+ return;
+ }
+ SetError(null);
+ JoinRequested?.Invoke(ep, _callsign);
+ }
+
+ private void SetDirectoryStatus(string message, bool isWarning)
+ {
+ if (_dirStatusLabel is null) return;
+ _dirStatusLabel.Text = message;
+ _dirStatusLabel.AddThemeColorOverride("font_color", isWarning ? ImperialChrome.OrangeCol : ImperialChrome.OliveCol);
+ }
+
+ private static string FormatMap(string? map) =>
+ string.Equals(map, "sion", StringComparison.OrdinalIgnoreCase) ? "SION" : "DESERT";
+
+ private static string FormatPhase(string? phase)
+ {
+ if (string.Equals(phase, "Lobby", StringComparison.OrdinalIgnoreCase)) return "LOBBY";
+ if (string.Equals(phase, "Completed", StringComparison.OrdinalIgnoreCase)) return "COMPLETE";
+ return "IN-MATCH";
+ }
+
+ private static string ShortError(string msg)
+ {
+ if (string.IsNullOrWhiteSpace(msg)) return "unreachable";
+ string oneLine = msg.Replace('\r', ' ').Replace('\n', ' ').Trim();
+ return oneLine.Length > 64 ? oneLine[..64] + "..." : oneLine;
+ }
+}
diff --git a/src/RustToDust.Core/IClientArenaSession.cs b/src/RustToDust.Core/IClientArenaSession.cs
index 0ad5b7e..95942dd 100644
--- a/src/RustToDust.Core/IClientArenaSession.cs
+++ b/src/RustToDust.Core/IClientArenaSession.cs
@@ -47,6 +47,7 @@ namespace RustToDust.Core
IReadOnlyList ActivePods { get; }
DropWaveState DropWaveState { get; }
IReadOnlyList PodEvents { get; }
+ LobbySnapshotDto? LobbyState => null;
bool IsContenderVisible(int contenderId);
bool IsSpectatorVisible(int spectatorId);
@@ -56,6 +57,9 @@ namespace RustToDust.Core
void DrainSimEvents(List dest);
bool RequestEquipCargo(int cargoIndex, string hardpointId);
void RequestNewMatch(int seed, ArenaMapKind mapKind);
+ bool SetLobbyReady(bool ready) => false;
+ bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => false;
+ bool RequestLobbyStart() => false;
(Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha);
(Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha);
diff --git a/src/RustToDust.Core/MatchState.cs b/src/RustToDust.Core/MatchState.cs
index 28bd77a..911e974 100644
--- a/src/RustToDust.Core/MatchState.cs
+++ b/src/RustToDust.Core/MatchState.cs
@@ -6,8 +6,47 @@ namespace RustToDust.Core
{
public enum MatchPhase
{
- Active,
- Completed
+ Active = 0,
+ Completed = 1,
+ Lobby = 2
+ }
+
+ public sealed class LobbySlotState
+ {
+ public int SlotId { get; init; }
+ public string Callsign { get; set; } = string.Empty;
+ public bool IsHuman { get; set; }
+ public bool IsReady { get; set; }
+ }
+
+ public sealed class LobbyState
+ {
+ public const float DefaultCountdownSeconds = 5.0f;
+
+ public LobbyState(int contenderCount, ArenaMapKind mapKind, int seed, int? hostSlotId = null, int minHumansToAutoStart = 1)
+ {
+ SelectedMap = mapKind;
+ SelectedSeed = seed;
+ HostSlotId = hostSlotId;
+ MinHumansToAutoStart = Math.Max(1, minHumansToAutoStart);
+ Slots = new LobbySlotState[contenderCount];
+ for (int i = 0; i < contenderCount; i++)
+ {
+ Slots[i] = new LobbySlotState
+ {
+ SlotId = i,
+ Callsign = $"Contender {i + 1:00}"
+ };
+ }
+ }
+
+ public int? HostSlotId { get; set; }
+ public int MinHumansToAutoStart { get; set; } = 1;
+ public float? CountdownSeconds { get; set; }
+ public bool ForceLaunched { get; set; }
+ public ArenaMapKind SelectedMap { get; set; }
+ public int SelectedSeed { get; set; }
+ public LobbySlotState[] Slots { get; }
}
public readonly record struct PlayerInput(
@@ -293,11 +332,15 @@ namespace RustToDust.Core
private int _nextDropId = 1;
private long _nextHitEventId = 1;
private int _nextTracerId = 1;
+ private readonly bool _pendingSkipInitialDrop;
+ private readonly List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> _pendingLootTargets;
+ private readonly List<(int ContenderId, float X, float Z, float Yaw)> _pendingContenderTargets;
- public MatchState(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool skipInitialDrop = false)
+ public MatchState(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool skipInitialDrop = false, bool startInLobby = false)
{
Seed = seed;
MapKind = mapKind;
+ _pendingSkipInitialDrop = skipInitialDrop;
Rng = new Random(seed);
Broadcast = new BroadcastFeed();
OrbitalDrop = new OrbitalDropSystem(this);
@@ -339,7 +382,24 @@ namespace RustToDust.Core
lootTargets = BuildInitialLootTargetsDesert();
}
- if (skipInitialDrop)
+ _pendingLootTargets = lootTargets;
+ _pendingContenderTargets = new List<(int ContenderId, float X, float Z, float Yaw)>(Contenders.Count);
+ for (int i = 0; i < Contenders.Count; i++)
+ {
+ var c = Contenders[i];
+ _pendingContenderTargets.Add((c.Id, c.X, c.Z, c.Yaw));
+ }
+
+ if (startInLobby)
+ {
+ Phase = MatchPhase.Lobby;
+ Lobby = new LobbyState(ContenderCount, mapKind, seed);
+ for (int i = 0; i < Contenders.Count; i++)
+ {
+ Contenders[i].Lifecycle = ContenderLifecycle.Deploying;
+ }
+ }
+ else if (skipInitialDrop)
{
for (int i = 0; i < Contenders.Count; i++)
{
@@ -351,19 +411,51 @@ namespace RustToDust.Core
if (t.Chassis is not null) SpawnChassisDrop(t.X, t.Z, t.Chassis);
else if (t.Module is not null) SpawnModuleDrop(t.X, t.Z, t.Module);
}
+ Broadcast.EmitMatchStart(0f, mapKind);
}
else
{
- var contenderTargets = new List<(int ContenderId, float X, float Z, float Yaw)>(Contenders.Count);
- for (int i = 0; i < Contenders.Count; i++)
- {
- var c = Contenders[i];
- contenderTargets.Add((c.Id, c.X, c.Z, c.Yaw));
- }
- OrbitalDrop.BeginWave0(contenderTargets, lootTargets, DefaultDropSurfaceQuery);
+ OrbitalDrop.BeginWave0(_pendingContenderTargets, _pendingLootTargets, DefaultDropSurfaceQuery);
+ Broadcast.EmitMatchStart(0f, mapKind);
+ }
+ }
+
+ public bool StartFromLobby(DropSurfaceQuery? surfaceQuery = null)
+ {
+ if (Phase != MatchPhase.Lobby)
+ {
+ return false;
}
- Broadcast.EmitMatchStart(0f, mapKind);
+ Phase = MatchPhase.Active;
+ Time = 0f;
+ WinnerContenderId = null;
+ if (Lobby is not null)
+ {
+ Lobby.CountdownSeconds = null;
+ Lobby.ForceLaunched = false;
+ }
+
+ if (_pendingSkipInitialDrop)
+ {
+ for (int i = 0; i < Contenders.Count; i++)
+ {
+ Contenders[i].Lifecycle = ContenderLifecycle.Active;
+ }
+ for (int i = 0; i < _pendingLootTargets.Count; i++)
+ {
+ var t = _pendingLootTargets[i];
+ if (t.Chassis is not null) SpawnChassisDrop(t.X, t.Z, t.Chassis);
+ else if (t.Module is not null) SpawnModuleDrop(t.X, t.Z, t.Module);
+ }
+ }
+ else
+ {
+ OrbitalDrop.BeginWave0(_pendingContenderTargets, _pendingLootTargets, surfaceQuery ?? DefaultDropSurfaceQuery);
+ }
+
+ Broadcast.EmitMatchStart(0f, MapKind);
+ return true;
}
public int Seed { get; }
@@ -372,6 +464,7 @@ namespace RustToDust.Core
public Random Rng { get; }
public float Time { get; set; }
public MatchPhase Phase { get; set; } = MatchPhase.Active;
+ public LobbyState? Lobby { get; set; }
public int? WinnerContenderId { get; set; }
public TerrainField Terrain { get; }
diff --git a/src/RustToDust.Core/SimEvents.cs b/src/RustToDust.Core/SimEvents.cs
index 9e70a6c..84211fb 100644
--- a/src/RustToDust.Core/SimEvents.cs
+++ b/src/RustToDust.Core/SimEvents.cs
@@ -33,6 +33,7 @@ namespace RustToDust.Core
[Union(11, typeof(MatchResetEvent))]
[Union(12, typeof(DropPodEvent))]
[Union(13, typeof(OrdnanceNodeEvent))]
+ [Union(14, typeof(MatchStartedEvent))]
public interface ISimEvent
{
}
@@ -318,6 +319,36 @@ namespace RustToDust.Core
[Key(12)] public int CurrentWaveIndex { get; set; }
[Key(13)] public bool RespawnCutoffReached { get; set; }
[Key(14)] public List ActivePods { get; set; } = new();
+ [Key(15)] public LobbySnapshotDto? Lobby { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class LobbySlotDto
+ {
+ [Key(0)] public int SlotId { get; set; }
+ [Key(1)] public string Callsign { get; set; } = string.Empty;
+ [Key(2)] public bool IsHuman { get; set; }
+ [Key(3)] public bool IsReady { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class LobbySnapshotDto
+ {
+ [Key(0)] public int? HostSlotId { get; set; }
+ [Key(1)] public int MinHumansToAutoStart { get; set; } = 1;
+ [Key(2)] public float? CountdownSeconds { get; set; }
+ [Key(3)] public bool ForceLaunched { get; set; }
+ [Key(4)] public byte SelectedMap { get; set; }
+ [Key(5)] public int SelectedSeed { get; set; }
+ [Key(6)] public List Slots { get; set; } = new();
+ }
+
+ [MessagePackObject]
+ public sealed class MatchStartedEvent : ISimEvent
+ {
+ [Key(0)] public uint MatchGeneration { get; set; }
+ [Key(1)] public byte MapKind { get; set; }
+ [Key(2)] public int Seed { get; set; }
}
[MessagePackObject]
@@ -339,6 +370,11 @@ namespace RustToDust.Core
[Union(6, typeof(SimEventBatchMsg))]
[Union(7, typeof(EntitySyncSnapshotMsg))]
[Union(8, typeof(InteractCmdMsg))]
+ [Union(9, typeof(LobbyReadyCmdMsg))]
+ [Union(10, typeof(LobbyConfigCmdMsg))]
+ [Union(11, typeof(LobbyStartCmdMsg))]
+ [Union(12, typeof(LobbySnapshotMsg))]
+ [Union(13, typeof(ClientKeepaliveMsg))]
public interface ISchemaWireMessage
{
}
@@ -420,4 +456,38 @@ namespace RustToDust.Core
[Key(9)] public byte[] ArmorBytes { get; set; } = Array.Empty();
[Key(10)] public ContenderLoadoutEvent? ContenderLoadout { get; set; }
}
+
+ [MessagePackObject]
+ public sealed class LobbyReadyCmdMsg : ISchemaWireMessage
+ {
+ [Key(0)] public uint ReqSeq { get; set; }
+ [Key(1)] public bool IsReady { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class LobbyConfigCmdMsg : ISchemaWireMessage
+ {
+ [Key(0)] public uint ReqSeq { get; set; }
+ [Key(1)] public int Seed { get; set; }
+ [Key(2)] public byte MapKind { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class LobbyStartCmdMsg : ISchemaWireMessage
+ {
+ [Key(0)] public uint ReqSeq { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class LobbySnapshotMsg : ISchemaWireMessage
+ {
+ [Key(0)] public uint MatchGeneration { get; set; }
+ [Key(1)] public LobbySnapshotDto Snapshot { get; set; } = new();
+ }
+
+ [MessagePackObject]
+ public sealed class ClientKeepaliveMsg : ISchemaWireMessage
+ {
+ [Key(0)] public uint ClientSendMs { get; set; }
+ }
}
diff --git a/src/RustToDust.Directory/DirectoryDtos.cs b/src/RustToDust.Directory/DirectoryDtos.cs
new file mode 100644
index 0000000..1b7268c
--- /dev/null
+++ b/src/RustToDust.Directory/DirectoryDtos.cs
@@ -0,0 +1,45 @@
+using System;
+
+namespace RustToDust.DirectoryService
+{
+ public sealed class DirectoryHeartbeatRequest
+ {
+ public Guid? ServerId { get; set; }
+ public string? LeaseToken { get; set; }
+ public string Name { get; set; } = "Rust to Dust";
+ public string? PublicHost { get; set; }
+ public int UdpPort { get; set; }
+ public string Map { get; set; } = "desert";
+ public int Seed { get; set; } = 42;
+ public int Humans { get; set; }
+ public int MaxHumans { get; set; } = 12;
+ public string Phase { get; set; } = "Active";
+ public int Wave { get; set; }
+ public int ProtocolVersion { get; set; } = 1;
+ public bool HasPassword { get; set; }
+ }
+
+ public sealed class DirectoryHeartbeatResponse
+ {
+ public Guid ServerId { get; set; }
+ public string LeaseToken { get; set; } = string.Empty;
+ public int TtlSeconds { get; set; }
+ }
+
+ public sealed class DirectoryServerView
+ {
+ public Guid ServerId { get; set; }
+ public string Name { get; set; } = string.Empty;
+ public string PublicHost { get; set; } = string.Empty;
+ public int UdpPort { get; set; }
+ public string Map { get; set; } = string.Empty;
+ public int Seed { get; set; }
+ public int Humans { get; set; }
+ public int MaxHumans { get; set; }
+ public string Phase { get; set; } = string.Empty;
+ public int Wave { get; set; }
+ public int ProtocolVersion { get; set; }
+ public bool HasPassword { get; set; }
+ public DateTimeOffset ExpiresAtUtc { get; set; }
+ }
+}
diff --git a/src/RustToDust.Directory/DirectoryRegistry.cs b/src/RustToDust.Directory/DirectoryRegistry.cs
new file mode 100644
index 0000000..cfa1198
--- /dev/null
+++ b/src/RustToDust.Directory/DirectoryRegistry.cs
@@ -0,0 +1,421 @@
+using System;
+using System.Collections.Generic;
+using System.Net;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace RustToDust.DirectoryService
+{
+ public sealed class DirectoryRegistryOptions
+ {
+ public TimeSpan EntryTtl { get; set; } = TimeSpan.FromSeconds(25);
+ public TimeSpan ReaperInterval { get; set; } = TimeSpan.FromSeconds(5);
+ public int MaxEntries { get; set; } = 256;
+ public int MaxEntriesPerIp { get; set; } = 8;
+ public int HeartbeatLimitPerMinute { get; set; } = 120;
+ public int ListLimitPerMinute { get; set; } = 60;
+ public Func UtcNow { get; set; } = () => DateTimeOffset.UtcNow;
+ }
+
+ public enum DirectoryOpStatus
+ {
+ Ok = 200,
+ NoContent = 204,
+ BadRequest = 400,
+ Forbidden = 403,
+ NotFound = 404,
+ Conflict = 409,
+ TooManyRequests = 429,
+ ServiceUnavailable = 503
+ }
+
+ public readonly record struct DirectoryOpResult(DirectoryOpStatus Status, T? Value, string? Error = null);
+
+ public sealed class DirectoryRegistry
+ {
+ private sealed class RegistryEntry
+ {
+ public Guid ServerId;
+ public string LeaseToken = string.Empty;
+ public byte[] LeaseTokenBytes = Array.Empty();
+ public string OwnerIp = string.Empty;
+ public string Name = string.Empty;
+ public string PublicHost = string.Empty;
+ public int UdpPort;
+ public string Map = string.Empty;
+ public int Seed;
+ public int Humans;
+ public int MaxHumans;
+ public string Phase = string.Empty;
+ public int Wave;
+ public int ProtocolVersion;
+ public bool HasPassword;
+ public DateTimeOffset ExpiresAtUtc;
+ }
+
+ private sealed class RateWindow
+ {
+ public long MinuteBucket;
+ public int Count;
+ }
+
+ private readonly object _gate = new();
+ private readonly Dictionary _entries = new();
+ private readonly Dictionary _heartbeatRates = new(StringComparer.Ordinal);
+ private readonly Dictionary _listRates = new(StringComparer.Ordinal);
+ private readonly DirectoryRegistryOptions _options;
+
+ public DirectoryRegistry(DirectoryRegistryOptions? options = null)
+ {
+ _options = options ?? new DirectoryRegistryOptions();
+ }
+
+ public int Count
+ {
+ get
+ {
+ lock (_gate)
+ {
+ PurgeExpiredLocked(_options.UtcNow());
+ return _entries.Count;
+ }
+ }
+ }
+
+ public DirectoryOpResult UpsertHeartbeat(DirectoryHeartbeatRequest req, IPAddress callerIp)
+ {
+ if (req is null)
+ {
+ return new(DirectoryOpStatus.BadRequest, null, "Request body required.");
+ }
+
+ IPAddress normalizedCaller = NormalizeIp(callerIp);
+ string callerKey = normalizedCaller.ToString();
+ DateTimeOffset now = _options.UtcNow();
+
+ lock (_gate)
+ {
+ PurgeExpiredLocked(now);
+
+ if (!AllowRateLocked(_heartbeatRates, callerKey, now, _options.HeartbeatLimitPerMinute))
+ {
+ return new(DirectoryOpStatus.TooManyRequests, null, "Heartbeat rate limit exceeded.");
+ }
+
+ if (req.UdpPort < 1 || req.UdpPort > 65535)
+ {
+ return new(DirectoryOpStatus.BadRequest, null, "udpPort must be in 1..65535.");
+ }
+
+ string resolvedHost;
+ if (string.IsNullOrWhiteSpace(req.PublicHost) ||
+ string.Equals(req.PublicHost.Trim(), "auto", StringComparison.OrdinalIgnoreCase))
+ {
+ resolvedHost = callerKey;
+ }
+ else
+ {
+ resolvedHost = req.PublicHost.Trim();
+ if (resolvedHost.Length > 253 || ContainsWhitespaceOrControl(resolvedHost))
+ {
+ return new(DirectoryOpStatus.BadRequest, null, "Invalid publicHost.");
+ }
+
+ if (!IPAddress.IsLoopback(normalizedCaller) && IsLoopbackOrWildcardHost(resolvedHost))
+ {
+ return new(DirectoryOpStatus.BadRequest, null, "Non-loopback callers cannot advertise a loopback or wildcard publicHost.");
+ }
+ }
+
+ string cleanName = SanitizeLabel(req.Name, "Rust to Dust", 48);
+ string cleanMap = SanitizeLabel(req.Map, "desert", 24).ToLowerInvariant();
+ string cleanPhase = SanitizeLabel(req.Phase, "Active", 16);
+ int maxHumans = Math.Clamp(req.MaxHumans, 1, 12);
+ int humans = Math.Clamp(req.Humans, 0, maxHumans);
+ int wave = Math.Max(0, req.Wave);
+ int protocolVersion = Math.Max(1, req.ProtocolVersion);
+
+ if (req.ServerId is { } serverId && serverId != Guid.Empty)
+ {
+ if (!_entries.TryGetValue(serverId, out var existing))
+ {
+ return new(DirectoryOpStatus.Conflict, null, "Unknown or expired serverId.");
+ }
+
+ if (!VerifyLeaseToken(existing, req.LeaseToken))
+ {
+ return new(DirectoryOpStatus.Forbidden, null, "Invalid leaseToken.");
+ }
+
+ existing.Name = cleanName;
+ existing.PublicHost = resolvedHost;
+ existing.UdpPort = req.UdpPort;
+ existing.Map = cleanMap;
+ existing.Seed = req.Seed;
+ existing.Humans = humans;
+ existing.MaxHumans = maxHumans;
+ existing.Phase = cleanPhase;
+ existing.Wave = wave;
+ existing.ProtocolVersion = protocolVersion;
+ existing.HasPassword = req.HasPassword;
+ existing.ExpiresAtUtc = now + _options.EntryTtl;
+
+ return new(DirectoryOpStatus.Ok, new DirectoryHeartbeatResponse
+ {
+ ServerId = existing.ServerId,
+ LeaseToken = existing.LeaseToken,
+ TtlSeconds = Math.Max(1, (int)Math.Ceiling(_options.EntryTtl.TotalSeconds))
+ });
+ }
+
+ if (_entries.Count >= _options.MaxEntries)
+ {
+ return new(DirectoryOpStatus.ServiceUnavailable, null, "Directory capacity reached.");
+ }
+
+ int ipCount = 0;
+ foreach (var entry in _entries.Values)
+ {
+ if (string.Equals(entry.OwnerIp, callerKey, StringComparison.Ordinal))
+ {
+ ipCount++;
+ }
+ }
+ if (ipCount >= _options.MaxEntriesPerIp)
+ {
+ return new(DirectoryOpStatus.TooManyRequests, null, "Per-IP server registration limit reached.");
+ }
+
+ Guid newId = Guid.NewGuid();
+ string token = Convert.ToHexString(RandomNumberGenerator.GetBytes(24)).ToLowerInvariant();
+ var created = new RegistryEntry
+ {
+ ServerId = newId,
+ LeaseToken = token,
+ LeaseTokenBytes = Encoding.UTF8.GetBytes(token),
+ OwnerIp = callerKey,
+ Name = cleanName,
+ PublicHost = resolvedHost,
+ UdpPort = req.UdpPort,
+ Map = cleanMap,
+ Seed = req.Seed,
+ Humans = humans,
+ MaxHumans = maxHumans,
+ Phase = cleanPhase,
+ Wave = wave,
+ ProtocolVersion = protocolVersion,
+ HasPassword = req.HasPassword,
+ ExpiresAtUtc = now + _options.EntryTtl
+ };
+ _entries[newId] = created;
+
+ return new(DirectoryOpStatus.Ok, new DirectoryHeartbeatResponse
+ {
+ ServerId = created.ServerId,
+ LeaseToken = created.LeaseToken,
+ TtlSeconds = Math.Max(1, (int)Math.Ceiling(_options.EntryTtl.TotalSeconds))
+ });
+ }
+ }
+
+ public DirectoryOpResult