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/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 3551af1..63473c3 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(
@@ -289,11 +328,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);
@@ -335,7 +378,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++)
{
@@ -347,19 +407,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; }
@@ -368,6 +460,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 7d2b9f2..5b7e75c 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))]
// Reserved [Union(13)] OrdnanceNodeEvent (Cut 7)
+ [Union(14, typeof(MatchStartedEvent))]
public interface ISimEvent
{
}
@@ -295,6 +296,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]
@@ -316,6 +347,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
{
}
@@ -397,4 +433,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