This commit is contained in:
dingo
2025-11-29 15:44:45 -05:00
parent 9c75aaafc9
commit bc8cbab8ce
23 changed files with 3333 additions and 2 deletions
+233
View File
@@ -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);
+806
View File
@@ -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;
/// <summary>
/// Handles all game-related messages and manages match instances.
/// Integrates with the existing SystemRevival server architecture.
/// </summary>
public sealed class GameHandler : IClientMessageHandler
{
private readonly ILogger<GameHandler> _log;
private readonly ISessionRegistry _sessions;
private readonly IMessageSerializer _ser;
private readonly MatchManager _matchManager;
public GameHandler(
ILogger<GameHandler> log,
ISessionRegistry sessions,
IMessageSerializer ser,
MatchManager matchManager)
{
_log = log;
_sessions = sessions;
_ser = ser;
_matchManager = matchManager;
}
public IReadOnlyCollection<int> 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<byte> 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<byte> payload, CancellationToken ct)
{
var request = _ser.Deserialize<LobbyJoinRequest>(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<byte> payload, CancellationToken ct)
{
var request = _ser.Deserialize<LobbyReadyRequest>(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<byte> payload, CancellationToken ct)
{
var input = _ser.Deserialize<MoveInputMsg>(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<byte> payload, CancellationToken ct)
{
var input = _ser.Deserialize<ShootInputMsg>(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<byte> payload, CancellationToken ct)
{
var input = _ser.Deserialize<ActionInputMsg>(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<byte> payload, CancellationToken ct)
{
var input = _ser.Deserialize<CraftInputMsg>(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<byte> payload, CancellationToken ct)
{
var input = _ser.Deserialize<DropInputMsg>(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<byte> payload, CancellationToken ct)
{
var msg = _ser.Deserialize<ChatMsg>(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<T>(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);
/// <summary>
/// Static OpCodes class for game-specific operations
/// </summary>
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;
}
/// <summary>
/// Manages lobbies, matchmaking, and active game instances
/// </summary>
public sealed class MatchManager : IDisposable
{
private readonly ILogger<MatchManager> _log;
private readonly IMessageSerializer _ser;
private readonly ConcurrentDictionary<string, Lobby> _lobbies = new();
private readonly ConcurrentDictionary<string, MatchInstance> _matches = new();
private readonly ConcurrentDictionary<ulong, string> _playerToLobby = new();
private readonly ConcurrentDictionary<ulong, string> _playerToMatch = new();
private readonly ConcurrentDictionary<ulong, IConnection> _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<MatchManager> 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<ulong, IConnection>? 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<T>(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<ulong, LobbyPlayer> 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<ulong, IConnection> Connections { get; } = new();
}
+45
View File
@@ -0,0 +1,45 @@
namespace VoidScavengers.Networking.Messages;
/// <summary>
/// OpCodes for Void Scavengers game - extends base OpCodes
/// </summary>
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
}
File diff suppressed because it is too large Load Diff
+241
View File
@@ -0,0 +1,241 @@
namespace VoidScavengers.Game;
/// <summary>
/// Item definitions for Void Scavengers
/// </summary>
public static class ItemDatabase
{
public static readonly Dictionary<int, ItemDef> 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
}
/// <summary>
/// Crafting recipes
/// </summary>
public static class RecipeDatabase
{
public static readonly Dictionary<int, Recipe> 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);
}
}
@@ -0,0 +1,481 @@
// <auto-generated />
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
{
/// <inheritdoc />
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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<DateTime?>("BannedUntil")
.HasColumnType("datetime(6)");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<string>("Email")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<bool>("IsBanned")
.HasColumnType("tinyint(1)");
b.Property<byte[]>("PasswordHash")
.IsRequired()
.HasColumnType("varbinary(64)");
b.Property<byte[]>("PasswordSalt")
.IsRequired()
.HasColumnType("varbinary(32)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<string>("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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("AccountId")
.HasColumnType("bigint unsigned");
b.Property<string>("AppearanceJson")
.HasColumnType("json");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<float>("FacingDeg")
.HasColumnType("float");
b.Property<uint>("HpCurrent")
.HasColumnType("int unsigned");
b.Property<uint>("HpMax")
.HasColumnType("int unsigned");
b.Property<uint>("Level")
.HasColumnType("int unsigned");
b.Property<uint>("MpCurrent")
.HasColumnType("int unsigned");
b.Property<uint>("MpMax")
.HasColumnType("int unsigned");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("varchar(32)");
b.Property<double>("PosX")
.HasColumnType("double");
b.Property<double>("PosY")
.HasColumnType("double");
b.Property<double>("PosZ")
.HasColumnType("double");
b.Property<uint>("StaminaCurrent")
.HasColumnType("int unsigned");
b.Property<uint>("StaminaMax")
.HasColumnType("int unsigned");
b.Property<uint>("StatDexterity")
.HasColumnType("int unsigned");
b.Property<uint>("StatEndurance")
.HasColumnType("int unsigned");
b.Property<uint>("StatIntelligence")
.HasColumnType("int unsigned");
b.Property<uint>("StatStrength")
.HasColumnType("int unsigned");
b.Property<uint>("StatWisdom")
.HasColumnType("int unsigned");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<ulong>("Xp")
.HasColumnType("bigint unsigned");
b.Property<ulong>("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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("CharacterId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<ulong>("ItemTemplateId")
.HasColumnType("bigint unsigned");
b.Property<byte>("SlotCode")
.HasColumnType("tinyint unsigned");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("CharacterId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<ulong>("ItemTemplateId")
.HasColumnType("bigint unsigned");
b.Property<uint>("Quantity")
.HasColumnType("int unsigned");
b.Property<uint>("SlotIndex")
.HasColumnType("int unsigned");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<byte>("ItemType")
.HasColumnType("tinyint unsigned");
b.Property<uint>("MaxStack")
.HasColumnType("int unsigned");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<byte>("Rarity")
.HasColumnType("tinyint unsigned");
b.Property<string>("StatsJson")
.HasColumnType("json");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<uint>("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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("AccountId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<string>("CreatedIp")
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("datetime(6)");
b.Property<DateTime?>("RevokedAt")
.HasColumnType("datetime(6)");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("varchar(128)");
b.Property<string>("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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<double>("MaxX")
.HasColumnType("double");
b.Property<double>("MaxY")
.HasColumnType("double");
b.Property<double>("MaxZ")
.HasColumnType("double");
b.Property<double>("MinX")
.HasColumnType("double");
b.Property<double>("MinY")
.HasColumnType("double");
b.Property<double>("MinZ")
.HasColumnType("double");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("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
}
}
}
@@ -0,0 +1,29 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SystemRevivalServer.Migrations
{
/// <inheritdoc />
public partial class UpdateSessionsrevokation : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "RevokedAt",
table: "sessions",
type: "datetime(6)",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RevokedAt",
table: "sessions");
}
}
}
+3
View File
@@ -325,6 +325,9 @@ namespace SystemRevivalServer.Migrations
b.Property<DateTime>("ExpiresAt")
.HasColumnType("datetime(6)");
b.Property<DateTime?>("RevokedAt")
.HasColumnType("datetime(6)");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(128)
+10
View File
@@ -0,0 +1,10 @@
// Server.Networking/IMessageBroadcaster.cs
using System.Threading;
using System.Threading.Tasks;
namespace Server.Networking;
public interface IMessageBroadcaster
{
Task BroadcastLocalAsync<T>(int opcode, T payload, CancellationToken ct);
}
+15
View File
@@ -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);
}
+18 -1
View File
@@ -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)
}
+21
View File
@@ -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);
}
+3
View File
@@ -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<ISessionRegistry, SessionRegistry>();
builder.Services.AddSingleton<IMessageSerializer, JsonSerializerAdapter>(); // if not already
builder.Services.AddSingleton<IClientMessageHandler, AuthHandler>(); // add more handlers similarly
builder.Services.AddSingleton<MessageRouter>();
builder.Services.AddSingleton<MatchManager>();
builder.Services.AddSingleton<IClientMessageHandler, GameHandler>();
// Health checks (optional DB/Redis implementations)
builder.Services.AddHealthChecks()
+3
View File
@@ -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);
}
+13 -1
View File
@@ -6,12 +6,16 @@ namespace Server.Services.Auth;
public sealed class SessionRegistry : ISessionRegistry
{
private readonly ConcurrentDictionary<Guid, (ulong accountId, string token)> _byConn = new();
private readonly ConcurrentDictionary<Guid, ulong> _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);
}
+82
View File
@@ -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<CharacterService> _log;
private readonly ICharactersRepository _repo;
public CharacterService(ILogger<CharacterService> 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<Character>() : 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);
}
}
@@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore;
namespace Server.Data;
public interface ICharactersRepository
{
Task<Character?> FindByIdAsync(ulong id, CancellationToken ct);
Task<Character?> FindByNameAsync(string name, CancellationToken ct);
Task<Character?> FindByAccountAsync(ulong accountId, CancellationToken ct); // 1 char / account (unique)
Task<Character> 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<Character?> FindByIdAsync(ulong id, CancellationToken ct) =>
_db.Characters.FirstOrDefaultAsync(x => x.Id == id, ct);
public Task<Character?> FindByNameAsync(string name, CancellationToken ct) =>
_db.Characters.FirstOrDefaultAsync(x => x.Name == name, ct);
public Task<Character?> FindByAccountAsync(ulong accountId, CancellationToken ct) =>
_db.Characters.FirstOrDefaultAsync(x => x.AccountId == accountId, ct);
public async Task<Character> AddAsync(Character c, CancellationToken ct)
{
_db.Characters.Add(c);
await _db.SaveChangesAsync(ct);
return c;
}
public Task SaveAsync(CancellationToken ct) => _db.SaveChangesAsync(ct);
}
+10
View File
@@ -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);
}
+89
View File
@@ -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<WorldHandler> _log;
private readonly IWorldService _world;
private readonly ISessionRegistry _sessions;
private readonly IZoneLeaseService _lease;
private readonly IMessageSerializer _ser;
private readonly HandlerContext _ctx;
public WorldHandler(
ILogger<WorldHandler> 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<int> SupportedOpCodes => new[]
{
OpCodes.WORLD_SPAWN_REQUEST,
OpCodes.WORLD_INPUT
};
public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory<byte> 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<WorldSpawnRequest>(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<WorldInput>(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;
}
}
}
}
+122
View File
@@ -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<WorldService> _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<ulong, ConcurrentDictionary<ulong, Entity>> _zones = new();
private readonly ConcurrentDictionary<ulong, ConcurrentQueue<(ulong CharId, float Dx, float Dy, float FacingRad)>> _inputs = new();
public WorldService(
ILogger<WorldService> 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<WorldSpawn> 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<WorldSpawn>());
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<WorldSpawn>());
}
// 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<WorldEntityState>());
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);
}
}
+23
View File
@@ -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<WorldSpawn> 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);
}
+4
View File
@@ -0,0 +1,4 @@
namespace Server.World;
public sealed record Pos(ulong ZoneId, float X, float Y, float Z, float FacingRad);
+42
View File
@@ -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<Pos?> 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<Pos?> 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);
}
}