diff --git a/Game/GameContracts.cs b/Game/GameContracts.cs
new file mode 100644
index 0000000..054357e
--- /dev/null
+++ b/Game/GameContracts.cs
@@ -0,0 +1,233 @@
+using System.Text.Json.Serialization;
+
+namespace VoidScavengers.Networking.Messages;
+
+// ===== Lobby Contracts =====
+public sealed record LobbyJoinRequest(string PlayerName);
+public sealed record LobbyJoinResult(bool Ok, string? Error, string? LobbyId, int PlayerCount);
+public sealed record LobbyState(string LobbyId, LobbyPlayer[] Players, int CountdownSeconds);
+public sealed record LobbyPlayer(ulong PlayerId, string Name, bool Ready);
+public sealed record LobbyReadyRequest(bool Ready);
+public sealed record LobbyCountdown(int SecondsRemaining);
+
+// ===== Game Start =====
+public sealed record GameStartInfo(
+ string MatchId,
+ int MapSeed,
+ float MapWidth,
+ float MapHeight,
+ PlayerSpawnInfo Self,
+ PlayerSpawnInfo[] OtherPlayers,
+ AsteroidInfo[] Asteroids,
+ ResourceNodeInfo[] Resources,
+ ExtractionZoneInfo[] ExtractionZones
+);
+
+public sealed record PlayerSpawnInfo(
+ ulong PlayerId,
+ string Name,
+ float X,
+ float Y,
+ float Rotation,
+ int Health,
+ int MaxHealth
+);
+
+public sealed record AsteroidInfo(
+ int Id,
+ float X,
+ float Y,
+ float Radius,
+ int AsteroidType // 0=small, 1=medium, 2=large
+);
+
+public sealed record ResourceNodeInfo(
+ int Id,
+ float X,
+ float Y,
+ int ResourceType, // 0=scrap, 1=energy, 2=rare
+ int Amount
+);
+
+public sealed record ExtractionZoneInfo(
+ int Id,
+ float X,
+ float Y,
+ float Radius,
+ bool Active,
+ int ActivatesAtTick
+);
+
+// ===== Game State Snapshots =====
+public sealed record GameStateSnapshot(
+ long Tick,
+ float TimeRemaining,
+ int PlayersAlive,
+ EntityState[] Entities,
+ ProjectileState[] Projectiles,
+ ResourceState[] Resources
+);
+
+public sealed record EntityState(
+ ulong Id,
+ int Type, // 0=player, 1=dropped_item
+ float X,
+ float Y,
+ float Rotation,
+ float VelX,
+ float VelY,
+ int Health,
+ int? ItemId // For dropped items
+);
+
+public sealed record ProjectileState(
+ int Id,
+ float X,
+ float Y,
+ float VelX,
+ float VelY,
+ ulong OwnerId,
+ int ProjectileType
+);
+
+public sealed record ResourceState(
+ int Id,
+ int Amount
+);
+
+// ===== Player Input =====
+public sealed record MoveInput(
+ float Dx, // -1 to 1 normalized
+ float Dy, // -1 to 1 normalized
+ float AimAngle, // Radians, where player is aiming
+ uint Seq // Client sequence number for reconciliation
+);
+
+public sealed record ActionInput(
+ int ActionType, // 0=interact, 1=pickup, 2=use_ability
+ int? TargetId
+);
+
+public sealed record ShootInput(
+ float AimAngle,
+ uint Seq
+);
+
+public sealed record DropInput(
+ int InventorySlot
+);
+
+public sealed record CraftRequest(
+ int RecipeId
+);
+
+// ===== Events =====
+public sealed record SpawnEvent(
+ ulong EntityId,
+ int EntityType,
+ float X,
+ float Y,
+ object? Data // Type-specific spawn data
+);
+
+public sealed record DespawnEvent(ulong EntityId);
+
+public sealed record DamageEvent(
+ ulong TargetId,
+ ulong? SourceId,
+ int Amount,
+ int NewHealth,
+ int DamageType // 0=projectile, 1=collision, 2=zone
+);
+
+public sealed record DeathEvent(
+ ulong PlayerId,
+ ulong? KillerId,
+ string PlayerName,
+ string? KillerName,
+ DroppedItemInfo[] DroppedItems
+);
+
+public sealed record DroppedItemInfo(
+ int DropId,
+ float X,
+ float Y,
+ int ItemId,
+ int Quantity
+);
+
+public sealed record PickupEvent(
+ ulong PlayerId,
+ int DropId,
+ int ItemId,
+ int Quantity
+);
+
+public sealed record ProjectileEvent(
+ int ProjectileId,
+ ulong OwnerId,
+ float X,
+ float Y,
+ float VelX,
+ float VelY,
+ int ProjectileType
+);
+
+public sealed record ExplosionEvent(
+ float X,
+ float Y,
+ float Radius,
+ int ExplosionType
+);
+
+public sealed record CraftCompleteEvent(
+ ulong PlayerId,
+ int RecipeId,
+ int ResultItemId,
+ int Quantity
+);
+
+public sealed record ExtractEvent(
+ ulong PlayerId,
+ string PlayerName,
+ int TotalLootValue
+);
+
+// ===== Game End =====
+public sealed record GameEndInfo(
+ string MatchId,
+ string Reason, // "last_standing", "time_expired", "all_extracted"
+ ulong? WinnerId,
+ string? WinnerName,
+ PlayerStatsInfo[] PlayerStats
+);
+
+public sealed record PlayerStatsInfo(
+ ulong PlayerId,
+ string Name,
+ int Kills,
+ int Deaths,
+ int DamageDealt,
+ int ResourcesCollected,
+ int ItemsCrafted,
+ bool Extracted,
+ int FinalPlacement
+);
+
+// ===== Inventory State (sent periodically or on change) =====
+public sealed record InventoryUpdate(
+ InventorySlot[] Slots,
+ int ScrapCount,
+ int EnergyCount,
+ int RareCount
+);
+
+public sealed record InventorySlot(
+ int SlotIndex,
+ int? ItemId,
+ int Quantity
+);
+
+// ===== Chat =====
+public sealed record ChatMessage(string Text);
+public sealed record ChatReceived(ulong SenderId, string SenderName, string Text, long Timestamp);
diff --git a/Game/GameHandler.cs b/Game/GameHandler.cs
new file mode 100644
index 0000000..f4d8788
--- /dev/null
+++ b/Game/GameHandler.cs
@@ -0,0 +1,806 @@
+using System.Collections.Concurrent;
+using System.Numerics;
+using System.Text.Json;
+using Microsoft.Extensions.Logging;
+using Server.Networking;
+using Server.Networking.Handling;
+using Server.Networking.Messages;
+using Server.Services.Auth;
+
+namespace VoidScavengers.Game;
+
+///
+/// Handles all game-related messages and manages match instances.
+/// Integrates with the existing SystemRevival server architecture.
+///
+public sealed class GameHandler : IClientMessageHandler
+{
+ private readonly ILogger _log;
+ private readonly ISessionRegistry _sessions;
+ private readonly IMessageSerializer _ser;
+ private readonly MatchManager _matchManager;
+
+ public GameHandler(
+ ILogger log,
+ ISessionRegistry sessions,
+ IMessageSerializer ser,
+ MatchManager matchManager)
+ {
+ _log = log;
+ _sessions = sessions;
+ _ser = ser;
+ _matchManager = matchManager;
+ }
+
+ public IReadOnlyCollection SupportedOpCodes => new[]
+ {
+ // Lobby
+ GameOpCodes.LOBBY_JOIN,
+ GameOpCodes.LOBBY_READY,
+ GameOpCodes.LOBBY_LEAVE,
+
+ // Game Input
+ GameOpCodes.INPUT_MOVE,
+ GameOpCodes.INPUT_ACTION,
+ GameOpCodes.INPUT_SHOOT,
+ GameOpCodes.INPUT_DROP,
+ GameOpCodes.INPUT_CRAFT,
+
+ // Chat
+ GameOpCodes.CHAT_SEND
+ };
+
+ public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ // All game operations require authentication
+ if (!_sessions.TryGet(connection.Id, out var accountId, out _))
+ {
+ await SendErrorAsync(connection, "auth_required", ct);
+ return;
+ }
+
+ try
+ {
+ switch (opCode)
+ {
+ case GameOpCodes.LOBBY_JOIN:
+ await HandleLobbyJoinAsync(connection, accountId, payload, ct);
+ break;
+
+ case GameOpCodes.LOBBY_READY:
+ await HandleLobbyReadyAsync(connection, accountId, payload, ct);
+ break;
+
+ case GameOpCodes.LOBBY_LEAVE:
+ await HandleLobbyLeaveAsync(connection, accountId, ct);
+ break;
+
+ case GameOpCodes.INPUT_MOVE:
+ await HandleMoveInputAsync(connection, accountId, payload, ct);
+ break;
+
+ case GameOpCodes.INPUT_SHOOT:
+ await HandleShootInputAsync(connection, accountId, payload, ct);
+ break;
+
+ case GameOpCodes.INPUT_ACTION:
+ await HandleActionInputAsync(connection, accountId, payload, ct);
+ break;
+
+ case GameOpCodes.INPUT_CRAFT:
+ await HandleCraftInputAsync(connection, accountId, payload, ct);
+ break;
+
+ case GameOpCodes.INPUT_DROP:
+ await HandleDropInputAsync(connection, accountId, payload, ct);
+ break;
+
+ case GameOpCodes.CHAT_SEND:
+ await HandleChatAsync(connection, accountId, payload, ct);
+ break;
+ }
+ }
+ catch (Exception ex)
+ {
+ _log.LogError(ex, "Error handling opcode {OpCode} from account {AccountId}", opCode, accountId);
+ await SendErrorAsync(connection, "internal_error", ct);
+ }
+ }
+
+ private async Task HandleLobbyJoinAsync(IConnection conn, ulong accountId, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ var request = _ser.Deserialize(payload);
+
+ // Get or create player name (in production, fetch from database)
+ string playerName = request?.PlayerName ?? $"Player{accountId % 10000}";
+
+ var (ok, lobbyId, error) = await _matchManager.JoinLobbyAsync(accountId, conn, playerName);
+
+ var result = new LobbyJoinResult(ok, error, lobbyId, ok ? _matchManager.GetLobbyPlayerCount(lobbyId!) : 0);
+ await SendAsync(conn, GameOpCodes.LOBBY_JOIN_RESULT, result, ct);
+ }
+
+ private async Task HandleLobbyReadyAsync(IConnection conn, ulong accountId, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ var request = _ser.Deserialize(payload);
+ await _matchManager.SetPlayerReadyAsync(accountId, request?.Ready ?? true);
+ }
+
+ private async Task HandleLobbyLeaveAsync(IConnection conn, ulong accountId, CancellationToken ct)
+ {
+ await _matchManager.LeaveLobbyAsync(accountId);
+ }
+
+ private Task HandleMoveInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ var input = _ser.Deserialize(payload);
+ if (input == null) return Task.CompletedTask;
+
+ _matchManager.EnqueueInput(accountId, new PlayerInput
+ {
+ PlayerId = accountId,
+ Type = InputType.Move,
+ Dx = input.Dx,
+ Dy = input.Dy,
+ AimAngle = input.AimAngle,
+ Seq = input.Seq
+ });
+
+ return Task.CompletedTask;
+ }
+
+ private Task HandleShootInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ var input = _ser.Deserialize(payload);
+ if (input == null) return Task.CompletedTask;
+
+ _matchManager.EnqueueInput(accountId, new PlayerInput
+ {
+ PlayerId = accountId,
+ Type = InputType.Shoot,
+ AimAngle = input.AimAngle,
+ Seq = input.Seq
+ });
+
+ return Task.CompletedTask;
+ }
+
+ private Task HandleActionInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ var input = _ser.Deserialize(payload);
+
+ _matchManager.EnqueueInput(accountId, new PlayerInput
+ {
+ PlayerId = accountId,
+ Type = InputType.Action,
+ TargetId = input?.TargetId
+ });
+
+ return Task.CompletedTask;
+ }
+
+ private Task HandleCraftInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ var input = _ser.Deserialize(payload);
+ if (input == null) return Task.CompletedTask;
+
+ _matchManager.EnqueueInput(accountId, new PlayerInput
+ {
+ PlayerId = accountId,
+ Type = InputType.Craft,
+ TargetId = input.RecipeId
+ });
+
+ return Task.CompletedTask;
+ }
+
+ private Task HandleDropInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ var input = _ser.Deserialize(payload);
+ if (input == null) return Task.CompletedTask;
+
+ _matchManager.EnqueueInput(accountId, new PlayerInput
+ {
+ PlayerId = accountId,
+ Type = InputType.Drop,
+ TargetId = input.SlotIndex
+ });
+
+ return Task.CompletedTask;
+ }
+
+ private async Task HandleChatAsync(IConnection conn, ulong accountId, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ var msg = _ser.Deserialize(payload);
+ if (string.IsNullOrWhiteSpace(msg?.Text)) return;
+
+ // Sanitize and limit message
+ string text = msg.Text.Trim();
+ if (text.Length > 200) text = text[..200];
+
+ await _matchManager.BroadcastChatAsync(accountId, text);
+ }
+
+ private async Task SendAsync(IConnection conn, int opCode, T data, CancellationToken ct)
+ {
+ var payload = _ser.Serialize(data);
+ var wire = _ser.Serialize(new ServerMessage(opCode, payload));
+ await conn.SendAsync(wire, ct);
+ }
+
+ private async Task SendErrorAsync(IConnection conn, string error, CancellationToken ct)
+ {
+ await SendAsync(conn, OpCodes.ERROR, new { error }, ct);
+ }
+}
+
+// ===== Input message types for deserialization =====
+public sealed record LobbyJoinRequest(string? PlayerName);
+public sealed record LobbyReadyRequest(bool Ready);
+public sealed record LobbyJoinResult(bool Ok, string? Error, string? LobbyId, int PlayerCount);
+public sealed record MoveInputMsg(float Dx, float Dy, float AimAngle, uint Seq);
+public sealed record ShootInputMsg(float AimAngle, uint Seq);
+public sealed record ActionInputMsg(int? TargetId);
+public sealed record CraftInputMsg(int RecipeId);
+public sealed record DropInputMsg(int SlotIndex);
+public sealed record ChatMsg(string Text);
+
+///
+/// Static OpCodes class for game-specific operations
+///
+public static class GameOpCodes
+{
+ // Lobby
+ public const int LOBBY_JOIN = 400;
+ public const int LOBBY_JOIN_RESULT = 401;
+ public const int LOBBY_STATE = 402;
+ public const int LOBBY_READY = 403;
+ public const int LOBBY_COUNTDOWN = 404;
+ public const int LOBBY_LEAVE = 405;
+
+ // Game State
+ public const int GAME_START = 420;
+ public const int GAME_STATE = 421;
+ public const int GAME_TICK = 422;
+ public const int GAME_END = 423;
+
+ // Input
+ public const int INPUT_MOVE = 450;
+ public const int INPUT_ACTION = 451;
+ public const int INPUT_SHOOT = 452;
+ public const int INPUT_DROP = 453;
+ public const int INPUT_CRAFT = 454;
+
+ // Events
+ public const int EVENT_SPAWN = 470;
+ public const int EVENT_DESPAWN = 471;
+ public const int EVENT_DAMAGE = 472;
+ public const int EVENT_DEATH = 473;
+ public const int EVENT_PICKUP = 474;
+ public const int EVENT_PROJECTILE = 475;
+ public const int EVENT_EXPLOSION = 476;
+
+ // Chat
+ public const int CHAT_SEND = 500;
+ public const int CHAT_RECEIVE = 501;
+}
+
+///
+/// Manages lobbies, matchmaking, and active game instances
+///
+public sealed class MatchManager : IDisposable
+{
+ private readonly ILogger _log;
+ private readonly IMessageSerializer _ser;
+
+ private readonly ConcurrentDictionary _lobbies = new();
+ private readonly ConcurrentDictionary _matches = new();
+ private readonly ConcurrentDictionary _playerToLobby = new();
+ private readonly ConcurrentDictionary _playerToMatch = new();
+ private readonly ConcurrentDictionary _playerConnections = new();
+
+ private readonly Timer _tickTimer;
+ private readonly Timer _lobbyTimer;
+
+ private const int MinPlayersToStart = 2;
+ private const int MaxPlayersPerLobby = 8;
+ private const int LobbyCountdownSeconds = 10;
+
+ public MatchManager(ILogger log, IMessageSerializer ser)
+ {
+ _log = log;
+ _ser = ser;
+
+ // Game tick timer (20 Hz)
+ _tickTimer = new Timer(OnGameTick, null, 50, 50);
+
+ // Lobby update timer (1 Hz)
+ _lobbyTimer = new Timer(OnLobbyTick, null, 1000, 1000);
+ }
+
+ public async Task<(bool ok, string? lobbyId, string? error)> JoinLobbyAsync(ulong accountId, IConnection conn, string playerName)
+ {
+ // Remove from any existing lobby
+ await LeaveLobbyAsync(accountId);
+
+ // Find or create lobby
+ Lobby? lobby = null;
+ foreach (var l in _lobbies.Values)
+ {
+ if (l.Phase == LobbyPhase.Waiting && l.Players.Count < MaxPlayersPerLobby)
+ {
+ lobby = l;
+ break;
+ }
+ }
+
+ if (lobby == null)
+ {
+ lobby = new Lobby
+ {
+ Id = Guid.NewGuid().ToString("N")[..8],
+ CreatedAt = DateTime.UtcNow
+ };
+ _lobbies[lobby.Id] = lobby;
+ _log.LogInformation("Created new lobby {LobbyId}", lobby.Id);
+ }
+
+ var player = new LobbyPlayer
+ {
+ AccountId = accountId,
+ Name = playerName,
+ Ready = false,
+ Connection = conn
+ };
+
+ lobby.Players[accountId] = player;
+ _playerToLobby[accountId] = lobby.Id;
+ _playerConnections[accountId] = conn;
+
+ _log.LogInformation("Player {AccountId} ({Name}) joined lobby {LobbyId}", accountId, playerName, lobby.Id);
+
+ // Broadcast updated lobby state
+ await BroadcastLobbyStateAsync(lobby);
+
+ return (true, lobby.Id, null);
+ }
+
+ public async Task LeaveLobbyAsync(ulong accountId)
+ {
+ if (_playerToLobby.TryRemove(accountId, out var lobbyId))
+ {
+ if (_lobbies.TryGetValue(lobbyId, out var lobby))
+ {
+ lobby.Players.Remove(accountId);
+
+ // Clean up empty lobbies
+ if (lobby.Players.Count == 0)
+ {
+ _lobbies.TryRemove(lobbyId, out _);
+ _log.LogInformation("Removed empty lobby {LobbyId}", lobbyId);
+ }
+ else
+ {
+ // Reset countdown if in progress
+ if (lobby.Phase == LobbyPhase.Countdown)
+ {
+ lobby.Phase = LobbyPhase.Waiting;
+ lobby.CountdownSeconds = 0;
+ }
+ await BroadcastLobbyStateAsync(lobby);
+ }
+ }
+ }
+
+ _playerConnections.TryRemove(accountId, out _);
+ }
+
+ public async Task SetPlayerReadyAsync(ulong accountId, bool ready)
+ {
+ if (!_playerToLobby.TryGetValue(accountId, out var lobbyId)) return;
+ if (!_lobbies.TryGetValue(lobbyId, out var lobby)) return;
+ if (!lobby.Players.TryGetValue(accountId, out var player)) return;
+
+ player.Ready = ready;
+ await BroadcastLobbyStateAsync(lobby);
+
+ // Check if all players ready
+ if (lobby.Players.Count >= MinPlayersToStart &&
+ lobby.Players.Values.All(p => p.Ready) &&
+ lobby.Phase == LobbyPhase.Waiting)
+ {
+ lobby.Phase = LobbyPhase.Countdown;
+ lobby.CountdownSeconds = LobbyCountdownSeconds;
+ _log.LogInformation("Lobby {LobbyId} starting countdown", lobbyId);
+ }
+ }
+
+ public int GetLobbyPlayerCount(string lobbyId)
+ {
+ return _lobbies.TryGetValue(lobbyId, out var lobby) ? lobby.Players.Count : 0;
+ }
+
+ public void EnqueueInput(ulong accountId, PlayerInput input)
+ {
+ if (!_playerToMatch.TryGetValue(accountId, out var matchId)) return;
+ if (!_matches.TryGetValue(matchId, out var match)) return;
+
+ match.Simulation.EnqueueInput(accountId, input);
+ }
+
+ public async Task BroadcastChatAsync(ulong senderId, string text)
+ {
+ // Find which match/lobby the sender is in
+ string? targetId = null;
+ Dictionary? targets = null;
+ string? senderName = null;
+
+ if (_playerToMatch.TryGetValue(senderId, out var matchId) &&
+ _matches.TryGetValue(matchId, out var match))
+ {
+ targets = match.Connections;
+ senderName = match.Simulation.Players.TryGetValue(senderId, out var p) ? p.Name : "Unknown";
+ }
+ else if (_playerToLobby.TryGetValue(senderId, out var lobbyId) &&
+ _lobbies.TryGetValue(lobbyId, out var lobby))
+ {
+ targets = lobby.Players.ToDictionary(kv => kv.Key, kv => kv.Value.Connection);
+ senderName = lobby.Players.TryGetValue(senderId, out var p) ? p.Name : "Unknown";
+ }
+
+ if (targets == null) return;
+
+ var chatMsg = new
+ {
+ senderId,
+ senderName,
+ text,
+ timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
+ };
+
+ var payload = _ser.Serialize(chatMsg);
+ var wire = _ser.Serialize(new ServerMessage(GameOpCodes.CHAT_RECEIVE, payload));
+
+ foreach (var (_, conn) in targets)
+ {
+ try
+ {
+ await conn.SendAsync(wire);
+ }
+ catch { /* ignore failed sends */ }
+ }
+ }
+
+ private async void OnLobbyTick(object? state)
+ {
+ foreach (var lobby in _lobbies.Values.ToList())
+ {
+ if (lobby.Phase == LobbyPhase.Countdown)
+ {
+ lobby.CountdownSeconds--;
+
+ // Broadcast countdown
+ await BroadcastToLobbyAsync(lobby, GameOpCodes.LOBBY_COUNTDOWN,
+ new { seconds = lobby.CountdownSeconds });
+
+ if (lobby.CountdownSeconds <= 0)
+ {
+ // Start the match!
+ await StartMatchAsync(lobby);
+ }
+ }
+ }
+ }
+
+ private async Task StartMatchAsync(Lobby lobby)
+ {
+ lobby.Phase = LobbyPhase.Starting;
+
+ var matchId = Guid.NewGuid().ToString("N")[..12];
+ var seed = (int)(DateTime.UtcNow.Ticks % int.MaxValue);
+ var simulation = new GameSimulation(matchId, seed);
+
+ var match = new MatchInstance
+ {
+ Id = matchId,
+ Simulation = simulation,
+ StartedAt = DateTime.UtcNow
+ };
+
+ // Add players to match
+ int playerIndex = 0;
+ foreach (var (accountId, lobbyPlayer) in lobby.Players)
+ {
+ var spawnPos = simulation.GetSpawnPosition(playerIndex, lobby.Players.Count);
+ simulation.AddPlayer(accountId, lobbyPlayer.Name, spawnPos);
+
+ match.Connections[accountId] = lobbyPlayer.Connection;
+ _playerToMatch[accountId] = matchId;
+ _playerToLobby.TryRemove(accountId, out _);
+
+ playerIndex++;
+ }
+
+ _matches[matchId] = match;
+ _lobbies.TryRemove(lobby.Id, out _);
+
+ // Start simulation
+ simulation.StartGame();
+
+ // Send GAME_START to all players
+ foreach (var (accountId, conn) in match.Connections)
+ {
+ var startInfo = BuildGameStartInfo(simulation, accountId);
+ var payload = _ser.Serialize(startInfo);
+ var wire = _ser.Serialize(new ServerMessage(GameOpCodes.GAME_START, payload));
+
+ try
+ {
+ await conn.SendAsync(wire);
+ }
+ catch (Exception ex)
+ {
+ _log.LogWarning(ex, "Failed to send GAME_START to {AccountId}", accountId);
+ }
+ }
+
+ _log.LogInformation("Match {MatchId} started with {PlayerCount} players", matchId, match.Connections.Count);
+ }
+
+ private object BuildGameStartInfo(GameSimulation sim, ulong forPlayerId)
+ {
+ var self = sim.Players[forPlayerId];
+ var others = sim.Players.Values.Where(p => p.Id != forPlayerId).ToArray();
+
+ return new
+ {
+ matchId = sim.MatchId,
+ mapSeed = sim.MapSeed,
+ mapWidth = sim.MapWidth,
+ mapHeight = sim.MapHeight,
+ self = new
+ {
+ playerId = self.Id,
+ name = self.Name,
+ x = self.X,
+ y = self.Y,
+ rotation = self.Rotation,
+ health = self.Health,
+ maxHealth = self.MaxHealth
+ },
+ otherPlayers = others.Select(p => new
+ {
+ playerId = p.Id,
+ name = p.Name,
+ x = p.X,
+ y = p.Y,
+ rotation = p.Rotation,
+ health = p.Health,
+ maxHealth = p.MaxHealth
+ }).ToArray(),
+ asteroids = sim.Asteroids.Values.Select(a => new
+ {
+ id = a.Id,
+ x = a.X,
+ y = a.Y,
+ radius = a.Radius,
+ type = a.Type
+ }).ToArray(),
+ resources = sim.Resources.Values.Select(r => new
+ {
+ id = r.Id,
+ x = r.X,
+ y = r.Y,
+ resourceType = r.ResourceType,
+ amount = r.Amount
+ }).ToArray(),
+ extractionZones = sim.ExtractionZones.Values.Select(z => new
+ {
+ id = z.Id,
+ x = z.X,
+ y = z.Y,
+ radius = z.Radius,
+ active = z.Active,
+ activatesAtTick = z.ActivatesAtTick
+ }).ToArray()
+ };
+ }
+
+ private async void OnGameTick(object? state)
+ {
+ foreach (var match in _matches.Values.ToList())
+ {
+ if (match.Simulation.Phase != GamePhase.InProgress) continue;
+
+ // Advance simulation
+ var events = match.Simulation.Tick();
+
+ // Broadcast state snapshot every tick
+ await BroadcastGameStateAsync(match);
+
+ // Broadcast events
+ foreach (var evt in events)
+ {
+ await BroadcastEventAsync(match, evt);
+
+ // Handle game end
+ if (evt.Type == EventType.GameEnd)
+ {
+ await EndMatchAsync(match);
+ }
+ }
+ }
+ }
+
+ private async Task BroadcastGameStateAsync(MatchInstance match)
+ {
+ var sim = match.Simulation;
+
+ var state = new
+ {
+ tick = sim.CurrentTick,
+ timeRemaining = sim.TimeRemaining,
+ playersAlive = sim.Players.Values.Count(p => p.Alive),
+ entities = sim.Players.Values.Where(p => p.Alive).Select(p => new
+ {
+ id = p.Id,
+ type = 0, // player
+ x = p.X,
+ y = p.Y,
+ rotation = p.Rotation,
+ health = p.Health,
+ scrap = p.Scrap,
+ energy = p.Energy,
+ rare = p.Rare
+ }).ToArray(),
+ projectiles = sim.Projectiles.Values.Select(p => new
+ {
+ id = p.Id,
+ x = p.X,
+ y = p.Y,
+ velX = p.VelX,
+ velY = p.VelY,
+ ownerId = p.OwnerId
+ }).ToArray(),
+ droppedItems = sim.DroppedItems.Values.Select(d => new
+ {
+ id = d.Id,
+ x = d.X,
+ y = d.Y,
+ itemId = d.ItemId,
+ quantity = d.Quantity
+ }).ToArray(),
+ resources = sim.Resources.Values.Where(r => r.Amount > 0).Select(r => new
+ {
+ id = r.Id,
+ amount = r.Amount
+ }).ToArray()
+ };
+
+ var payload = _ser.Serialize(state);
+ var wire = _ser.Serialize(new ServerMessage(GameOpCodes.GAME_STATE, payload));
+
+ foreach (var (_, conn) in match.Connections)
+ {
+ try
+ {
+ await conn.SendAsync(wire);
+ }
+ catch { /* ignore */ }
+ }
+ }
+
+ private async Task BroadcastEventAsync(MatchInstance match, GameEvent evt)
+ {
+ int opCode = evt.Type switch
+ {
+ EventType.Spawn => GameOpCodes.EVENT_SPAWN,
+ EventType.Despawn => GameOpCodes.EVENT_DESPAWN,
+ EventType.Damage => GameOpCodes.EVENT_DAMAGE,
+ EventType.Death => GameOpCodes.EVENT_DEATH,
+ EventType.Pickup => GameOpCodes.EVENT_PICKUP,
+ EventType.Projectile => GameOpCodes.EVENT_PROJECTILE,
+ EventType.Explosion => GameOpCodes.EVENT_EXPLOSION,
+ EventType.GameEnd => GameOpCodes.GAME_END,
+ _ => 0
+ };
+
+ if (opCode == 0) return;
+
+ var payload = _ser.Serialize(evt.Data);
+ var wire = _ser.Serialize(new ServerMessage(opCode, payload));
+
+ foreach (var (_, conn) in match.Connections)
+ {
+ try
+ {
+ await conn.SendAsync(wire);
+ }
+ catch { /* ignore */ }
+ }
+ }
+
+ private async Task EndMatchAsync(MatchInstance match)
+ {
+ // Remove players from match tracking
+ foreach (var accountId in match.Connections.Keys)
+ {
+ _playerToMatch.TryRemove(accountId, out _);
+ }
+
+ _matches.TryRemove(match.Id, out _);
+ _log.LogInformation("Match {MatchId} ended", match.Id);
+ }
+
+ private async Task BroadcastLobbyStateAsync(Lobby lobby)
+ {
+ var state = new
+ {
+ lobbyId = lobby.Id,
+ phase = lobby.Phase.ToString(),
+ countdownSeconds = lobby.CountdownSeconds,
+ players = lobby.Players.Values.Select(p => new
+ {
+ accountId = p.AccountId,
+ name = p.Name,
+ ready = p.Ready
+ }).ToArray()
+ };
+
+ await BroadcastToLobbyAsync(lobby, GameOpCodes.LOBBY_STATE, state);
+ }
+
+ private async Task BroadcastToLobbyAsync(Lobby lobby, int opCode, T data)
+ {
+ var payload = _ser.Serialize(data);
+ var wire = _ser.Serialize(new ServerMessage(opCode, payload));
+
+ foreach (var player in lobby.Players.Values)
+ {
+ try
+ {
+ await player.Connection.SendAsync(wire);
+ }
+ catch { /* ignore */ }
+ }
+ }
+
+ public void Dispose()
+ {
+ _tickTimer.Dispose();
+ _lobbyTimer.Dispose();
+ }
+}
+
+// ===== Lobby & Match Data Structures =====
+public sealed class Lobby
+{
+ public string Id { get; set; } = "";
+ public LobbyPhase Phase { get; set; } = LobbyPhase.Waiting;
+ public int CountdownSeconds { get; set; }
+ public DateTime CreatedAt { get; set; }
+ public Dictionary Players { get; } = new();
+}
+
+public sealed class LobbyPlayer
+{
+ public ulong AccountId { get; set; }
+ public string Name { get; set; } = "";
+ public bool Ready { get; set; }
+ public IConnection Connection { get; set; } = null!;
+}
+
+public enum LobbyPhase
+{
+ Waiting,
+ Countdown,
+ Starting
+}
+
+public sealed class MatchInstance
+{
+ public string Id { get; set; } = "";
+ public GameSimulation Simulation { get; set; } = null!;
+ public DateTime StartedAt { get; set; }
+ public Dictionary Connections { get; } = new();
+}
diff --git a/Game/GameOpCodes.cs b/Game/GameOpCodes.cs
new file mode 100644
index 0000000..8fa929f
--- /dev/null
+++ b/Game/GameOpCodes.cs
@@ -0,0 +1,45 @@
+namespace VoidScavengers.Networking.Messages;
+
+///
+/// OpCodes for Void Scavengers game - extends base OpCodes
+///
+public static class GameOpCodes
+{
+ // ===== Lobby/Matchmaking (400-419) =====
+ public const int LOBBY_JOIN = 400;
+ public const int LOBBY_JOIN_RESULT = 401;
+ public const int LOBBY_STATE = 402; // Periodic update of lobby players
+ public const int LOBBY_READY = 403;
+ public const int LOBBY_COUNTDOWN = 404; // Game starting in X seconds
+ public const int LOBBY_LEAVE = 405;
+
+ // ===== Game State (420-449) =====
+ public const int GAME_START = 420; // Server -> Client: Round begins
+ public const int GAME_STATE = 421; // Server -> Client: Full world snapshot
+ public const int GAME_TICK = 422; // Server -> Client: Delta update
+ public const int GAME_END = 423; // Server -> Client: Round over
+ public const int GAME_STATS = 424; // Server -> Client: End-of-round stats
+
+ // ===== Player Input (450-469) =====
+ public const int INPUT_MOVE = 450; // Client -> Server: Movement input
+ public const int INPUT_ACTION = 451; // Client -> Server: Use/Interact/Pickup
+ public const int INPUT_SHOOT = 452; // Client -> Server: Fire weapon
+ public const int INPUT_DROP = 453; // Client -> Server: Drop item
+ public const int INPUT_CRAFT = 454; // Client -> Server: Craft request
+
+ // ===== World Events (470-499) =====
+ public const int EVENT_SPAWN = 470; // Entity spawned
+ public const int EVENT_DESPAWN = 471; // Entity removed
+ public const int EVENT_DAMAGE = 472; // Damage dealt
+ public const int EVENT_DEATH = 473; // Player/entity died
+ public const int EVENT_PICKUP = 474; // Item picked up
+ public const int EVENT_PROJECTILE = 475; // Projectile created
+ public const int EVENT_EXPLOSION = 476; // Area effect
+ public const int EVENT_CRAFT_COMPLETE = 477; // Crafting finished
+ public const int EVENT_EXTRACT = 478; // Player extracted with loot
+
+ // ===== Chat/Social (500-509) =====
+ public const int CHAT_SEND = 500;
+ public const int CHAT_RECEIVE = 501;
+ public const int CHAT_PROXIMITY = 502; // Location-based chat
+}
diff --git a/Game/GameSimulation.cs b/Game/GameSimulation.cs
new file mode 100644
index 0000000..9d00fde
--- /dev/null
+++ b/Game/GameSimulation.cs
@@ -0,0 +1,1004 @@
+using System.Collections.Concurrent;
+using System.Numerics;
+
+namespace VoidScavengers.Game;
+
+///
+/// Core game simulation for a single match instance
+///
+public sealed class GameSimulation
+{
+ public string MatchId { get; }
+ public int MapSeed { get; }
+ public float MapWidth { get; }
+ public float MapHeight { get; }
+ public long CurrentTick { get; private set; }
+ public GamePhase Phase { get; private set; } = GamePhase.WaitingForPlayers;
+ public float TimeRemaining { get; private set; }
+
+ private readonly Random _rng;
+ private readonly Dictionary _players = new();
+ private readonly Dictionary _asteroids = new();
+ private readonly Dictionary _resources = new();
+ private readonly Dictionary _droppedItems = new();
+ private readonly Dictionary _projectiles = new();
+ private readonly Dictionary _extractionZones = new();
+
+ private readonly ConcurrentQueue _inputQueue = new();
+ private readonly List _pendingEvents = new();
+
+ private int _nextEntityId = 1;
+ private int _nextProjectileId = 1;
+
+ // Game constants
+ public const float TickRate = 20f; // 20 ticks per second
+ public const float TickDelta = 1f / TickRate;
+ public const float MatchDuration = 300f; // 5 minutes
+ public const float PlayerSpeed = 120f;
+ public const float PlayerRadius = 12f;
+ public const int StartingHealth = 100;
+ public const float PickupRadius = 24f;
+ public const float ExtractionTime = 5f; // Seconds to extract
+
+ public GameSimulation(string matchId, int seed, float width = 2000f, float height = 2000f)
+ {
+ MatchId = matchId;
+ MapSeed = seed;
+ MapWidth = width;
+ MapHeight = height;
+ _rng = new Random(seed);
+ TimeRemaining = MatchDuration;
+
+ GenerateMap();
+ }
+
+ private void GenerateMap()
+ {
+ // Generate asteroids (obstacles)
+ int asteroidCount = 40 + _rng.Next(20);
+ for (int i = 0; i < asteroidCount; i++)
+ {
+ var asteroid = new Asteroid
+ {
+ Id = _nextEntityId++,
+ X = 100 + (float)_rng.NextDouble() * (MapWidth - 200),
+ Y = 100 + (float)_rng.NextDouble() * (MapHeight - 200),
+ Radius = 30 + (float)_rng.NextDouble() * 50,
+ Type = _rng.Next(3)
+ };
+ _asteroids[asteroid.Id] = asteroid;
+ }
+
+ // Generate resource nodes
+ int resourceCount = 60 + _rng.Next(30);
+ for (int i = 0; i < resourceCount; i++)
+ {
+ var typeRoll = _rng.NextDouble();
+ int resourceType = typeRoll < 0.6 ? 0 : (typeRoll < 0.9 ? 1 : 2); // 60% scrap, 30% energy, 10% rare
+
+ var resource = new ResourceNode
+ {
+ Id = _nextEntityId++,
+ X = 50 + (float)_rng.NextDouble() * (MapWidth - 100),
+ Y = 50 + (float)_rng.NextDouble() * (MapHeight - 100),
+ ResourceType = resourceType,
+ Amount = resourceType switch
+ {
+ 0 => 3 + _rng.Next(5), // Scrap: 3-7
+ 1 => 2 + _rng.Next(3), // Energy: 2-4
+ 2 => 1 + _rng.Next(2), // Rare: 1-2
+ _ => 1
+ },
+ MaxAmount = 0 // Set below
+ };
+ resource.MaxAmount = resource.Amount;
+ _resources[resource.Id] = resource;
+ }
+
+ // Generate extraction zones (3-4 around map edges)
+ var zonePositions = new[]
+ {
+ (MapWidth * 0.1f, MapHeight * 0.5f),
+ (MapWidth * 0.9f, MapHeight * 0.5f),
+ (MapWidth * 0.5f, MapHeight * 0.1f),
+ (MapWidth * 0.5f, MapHeight * 0.9f)
+ };
+
+ for (int i = 0; i < zonePositions.Length; i++)
+ {
+ var zone = new ExtractionZone
+ {
+ Id = _nextEntityId++,
+ X = zonePositions[i].Item1,
+ Y = zonePositions[i].Item2,
+ Radius = 60f,
+ Active = i == 0, // First zone active at start
+ ActivatesAtTick = i == 0 ? 0 : (long)(TickRate * 60 * (i + 1)) // Stagger activation
+ };
+ _extractionZones[zone.Id] = zone;
+ }
+ }
+
+ public Vector2 GetSpawnPosition(int playerIndex, int totalPlayers)
+ {
+ // Spawn players in a circle around the center
+ float angle = (float)(2 * Math.PI * playerIndex / Math.Max(totalPlayers, 1));
+ float spawnRadius = Math.Min(MapWidth, MapHeight) * 0.35f;
+ float centerX = MapWidth / 2;
+ float centerY = MapHeight / 2;
+
+ return new Vector2(
+ centerX + (float)Math.Cos(angle) * spawnRadius,
+ centerY + (float)Math.Sin(angle) * spawnRadius
+ );
+ }
+
+ public PlayerEntity AddPlayer(ulong playerId, string name, Vector2 position)
+ {
+ var player = new PlayerEntity
+ {
+ Id = playerId,
+ Name = name,
+ X = position.X,
+ Y = position.Y,
+ Rotation = (float)_rng.NextDouble() * MathF.PI * 2,
+ Health = StartingHealth,
+ MaxHealth = StartingHealth,
+ Speed = PlayerSpeed,
+ Alive = true,
+ Scrap = 0,
+ Energy = 0,
+ Rare = 0,
+ EquippedWeaponId = null,
+ Inventory = new int?[6] // 6 inventory slots
+ };
+ _players[playerId] = player;
+ return player;
+ }
+
+ public void RemovePlayer(ulong playerId)
+ {
+ if (_players.TryGetValue(playerId, out var player))
+ {
+ if (player.Alive)
+ {
+ // Drop all items
+ DropPlayerLoot(player);
+ }
+ _players.Remove(playerId);
+ }
+ }
+
+ public void EnqueueInput(ulong playerId, PlayerInput input)
+ {
+ input.PlayerId = playerId;
+ _inputQueue.Enqueue(input);
+ }
+
+ public void StartGame()
+ {
+ Phase = GamePhase.InProgress;
+ CurrentTick = 0;
+ TimeRemaining = MatchDuration;
+ }
+
+ ///
+ /// Advance simulation by one tick. Returns events that occurred.
+ ///
+ public List Tick()
+ {
+ if (Phase != GamePhase.InProgress) return new List();
+
+ _pendingEvents.Clear();
+ CurrentTick++;
+ TimeRemaining -= TickDelta;
+
+ // Process all queued inputs
+ while (_inputQueue.TryDequeue(out var input))
+ {
+ ProcessInput(input);
+ }
+
+ // Update all entities
+ UpdatePlayers();
+ UpdateProjectiles();
+ UpdateExtractionZones();
+
+ // Check win conditions
+ CheckEndConditions();
+
+ return new List(_pendingEvents);
+ }
+
+ private void ProcessInput(PlayerInput input)
+ {
+ if (!_players.TryGetValue(input.PlayerId, out var player) || !player.Alive)
+ return;
+
+ switch (input.Type)
+ {
+ case InputType.Move:
+ player.InputDx = Math.Clamp(input.Dx, -1f, 1f);
+ player.InputDy = Math.Clamp(input.Dy, -1f, 1f);
+ player.Rotation = input.AimAngle;
+ break;
+
+ case InputType.Shoot:
+ TryShoot(player, input.AimAngle);
+ break;
+
+ case InputType.Action:
+ TryAction(player, input.TargetId);
+ break;
+
+ case InputType.Craft:
+ TryCraft(player, input.TargetId ?? 0);
+ break;
+
+ case InputType.Drop:
+ TryDrop(player, input.TargetId ?? 0);
+ break;
+ }
+ }
+
+ private void UpdatePlayers()
+ {
+ foreach (var player in _players.Values)
+ {
+ if (!player.Alive) continue;
+
+ // Apply movement
+ float dx = player.InputDx * player.Speed * TickDelta;
+ float dy = player.InputDy * player.Speed * TickDelta;
+
+ float newX = player.X + dx;
+ float newY = player.Y + dy;
+
+ // Collision with asteroids
+ bool blocked = false;
+ foreach (var asteroid in _asteroids.Values)
+ {
+ float distSq = (newX - asteroid.X) * (newX - asteroid.X) +
+ (newY - asteroid.Y) * (newY - asteroid.Y);
+ float minDist = PlayerRadius + asteroid.Radius;
+ if (distSq < minDist * minDist)
+ {
+ blocked = true;
+ // Push out of collision
+ float dist = MathF.Sqrt(distSq);
+ if (dist > 0.001f)
+ {
+ float overlap = minDist - dist;
+ newX += (newX - asteroid.X) / dist * overlap;
+ newY += (newY - asteroid.Y) / dist * overlap;
+ }
+ }
+ }
+
+ // Clamp to map bounds
+ newX = Math.Clamp(newX, PlayerRadius, MapWidth - PlayerRadius);
+ newY = Math.Clamp(newY, PlayerRadius, MapHeight - PlayerRadius);
+
+ player.X = newX;
+ player.Y = newY;
+
+ // Check resource pickup
+ CheckResourcePickup(player);
+
+ // Check dropped item pickup
+ CheckDroppedItemPickup(player);
+
+ // Update extraction progress
+ UpdateExtraction(player);
+
+ // Clear input for next tick
+ player.InputDx = 0;
+ player.InputDy = 0;
+ }
+ }
+
+ private void CheckResourcePickup(PlayerEntity player)
+ {
+ foreach (var resource in _resources.Values.ToList())
+ {
+ if (resource.Amount <= 0) continue;
+
+ float distSq = (player.X - resource.X) * (player.X - resource.X) +
+ (player.Y - resource.Y) * (player.Y - resource.Y);
+
+ if (distSq < PickupRadius * PickupRadius)
+ {
+ int amount = resource.Amount;
+ switch (resource.ResourceType)
+ {
+ case 0: player.Scrap += amount; break;
+ case 1: player.Energy += amount; break;
+ case 2: player.Rare += amount; break;
+ }
+
+ resource.Amount = 0;
+
+ _pendingEvents.Add(new GameEvent
+ {
+ Type = EventType.Pickup,
+ PlayerId = player.Id,
+ TargetId = resource.Id,
+ Data = new { resourceType = resource.ResourceType, amount }
+ });
+ }
+ }
+ }
+
+ private void CheckDroppedItemPickup(PlayerEntity player)
+ {
+ foreach (var drop in _droppedItems.Values.ToList())
+ {
+ float distSq = (player.X - drop.X) * (player.X - drop.X) +
+ (player.Y - drop.Y) * (player.Y - drop.Y);
+
+ if (distSq < PickupRadius * PickupRadius)
+ {
+ // Try to add to inventory
+ if (TryAddToInventory(player, drop.ItemId, drop.Quantity))
+ {
+ _droppedItems.Remove(drop.Id);
+ _pendingEvents.Add(new GameEvent
+ {
+ Type = EventType.Pickup,
+ PlayerId = player.Id,
+ TargetId = drop.Id,
+ Data = new { itemId = drop.ItemId, quantity = drop.Quantity }
+ });
+ }
+ }
+ }
+ }
+
+ private bool TryAddToInventory(PlayerEntity player, int itemId, int quantity)
+ {
+ var itemDef = ItemDatabase.Get(itemId);
+ if (itemDef == null) return false;
+
+ // For weapons/tools/armor, find empty slot
+ if (!itemDef.Stackable)
+ {
+ for (int i = 0; i < player.Inventory.Length; i++)
+ {
+ if (player.Inventory[i] == null)
+ {
+ player.Inventory[i] = itemId;
+ // Auto-equip weapon if none equipped
+ if (itemDef.Type == ItemType.Weapon && player.EquippedWeaponId == null)
+ {
+ player.EquippedWeaponId = itemId;
+ }
+ return true;
+ }
+ }
+ return false; // No room
+ }
+
+ // Resources are stored separately, always accepted
+ return true;
+ }
+
+ private void UpdateExtraction(PlayerEntity player)
+ {
+ bool inZone = false;
+ foreach (var zone in _extractionZones.Values)
+ {
+ if (!zone.Active) continue;
+
+ float distSq = (player.X - zone.X) * (player.X - zone.X) +
+ (player.Y - zone.Y) * (player.Y - zone.Y);
+
+ if (distSq < zone.Radius * zone.Radius)
+ {
+ inZone = true;
+ player.ExtractionProgress += TickDelta;
+
+ if (player.ExtractionProgress >= ExtractionTime)
+ {
+ // Player extracts!
+ ExtractPlayer(player);
+ }
+ break;
+ }
+ }
+
+ if (!inZone)
+ {
+ player.ExtractionProgress = 0;
+ }
+ }
+
+ private void ExtractPlayer(PlayerEntity player)
+ {
+ player.Alive = false;
+ player.Extracted = true;
+
+ // Calculate total loot value
+ int totalValue = player.Scrap * 1 + player.Energy * 2 + player.Rare * 5;
+ foreach (var itemId in player.Inventory)
+ {
+ if (itemId.HasValue)
+ {
+ var item = ItemDatabase.Get(itemId.Value);
+ if (item != null) totalValue += item.LootValue;
+ }
+ }
+
+ _pendingEvents.Add(new GameEvent
+ {
+ Type = EventType.Extract,
+ PlayerId = player.Id,
+ Data = new { playerName = player.Name, totalValue }
+ });
+ }
+
+ private void TryShoot(PlayerEntity player, float angle)
+ {
+ if (player.EquippedWeaponId == null) return;
+ var weapon = ItemDatabase.Get(player.EquippedWeaponId.Value);
+ if (weapon == null || weapon.Type != ItemType.Weapon) return;
+
+ // Check fire rate cooldown
+ float cooldown = 1f / weapon.FireRate;
+ if (CurrentTick - player.LastShotTick < cooldown * TickRate) return;
+
+ player.LastShotTick = CurrentTick;
+
+ // Create projectile(s)
+ int pellets = weapon.PelletCount;
+ for (int i = 0; i < pellets; i++)
+ {
+ float spread = pellets > 1 ? (float)(_rng.NextDouble() - 0.5) * weapon.Spread : 0;
+ float finalAngle = angle + spread;
+
+ var proj = new Projectile
+ {
+ Id = _nextProjectileId++,
+ OwnerId = player.Id,
+ X = player.X,
+ Y = player.Y,
+ VelX = MathF.Cos(finalAngle) * weapon.ProjectileSpeed,
+ VelY = MathF.Sin(finalAngle) * weapon.ProjectileSpeed,
+ Damage = weapon.Damage,
+ Range = weapon.Range,
+ DistanceTraveled = 0,
+ ExplosionRadius = weapon.ExplosionRadius,
+ WeaponId = weapon.Id
+ };
+ _projectiles[proj.Id] = proj;
+
+ _pendingEvents.Add(new GameEvent
+ {
+ Type = EventType.Projectile,
+ Data = new { proj.Id, proj.OwnerId, proj.X, proj.Y, proj.VelX, proj.VelY, weapon.Id }
+ });
+ }
+ }
+
+ private void UpdateProjectiles()
+ {
+ foreach (var proj in _projectiles.Values.ToList())
+ {
+ float dx = proj.VelX * TickDelta;
+ float dy = proj.VelY * TickDelta;
+ float moveDist = MathF.Sqrt(dx * dx + dy * dy);
+
+ proj.X += dx;
+ proj.Y += dy;
+ proj.DistanceTraveled += moveDist;
+
+ // Check range
+ if (proj.DistanceTraveled > proj.Range)
+ {
+ if (proj.ExplosionRadius > 0)
+ {
+ CreateExplosion(proj.X, proj.Y, proj.ExplosionRadius, proj.Damage, proj.OwnerId);
+ }
+ _projectiles.Remove(proj.Id);
+ continue;
+ }
+
+ // Check asteroid collision
+ bool hitAsteroid = false;
+ foreach (var asteroid in _asteroids.Values)
+ {
+ float distSq = (proj.X - asteroid.X) * (proj.X - asteroid.X) +
+ (proj.Y - asteroid.Y) * (proj.Y - asteroid.Y);
+ if (distSq < asteroid.Radius * asteroid.Radius)
+ {
+ hitAsteroid = true;
+ if (proj.ExplosionRadius > 0)
+ {
+ CreateExplosion(proj.X, proj.Y, proj.ExplosionRadius, proj.Damage, proj.OwnerId);
+ }
+ break;
+ }
+ }
+ if (hitAsteroid)
+ {
+ _projectiles.Remove(proj.Id);
+ continue;
+ }
+
+ // Check player collision
+ foreach (var target in _players.Values)
+ {
+ if (target.Id == proj.OwnerId || !target.Alive) continue;
+
+ float distSq = (proj.X - target.X) * (proj.X - target.X) +
+ (proj.Y - target.Y) * (proj.Y - target.Y);
+
+ if (distSq < PlayerRadius * PlayerRadius)
+ {
+ if (proj.ExplosionRadius > 0)
+ {
+ CreateExplosion(proj.X, proj.Y, proj.ExplosionRadius, proj.Damage, proj.OwnerId);
+ }
+ else
+ {
+ DealDamage(target, proj.Damage, proj.OwnerId);
+ }
+ _projectiles.Remove(proj.Id);
+ break;
+ }
+ }
+
+ // Out of bounds
+ if (proj.X < 0 || proj.X > MapWidth || proj.Y < 0 || proj.Y > MapHeight)
+ {
+ _projectiles.Remove(proj.Id);
+ }
+ }
+ }
+
+ private void CreateExplosion(float x, float y, float radius, int damage, ulong ownerId)
+ {
+ _pendingEvents.Add(new GameEvent
+ {
+ Type = EventType.Explosion,
+ Data = new { x, y, radius }
+ });
+
+ foreach (var target in _players.Values)
+ {
+ if (!target.Alive) continue;
+
+ float distSq = (x - target.X) * (x - target.X) + (y - target.Y) * (y - target.Y);
+ if (distSq < radius * radius)
+ {
+ // Damage falloff based on distance
+ float dist = MathF.Sqrt(distSq);
+ float falloff = 1f - (dist / radius);
+ int actualDamage = (int)(damage * falloff);
+ if (actualDamage > 0)
+ {
+ DealDamage(target, actualDamage, ownerId);
+ }
+ }
+ }
+ }
+
+ private void DealDamage(PlayerEntity target, int damage, ulong? sourceId)
+ {
+ target.Health -= damage;
+
+ _pendingEvents.Add(new GameEvent
+ {
+ Type = EventType.Damage,
+ PlayerId = target.Id,
+ SourceId = sourceId,
+ Data = new { damage, newHealth = target.Health }
+ });
+
+ if (target.Health <= 0)
+ {
+ KillPlayer(target, sourceId);
+ }
+ }
+
+ private void KillPlayer(PlayerEntity player, ulong? killerId)
+ {
+ player.Alive = false;
+ player.Health = 0;
+
+ var drops = DropPlayerLoot(player);
+
+ string? killerName = null;
+ if (killerId.HasValue && _players.TryGetValue(killerId.Value, out var killer))
+ {
+ killerName = killer.Name;
+ killer.Kills++;
+ }
+ player.Deaths++;
+
+ _pendingEvents.Add(new GameEvent
+ {
+ Type = EventType.Death,
+ PlayerId = player.Id,
+ SourceId = killerId,
+ Data = new
+ {
+ playerName = player.Name,
+ killerName,
+ drops = drops.Select(d => new { d.Id, d.X, d.Y, d.ItemId, d.Quantity }).ToArray()
+ }
+ });
+ }
+
+ private List DropPlayerLoot(PlayerEntity player)
+ {
+ var drops = new List();
+ float dropAngle = 0;
+ float dropRadius = 30f;
+
+ // Drop resources as items
+ if (player.Scrap > 0)
+ {
+ drops.Add(CreateDrop(player.X, player.Y, 1, player.Scrap, ref dropAngle, dropRadius));
+ }
+ if (player.Energy > 0)
+ {
+ drops.Add(CreateDrop(player.X, player.Y, 2, player.Energy, ref dropAngle, dropRadius));
+ }
+ if (player.Rare > 0)
+ {
+ drops.Add(CreateDrop(player.X, player.Y, 3, player.Rare, ref dropAngle, dropRadius));
+ }
+
+ // Drop inventory items
+ foreach (var itemId in player.Inventory)
+ {
+ if (itemId.HasValue)
+ {
+ drops.Add(CreateDrop(player.X, player.Y, itemId.Value, 1, ref dropAngle, dropRadius));
+ }
+ }
+
+ // Clear player resources
+ player.Scrap = 0;
+ player.Energy = 0;
+ player.Rare = 0;
+ player.Inventory = new int?[6];
+ player.EquippedWeaponId = null;
+
+ return drops;
+ }
+
+ private DroppedItem CreateDrop(float x, float y, int itemId, int quantity, ref float angle, float radius)
+ {
+ var drop = new DroppedItem
+ {
+ Id = _nextEntityId++,
+ X = x + MathF.Cos(angle) * radius,
+ Y = y + MathF.Sin(angle) * radius,
+ ItemId = itemId,
+ Quantity = quantity
+ };
+ _droppedItems[drop.Id] = drop;
+ angle += MathF.PI / 4; // Spread drops around
+ return drop;
+ }
+
+ private void TryAction(PlayerEntity player, int? targetId)
+ {
+ // For now, action just triggers resource gathering from a nearby node
+ // Could be extended for interacting with terminals, doors, etc.
+ }
+
+ private void TryCraft(PlayerEntity player, int recipeId)
+ {
+ var recipe = RecipeDatabase.Get(recipeId);
+ if (recipe == null) return;
+
+ var (scrapCost, energyCost, rareCost) = recipe.GetCost();
+
+ if (player.Scrap < scrapCost || player.Energy < energyCost || player.Rare < rareCost)
+ return;
+
+ var item = ItemDatabase.Get(recipe.ResultItemId);
+ if (item == null) return;
+
+ // Check if there's room for non-stackable items
+ if (!item.Stackable)
+ {
+ bool hasRoom = player.Inventory.Any(s => s == null);
+ if (!hasRoom) return;
+ }
+
+ // Deduct resources
+ player.Scrap -= scrapCost;
+ player.Energy -= energyCost;
+ player.Rare -= rareCost;
+
+ // Add item
+ if (item.Stackable)
+ {
+ // Resources handled separately - shouldn't craft resources
+ }
+ else
+ {
+ for (int i = 0; i < player.Inventory.Length; i++)
+ {
+ if (player.Inventory[i] == null)
+ {
+ player.Inventory[i] = recipe.ResultItemId;
+ // Auto-equip weapon if none equipped
+ if (item.Type == ItemType.Weapon && player.EquippedWeaponId == null)
+ {
+ player.EquippedWeaponId = recipe.ResultItemId;
+ }
+ break;
+ }
+ }
+ }
+
+ player.ItemsCrafted++;
+
+ _pendingEvents.Add(new GameEvent
+ {
+ Type = EventType.Craft,
+ PlayerId = player.Id,
+ Data = new { recipeId, resultItemId = recipe.ResultItemId }
+ });
+ }
+
+ private void TryDrop(PlayerEntity player, int slotIndex)
+ {
+ if (slotIndex < 0 || slotIndex >= player.Inventory.Length) return;
+ if (player.Inventory[slotIndex] == null) return;
+
+ int itemId = player.Inventory[slotIndex].Value;
+ player.Inventory[slotIndex] = null;
+
+ // If dropping equipped weapon, unequip
+ if (player.EquippedWeaponId == itemId)
+ {
+ player.EquippedWeaponId = null;
+ // Try to equip another weapon
+ foreach (var invItem in player.Inventory)
+ {
+ if (invItem.HasValue)
+ {
+ var def = ItemDatabase.Get(invItem.Value);
+ if (def?.Type == ItemType.Weapon)
+ {
+ player.EquippedWeaponId = invItem.Value;
+ break;
+ }
+ }
+ }
+ }
+
+ float dropAngle = player.Rotation + MathF.PI; // Drop behind player
+ var drop = new DroppedItem
+ {
+ Id = _nextEntityId++,
+ X = player.X + MathF.Cos(dropAngle) * 30f,
+ Y = player.Y + MathF.Sin(dropAngle) * 30f,
+ ItemId = itemId,
+ Quantity = 1
+ };
+ _droppedItems[drop.Id] = drop;
+
+ _pendingEvents.Add(new GameEvent
+ {
+ Type = EventType.Drop,
+ PlayerId = player.Id,
+ Data = new { drop.Id, drop.X, drop.Y, drop.ItemId }
+ });
+ }
+
+ private void UpdateExtractionZones()
+ {
+ foreach (var zone in _extractionZones.Values)
+ {
+ if (!zone.Active && CurrentTick >= zone.ActivatesAtTick)
+ {
+ zone.Active = true;
+ _pendingEvents.Add(new GameEvent
+ {
+ Type = EventType.ZoneActivate,
+ Data = new { zoneId = zone.Id, zone.X, zone.Y, zone.Radius }
+ });
+ }
+ }
+ }
+
+ private void CheckEndConditions()
+ {
+ if (Phase != GamePhase.InProgress) return;
+
+ int alivePlayers = _players.Values.Count(p => p.Alive);
+
+ // Time expired
+ if (TimeRemaining <= 0)
+ {
+ EndGame("time_expired");
+ return;
+ }
+
+ // Last player standing (need at least 2 to start)
+ if (alivePlayers <= 1 && _players.Count >= 2)
+ {
+ EndGame("last_standing");
+ return;
+ }
+
+ // All players extracted
+ if (_players.Count > 0 && _players.Values.All(p => !p.Alive))
+ {
+ EndGame("all_eliminated_or_extracted");
+ }
+ }
+
+ private void EndGame(string reason)
+ {
+ Phase = GamePhase.Ended;
+
+ var winner = _players.Values
+ .Where(p => p.Alive || p.Extracted)
+ .OrderByDescending(p => p.Extracted ? 1 : 0)
+ .ThenByDescending(p => p.Kills)
+ .FirstOrDefault();
+
+ _pendingEvents.Add(new GameEvent
+ {
+ Type = EventType.GameEnd,
+ Data = new
+ {
+ reason,
+ winnerId = winner?.Id,
+ winnerName = winner?.Name
+ }
+ });
+ }
+
+ // ===== State Accessors =====
+ public IReadOnlyDictionary Players => _players;
+ public IReadOnlyDictionary Asteroids => _asteroids;
+ public IReadOnlyDictionary Resources => _resources;
+ public IReadOnlyDictionary DroppedItems => _droppedItems;
+ public IReadOnlyDictionary Projectiles => _projectiles;
+ public IReadOnlyDictionary ExtractionZones => _extractionZones;
+}
+
+// ===== Entity Classes =====
+public sealed class PlayerEntity
+{
+ public ulong Id { get; set; }
+ public string Name { get; set; } = "";
+ public float X { get; set; }
+ public float Y { get; set; }
+ public float Rotation { get; set; }
+ public int Health { get; set; }
+ public int MaxHealth { get; set; }
+ public float Speed { get; set; }
+ public bool Alive { get; set; }
+ public bool Extracted { get; set; }
+
+ public int Scrap { get; set; }
+ public int Energy { get; set; }
+ public int Rare { get; set; }
+ public int?[] Inventory { get; set; } = new int?[6];
+ public int? EquippedWeaponId { get; set; }
+
+ public float InputDx { get; set; }
+ public float InputDy { get; set; }
+ public long LastShotTick { get; set; }
+ public float ExtractionProgress { get; set; }
+
+ public int Kills { get; set; }
+ public int Deaths { get; set; }
+ public int DamageDealt { get; set; }
+ public int ItemsCrafted { get; set; }
+}
+
+public sealed class Asteroid
+{
+ public int Id { get; set; }
+ public float X { get; set; }
+ public float Y { get; set; }
+ public float Radius { get; set; }
+ public int Type { get; set; }
+}
+
+public sealed class ResourceNode
+{
+ public int Id { get; set; }
+ public float X { get; set; }
+ public float Y { get; set; }
+ public int ResourceType { get; set; }
+ public int Amount { get; set; }
+ public int MaxAmount { get; set; }
+}
+
+public sealed class DroppedItem
+{
+ public int Id { get; set; }
+ public float X { get; set; }
+ public float Y { get; set; }
+ public int ItemId { get; set; }
+ public int Quantity { get; set; }
+}
+
+public sealed class Projectile
+{
+ public int Id { get; set; }
+ public ulong OwnerId { get; set; }
+ public float X { get; set; }
+ public float Y { get; set; }
+ public float VelX { get; set; }
+ public float VelY { get; set; }
+ public int Damage { get; set; }
+ public float Range { get; set; }
+ public float DistanceTraveled { get; set; }
+ public float ExplosionRadius { get; set; }
+ public int WeaponId { get; set; }
+}
+
+public sealed class ExtractionZone
+{
+ public int Id { get; set; }
+ public float X { get; set; }
+ public float Y { get; set; }
+ public float Radius { get; set; }
+ public bool Active { get; set; }
+ public long ActivatesAtTick { get; set; }
+}
+
+public enum GamePhase
+{
+ WaitingForPlayers,
+ Countdown,
+ InProgress,
+ Ended
+}
+
+public sealed class PlayerInput
+{
+ public ulong PlayerId { get; set; }
+ public InputType Type { get; set; }
+ public float Dx { get; set; }
+ public float Dy { get; set; }
+ public float AimAngle { get; set; }
+ public int? TargetId { get; set; }
+ public uint Seq { get; set; }
+}
+
+public enum InputType
+{
+ Move,
+ Shoot,
+ Action,
+ Craft,
+ Drop
+}
+
+public sealed class GameEvent
+{
+ public EventType Type { get; set; }
+ public ulong? PlayerId { get; set; }
+ public ulong? SourceId { get; set; }
+ public int? TargetId { get; set; }
+ public object? Data { get; set; }
+}
+
+public enum EventType
+{
+ Spawn,
+ Despawn,
+ Damage,
+ Death,
+ Pickup,
+ Projectile,
+ Explosion,
+ Craft,
+ Drop,
+ Extract,
+ ZoneActivate,
+ GameEnd
+}
diff --git a/Game/ItemDatabase.cs b/Game/ItemDatabase.cs
new file mode 100644
index 0000000..babe6b0
--- /dev/null
+++ b/Game/ItemDatabase.cs
@@ -0,0 +1,241 @@
+namespace VoidScavengers.Game;
+
+///
+/// Item definitions for Void Scavengers
+///
+public static class ItemDatabase
+{
+ public static readonly Dictionary Items = new()
+ {
+ // ===== Resources (1-99) =====
+ [1] = new ItemDef(1, "Scrap Metal", ItemType.Resource, 0, "Basic salvage material", 1, true),
+ [2] = new ItemDef(2, "Energy Cell", ItemType.Resource, 0, "Charged power source", 2, true),
+ [3] = new ItemDef(3, "Rare Alloy", ItemType.Resource, 0, "Precious refined metal", 5, true),
+
+ // ===== Weapons (100-199) =====
+ [100] = new ItemDef(100, "Pulse Pistol", ItemType.Weapon, 15, "Basic sidearm", 10, false)
+ {
+ Damage = 10,
+ FireRate = 4f, // shots per second
+ ProjectileSpeed = 400f,
+ Range = 300f,
+ AmmoType = 0 // energy-based, no ammo needed
+ },
+ [101] = new ItemDef(101, "Scatter Gun", ItemType.Weapon, 25, "Close-range devastation", 20, false)
+ {
+ Damage = 6, // per pellet, 5 pellets
+ FireRate = 1.5f,
+ ProjectileSpeed = 350f,
+ Range = 150f,
+ AmmoType = 0,
+ PelletCount = 5,
+ Spread = 0.4f
+ },
+ [102] = new ItemDef(102, "Rail Rifle", ItemType.Weapon, 40, "Long-range precision", 35, false)
+ {
+ Damage = 45,
+ FireRate = 0.8f,
+ ProjectileSpeed = 800f,
+ Range = 600f,
+ AmmoType = 0
+ },
+ [103] = new ItemDef(103, "Plasma Launcher", ItemType.Weapon, 60, "Area damage weapon", 50, false)
+ {
+ Damage = 30,
+ FireRate = 0.5f,
+ ProjectileSpeed = 250f,
+ Range = 400f,
+ AmmoType = 0,
+ ExplosionRadius = 50f
+ },
+
+ // ===== Tools (200-299) =====
+ [200] = new ItemDef(200, "Mining Laser", ItemType.Tool, 15, "Harvests resources faster", 12, false)
+ {
+ HarvestMultiplier = 2.0f
+ },
+ [201] = new ItemDef(201, "Scanner", ItemType.Tool, 20, "Reveals nearby resources and players", 15, false)
+ {
+ ScanRadius = 200f,
+ ScanCooldown = 10f
+ },
+ [202] = new ItemDef(202, "Portable Shield", ItemType.Tool, 35, "Deployable cover", 25, false)
+ {
+ ShieldHealth = 100,
+ ShieldDuration = 15f
+ },
+
+ // ===== Consumables (300-399) =====
+ [300] = new ItemDef(300, "Repair Kit", ItemType.Consumable, 10, "Restores 30 health", 8, true)
+ {
+ HealAmount = 30
+ },
+ [301] = new ItemDef(301, "Shield Booster", ItemType.Consumable, 15, "Temporary damage reduction", 12, true)
+ {
+ ShieldBoostDuration = 10f,
+ DamageReduction = 0.3f
+ },
+ [302] = new ItemDef(302, "Speed Stim", ItemType.Consumable, 12, "Temporary speed boost", 10, true)
+ {
+ SpeedBoostDuration = 8f,
+ SpeedMultiplier = 1.5f
+ },
+
+ // ===== Armor/Equipment (400-499) =====
+ [400] = new ItemDef(400, "Light Suit", ItemType.Armor, 20, "+20 max health", 15, false)
+ {
+ HealthBonus = 20,
+ SpeedPenalty = 0f
+ },
+ [401] = new ItemDef(401, "Heavy Suit", ItemType.Armor, 45, "+50 max health, slower", 35, false)
+ {
+ HealthBonus = 50,
+ SpeedPenalty = 0.15f
+ },
+ [402] = new ItemDef(402, "Thruster Pack", ItemType.Armor, 30, "Dash ability", 25, false)
+ {
+ DashDistance = 100f,
+ DashCooldown = 5f
+ }
+ };
+
+ public static ItemDef? Get(int id) => Items.TryGetValue(id, out var item) ? item : null;
+}
+
+public sealed class ItemDef
+{
+ public int Id { get; }
+ public string Name { get; }
+ public ItemType Type { get; }
+ public int CraftCost { get; } // Total resource value to craft
+ public string Description { get; }
+ public int LootValue { get; } // Value when extracted
+ public bool Stackable { get; }
+
+ // Weapon stats
+ public int Damage { get; init; }
+ public float FireRate { get; init; }
+ public float ProjectileSpeed { get; init; }
+ public float Range { get; init; }
+ public int AmmoType { get; init; }
+ public int PelletCount { get; init; } = 1;
+ public float Spread { get; init; }
+ public float ExplosionRadius { get; init; }
+
+ // Tool stats
+ public float HarvestMultiplier { get; init; } = 1f;
+ public float ScanRadius { get; init; }
+ public float ScanCooldown { get; init; }
+ public int ShieldHealth { get; init; }
+ public float ShieldDuration { get; init; }
+
+ // Consumable stats
+ public int HealAmount { get; init; }
+ public float ShieldBoostDuration { get; init; }
+ public float DamageReduction { get; init; }
+ public float SpeedBoostDuration { get; init; }
+ public float SpeedMultiplier { get; init; } = 1f;
+
+ // Armor stats
+ public int HealthBonus { get; init; }
+ public float SpeedPenalty { get; init; }
+ public float DashDistance { get; init; }
+ public float DashCooldown { get; init; }
+
+ public ItemDef(int id, string name, ItemType type, int craftCost, string desc, int lootValue, bool stackable)
+ {
+ Id = id;
+ Name = name;
+ Type = type;
+ CraftCost = craftCost;
+ Description = desc;
+ LootValue = lootValue;
+ Stackable = stackable;
+ }
+}
+
+public enum ItemType
+{
+ Resource,
+ Weapon,
+ Tool,
+ Consumable,
+ Armor
+}
+
+///
+/// Crafting recipes
+///
+public static class RecipeDatabase
+{
+ public static readonly Dictionary Recipes = new()
+ {
+ // Basic weapons
+ [1] = new Recipe(1, 100, new[] { (1, 5), (2, 2) }), // Pulse Pistol: 5 scrap + 2 energy
+ [2] = new Recipe(2, 101, new[] { (1, 8), (2, 3) }), // Scatter Gun: 8 scrap + 3 energy
+ [3] = new Recipe(3, 102, new[] { (1, 10), (2, 5), (3, 2) }), // Rail Rifle: 10 scrap + 5 energy + 2 rare
+ [4] = new Recipe(4, 103, new[] { (1, 15), (2, 8), (3, 4) }), // Plasma Launcher
+
+ // Tools
+ [10] = new Recipe(10, 200, new[] { (1, 6), (2, 3) }), // Mining Laser
+ [11] = new Recipe(11, 201, new[] { (1, 8), (2, 4), (3, 1) }), // Scanner
+ [12] = new Recipe(12, 202, new[] { (1, 12), (2, 6), (3, 2) }), // Portable Shield
+
+ // Consumables
+ [20] = new Recipe(20, 300, new[] { (1, 3), (2, 2) }), // Repair Kit
+ [21] = new Recipe(21, 301, new[] { (1, 4), (2, 3) }), // Shield Booster
+ [22] = new Recipe(22, 302, new[] { (1, 3), (2, 4) }), // Speed Stim
+
+ // Armor
+ [30] = new Recipe(30, 400, new[] { (1, 8), (3, 1) }), // Light Suit
+ [31] = new Recipe(31, 401, new[] { (1, 15), (3, 3) }), // Heavy Suit
+ [32] = new Recipe(32, 402, new[] { (1, 10), (2, 5), (3, 2) }), // Thruster Pack
+ };
+
+ public static Recipe? Get(int id) => Recipes.TryGetValue(id, out var r) ? r : null;
+}
+
+public sealed class Recipe
+{
+ public int Id { get; }
+ public int ResultItemId { get; }
+ public (int ItemId, int Quantity)[] Ingredients { get; }
+
+ public Recipe(int id, int resultItemId, (int, int)[] ingredients)
+ {
+ Id = id;
+ ResultItemId = resultItemId;
+ Ingredients = ingredients;
+ }
+
+ public bool CanCraft(int scrap, int energy, int rare)
+ {
+ foreach (var (itemId, qty) in Ingredients)
+ {
+ int available = itemId switch
+ {
+ 1 => scrap,
+ 2 => energy,
+ 3 => rare,
+ _ => 0
+ };
+ if (available < qty) return false;
+ }
+ return true;
+ }
+
+ public (int scrap, int energy, int rare) GetCost()
+ {
+ int s = 0, e = 0, r = 0;
+ foreach (var (itemId, qty) in Ingredients)
+ {
+ switch (itemId)
+ {
+ case 1: s += qty; break;
+ case 2: e += qty; break;
+ case 3: r += qty; break;
+ }
+ }
+ return (s, e, r);
+ }
+}
diff --git a/Migrations/20251110195003_UpdateSessions-revokation.Designer.cs b/Migrations/20251110195003_UpdateSessions-revokation.Designer.cs
new file mode 100644
index 0000000..23b469a
--- /dev/null
+++ b/Migrations/20251110195003_UpdateSessions-revokation.Designer.cs
@@ -0,0 +1,481 @@
+//
+using System;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Metadata;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using Server.Data;
+
+#nullable disable
+
+namespace SystemRevivalServer.Migrations
+{
+ [DbContext(typeof(GameDbContext))]
+ [Migration("20251110195003_UpdateSessions-revokation")]
+ partial class UpdateSessionsrevokation
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "9.0.10")
+ .HasAnnotation("Relational:MaxIdentifierLength", 64);
+
+ MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder);
+
+ modelBuilder.Entity("Server.Data.Account", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("BannedUntil")
+ .HasColumnType("datetime(6)");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("Email")
+ .HasMaxLength(255)
+ .HasColumnType("varchar(255)");
+
+ b.Property("IsBanned")
+ .HasColumnType("tinyint(1)");
+
+ b.Property("PasswordHash")
+ .IsRequired()
+ .HasColumnType("varbinary(64)");
+
+ b.Property("PasswordSalt")
+ .IsRequired()
+ .HasColumnType("varbinary(32)");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.Property("Username")
+ .IsRequired()
+ .HasMaxLength(32)
+ .HasColumnType("varchar(32)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Email")
+ .IsUnique();
+
+ b.HasIndex("Username")
+ .IsUnique();
+
+ b.ToTable("accounts", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.Character", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("AccountId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("AppearanceJson")
+ .HasColumnType("json");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("FacingDeg")
+ .HasColumnType("float");
+
+ b.Property("HpCurrent")
+ .HasColumnType("int unsigned");
+
+ b.Property("HpMax")
+ .HasColumnType("int unsigned");
+
+ b.Property("Level")
+ .HasColumnType("int unsigned");
+
+ b.Property("MpCurrent")
+ .HasColumnType("int unsigned");
+
+ b.Property("MpMax")
+ .HasColumnType("int unsigned");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(32)
+ .HasColumnType("varchar(32)");
+
+ b.Property("PosX")
+ .HasColumnType("double");
+
+ b.Property("PosY")
+ .HasColumnType("double");
+
+ b.Property("PosZ")
+ .HasColumnType("double");
+
+ b.Property("StaminaCurrent")
+ .HasColumnType("int unsigned");
+
+ b.Property("StaminaMax")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatDexterity")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatEndurance")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatIntelligence")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatStrength")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatWisdom")
+ .HasColumnType("int unsigned");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.Property("Xp")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("ZoneId")
+ .HasColumnType("bigint unsigned");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AccountId")
+ .IsUnique();
+
+ b.HasIndex("ZoneId");
+
+ b.ToTable("characters", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.EquipmentSlot", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("CharacterId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("ItemTemplateId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("SlotCode")
+ .HasColumnType("tinyint unsigned");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.HasKey("Id");
+
+ b.HasIndex("ItemTemplateId");
+
+ b.HasIndex("CharacterId", "SlotCode")
+ .IsUnique();
+
+ b.ToTable("equipment", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.InventoryItem", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("CharacterId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("ItemTemplateId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("Quantity")
+ .HasColumnType("int unsigned");
+
+ b.Property("SlotIndex")
+ .HasColumnType("int unsigned");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.HasKey("Id");
+
+ b.HasIndex("CharacterId");
+
+ b.HasIndex("ItemTemplateId");
+
+ b.HasIndex("CharacterId", "SlotIndex")
+ .IsUnique();
+
+ b.ToTable("inventories", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.ItemTemplate", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("ItemType")
+ .HasColumnType("tinyint unsigned");
+
+ b.Property("MaxStack")
+ .HasColumnType("int unsigned");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("varchar(64)");
+
+ b.Property("Rarity")
+ .HasColumnType("tinyint unsigned");
+
+ b.Property("StatsJson")
+ .HasColumnType("json");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.Property("Weight")
+ .HasColumnType("int unsigned");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Name")
+ .IsUnique();
+
+ b.ToTable("item_templates", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.Session", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("AccountId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("CreatedIp")
+ .HasMaxLength(64)
+ .HasColumnType("varchar(64)");
+
+ b.Property("ExpiresAt")
+ .HasColumnType("datetime(6)");
+
+ b.Property("RevokedAt")
+ .HasColumnType("datetime(6)");
+
+ b.Property("TokenHash")
+ .IsRequired()
+ .HasMaxLength(128)
+ .HasColumnType("varchar(128)");
+
+ b.Property("UserAgent")
+ .HasMaxLength(256)
+ .HasColumnType("varchar(256)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AccountId");
+
+ b.HasIndex("TokenHash")
+ .IsUnique();
+
+ b.ToTable("sessions", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.Zone", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("MaxX")
+ .HasColumnType("double");
+
+ b.Property("MaxY")
+ .HasColumnType("double");
+
+ b.Property("MaxZ")
+ .HasColumnType("double");
+
+ b.Property("MinX")
+ .HasColumnType("double");
+
+ b.Property("MinY")
+ .HasColumnType("double");
+
+ b.Property("MinZ")
+ .HasColumnType("double");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("varchar(64)");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.HasKey("Id");
+
+ b.HasIndex("Name")
+ .IsUnique();
+
+ b.ToTable("zones", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.Character", b =>
+ {
+ b.HasOne("Server.Data.Account", "Account")
+ .WithMany("Characters")
+ .HasForeignKey("AccountId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("Server.Data.Zone", "Zone")
+ .WithMany()
+ .HasForeignKey("ZoneId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired();
+
+ b.Navigation("Account");
+
+ b.Navigation("Zone");
+ });
+
+ modelBuilder.Entity("Server.Data.EquipmentSlot", b =>
+ {
+ b.HasOne("Server.Data.Character", "Character")
+ .WithMany()
+ .HasForeignKey("CharacterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("Server.Data.ItemTemplate", "ItemTemplate")
+ .WithMany()
+ .HasForeignKey("ItemTemplateId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired();
+
+ b.Navigation("Character");
+
+ b.Navigation("ItemTemplate");
+ });
+
+ modelBuilder.Entity("Server.Data.InventoryItem", b =>
+ {
+ b.HasOne("Server.Data.Character", "Character")
+ .WithMany()
+ .HasForeignKey("CharacterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("Server.Data.ItemTemplate", "ItemTemplate")
+ .WithMany()
+ .HasForeignKey("ItemTemplateId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired();
+
+ b.Navigation("Character");
+
+ b.Navigation("ItemTemplate");
+ });
+
+ modelBuilder.Entity("Server.Data.Session", b =>
+ {
+ b.HasOne("Server.Data.Account", "Account")
+ .WithMany("Sessions")
+ .HasForeignKey("AccountId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Account");
+ });
+
+ modelBuilder.Entity("Server.Data.Account", b =>
+ {
+ b.Navigation("Characters");
+
+ b.Navigation("Sessions");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/Migrations/20251110195003_UpdateSessions-revokation.cs b/Migrations/20251110195003_UpdateSessions-revokation.cs
new file mode 100644
index 0000000..90c2117
--- /dev/null
+++ b/Migrations/20251110195003_UpdateSessions-revokation.cs
@@ -0,0 +1,29 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace SystemRevivalServer.Migrations
+{
+ ///
+ public partial class UpdateSessionsrevokation : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn(
+ name: "RevokedAt",
+ table: "sessions",
+ type: "datetime(6)",
+ nullable: true);
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropColumn(
+ name: "RevokedAt",
+ table: "sessions");
+ }
+ }
+}
diff --git a/Migrations/GameDbContextModelSnapshot.cs b/Migrations/GameDbContextModelSnapshot.cs
index 21ef9be..e20f297 100644
--- a/Migrations/GameDbContextModelSnapshot.cs
+++ b/Migrations/GameDbContextModelSnapshot.cs
@@ -325,6 +325,9 @@ namespace SystemRevivalServer.Migrations
b.Property("ExpiresAt")
.HasColumnType("datetime(6)");
+ b.Property("RevokedAt")
+ .HasColumnType("datetime(6)");
+
b.Property("TokenHash")
.IsRequired()
.HasMaxLength(128)
diff --git a/Networking/IMessageBroadcaster.cs b/Networking/IMessageBroadcaster.cs
new file mode 100644
index 0000000..ef36dff
--- /dev/null
+++ b/Networking/IMessageBroadcaster.cs
@@ -0,0 +1,10 @@
+// Server.Networking/IMessageBroadcaster.cs
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Server.Networking;
+
+public interface IMessageBroadcaster
+{
+ Task BroadcastLocalAsync(int opcode, T payload, CancellationToken ct);
+}
diff --git a/Networking/Messages/CharContracts.cs b/Networking/Messages/CharContracts.cs
new file mode 100644
index 0000000..4548424
--- /dev/null
+++ b/Networking/Messages/CharContracts.cs
@@ -0,0 +1,15 @@
+namespace SystemRevivalServer.Networking.Messages
+{
+ public sealed record CharSummary(ulong CharacterId, string Name, int Level);
+
+ public sealed record CharListRequest(); // empty
+ public sealed record CharListResponse(bool Ok, string? Error, CharSummary[] Characters);
+
+ public sealed record CharCreateRequest(string Name);
+ public sealed record CharCreateResponse(bool Ok, string? Error, ulong CharacterId);
+
+ public sealed record CharSelectRequest(ulong CharacterId);
+ public sealed record CharSelectResponse(bool Ok, string? Error, ulong CharacterId, int ZoneId, float X, float Y, float Z);
+
+
+}
diff --git a/Networking/Messages/OpCodes.cs b/Networking/Messages/OpCodes.cs
index 2d58de9..a3bf5c3 100644
--- a/Networking/Messages/OpCodes.cs
+++ b/Networking/Messages/OpCodes.cs
@@ -13,5 +13,22 @@ public static class OpCodes
public const int AUTH_WITH_TOKEN = 112;
public const int AUTH_WITH_TOKEN_RESULT = 113;
- public const int ERROR = 900; // generic error envelope if you want
+ public const int ERROR = 900;
+
+ public const int CHAR_LIST = 200;
+ public const int CHAR_LIST_RESULT = 201;
+
+ public const int CHAR_CREATE = 202;
+ public const int CHAR_CREATE_RESULT = 203;
+
+ public const int CHAR_SELECT = 204;
+ public const int CHAR_SELECT_RESULT = 205;
+
+ public const int WORLD_SPAWN_REQUEST = 300; // client -> server (after select)
+ public const int WORLD_SPAWN = 301; // server -> client (your own + others joining)
+ public const int WORLD_DESPAWN = 302; // server -> client
+
+ public const int WORLD_INPUT = 310; // client -> server (per tick or at ~20 Hz)
+ public const int WORLD_STATE = 311; // server -> client (snapshots, ~10–20 Hz)
+
}
diff --git a/Networking/Messages/WorldContracts.cs b/Networking/Messages/WorldContracts.cs
new file mode 100644
index 0000000..7482d62
--- /dev/null
+++ b/Networking/Messages/WorldContracts.cs
@@ -0,0 +1,21 @@
+namespace SystemRevivalServer.Networking.Messages
+{
+ public sealed record WorldSpawnRequest(int ZoneId);
+ public sealed record WorldSpawn(
+ ulong CharacterId, string Name, int ZoneId,
+ float X, float Y, float Z, float Facing, float Speed);
+
+ public sealed record WorldDespawn(ulong CharacterId);
+
+ // Client input: normalized vector and an optional facing
+ public sealed record WorldInput(
+ int ZoneId, float Dx, float Dy, float Facing, uint ClientSeq);
+
+ // Server state snapshot (pack multiple entities)
+ public sealed record WorldEntityState(
+ ulong CharacterId, float X, float Y, float Z, float Facing, float Speed);
+
+ public sealed record WorldState(
+ int ZoneId, long Tick, WorldEntityState[] Entities);
+
+}
diff --git a/Program.cs b/Program.cs
index dd72871..44d2f89 100644
--- a/Program.cs
+++ b/Program.cs
@@ -14,6 +14,7 @@ using Server.Persistence;
using Server.Redis;
using Server.Services;
using Server.Services.Auth;
+using VoidScavengers.Game;
var builder = WebApplication.CreateBuilder(args);
@@ -52,6 +53,8 @@ builder.Services.AddSingleton();
builder.Services.AddSingleton(); // if not already
builder.Services.AddSingleton(); // add more handlers similarly
builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
// Health checks (optional DB/Redis implementations)
builder.Services.AddHealthChecks()
diff --git a/Services/Auth/ISessionRegistry.cs b/Services/Auth/ISessionRegistry.cs
index 7806a8f..a60169b 100644
--- a/Services/Auth/ISessionRegistry.cs
+++ b/Services/Auth/ISessionRegistry.cs
@@ -10,4 +10,7 @@ public interface ISessionRegistry
bool IsAuthenticated(Guid connectionId);
bool TryGetAccountId(Guid connectionId, out ulong accountId);
bool TryGet(Guid connectionId, out ulong accountId, out string token);
+ void BindCharacter(Guid connectionId, ulong characterId);
+ void UnbindCharacter(Guid connectionId);
+ bool TryGetCharacter(Guid connectionId, out ulong characterId);
}
diff --git a/Services/Auth/SessionRegistry.cs b/Services/Auth/SessionRegistry.cs
index a1bf0d2..d49f710 100644
--- a/Services/Auth/SessionRegistry.cs
+++ b/Services/Auth/SessionRegistry.cs
@@ -6,12 +6,16 @@ namespace Server.Services.Auth;
public sealed class SessionRegistry : ISessionRegistry
{
private readonly ConcurrentDictionary _byConn = new();
+ private readonly ConcurrentDictionary _charByConn = new();
public void Bind(Guid connectionId, ulong accountId, string token)
=> _byConn[connectionId] = (accountId, token);
public void Unbind(Guid connectionId)
- => _byConn.TryRemove(connectionId, out _);
+ {
+ _byConn.TryRemove(connectionId, out _);
+ _charByConn.TryRemove(connectionId, out _);
+ }
public bool IsAuthenticated(Guid connectionId)
=> _byConn.ContainsKey(connectionId);
@@ -28,4 +32,12 @@ public sealed class SessionRegistry : ISessionRegistry
{ accountId = v.accountId; token = v.token; return true; }
accountId = 0; token = string.Empty; return false;
}
+ public void BindCharacter(Guid connectionId, ulong characterId)
+ => _charByConn[connectionId] = characterId;
+
+ public void UnbindCharacter(Guid connectionId)
+ => _charByConn.TryRemove(connectionId, out _);
+
+ public bool TryGetCharacter(Guid connectionId, out ulong characterId)
+ => _charByConn.TryGetValue(connectionId, out characterId);
}
diff --git a/Services/Characters/CharacterService.cs b/Services/Characters/CharacterService.cs
new file mode 100644
index 0000000..9971425
--- /dev/null
+++ b/Services/Characters/CharacterService.cs
@@ -0,0 +1,82 @@
+// Server.Services.Characters/CharacterService.cs
+using Microsoft.Extensions.Logging;
+using Server.Data;
+
+namespace Server.Services.Characters;
+
+public sealed class CharacterService : ICharacterService
+{
+ private readonly ILogger _log;
+ private readonly ICharactersRepository _repo;
+
+ public CharacterService(ILogger log, ICharactersRepository repo)
+ { _log = log; _repo = repo; }
+
+ public async Task<(bool ok, string? error, Character[] list)> ListAsync(ulong accountId, CancellationToken ct)
+ {
+ var one = await _repo.FindByAccountAsync(accountId, ct);
+ return (true, null, one is null ? Array.Empty() : new[] { one });
+ }
+
+ public async Task<(bool ok, string? error, Character created)> CreateAsync(ulong accountId, string name, CancellationToken ct)
+ {
+ if (string.IsNullOrWhiteSpace(name) || name.Length is < 3 or > 32)
+ return (false, "invalid_name", null!);
+
+ name = name.Trim();
+
+ // 1 char / account
+ if (await _repo.FindByAccountAsync(accountId, ct) is not null)
+ return (false, "char_limit", null!);
+
+ // unique names
+ if (await _repo.FindByNameAsync(name, ct) is not null)
+ return (false, "name_taken", null!);
+
+ var now = DateTime.UtcNow;
+
+ var c = new Character
+ {
+ AccountId = accountId,
+ Name = name,
+
+ Level = 1,
+ Xp = 0,
+
+ StatStrength = 1,
+ StatDexterity = 1,
+ StatWisdom = 1,
+ StatIntelligence = 1,
+ StatEndurance = 1,
+
+ HpCurrent = 10,
+ HpMax = 10,
+ MpCurrent = 0,
+ MpMax = 0,
+ StaminaCurrent = 0,
+ StaminaMax = 0,
+
+ ZoneId = 1,
+ PosX = 0,
+ PosY = 0,
+ PosZ = 0,
+ FacingDeg = 0f,
+
+ AppearanceJson = null,
+ CreatedAt = now,
+ UpdatedAt = now
+ };
+
+ var created = await _repo.AddAsync(c, ct);
+ _log.LogInformation("Character {Id} '{Name}' created for account {Acct}", created.Id, created.Name, accountId);
+ return (true, null, created);
+ }
+
+ public async Task<(bool ok, string? error, Character selected)> SelectAsync(ulong accountId, ulong characterId, CancellationToken ct)
+ {
+ var c = await _repo.FindByIdAsync(characterId, ct);
+ if (c is null || c.AccountId != accountId)
+ return (false, "char_not_found", null!);
+ return (true, null, c);
+ }
+}
diff --git a/Services/Characters/ICharacterRepository.cs b/Services/Characters/ICharacterRepository.cs
new file mode 100644
index 0000000..3440a04
--- /dev/null
+++ b/Services/Characters/ICharacterRepository.cs
@@ -0,0 +1,36 @@
+using Microsoft.EntityFrameworkCore;
+
+namespace Server.Data;
+
+public interface ICharactersRepository
+{
+ Task FindByIdAsync(ulong id, CancellationToken ct);
+ Task FindByNameAsync(string name, CancellationToken ct);
+ Task FindByAccountAsync(ulong accountId, CancellationToken ct); // 1 char / account (unique)
+ Task AddAsync(Character c, CancellationToken ct);
+ Task SaveAsync(CancellationToken ct);
+}
+
+public sealed class CharactersRepository : ICharactersRepository
+{
+ private readonly GameDbContext _db;
+ public CharactersRepository(GameDbContext db) => _db = db;
+
+ public Task FindByIdAsync(ulong id, CancellationToken ct) =>
+ _db.Characters.FirstOrDefaultAsync(x => x.Id == id, ct);
+
+ public Task FindByNameAsync(string name, CancellationToken ct) =>
+ _db.Characters.FirstOrDefaultAsync(x => x.Name == name, ct);
+
+ public Task FindByAccountAsync(ulong accountId, CancellationToken ct) =>
+ _db.Characters.FirstOrDefaultAsync(x => x.AccountId == accountId, ct);
+
+ public async Task AddAsync(Character c, CancellationToken ct)
+ {
+ _db.Characters.Add(c);
+ await _db.SaveChangesAsync(ct);
+ return c;
+ }
+
+ public Task SaveAsync(CancellationToken ct) => _db.SaveChangesAsync(ct);
+}
diff --git a/Services/Characters/ICharacterService.cs b/Services/Characters/ICharacterService.cs
new file mode 100644
index 0000000..cd34b03
--- /dev/null
+++ b/Services/Characters/ICharacterService.cs
@@ -0,0 +1,10 @@
+using Server.Data;
+
+namespace Server.Services.Characters;
+
+public interface ICharacterService
+{
+ Task<(bool ok, string? error, Character[] list)> ListAsync(ulong accountId, CancellationToken ct);
+ Task<(bool ok, string? error, Character created)> CreateAsync(ulong accountId, string name, CancellationToken ct);
+ Task<(bool ok, string? error, Character selected)> SelectAsync(ulong accountId, ulong characterId, CancellationToken ct);
+}
diff --git a/Services/World/WorldHandler.cs b/Services/World/WorldHandler.cs
new file mode 100644
index 0000000..3bbb4a8
--- /dev/null
+++ b/Services/World/WorldHandler.cs
@@ -0,0 +1,89 @@
+// Server.Services.World/WorldHandler.cs
+using Microsoft.Extensions.Logging;
+using Server.Networking;
+using Server.Networking.Handling;
+using Server.Networking.Messages;
+using Server.Services.Auth;
+using SystemRevivalServer.Networking.Messages;
+
+namespace Server.Services.World;
+
+public sealed class WorldHandler : IClientMessageHandler
+{
+ private readonly ILogger _log;
+ private readonly IWorldService _world;
+ private readonly ISessionRegistry _sessions;
+ private readonly IZoneLeaseService _lease;
+ private readonly IMessageSerializer _ser;
+ private readonly HandlerContext _ctx;
+
+ public WorldHandler(
+ ILogger log,
+ IWorldService world,
+ ISessionRegistry sessions,
+ IZoneLeaseService lease,
+ IMessageSerializer ser)
+ {
+ _log = log; _world = world; _sessions = sessions; _lease = lease; _ser = ser;
+ _ctx = new HandlerContext(ser);
+ }
+
+ public IReadOnlyCollection SupportedOpCodes => new[]
+ {
+ OpCodes.WORLD_SPAWN_REQUEST,
+ OpCodes.WORLD_INPUT
+ };
+
+ public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ // Expect: TryGet(connId, out accountId, out token)
+ if (!_sessions.TryGet(connection.Id, out var accountId, out var token))
+ {
+ await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = "auth_required" }, ct);
+ return;
+ }
+
+ // Expect: TryGetCharacter(connId, out characterId) ← add this to ISessionRegistry if missing
+ if (!_sessions.TryGetCharacter(connection.Id, out var charId))
+ {
+ await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = "character_required" }, ct);
+ return;
+ }
+
+ switch (opCode)
+ {
+ case OpCodes.WORLD_SPAWN_REQUEST:
+ {
+ var req = _ser.Deserialize(payload);
+ if (!_lease.IsOwner((ulong)req.ZoneId))
+ {
+ await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = "not_owner_zone" }, ct);
+ return;
+ }
+
+ var result = await _world.SpawnAsync(accountId, charId, ct);
+ var ok = result.ok; var error = result.error; var self = result.self; var neighbors = result.neighbors;
+
+ if (!ok)
+ {
+ await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = error ?? "spawn_failed" }, ct);
+ return;
+ }
+
+ await _ctx.ReplyObjectAsync(connection, OpCodes.WORLD_SPAWN, self, ct);
+ foreach (var n in neighbors)
+ await _ctx.ReplyObjectAsync(connection, OpCodes.WORLD_SPAWN, n, ct);
+ break;
+ }
+
+ case OpCodes.WORLD_INPUT:
+ {
+ var req = _ser.Deserialize(payload);
+ if (!_lease.IsOwner((ulong)req.ZoneId)) return; // ignore for MVP
+ _world.EnqueueInput((ulong)req.ZoneId, charId, req.Dx, req.Dy, req.Facing, req.ClientSeq);
+ break;
+ }
+ }
+ }
+
+}
diff --git a/Services/World/WorldService.cs b/Services/World/WorldService.cs
new file mode 100644
index 0000000..5e84734
--- /dev/null
+++ b/Services/World/WorldService.cs
@@ -0,0 +1,122 @@
+// Server.Services.World/WorldService.cs
+using System.Collections.Concurrent;
+using Microsoft.Extensions.Logging;
+using Server.Data;
+using Server.World;
+using StackExchange.Redis;
+using SystemRevivalServer.Networking.Messages;
+
+namespace Server.Services.World;
+
+public sealed class WorldService : IWorldService
+{
+ private readonly ILogger _log;
+ private readonly ICharactersRepository _chars;
+ private readonly IPresenceStore _presence;
+ private readonly IDatabase _db; // Redis
+ private readonly TimeSpan _cellTtl = TimeSpan.FromSeconds(30);
+
+ // In-memory zone state (per owner node)
+ private sealed record Entity(ulong Id, string Name, float X, float Y, float Z, float FacingRad, float Speed);
+
+ private readonly ConcurrentDictionary> _zones = new();
+ private readonly ConcurrentDictionary> _inputs = new();
+
+ public WorldService(
+ ILogger log,
+ ICharactersRepository chars,
+ IPresenceStore presence,
+ IDatabase db)
+ {
+ _log = log; _chars = chars; _presence = presence; _db = db;
+ }
+
+ public async Task<(bool ok, string? error, WorldSpawn self, IEnumerable neighbors)>
+ SpawnAsync(ulong accountId, ulong characterId, CancellationToken ct)
+ {
+ // Prefer Redis presence; fallback to DB row.
+ var pos = await _presence.GetAsync(characterId, ct);
+ Character? row;
+
+ if (pos is null)
+ {
+ row = await _chars.FindByIdAsync(characterId, ct);
+ if (row is null || row.AccountId != accountId)
+ return (false, "char_not_found", default!, Array.Empty());
+
+ var facingRad = row.FacingDeg * (MathF.PI / 180f);
+ pos = new Pos(row.ZoneId, (float)row.PosX, (float)row.PosY, (float)row.PosZ, facingRad);
+ await _presence.SetAsync(characterId, pos, ct);
+ }
+ else
+ {
+ row = await _chars.FindByIdAsync(characterId, ct);
+ if (row is null)
+ return (false, "char_not_found", default!, Array.Empty());
+ }
+
+ // Update spatial cell
+ var cell = SpatialIndex.Cell(pos.X, pos.Y, pos.Z);
+ await SpatialIndex.UpdateAsync(_db, pos.ZoneId, characterId, cell, cell, _cellTtl);
+
+ // Track in-memory entity
+ var zone = _zones.GetOrAdd(pos.ZoneId, _ => new());
+ var ent = new Entity(characterId, row!.Name, pos.X, pos.Y, pos.Z, pos.FacingRad, 5f);
+ zone[characterId] = ent;
+
+ var self = new WorldSpawn(ent.Id, ent.Name, (int)pos.ZoneId, ent.X, ent.Y, ent.Z, ent.FacingRad, ent.Speed);
+ var neighbors = zone.Values.Where(e => e.Id != ent.Id)
+ .Select(e => new WorldSpawn(e.Id, e.Name, (int)pos.ZoneId, e.X, e.Y, e.Z, e.FacingRad, e.Speed))
+ .ToArray();
+
+ return (true, null, self, neighbors);
+ }
+
+
+
+ public void EnqueueInput(ulong zoneId, ulong characterId, float dx, float dy, float facingRad, uint clientSeq)
+ {
+ var q = _inputs.GetOrAdd(zoneId, _ => new());
+ q.Enqueue((characterId, dx, dy, facingRad));
+ }
+
+ public async Task TickOwnerAsync(ulong zoneId, float dt, CancellationToken ct)
+ {
+ if (!_zones.TryGetValue(zoneId, out var ents)) return;
+
+ if (_inputs.TryGetValue(zoneId, out var q))
+ {
+ while (q.TryDequeue(out var itm))
+ {
+ if (!ents.TryGetValue(itm.CharId, out var e)) continue;
+
+ // Normalize input
+ var dx = itm.Dx; var dy = itm.Dy;
+ var mag = MathF.Sqrt(dx * dx + dy * dy);
+ if (mag > 1e-4f) { dx /= mag; dy /= mag; }
+
+ var nx = e.X + dx * e.Speed * dt;
+ var ny = e.Y + dy * e.Speed * dt;
+ var nf = float.IsFinite(itm.FacingRad) ? itm.FacingRad : e.FacingRad;
+
+ var updated = e with { X = nx, Y = ny, FacingRad = nf };
+ ents[e.Id] = updated;
+
+ await _presence.SetAsync(e.Id, new Pos(zoneId, nx, ny, e.Z, nf), ct);
+
+ var oldCell = SpatialIndex.Cell(e.X, e.Y, e.Z);
+ var newCell = SpatialIndex.Cell(nx, ny, e.Z);
+ await SpatialIndex.UpdateAsync(_db, zoneId, e.Id, oldCell, newCell, _cellTtl);
+ }
+ }
+ }
+
+ public WorldState BuildSnapshot(ulong zoneId, long tick)
+ {
+ if (!_zones.TryGetValue(zoneId, out var ents))
+ return new WorldState((int)zoneId, tick, Array.Empty());
+
+ var list = ents.Values.Select(e => new WorldEntityState(e.Id, e.X, e.Y, e.Z, e.FacingRad, e.Speed)).ToArray();
+ return new WorldState((int)zoneId, tick, list);
+ }
+}
diff --git a/World/IWorldService.cs b/World/IWorldService.cs
new file mode 100644
index 0000000..ee8e766
--- /dev/null
+++ b/World/IWorldService.cs
@@ -0,0 +1,23 @@
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using SystemRevivalServer.Networking.Messages;
+
+namespace Server.Services.World;
+
+public interface IWorldService
+{
+ /// Spawn the selected character into the world (owner-only).
+ /// Returns the player's own spawn data and a list of already-present neighbors to display.
+ Task<(bool ok, string? error, WorldSpawn self, IEnumerable neighbors)>
+ SpawnAsync(ulong accountId, ulong characterId, CancellationToken ct);
+
+ /// Queue a client input for the zone owner to process.
+ void EnqueueInput(ulong zoneId, ulong characterId, float dx, float dy, float facingRad, uint clientSeq);
+
+ /// Owner tick: integrate movement, update presence/grid.
+ Task TickOwnerAsync(ulong zoneId, float dt, CancellationToken ct);
+
+ /// Build a snapshot (naive: full-zone). Call at 10Hz and broadcast.
+ WorldState BuildSnapshot(ulong zoneId, long tick);
+}
diff --git a/World/PresenceModels.cs b/World/PresenceModels.cs
new file mode 100644
index 0000000..b70c020
--- /dev/null
+++ b/World/PresenceModels.cs
@@ -0,0 +1,4 @@
+namespace Server.World;
+
+public sealed record Pos(ulong ZoneId, float X, float Y, float Z, float FacingRad);
+
diff --git a/World/RedisPresenceStore.cs b/World/RedisPresenceStore.cs
new file mode 100644
index 0000000..c48d95f
--- /dev/null
+++ b/World/RedisPresenceStore.cs
@@ -0,0 +1,42 @@
+// Server.World/Presence.cs
+using StackExchange.Redis;
+
+namespace Server.World;
+
+public interface IPresenceStore
+{
+ Task SetAsync(ulong charId, Pos p, CancellationToken ct);
+ Task GetAsync(ulong charId, CancellationToken ct);
+}
+
+public sealed class RedisPresenceStore : IPresenceStore
+{
+ private readonly IDatabase _db;
+ public RedisPresenceStore(IDatabase db) => _db = db;
+ private static RedisKey PKey(ulong cid) => new($"p:{cid}:pos");
+
+ public async Task SetAsync(ulong charId, Pos p, CancellationToken ct)
+ {
+ var entries = new HashEntry[]
+ {
+ new("zone", (long)p.ZoneId),
+ new("x", p.X), new("y", p.Y), new("z", p.Z),
+ new("facingRad", p.FacingRad),
+ new("ts", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()),
+ };
+ await _db.HashSetAsync(PKey(charId), entries);
+ }
+
+ public async Task GetAsync(ulong charId, CancellationToken ct)
+ {
+ var vals = await _db.HashGetAllAsync(PKey(charId));
+ if (vals.Length == 0) return null;
+
+ ulong zone = (ulong)(long)vals.First(v => v.Name == "zone").Value;
+ float x = (float)vals.First(v => v.Name == "x").Value;
+ float y = (float)vals.First(v => v.Name == "y").Value;
+ float z = (float)vals.First(v => v.Name == "z").Value;
+ float f = (float)vals.First(v => v.Name == "facingRad").Value;
+ return new Pos(zone, x, y, z, f);
+ }
+}