diff --git a/Persistence/IWalPublisher.cs b/Persistence/IWalPublisher.cs deleted file mode 100644 index 4d4a7d4..0000000 --- a/Persistence/IWalPublisher.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace Server.Persistence; -public interface IWalPublisher -{ - Task PublishAsync(string type, ulong charId, ulong zoneId, object payload, long tickId); -} diff --git a/Persistence/WalPublisher.cs b/Persistence/WalPublisher.cs deleted file mode 100644 index e8c6dd1..0000000 --- a/Persistence/WalPublisher.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Text.Json; -using Server.Redis; - -namespace Server.Persistence; - -public sealed class WalPublisher : IWalPublisher -{ - private readonly IRedisManager _redis; - public WalPublisher(IRedisManager redis) { _redis = redis; } - - public async Task PublishAsync(string type, ulong charId, ulong zoneId, object payload, long tickId) - { - var ev = new - { - eventId = Guid.NewGuid().ToString("N"), - type, - charId, - zoneId, - tickId, - ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), - payload = payload - }; - var json = JsonSerializer.Serialize(ev); - await _redis.Db.StreamAddAsync("wal:game", new StackExchange.Redis.NameValueEntry[] { - new("data", json) - }, maxLength: 1_000_000, useApproximateMaxLength: true); - } -} diff --git a/Program.cs b/Program.cs index eaae2e9..8a5e01f 100644 --- a/Program.cs +++ b/Program.cs @@ -11,7 +11,6 @@ using DataServer.Data; using Server.Networking; using Server.Networking.Handling; using Server.Networking.Messages; -using Server.Persistence; using Server.Redis; using Server.Services; using Server.Services.Auth; @@ -60,9 +59,6 @@ builder.Services.AddOptions() // Redis + zone leases + WAL builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddHostedService(sp => (ZoneLeaseService)sp.GetRequiredService()); -builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); diff --git a/Services/Characters/CharacterService.cs b/Services/Characters/CharacterService.cs deleted file mode 100644 index 75865e9..0000000 --- a/Services/Characters/CharacterService.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Server.Services.Characters/CharacterService.cs -using Microsoft.Extensions.Logging; -using DataServer.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, Old_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, Old_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 Old_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, Old_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 deleted file mode 100644 index 012ea69..0000000 --- a/Services/Characters/ICharacterRepository.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Microsoft.EntityFrameworkCore; - -namespace DataServer.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(Old_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(Old_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 deleted file mode 100644 index 030b3c8..0000000 --- a/Services/Characters/ICharacterService.cs +++ /dev/null @@ -1,10 +0,0 @@ -using DataServer.Data; - -namespace Server.Services.Characters; - -public interface ICharacterService -{ - Task<(bool ok, string? error, Old_Character[] list)> ListAsync(ulong accountId, CancellationToken ct); - Task<(bool ok, string? error, Old_Character created)> CreateAsync(ulong accountId, string name, CancellationToken ct); - Task<(bool ok, string? error, Old_Character selected)> SelectAsync(ulong accountId, ulong characterId, CancellationToken ct); -} diff --git a/Services/IZoneLeaseService.cs b/Services/IZoneLeaseService.cs deleted file mode 100644 index 0354f7e..0000000 --- a/Services/IZoneLeaseService.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Server.Services; -public interface IZoneLeaseService -{ - ValueTask TryAcquireAsync(ulong zoneId, CancellationToken ct = default); - ValueTask RenewAsync(ulong zoneId, CancellationToken ct = default); - ValueTask ReleaseAsync(ulong zoneId, CancellationToken ct = default); - bool IsOwner(ulong zoneId); - long CurrentFence(ulong zoneId); -} diff --git a/Services/World/WorldHandler.cs b/Services/World/WorldHandler.cs deleted file mode 100644 index e1592f8..0000000 --- a/Services/World/WorldHandler.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Server.Services.World/WorldHandler.cs -using Server.Networking; -using Server.Networking.Handling; -using Server.Networking.Messages; -using Server.Services.Auth; - -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 deleted file mode 100644 index 02e1b5b..0000000 --- a/Services/World/WorldService.cs +++ /dev/null @@ -1,122 +0,0 @@ -// Server.Services.World/WorldService.cs -using System.Collections.Concurrent; -using Microsoft.Extensions.Logging; -using DataServer.Data; -using Server.World; -using StackExchange.Redis; -using Server.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); - Old_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/Services/ZoneLeaseService.cs b/Services/ZoneLeaseService.cs deleted file mode 100644 index a69423b..0000000 --- a/Services/ZoneLeaseService.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.Collections.Concurrent; -using Microsoft.Extensions.Logging; -using Server.Redis; - -namespace Server.Services; - -public sealed class ZoneLeaseService : IZoneLeaseService, IHostedService, IDisposable -{ - private readonly IRedisManager _redis; - private readonly ILogger _log; - private readonly string _podId = Environment.GetEnvironmentVariable("POD_ID") ?? Guid.NewGuid().ToString("N"); - private readonly TimeSpan _ttl = TimeSpan.FromSeconds(5); - private readonly TimeSpan _renew = TimeSpan.FromSeconds(2); - private readonly ConcurrentDictionary _owned = new(); - private Timer? _timer; - - public ZoneLeaseService(IRedisManager redis, ILogger log) - { _redis = redis; _log = log; } - - public bool IsOwner(ulong zoneId) => _owned.ContainsKey(zoneId); - public long CurrentFence(ulong zoneId) => _owned.TryGetValue(zoneId, out var f) ? f : -1; - - public async ValueTask TryAcquireAsync(ulong zoneId, CancellationToken ct = default) - { - var fence = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var val = $"{_podId}:{fence}"; - var key = $"zone:owner:{{{zoneId}}}"; // hash tag for cluster - var ok = await _redis.Db.StringSetAsync(key, val, _ttl, when: StackExchange.Redis.When.NotExists); - if (ok) { _owned[zoneId] = fence; _log.LogInformation("Zone {Zone} acquired, fence={Fence}", zoneId, fence); } - return ok; - } - - public async ValueTask RenewAsync(ulong zoneId, CancellationToken ct = default) - { - if (!_owned.TryGetValue(zoneId, out var fence)) return false; - var key = $"zone:owner:{{{zoneId}}}"; - // renew if matches (Lua CAS) - const string lua = @" - if redis.call('GET', KEYS[1]) == ARGV[1] then - redis.call('PEXPIRE', KEYS[1], ARGV[2]); return 1 - else return 0 end"; - var res = (int)(long)await _redis.Db.ScriptEvaluateAsync(lua, - new StackExchange.Redis.RedisKey[] { key }, - new StackExchange.Redis.RedisValue[] { $"{_podId}:{fence}", (long)_ttl.TotalMilliseconds }); - return res == 1; - } - - public async ValueTask ReleaseAsync(ulong zoneId, CancellationToken ct = default) - { - if (!_owned.TryRemove(zoneId, out var fence)) return; - var key = $"zone:owner:{{{zoneId}}}"; - const string lua = @"if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end"; - await _redis.Db.ScriptEvaluateAsync(lua, - new StackExchange.Redis.RedisKey[] { key }, - new StackExchange.Redis.RedisValue[] { $"{_podId}:{fence}" }); - _log.LogInformation("Zone {Zone} released", zoneId); - } - - // Background renew loop - public Task StartAsync(CancellationToken _) { _timer = new Timer(async _ => await RenewAll(), null, _renew, _renew); return Task.CompletedTask; } - public Task StopAsync(CancellationToken _) { _timer?.Dispose(); return Task.CompletedTask; } - private async Task RenewAll() - { - foreach (var z in _owned.Keys) { if (!await RenewAsync(z)) _owned.TryRemove(z, out _); } - } - public void Dispose() => _timer?.Dispose(); -} diff --git a/World/IWorldService.cs b/World/IWorldService.cs deleted file mode 100644 index 04a5036..0000000 --- a/World/IWorldService.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Server.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 deleted file mode 100644 index b70c020..0000000 --- a/World/PresenceModels.cs +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index c48d95f..0000000 --- a/World/RedisPresenceStore.cs +++ /dev/null @@ -1,42 +0,0 @@ -// 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); - } -} diff --git a/World/SpatialIndex.cs b/World/SpatialIndex.cs deleted file mode 100644 index 9724933..0000000 --- a/World/SpatialIndex.cs +++ /dev/null @@ -1,37 +0,0 @@ -using StackExchange.Redis; - -namespace Server.World; - -public static class SpatialIndex -{ - public const int CellSize = 50; // units - public static (int cx, int cy, int cz) Cell(double x, double y, double z) => - ((int)Math.Floor(x / CellSize), (int)Math.Floor(y / CellSize), (int)Math.Floor(z / CellSize)); - - public static async Task UpdateAsync(IDatabase db, ulong zoneId, ulong charId, - (int cx, int cy, int cz) oldCell, (int cx, int cy, int cz) newCell, TimeSpan ttl) - { - var oldKey = $"z:{{{zoneId}}}:c:{oldCell.cx}:{oldCell.cy}:{oldCell.cz}"; - var newKey = $"z:{{{zoneId}}}:c:{newCell.cx}:{newCell.cy}:{newCell.cz}"; - - var batch = db.CreateBatch(); - var tasks = new List(); - - if (oldCell != newCell) - tasks.Add(batch.SetRemoveAsync(oldKey, charId)); - - tasks.Add(batch.SetAddAsync(newKey, charId)); - tasks.Add(batch.KeyExpireAsync(newKey, ttl)); - - batch.Execute(); - await Task.WhenAll(tasks); - } - - - public static IEnumerable NeighborCellKeys(ulong zoneId, (int cx, int cy, int cz) c, int r = 1) - { - for (int dx = -r; dx <= r; dx++) - for (int dy = -r; dy <= r; dy++) - yield return $"z:{{{zoneId}}}:c:{c.cx + dx}:{c.cy + dy}:{c.cz}"; - } -} diff --git a/data/GameDbContext.cs b/data/GameDbContext.cs index b3c2660..500388a 100644 --- a/data/GameDbContext.cs +++ b/data/GameDbContext.cs @@ -11,11 +11,7 @@ public sealed class GameDbContext : DbContext public DbSet Accounts => Set(); public DbSet Sessions => Set(); - public DbSet Characters => Set(); public DbSet Zones => Set(); - public DbSet ItemTemplates => Set(); - public DbSet Inventory => Set(); - public DbSet Equipment => Set(); public DbSet DungeonCharacters => Set(); public DbSet DungeonCharacterItems => Set(); public DbSet DungeonStashItems => Set(); diff --git a/data/entities/Account.cs b/data/entities/Account.cs index 2e69e4d..663bb54 100644 --- a/data/entities/Account.cs +++ b/data/entities/Account.cs @@ -1,4 +1,5 @@ -using Microsoft.EntityFrameworkCore; +using DataServer.Data.Entities; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace DataServer.Data; @@ -20,7 +21,7 @@ public sealed class Account public DateTime UpdatedAt { get; set; } public ICollection Sessions { get; set; } = new List(); - public ICollection Characters { get; set; } = new List(); + public ICollection Characters { get; set; } = new List(); // Helper methods public bool IsAdmin => Role == AccountRole.Admin || Role == AccountRole.SuperAdmin; diff --git a/data/entities/Character.cs b/data/entities/Character.cs deleted file mode 100644 index 7f600bc..0000000 --- a/data/entities/Character.cs +++ /dev/null @@ -1,156 +0,0 @@ -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using DataServer.Data; -namespace DataServer.Data.Entities; - -/// -/// Derived stats calculator - used at runtime -/// -public static class CharacterStats -{ - public static int GetMaxHealth(Character c) => 50 + (c.Endurance * 10); - public static int GetMaxMana(Character c) => 20 + (c.Wisdom * 8); - public static int GetMaxStamina(Character c) => 50 + (c.Endurance * 5); - public static float GetXpBonus(Character c) => 1.0f + (c.Wisdom * 0.02f); - public static float GetMoveSpeed(Character c) => 100f + (c.Dexterity * 2f); - public static float GetAttackSpeed(Character c) => 1.0f + (c.Dexterity * 0.02f); - public static float GetRegenRate(Character c) => 1.0f + (c.Endurance * 0.1f); - - /// - /// Calculate combat stats including equipment bonuses - /// - public static CharacterCombatStats GetCombatStats(Character c, List? equippedItems = null) - { - var stats = new CharacterCombatStats - { - Strength = c.Strength, - Intelligence = c.Intelligence, - Wisdom = c.Wisdom, - Endurance = c.Endurance, - Dexterity = c.Dexterity - }; - - if (equippedItems != null) - { - foreach (var item in equippedItems) - { - stats.Strength += item.BonusStrength; - stats.Intelligence += item.BonusIntelligence; - stats.Wisdom += item.BonusWisdom; - stats.Endurance += item.BonusEndurance; - stats.Dexterity += item.BonusDexterity; - stats.BonusHealth += item.BonusHealth; - stats.BonusMana += item.BonusMana; - stats.Armor += item.Armor; - stats.MagicResist += item.MagicResist; - } - } - - stats.MaxHealth = 50 + (stats.Endurance * 10) + stats.BonusHealth; - stats.MaxMana = 20 + (stats.Wisdom * 8) + stats.BonusMana; - stats.MaxStamina = 50 + (stats.Endurance * 5); - stats.MoveSpeed = 100f + (stats.Dexterity * 2f); - stats.AttackSpeed = 1.0f + (stats.Dexterity * 0.02f); - stats.RegenRate = 1.0f + (stats.Endurance * 0.1f); - stats.PhysicalDamageMultiplier = 1.0f + (stats.Strength * 0.05f); - stats.SpellDamageMultiplier = 1.0f + (stats.Intelligence * 0.05f); - stats.XpBonus = 1.0f + (stats.Wisdom * 0.02f); - - return stats; - } -} - -public class CharacterCombatStats -{ - public int Strength { get; set; } - public int Intelligence { get; set; } - public int Wisdom { get; set; } - public int Endurance { get; set; } - public int Dexterity { get; set; } - public int MaxHealth { get; set; } - public int MaxMana { get; set; } - public int MaxStamina { get; set; } - public int BonusHealth { get; set; } - public int BonusMana { get; set; } - public int Armor { get; set; } - public int MagicResist { get; set; } - public float MoveSpeed { get; set; } - public float AttackSpeed { get; set; } - public float RegenRate { get; set; } - public float PhysicalDamageMultiplier { get; set; } - public float SpellDamageMultiplier { get; set; } - public float XpBonus { get; set; } -} - -/// -/// Persistent player character with stats and equipment -/// -[Table("characters")] -public class Character -{ - [Key] - public ulong Id { get; set; } - - [Required] - public ulong AccountId { get; set; } - - [Required] - [MaxLength(32)] - public string Name { get; set; } = ""; - - public DateTime CreatedAt { get; set; } = DateTime.UtcNow; - public DateTime LastPlayedAt { get; set; } = DateTime.UtcNow; - - // Progression - public int Level { get; set; } = 1; - public long Experience { get; set; } = 0; - public int UnspentStatPoints { get; set; } = 5; // Start with 5 points - - // Core Stats (5 points per level to distribute) - public int Strength { get; set; } = 1; // Physical damage, heavy equipment - public int Intelligence { get; set; } = 1; // Spell damage, magical equipment - public int Wisdom { get; set; } = 1; // Max mana, XP bonus, spell learning - public int Endurance { get; set; } = 1; // Max HP, max stamina, regen rate - public int Dexterity { get; set; } = 1; // Move speed, attack speed, light equipment - - // Derived stats (calculated from base stats) - [NotMapped] public int MaxHealth => 50 + (Endurance * 10); - [NotMapped] public int MaxMana => 20 + (Wisdom * 8); - [NotMapped] public int MaxStamina => 50 + (Endurance * 5); - [NotMapped] public float XpBonus => 1.0f + (Wisdom * 0.02f); // 2% per WIS - [NotMapped] public float MoveSpeed => 100f + (Dexterity * 2f); - [NotMapped] public float AttackSpeed => 1.0f + (Dexterity * 0.02f); - [NotMapped] public float RegenRate => 1.0f + (Endurance * 0.1f); // HP/Mana/Stamina regen multiplier - - // Current state (saved on logout/death) - public int CurrentHealth { get; set; } = 50; - public int CurrentMana { get; set; } = 20; - - // Equipment slots (ItemId references, null = empty) - public ulong? EquippedWeapon { get; set; } - public ulong? EquippedOffhand { get; set; } - public ulong? EquippedHead { get; set; } - public ulong? EquippedChest { get; set; } - public ulong? EquippedLegs { get; set; } - public ulong? EquippedBoots { get; set; } - public ulong? EquippedGloves { get; set; } - public ulong? EquippedAccessory { get; set; } - - // Lifetime stats - public int TotalKills { get; set; } - public int TotalDeaths { get; set; } - public int PlayersKilled { get; set; } - public int DungeonsCompleted { get; set; } - public int BossesKilled { get; set; } - - // Soft delete - public bool IsDeleted { get; set; } = false; - - // Navigation - public virtual Account? Account { get; set; } - public virtual ICollection Inventory { get; set; } = new List(); - public virtual ICollection Stash { get; set; } = new List(); - public virtual ICollection LearnedSpells { get; set; } = new List(); -} - - diff --git a/data/entities/Dungeon.cs b/data/entities/Dungeon.cs index 878ef6d..3d60605 100644 --- a/data/entities/Dungeon.cs +++ b/data/entities/Dungeon.cs @@ -59,7 +59,7 @@ public class DungeonVisit // Navigation public virtual DungeonInstance? Dungeon { get; set; } - public virtual Character? Character { get; set; } + //public virtual Character? Character { get; set; } } @@ -103,7 +103,7 @@ public class LootTableEntry // Navigation public virtual LootTable? LootTable { get; set; } - public virtual ItemDefinition? ItemDefinition { get; set; } + //public virtual ItemDefinition? ItemDefinition { get; set; } } // Enums diff --git a/data/entities/EquipmentSlot.cs b/data/entities/EquipmentSlot.cs deleted file mode 100644 index f2cc5e6..0000000 --- a/data/entities/EquipmentSlot.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace DataServer.Data; - -public sealed class EquipmentSlot -{ - public ulong Id { get; set; } - public ulong CharacterId { get; set; } - public byte SlotCode { get; set; } // 1=head,2=chest,... - public ulong ItemTemplateId { get; set; } - public DateTime CreatedAt { get; set; } - public DateTime UpdatedAt { get; set; } - - public Old_Character? Old_Character { get; set; } - public ItemTemplate? ItemTemplate { get; set; } -} - -public sealed class EquipmentSlotConfig : IEntityTypeConfiguration -{ - public void Configure(EntityTypeBuilder e) - { - e.ToTable("equipment"); - e.HasKey(x => x.Id); - e.Property(x => x.Id).ValueGeneratedOnAdd(); - e.HasIndex(x => new { x.CharacterId, x.SlotCode }).IsUnique(); - e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); - e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") - .ValueGeneratedOnAddOrUpdate(); - - e.HasOne(x => x.Old_Character).WithMany().HasForeignKey(x => x.CharacterId).OnDelete(DeleteBehavior.Cascade); - e.HasOne(x => x.ItemTemplate).WithMany().HasForeignKey(x => x.ItemTemplateId).OnDelete(DeleteBehavior.Restrict); - } -} diff --git a/data/entities/InventoryItem.cs b/data/entities/InventoryItem.cs deleted file mode 100644 index 6e57ee9..0000000 --- a/data/entities/InventoryItem.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace DataServer.Data; - -public sealed class InventoryItem -{ - public ulong Id { get; set; } - public ulong CharacterId { get; set; } - public uint SlotIndex { get; set; } - public ulong ItemTemplateId { get; set; } - public uint Quantity { get; set; } = 1; - public DateTime CreatedAt { get; set; } - public DateTime UpdatedAt { get; set; } - - public Old_Character? Old_Character { get; set; } - public ItemTemplate? ItemTemplate { get; set; } -} - -public sealed class InventoryItemConfig : IEntityTypeConfiguration -{ - public void Configure(EntityTypeBuilder e) - { - e.ToTable("inventories"); - e.HasKey(x => x.Id); - e.Property(x => x.Id).ValueGeneratedOnAdd(); - e.HasIndex(x => new { x.CharacterId, x.SlotIndex }).IsUnique(); - e.HasIndex(x => x.CharacterId); - e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); - e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") - .ValueGeneratedOnAddOrUpdate(); - - e.HasOne(x => x.Old_Character).WithMany().HasForeignKey(x => x.CharacterId).OnDelete(DeleteBehavior.Cascade); - e.HasOne(x => x.ItemTemplate).WithMany().HasForeignKey(x => x.ItemTemplateId).OnDelete(DeleteBehavior.Restrict); - } -} diff --git a/data/entities/ItemTemplate.cs b/data/entities/ItemTemplate.cs deleted file mode 100644 index c3c2957..0000000 --- a/data/entities/ItemTemplate.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace DataServer.Data; - -public sealed class ItemTemplate -{ - public ulong Id { get; set; } - public string Name { get; set; } = ""; - public byte ItemType { get; set; } = 1; - public byte Rarity { get; set; } = 1; - public uint MaxStack { get; set; } = 1; - public uint Weight { get; set; } = 0; - public string? StatsJson { get; set; } - public DateTime CreatedAt { get; set; } - public DateTime UpdatedAt { get; set; } -} - -public sealed class ItemTemplateConfig : IEntityTypeConfiguration -{ - public void Configure(EntityTypeBuilder e) - { - e.ToTable("item_templates"); - e.HasKey(x => x.Id); - e.Property(x => x.Id).ValueGeneratedOnAdd(); - e.Property(x => x.Name).HasMaxLength(64).IsRequired(); - e.HasIndex(x => x.Name).IsUnique(); - e.Property(x => x.StatsJson).HasColumnType("json"); - e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); - e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") - .ValueGeneratedOnAddOrUpdate(); - } -} diff --git a/data/entities/Items.cs b/data/entities/Items.cs deleted file mode 100644 index 9b6266a..0000000 --- a/data/entities/Items.cs +++ /dev/null @@ -1,185 +0,0 @@ -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using DataServer.Data.Enums; - -namespace DataServer.Data.Entities; - -/// -/// Item template/definition - what an item IS -/// -[Table("item_definitions")] -public class ItemDefinition -{ - [Key] - public int Id { get; set; } - - [Required] - [MaxLength(64)] - public string Name { get; set; } = ""; - - [MaxLength(256)] - public string Description { get; set; } = ""; - - public ItemType Type { get; set; } - public ItemRarity Rarity { get; set; } = ItemRarity.Common; - public EquipmentSlot? EquipSlot { get; set; } // Null if not equippable - - // Stat requirements to equip/use - public int RequiredStrength { get; set; } = 0; - public int RequiredIntelligence { get; set; } = 0; - public int RequiredWisdom { get; set; } = 0; - public int RequiredDexterity { get; set; } = 0; - public int RequiredLevel { get; set; } = 1; - - // Stat bonuses when equipped - public int BonusStrength { get; set; } = 0; - public int BonusIntelligence { get; set; } = 0; - public int BonusWisdom { get; set; } = 0; - public int BonusEndurance { get; set; } = 0; - public int BonusDexterity { get; set; } = 0; - public int BonusHealth { get; set; } = 0; - public int BonusMana { get; set; } = 0; - - // Weapon stats - public int MinDamage { get; set; } = 0; - public int MaxDamage { get; set; } = 0; - public float AttackRange { get; set; } = 0; // 0 = melee - public DamageType DamageType { get; set; } = DamageType.Physical; - - // Armor stats - public int Armor { get; set; } = 0; - public int MagicResist { get; set; } = 0; - - // Consumable effects - public int HealAmount { get; set; } = 0; - public int ManaRestore { get; set; } = 0; - public int StaminaRestore { get; set; } = 0; - - // Special - public bool IsTeleportScroll { get; set; } = false; - public int? TeachesSpellId { get; set; } // For spell tomes - - // Stacking - public bool Stackable { get; set; } = false; - public int MaxStack { get; set; } = 1; - - // Visuals - public int SpriteId { get; set; } = 0; - - public bool IsEnabled { get; set; } = true; -} - -/// -/// Actual item instance owned by a character (inventory or equipped) -/// -[Table("character_items")] -public class CharacterItem -{ - [Key] - public ulong Id { get; set; } - - public ulong CharacterId { get; set; } - public int ItemDefinitionId { get; set; } - - public int Quantity { get; set; } = 1; - public int SlotIndex { get; set; } // Inventory position (0-29 for example) - - public DateTime AcquiredAt { get; set; } = DateTime.UtcNow; - - // Navigation - public virtual Character? Character { get; set; } - public virtual ItemDefinition? Definition { get; set; } -} - -/// -/// Items stored in character's stash (safe storage in hub) -/// -[Table("stash_items")] -public class StashItem -{ - [Key] - public ulong Id { get; set; } - - public ulong CharacterId { get; set; } - public int ItemDefinitionId { get; set; } - - public int Quantity { get; set; } = 1; - public int SlotIndex { get; set; } - - public DateTime StoredAt { get; set; } = DateTime.UtcNow; - - // Navigation - public virtual Character? Character { get; set; } - public virtual ItemDefinition? Definition { get; set; } -} - -/// -/// Spell definition - learnable abilities -/// -[Table("spell_definitions")] -public class SpellDefinition -{ - [Key] - public int Id { get; set; } - - [Required] - [MaxLength(64)] - public string Name { get; set; } = ""; - - [MaxLength(256)] - public string Description { get; set; } = ""; - - public SpellType Type { get; set; } - - // Requirements - public int RequiredWisdom { get; set; } = 1; - public int RequiredIntelligence { get; set; } = 0; - public int RequiredLevel { get; set; } = 1; - - // Costs - public int ManaCost { get; set; } = 10; - public float Cooldown { get; set; } = 1.0f; // Seconds - - // Effects - public int BaseDamage { get; set; } = 0; // Scales with INT - public int BaseHealing { get; set; } = 0; // Scales with WIS - public float Range { get; set; } = 100f; - public float AreaOfEffect { get; set; } = 0; // 0 = single target - - // Special - public bool IsTeleport { get; set; } = false; - public bool IsShield { get; set; } = false; - public int ShieldAmount { get; set; } = 0; - - // Visuals - public int SpriteId { get; set; } = 0; - public string EffectColor { get; set; } = "#ffffff"; - - public bool IsEnabled { get; set; } = true; -} - -/// -/// Spells a character has learned -/// -[Table("learned_spells")] -public class LearnedSpell -{ - [Key] - public ulong Id { get; set; } - - public ulong CharacterId { get; set; } - public int SpellDefinitionId { get; set; } - - public DateTime LearnedAt { get; set; } = DateTime.UtcNow; - - // Could add spell levels/upgrades later - public int SpellLevel { get; set; } = 1; - - // Navigation - public virtual Character? Character { get; set; } - public virtual SpellDefinition? Definition { get; set; } -} - - - - diff --git a/data/entities/Old_Character.cs b/data/entities/Old_Character.cs deleted file mode 100644 index b86a533..0000000 --- a/data/entities/Old_Character.cs +++ /dev/null @@ -1,64 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace DataServer.Data; - -public sealed class Old_Character -{ - public ulong Id { get; set; } - public ulong AccountId { get; set; } - public string Name { get; set; } = ""; - - public uint Level { get; set; } = 1; - public ulong Xp { get; set; } = 0; - - public uint StatStrength { get; set; } = 1; - public uint StatDexterity { get; set; } = 1; - public uint StatWisdom { get; set; } = 1; - public uint StatIntelligence { get; set; } = 1; - public uint StatEndurance { get; set; } = 1; - - public uint HpCurrent { get; set; } = 10; - public uint HpMax { get; set; } = 10; - public uint MpCurrent { get; set; } = 0; - public uint MpMax { get; set; } = 0; - public uint StaminaCurrent { get; set; } = 0; - public uint StaminaMax { get; set; } = 0; - - public ulong ZoneId { get; set; } - public double PosX { get; set; } - public double PosY { get; set; } - public double PosZ { get; set; } - public float FacingDeg { get; set; } - - // store as JSON in MySQL 8 - public string? AppearanceJson { get; set; } - - public DateTime CreatedAt { get; set; } - public DateTime UpdatedAt { get; set; } - - public Account? Account { get; set; } - public Zone? Zone { get; set; } -} - -public sealed class CharacterConfig : IEntityTypeConfiguration -{ - public void Configure(EntityTypeBuilder e) - { - e.ToTable("characters"); - e.HasKey(x => x.Id); - e.Property(x => x.Id).ValueGeneratedOnAdd(); - e.Property(x => x.Name).HasMaxLength(32).IsRequired(); - - e.HasIndex(x => x.AccountId).IsUnique(); // 1 character per account (change later if needed) - e.HasIndex(x => x.ZoneId); - - e.Property(x => x.AppearanceJson).HasColumnType("json"); - e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); - e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") - .ValueGeneratedOnAddOrUpdate(); - - e.HasOne(x => x.Account).WithMany(a => a.Characters).HasForeignKey(x => x.AccountId).OnDelete(DeleteBehavior.Cascade); - e.HasOne(x => x.Zone).WithMany().HasForeignKey(x => x.ZoneId).OnDelete(DeleteBehavior.Restrict); - } -}