From d66ff2af40ee84000bba1313918da17816df5c52 Mon Sep 17 00:00:00 2001 From: dingo Date: Thu, 4 Dec 2025 09:30:32 -0500 Subject: [PATCH] ItemDB+API --- Api/ItemsController.cs | 300 +++++++ Api/StatsController.cs | 343 ++++++++ Game/ItemService.cs | 279 ++++++ ...3006_AddVoidScavengersEntities.Designer.cs | 831 ++++++++++++++++++ ...0251204143006_AddVoidScavengersEntities.cs | 118 +++ Migrations/GameDbContextModelSnapshot.cs | 173 ++++ Program.cs | 5 +- data/GameDbContext.cs | 2 + data/entities/GameItem.cs | 84 ++ data/entities/GameRecipe.cs | 49 ++ 10 files changed, 2183 insertions(+), 1 deletion(-) create mode 100644 Api/ItemsController.cs create mode 100644 Api/StatsController.cs create mode 100644 Game/ItemService.cs create mode 100644 Migrations/20251204143006_AddVoidScavengersEntities.Designer.cs create mode 100644 Migrations/20251204143006_AddVoidScavengersEntities.cs create mode 100644 data/entities/GameItem.cs create mode 100644 data/entities/GameRecipe.cs diff --git a/Api/ItemsController.cs b/Api/ItemsController.cs new file mode 100644 index 0000000..89d75b2 --- /dev/null +++ b/Api/ItemsController.cs @@ -0,0 +1,300 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Server.Data; +using VoidScavengers.Game; + +namespace VoidScavengers.Api; + +/// +/// API endpoints for game items and recipes +/// +[ApiController] +[Route("api/items")] +public class ItemsController : ControllerBase +{ + private readonly GameDbContext _db; + private readonly IItemService _itemService; + + public ItemsController(GameDbContext db, IItemService itemService) + { + _db = db; + _itemService = itemService; + } + + /// + /// Get all items (from cache) + /// + [HttpGet] + public IActionResult GetAllItems([FromQuery] ItemCategory? category = null) + { + var items = category.HasValue + ? _itemService.GetItemsByCategory(category.Value) + : _itemService.GetAllItems(); + + return Ok(items); + } + + /// + /// Get a specific item + /// + [HttpGet("{id}")] + public IActionResult GetItem(int id) + { + var item = _itemService.GetItem(id); + if (item == null) + return NotFound(new { error = "Item not found" }); + + return Ok(item); + } + + /// + /// Get all recipes (from cache) + /// + [HttpGet("recipes")] + public IActionResult GetAllRecipes() + { + var recipes = _itemService.GetAllRecipes(); + + // Enrich with item names + var enriched = recipes.Select(r => new + { + r.Id, + r.ResultItemId, + ResultItemName = _itemService.GetItem(r.ResultItemId)?.Name ?? "Unknown", + r.ScrapCost, + r.EnergyCost, + r.RareCost + }); + + return Ok(enriched); + } + + /// + /// Force reload the item cache (admin only) + /// + [HttpPost("reload")] + public async Task ReloadCache([FromHeader(Name = "X-Admin-Key")] string? adminKey) + { + // Simple admin key check - in production use proper auth + var expectedKey = Environment.GetEnvironmentVariable("ADMIN_KEY") ?? "dev-admin-key"; + if (adminKey != expectedKey) + return Unauthorized(new { error = "Invalid admin key" }); + + await _itemService.ReloadCacheAsync(); + return Ok(new { message = "Cache reloaded", itemCount = _itemService.GetAllItems().Count }); + } + + /// + /// Create or update an item (admin only) + /// + [HttpPost] + public async Task UpsertItem( + [FromHeader(Name = "X-Admin-Key")] string? adminKey, + [FromBody] GameItemDto dto) + { + var expectedKey = Environment.GetEnvironmentVariable("ADMIN_KEY") ?? "dev-admin-key"; + if (adminKey != expectedKey) + return Unauthorized(new { error = "Invalid admin key" }); + + var existing = await _db.GameItems.FindAsync(dto.Id); + + if (existing == null) + { + var item = new GameItem + { + Id = dto.Id, + Name = dto.Name, + Category = dto.Category, + CraftCost = dto.CraftCost, + Description = dto.Description, + LootValue = dto.LootValue, + Stackable = dto.Stackable, + IsEnabled = dto.IsEnabled, + Damage = dto.Damage, + FireRate = dto.FireRate, + ProjectileSpeed = dto.ProjectileSpeed, + Range = dto.Range, + AmmoType = dto.AmmoType, + PelletCount = dto.PelletCount, + Spread = dto.Spread, + ExplosionRadius = dto.ExplosionRadius, + HarvestMultiplier = dto.HarvestMultiplier, + ScanRadius = dto.ScanRadius, + ScanCooldown = dto.ScanCooldown, + ShieldHealth = dto.ShieldHealth, + ShieldDuration = dto.ShieldDuration, + HealAmount = dto.HealAmount, + ShieldBoostDuration = dto.ShieldBoostDuration, + DamageReduction = dto.DamageReduction, + SpeedBoostDuration = dto.SpeedBoostDuration, + SpeedMultiplier = dto.SpeedMultiplier, + HealthBonus = dto.HealthBonus, + SpeedPenalty = dto.SpeedPenalty, + DashDistance = dto.DashDistance, + DashCooldown = dto.DashCooldown, + CreatedAt = DateTime.UtcNow + }; + _db.GameItems.Add(item); + } + else + { + existing.Name = dto.Name; + existing.Category = dto.Category; + existing.CraftCost = dto.CraftCost; + existing.Description = dto.Description; + existing.LootValue = dto.LootValue; + existing.Stackable = dto.Stackable; + existing.IsEnabled = dto.IsEnabled; + existing.Damage = dto.Damage; + existing.FireRate = dto.FireRate; + existing.ProjectileSpeed = dto.ProjectileSpeed; + existing.Range = dto.Range; + existing.AmmoType = dto.AmmoType; + existing.PelletCount = dto.PelletCount; + existing.Spread = dto.Spread; + existing.ExplosionRadius = dto.ExplosionRadius; + existing.HarvestMultiplier = dto.HarvestMultiplier; + existing.ScanRadius = dto.ScanRadius; + existing.ScanCooldown = dto.ScanCooldown; + existing.ShieldHealth = dto.ShieldHealth; + existing.ShieldDuration = dto.ShieldDuration; + existing.HealAmount = dto.HealAmount; + existing.ShieldBoostDuration = dto.ShieldBoostDuration; + existing.DamageReduction = dto.DamageReduction; + existing.SpeedBoostDuration = dto.SpeedBoostDuration; + existing.SpeedMultiplier = dto.SpeedMultiplier; + existing.HealthBonus = dto.HealthBonus; + existing.SpeedPenalty = dto.SpeedPenalty; + existing.DashDistance = dto.DashDistance; + existing.DashCooldown = dto.DashCooldown; + } + + await _db.SaveChangesAsync(); + await _itemService.ReloadCacheAsync(); + + return Ok(new { message = existing == null ? "Item created" : "Item updated", id = dto.Id }); + } + + /// + /// Create or update a recipe (admin only) + /// + [HttpPost("recipes")] + public async Task UpsertRecipe( + [FromHeader(Name = "X-Admin-Key")] string? adminKey, + [FromBody] GameRecipeDto dto) + { + var expectedKey = Environment.GetEnvironmentVariable("ADMIN_KEY") ?? "dev-admin-key"; + if (adminKey != expectedKey) + return Unauthorized(new { error = "Invalid admin key" }); + + var existing = await _db.GameRecipes.FindAsync(dto.Id); + + if (existing == null) + { + var recipe = new GameRecipe + { + Id = dto.Id, + ResultItemId = dto.ResultItemId, + ScrapCost = dto.ScrapCost, + EnergyCost = dto.EnergyCost, + RareCost = dto.RareCost, + IsEnabled = dto.IsEnabled, + CreatedAt = DateTime.UtcNow + }; + _db.GameRecipes.Add(recipe); + } + else + { + existing.ResultItemId = dto.ResultItemId; + existing.ScrapCost = dto.ScrapCost; + existing.EnergyCost = dto.EnergyCost; + existing.RareCost = dto.RareCost; + existing.IsEnabled = dto.IsEnabled; + } + + await _db.SaveChangesAsync(); + await _itemService.ReloadCacheAsync(); + + return Ok(new { message = existing == null ? "Recipe created" : "Recipe updated", id = dto.Id }); + } + + /// + /// Seed default items if database is empty (admin only) + /// + [HttpPost("seed")] + public async Task SeedDefaults([FromHeader(Name = "X-Admin-Key")] string? adminKey) + { + var expectedKey = Environment.GetEnvironmentVariable("ADMIN_KEY") ?? "dev-admin-key"; + if (adminKey != expectedKey) + return Unauthorized(new { error = "Invalid admin key" }); + + var existingItemCount = await _db.GameItems.CountAsync(); + var existingRecipeCount = await _db.GameRecipes.CountAsync(); + + if (existingItemCount > 0 || existingRecipeCount > 0) + return BadRequest(new { error = "Database already has items/recipes. Clear first or use upsert." }); + + var defaultItems = DefaultItemData.GetDefaultItems(); + var defaultRecipes = DefaultItemData.GetDefaultRecipes(); + + _db.GameItems.AddRange(defaultItems); + _db.GameRecipes.AddRange(defaultRecipes); + + await _db.SaveChangesAsync(); + await _itemService.ReloadCacheAsync(); + + return Ok(new { + message = "Default items seeded", + itemsAdded = defaultItems.Count, + recipesAdded = defaultRecipes.Count + }); + } +} + +public class GameItemDto +{ + public int Id { get; set; } + public string Name { get; set; } = ""; + public ItemCategory Category { get; set; } + public int CraftCost { get; set; } + public string Description { get; set; } = ""; + public int LootValue { get; set; } + public bool Stackable { get; set; } + public bool IsEnabled { get; set; } = true; + + public int Damage { get; set; } + public float FireRate { get; set; } + public float ProjectileSpeed { get; set; } + public float Range { get; set; } + public int AmmoType { get; set; } + public int PelletCount { get; set; } = 1; + public float Spread { get; set; } + public float ExplosionRadius { get; set; } + + public float HarvestMultiplier { get; set; } = 1f; + public float ScanRadius { get; set; } + public float ScanCooldown { get; set; } + public int ShieldHealth { get; set; } + public float ShieldDuration { get; set; } + + public int HealAmount { get; set; } + public float ShieldBoostDuration { get; set; } + public float DamageReduction { get; set; } + public float SpeedBoostDuration { get; set; } + public float SpeedMultiplier { get; set; } = 1f; + + public int HealthBonus { get; set; } + public float SpeedPenalty { get; set; } + public float DashDistance { get; set; } + public float DashCooldown { get; set; } +} + +public class GameRecipeDto +{ + public int Id { get; set; } + public int ResultItemId { get; set; } + public int ScrapCost { get; set; } + public int EnergyCost { get; set; } + public int RareCost { get; set; } + public bool IsEnabled { get; set; } = true; +} diff --git a/Api/StatsController.cs b/Api/StatsController.cs new file mode 100644 index 0000000..047696d --- /dev/null +++ b/Api/StatsController.cs @@ -0,0 +1,343 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Server.Data; + +namespace VoidScavengers.Api; + +/// +/// API endpoints for player statistics and leaderboards +/// +[ApiController] +[Route("api/stats")] +public class StatsController : ControllerBase +{ + private readonly GameDbContext _db; + + public StatsController(GameDbContext db) + { + _db = db; + } + + /// + /// Get stats for a specific player by account ID + /// + [HttpGet("player/{accountId}")] + public async Task GetPlayerStats(ulong accountId) + { + var stats = await _db.PlayerStats + .Where(s => s.AccountId == accountId) + .Select(s => new PlayerStatsDto + { + AccountId = s.AccountId, + Username = s.Account.Username, + MatchesPlayed = s.MatchesPlayed, + Wins = s.Wins, + Losses = s.Losses, + Extractions = s.Extractions, + WinRate = s.MatchesPlayed > 0 ? (float)s.Wins / s.MatchesPlayed * 100 : 0, + Kills = s.Kills, + Deaths = s.Deaths, + KdRatio = s.Deaths > 0 ? (float)s.Kills / s.Deaths : s.Kills, + TotalDamageDealt = s.TotalDamageDealt, + TotalDamageTaken = s.TotalDamageTaken, + TotalScrapCollected = s.TotalScrapCollected, + TotalEnergyCollected = s.TotalEnergyCollected, + TotalRareCollected = s.TotalRareCollected, + ItemsCrafted = s.ItemsCrafted, + TotalPlayTimeSeconds = s.TotalPlayTimeSeconds, + LongestSurvivalSeconds = s.LongestSurvivalSeconds, + Elo = s.Elo + }) + .FirstOrDefaultAsync(); + + if (stats == null) + return NotFound(new { error = "Player stats not found" }); + + return Ok(stats); + } + + /// + /// Get stats for a player by username + /// + [HttpGet("player/name/{username}")] + public async Task GetPlayerStatsByName(string username) + { + var stats = await _db.PlayerStats + .Where(s => s.Account.Username == username) + .Select(s => new PlayerStatsDto + { + AccountId = s.AccountId, + Username = s.Account.Username, + MatchesPlayed = s.MatchesPlayed, + Wins = s.Wins, + Losses = s.Losses, + Extractions = s.Extractions, + WinRate = s.MatchesPlayed > 0 ? (float)s.Wins / s.MatchesPlayed * 100 : 0, + Kills = s.Kills, + Deaths = s.Deaths, + KdRatio = s.Deaths > 0 ? (float)s.Kills / s.Deaths : s.Kills, + TotalDamageDealt = s.TotalDamageDealt, + TotalDamageTaken = s.TotalDamageTaken, + TotalScrapCollected = s.TotalScrapCollected, + TotalEnergyCollected = s.TotalEnergyCollected, + TotalRareCollected = s.TotalRareCollected, + ItemsCrafted = s.ItemsCrafted, + TotalPlayTimeSeconds = s.TotalPlayTimeSeconds, + LongestSurvivalSeconds = s.LongestSurvivalSeconds, + Elo = s.Elo + }) + .FirstOrDefaultAsync(); + + if (stats == null) + return NotFound(new { error = "Player not found" }); + + return Ok(stats); + } + + /// + /// Get leaderboard by Elo rating + /// + [HttpGet("leaderboard")] + public async Task GetLeaderboard( + [FromQuery] string sort = "elo", + [FromQuery] int page = 1, + [FromQuery] int pageSize = 20) + { + pageSize = Math.Clamp(pageSize, 1, 100); + page = Math.Max(1, page); + + var query = _db.PlayerStats + .Where(s => s.MatchesPlayed >= 5); // Minimum games to appear on leaderboard + + query = sort.ToLower() switch + { + "wins" => query.OrderByDescending(s => s.Wins), + "kills" => query.OrderByDescending(s => s.Kills), + "winrate" => query.OrderByDescending(s => s.MatchesPlayed > 0 ? (float)s.Wins / s.MatchesPlayed : 0), + "kd" => query.OrderByDescending(s => s.Deaths > 0 ? (float)s.Kills / s.Deaths : s.Kills), + "extractions" => query.OrderByDescending(s => s.Extractions), + "playtime" => query.OrderByDescending(s => s.TotalPlayTimeSeconds), + _ => query.OrderByDescending(s => s.Elo) + }; + + var totalCount = await query.CountAsync(); + var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize); + + var entries = await query + .Skip((page - 1) * pageSize) + .Take(pageSize) + .Select(s => new LeaderboardEntryDto + { + Rank = 0, // Calculated below + AccountId = s.AccountId, + Username = s.Account.Username, + Elo = s.Elo, + Wins = s.Wins, + Losses = s.Losses, + WinRate = s.MatchesPlayed > 0 ? (float)s.Wins / s.MatchesPlayed * 100 : 0, + Kills = s.Kills, + Deaths = s.Deaths, + KdRatio = s.Deaths > 0 ? (float)s.Kills / s.Deaths : s.Kills, + Extractions = s.Extractions, + MatchesPlayed = s.MatchesPlayed + }) + .ToListAsync(); + + // Calculate ranks + int startRank = (page - 1) * pageSize + 1; + for (int i = 0; i < entries.Count; i++) + { + entries[i].Rank = startRank + i; + } + + return Ok(new LeaderboardResponse + { + Entries = entries, + Page = page, + PageSize = pageSize, + TotalPages = totalPages, + TotalCount = totalCount, + SortBy = sort + }); + } + + /// + /// Get match history for a player + /// + [HttpGet("player/{accountId}/history")] + public async Task GetMatchHistory( + ulong accountId, + [FromQuery] int page = 1, + [FromQuery] int pageSize = 20) + { + pageSize = Math.Clamp(pageSize, 1, 50); + page = Math.Max(1, page); + + var query = _db.MatchHistory + .Where(m => m.AccountId == accountId) + .OrderByDescending(m => m.PlayedAt); + + var totalCount = await query.CountAsync(); + var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize); + + var matches = await query + .Skip((page - 1) * pageSize) + .Take(pageSize) + .Select(m => new MatchHistoryDto + { + MatchId = m.MatchId, + PlayedAt = m.PlayedAt, + Result = m.Result.ToString(), + Placement = m.Placement, + TotalPlayers = m.TotalPlayers, + Kills = m.Kills, + Deaths = m.Deaths, + DamageDealt = m.DamageDealt, + DamageTaken = m.DamageTaken, + ScrapCollected = m.ScrapCollected, + EnergyCollected = m.EnergyCollected, + RareCollected = m.RareCollected, + ItemsCrafted = m.ItemsCrafted, + SurvivalTimeSeconds = m.SurvivalTimeSeconds, + EloChange = m.EloChange, + EloAfter = m.EloAfter + }) + .ToListAsync(); + + return Ok(new MatchHistoryResponse + { + Matches = matches, + Page = page, + PageSize = pageSize, + TotalPages = totalPages, + TotalCount = totalCount + }); + } + + /// + /// Get global statistics + /// + [HttpGet("global")] + public async Task GetGlobalStats() + { + var stats = await _db.PlayerStats + .GroupBy(s => 1) + .Select(g => new GlobalStatsDto + { + TotalPlayers = g.Count(), + TotalMatchesPlayed = g.Sum(s => s.MatchesPlayed), + TotalKills = g.Sum(s => s.Kills), + TotalExtractions = g.Sum(s => s.Extractions), + TotalPlayTimeHours = g.Sum(s => s.TotalPlayTimeSeconds) / 3600.0, + AverageElo = g.Average(s => (double)s.Elo), + TopElo = g.Max(s => s.Elo) + }) + .FirstOrDefaultAsync(); + + if (stats == null) + { + return Ok(new GlobalStatsDto()); + } + + // Get active players (played in last 7 days) + var sevenDaysAgo = DateTime.UtcNow.AddDays(-7); + stats.ActivePlayers = await _db.MatchHistory + .Where(m => m.PlayedAt >= sevenDaysAgo) + .Select(m => m.AccountId) + .Distinct() + .CountAsync(); + + return Ok(stats); + } +} + +// DTOs +public class PlayerStatsDto +{ + public ulong AccountId { get; set; } + public string Username { get; set; } = ""; + public int MatchesPlayed { get; set; } + public int Wins { get; set; } + public int Losses { get; set; } + public int Extractions { get; set; } + public float WinRate { get; set; } + public int Kills { get; set; } + public int Deaths { get; set; } + public float KdRatio { get; set; } + public long TotalDamageDealt { get; set; } + public long TotalDamageTaken { get; set; } + public long TotalScrapCollected { get; set; } + public long TotalEnergyCollected { get; set; } + public long TotalRareCollected { get; set; } + public int ItemsCrafted { get; set; } + public long TotalPlayTimeSeconds { get; set; } + public int LongestSurvivalSeconds { get; set; } + public int Elo { get; set; } +} + +public class LeaderboardEntryDto +{ + public int Rank { get; set; } + public ulong AccountId { get; set; } + public string Username { get; set; } = ""; + public int Elo { get; set; } + public int Wins { get; set; } + public int Losses { get; set; } + public float WinRate { get; set; } + public int Kills { get; set; } + public int Deaths { get; set; } + public float KdRatio { get; set; } + public int Extractions { get; set; } + public int MatchesPlayed { get; set; } +} + +public class LeaderboardResponse +{ + public List Entries { get; set; } = new(); + public int Page { get; set; } + public int PageSize { get; set; } + public int TotalPages { get; set; } + public int TotalCount { get; set; } + public string SortBy { get; set; } = ""; +} + +public class MatchHistoryDto +{ + public string MatchId { get; set; } = ""; + public DateTime PlayedAt { get; set; } + public string Result { get; set; } = ""; + public int Placement { get; set; } + public int TotalPlayers { get; set; } + public int Kills { get; set; } + public int Deaths { get; set; } + public int DamageDealt { get; set; } + public int DamageTaken { get; set; } + public int ScrapCollected { get; set; } + public int EnergyCollected { get; set; } + public int RareCollected { get; set; } + public int ItemsCrafted { get; set; } + public int SurvivalTimeSeconds { get; set; } + public int EloChange { get; set; } + public int EloAfter { get; set; } +} + +public class MatchHistoryResponse +{ + public List Matches { get; set; } = new(); + public int Page { get; set; } + public int PageSize { get; set; } + public int TotalPages { get; set; } + public int TotalCount { get; set; } +} + +public class GlobalStatsDto +{ + public int TotalPlayers { get; set; } + public int ActivePlayers { get; set; } + public int TotalMatchesPlayed { get; set; } + public int TotalKills { get; set; } + public int TotalExtractions { get; set; } + public double TotalPlayTimeHours { get; set; } + public double AverageElo { get; set; } + public int TopElo { get; set; } +} diff --git a/Game/ItemService.cs b/Game/ItemService.cs new file mode 100644 index 0000000..db02126 --- /dev/null +++ b/Game/ItemService.cs @@ -0,0 +1,279 @@ +using System.Collections.Concurrent; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Server.Data; + +namespace VoidScavengers.Game; + +/// +/// Interface for item data access +/// +public interface IItemService +{ + GameItemData? GetItem(int id); + GameRecipeData? GetRecipe(int id); + IReadOnlyList GetAllItems(); + IReadOnlyList GetAllRecipes(); + IReadOnlyList GetItemsByCategory(ItemCategory category); + Task ReloadCacheAsync(); +} + +/// +/// Runtime item data (cached from database) +/// +public sealed class GameItemData +{ + public int Id { get; init; } + public string Name { get; init; } = ""; + public ItemCategory Category { get; init; } + public int CraftCost { get; init; } + public string Description { get; init; } = ""; + public int LootValue { get; init; } + public bool Stackable { get; init; } + + // 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 static GameItemData FromEntity(GameItem e) => new() + { + Id = e.Id, + Name = e.Name, + Category = e.Category, + CraftCost = e.CraftCost, + Description = e.Description, + LootValue = e.LootValue, + Stackable = e.Stackable, + Damage = e.Damage, + FireRate = e.FireRate, + ProjectileSpeed = e.ProjectileSpeed, + Range = e.Range, + AmmoType = e.AmmoType, + PelletCount = e.PelletCount, + Spread = e.Spread, + ExplosionRadius = e.ExplosionRadius, + HarvestMultiplier = e.HarvestMultiplier, + ScanRadius = e.ScanRadius, + ScanCooldown = e.ScanCooldown, + ShieldHealth = e.ShieldHealth, + ShieldDuration = e.ShieldDuration, + HealAmount = e.HealAmount, + ShieldBoostDuration = e.ShieldBoostDuration, + DamageReduction = e.DamageReduction, + SpeedBoostDuration = e.SpeedBoostDuration, + SpeedMultiplier = e.SpeedMultiplier, + HealthBonus = e.HealthBonus, + SpeedPenalty = e.SpeedPenalty, + DashDistance = e.DashDistance, + DashCooldown = e.DashCooldown + }; +} + +/// +/// Runtime recipe data (cached from database) +/// +public sealed class GameRecipeData +{ + public int Id { get; init; } + public int ResultItemId { get; init; } + public int ScrapCost { get; init; } + public int EnergyCost { get; init; } + public int RareCost { get; init; } + + public bool CanCraft(int scrap, int energy, int rare) + { + return scrap >= ScrapCost && energy >= EnergyCost && rare >= RareCost; + } + + public static GameRecipeData FromEntity(GameRecipe e) => new() + { + Id = e.Id, + ResultItemId = e.ResultItemId, + ScrapCost = e.ScrapCost, + EnergyCost = e.EnergyCost, + RareCost = e.RareCost + }; +} + +/// +/// Cached item service that loads from database and refreshes periodically +/// +public sealed class CachedItemService : IItemService, IDisposable +{ + private readonly ILogger _log; + private readonly IServiceScopeFactory _scopeFactory; + private readonly Timer _refreshTimer; + + private ConcurrentDictionary _items = new(); + private ConcurrentDictionary _recipes = new(); + private ConcurrentDictionary> _itemsByCategory = new(); + + private static readonly TimeSpan RefreshInterval = TimeSpan.FromMinutes(5); + + public CachedItemService(ILogger log, IServiceScopeFactory scopeFactory) + { + _log = log; + _scopeFactory = scopeFactory; + + // Initial load + _ = ReloadCacheAsync(); + + // Periodic refresh + _refreshTimer = new Timer(_ => _ = ReloadCacheAsync(), null, RefreshInterval, RefreshInterval); + } + + public GameItemData? GetItem(int id) => _items.TryGetValue(id, out var item) ? item : null; + + public GameRecipeData? GetRecipe(int id) => _recipes.TryGetValue(id, out var recipe) ? recipe : null; + + public IReadOnlyList GetAllItems() => _items.Values.ToList(); + + public IReadOnlyList GetAllRecipes() => _recipes.Values.ToList(); + + public IReadOnlyList GetItemsByCategory(ItemCategory category) + { + return _itemsByCategory.TryGetValue(category, out var items) ? items : new List(); + } + + public async Task ReloadCacheAsync() + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + // Load items + var items = await db.GameItems + .Where(i => i.IsEnabled) + .ToListAsync(); + + var newItems = new ConcurrentDictionary(); + var newByCategory = new ConcurrentDictionary>(); + + foreach (var item in items) + { + var data = GameItemData.FromEntity(item); + newItems[item.Id] = data; + + if (!newByCategory.ContainsKey(item.Category)) + newByCategory[item.Category] = new List(); + newByCategory[item.Category].Add(data); + } + + // Load recipes + var recipes = await db.GameRecipes + .Where(r => r.IsEnabled) + .ToListAsync(); + + var newRecipes = new ConcurrentDictionary(); + foreach (var recipe in recipes) + { + newRecipes[recipe.Id] = GameRecipeData.FromEntity(recipe); + } + + // Atomic swap + _items = newItems; + _recipes = newRecipes; + _itemsByCategory = newByCategory; + + _log.LogInformation("Loaded {ItemCount} items and {RecipeCount} recipes from database", + items.Count, recipes.Count); + } + catch (Exception ex) + { + _log.LogError(ex, "Failed to reload item cache from database"); + } + } + + public void Dispose() + { + _refreshTimer.Dispose(); + } +} + +/// +/// Fallback static item database (used if DB is empty or for seeding) +/// +public static class DefaultItemData +{ + public static List GetDefaultItems() => new() + { + // Resources + new() { Id = 1, Name = "Scrap Metal", Category = ItemCategory.Resource, CraftCost = 0, Description = "Basic salvage material", LootValue = 1, Stackable = true }, + new() { Id = 2, Name = "Energy Cell", Category = ItemCategory.Resource, CraftCost = 0, Description = "Charged power source", LootValue = 2, Stackable = true }, + new() { Id = 3, Name = "Rare Alloy", Category = ItemCategory.Resource, CraftCost = 0, Description = "Precious refined metal", LootValue = 5, Stackable = true }, + + // Weapons + new() { Id = 100, Name = "Pulse Pistol", Category = ItemCategory.Weapon, CraftCost = 15, Description = "Basic sidearm", LootValue = 10, Stackable = false, Damage = 10, FireRate = 4f, ProjectileSpeed = 400f, Range = 300f }, + new() { Id = 101, Name = "Scatter Gun", Category = ItemCategory.Weapon, CraftCost = 25, Description = "Close-range devastation", LootValue = 20, Stackable = false, Damage = 6, FireRate = 1.5f, ProjectileSpeed = 350f, Range = 150f, PelletCount = 5, Spread = 0.4f }, + new() { Id = 102, Name = "Rail Rifle", Category = ItemCategory.Weapon, CraftCost = 40, Description = "Long-range precision", LootValue = 35, Stackable = false, Damage = 45, FireRate = 0.8f, ProjectileSpeed = 800f, Range = 600f }, + new() { Id = 103, Name = "Plasma Launcher", Category = ItemCategory.Weapon, CraftCost = 60, Description = "Area damage weapon", LootValue = 50, Stackable = false, Damage = 30, FireRate = 0.5f, ProjectileSpeed = 250f, Range = 400f, ExplosionRadius = 50f }, + + // Tools + new() { Id = 200, Name = "Mining Laser", Category = ItemCategory.Tool, CraftCost = 15, Description = "Harvests resources faster", LootValue = 12, Stackable = false, HarvestMultiplier = 2.0f }, + new() { Id = 201, Name = "Scanner", Category = ItemCategory.Tool, CraftCost = 20, Description = "Reveals nearby resources and players", LootValue = 15, Stackable = false, ScanRadius = 200f, ScanCooldown = 10f }, + new() { Id = 202, Name = "Portable Shield", Category = ItemCategory.Tool, CraftCost = 35, Description = "Deployable cover", LootValue = 25, Stackable = false, ShieldHealth = 100, ShieldDuration = 15f }, + + // Consumables + new() { Id = 300, Name = "Repair Kit", Category = ItemCategory.Consumable, CraftCost = 10, Description = "Restores 30 health", LootValue = 8, Stackable = true, HealAmount = 30 }, + new() { Id = 301, Name = "Shield Booster", Category = ItemCategory.Consumable, CraftCost = 15, Description = "Temporary damage reduction", LootValue = 12, Stackable = true, ShieldBoostDuration = 10f, DamageReduction = 0.3f }, + new() { Id = 302, Name = "Speed Stim", Category = ItemCategory.Consumable, CraftCost = 12, Description = "Temporary speed boost", LootValue = 10, Stackable = true, SpeedBoostDuration = 8f, SpeedMultiplier = 1.5f }, + + // Armor + new() { Id = 400, Name = "Light Suit", Category = ItemCategory.Armor, CraftCost = 20, Description = "+20 max health", LootValue = 15, Stackable = false, HealthBonus = 20 }, + new() { Id = 401, Name = "Heavy Suit", Category = ItemCategory.Armor, CraftCost = 45, Description = "+50 max health, slower", LootValue = 35, Stackable = false, HealthBonus = 50, SpeedPenalty = 0.15f }, + new() { Id = 402, Name = "Thruster Pack", Category = ItemCategory.Armor, CraftCost = 30, Description = "Dash ability", LootValue = 25, Stackable = false, DashDistance = 100f, DashCooldown = 5f } + }; + + public static List GetDefaultRecipes() => new() + { + // Weapons + new() { Id = 1, ResultItemId = 100, ScrapCost = 5, EnergyCost = 2, RareCost = 0 }, + new() { Id = 2, ResultItemId = 101, ScrapCost = 8, EnergyCost = 3, RareCost = 0 }, + new() { Id = 3, ResultItemId = 102, ScrapCost = 10, EnergyCost = 5, RareCost = 2 }, + new() { Id = 4, ResultItemId = 103, ScrapCost = 15, EnergyCost = 8, RareCost = 4 }, + + // Tools + new() { Id = 10, ResultItemId = 200, ScrapCost = 6, EnergyCost = 3, RareCost = 0 }, + new() { Id = 11, ResultItemId = 201, ScrapCost = 8, EnergyCost = 4, RareCost = 1 }, + new() { Id = 12, ResultItemId = 202, ScrapCost = 12, EnergyCost = 6, RareCost = 2 }, + + // Consumables + new() { Id = 20, ResultItemId = 300, ScrapCost = 3, EnergyCost = 2, RareCost = 0 }, + new() { Id = 21, ResultItemId = 301, ScrapCost = 4, EnergyCost = 3, RareCost = 0 }, + new() { Id = 22, ResultItemId = 302, ScrapCost = 3, EnergyCost = 4, RareCost = 0 }, + + // Armor + new() { Id = 30, ResultItemId = 400, ScrapCost = 8, EnergyCost = 0, RareCost = 1 }, + new() { Id = 31, ResultItemId = 401, ScrapCost = 15, EnergyCost = 0, RareCost = 3 }, + new() { Id = 32, ResultItemId = 402, ScrapCost = 10, EnergyCost = 5, RareCost = 2 } + }; +} diff --git a/Migrations/20251204143006_AddVoidScavengersEntities.Designer.cs b/Migrations/20251204143006_AddVoidScavengersEntities.Designer.cs new file mode 100644 index 0000000..882c253 --- /dev/null +++ b/Migrations/20251204143006_AddVoidScavengersEntities.Designer.cs @@ -0,0 +1,831 @@ +// +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("20251204143006_AddVoidScavengersEntities")] + partial class AddVoidScavengersEntities + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("BannedUntil") + .HasColumnType("datetime(6)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Email") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IsBanned") + .HasColumnType("tinyint(1)"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("varbinary(64)"); + + b.Property("PasswordSalt") + .IsRequired() + .HasColumnType("varbinary(32)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("accounts", (string)null); + }); + + modelBuilder.Entity("Server.Data.Character", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("AppearanceJson") + .HasColumnType("json"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("FacingDeg") + .HasColumnType("float"); + + b.Property("HpCurrent") + .HasColumnType("int unsigned"); + + b.Property("HpMax") + .HasColumnType("int unsigned"); + + b.Property("Level") + .HasColumnType("int unsigned"); + + b.Property("MpCurrent") + .HasColumnType("int unsigned"); + + b.Property("MpMax") + .HasColumnType("int unsigned"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("PosX") + .HasColumnType("double"); + + b.Property("PosY") + .HasColumnType("double"); + + b.Property("PosZ") + .HasColumnType("double"); + + b.Property("StaminaCurrent") + .HasColumnType("int unsigned"); + + b.Property("StaminaMax") + .HasColumnType("int unsigned"); + + b.Property("StatDexterity") + .HasColumnType("int unsigned"); + + b.Property("StatEndurance") + .HasColumnType("int unsigned"); + + b.Property("StatIntelligence") + .HasColumnType("int unsigned"); + + b.Property("StatStrength") + .HasColumnType("int unsigned"); + + b.Property("StatWisdom") + .HasColumnType("int unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Xp") + .HasColumnType("bigint unsigned"); + + b.Property("ZoneId") + .HasColumnType("bigint unsigned"); + + b.HasKey("Id"); + + b.HasIndex("AccountId") + .IsUnique(); + + b.HasIndex("ZoneId"); + + b.ToTable("characters", (string)null); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("SlotCode") + .HasColumnType("tinyint unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotCode") + .IsUnique(); + + b.ToTable("equipment", (string)null); + }); + + modelBuilder.Entity("Server.Data.GameItem", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("AmmoType") + .HasColumnType("int"); + + b.Property("Category") + .HasColumnType("int"); + + b.Property("CraftCost") + .HasColumnType("int"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Damage") + .HasColumnType("int"); + + b.Property("DamageReduction") + .HasColumnType("float"); + + b.Property("DashCooldown") + .HasColumnType("float"); + + b.Property("DashDistance") + .HasColumnType("float"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ExplosionRadius") + .HasColumnType("float"); + + b.Property("FireRate") + .HasColumnType("float"); + + b.Property("HarvestMultiplier") + .HasColumnType("float"); + + b.Property("HealAmount") + .HasColumnType("int"); + + b.Property("HealthBonus") + .HasColumnType("int"); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("tinyint(1)") + .HasDefaultValue(true); + + b.Property("LootValue") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PelletCount") + .HasColumnType("int"); + + b.Property("ProjectileSpeed") + .HasColumnType("float"); + + b.Property("Range") + .HasColumnType("float"); + + b.Property("ScanCooldown") + .HasColumnType("float"); + + b.Property("ScanRadius") + .HasColumnType("float"); + + b.Property("ShieldBoostDuration") + .HasColumnType("float"); + + b.Property("ShieldDuration") + .HasColumnType("float"); + + b.Property("ShieldHealth") + .HasColumnType("int"); + + b.Property("SpeedBoostDuration") + .HasColumnType("float"); + + b.Property("SpeedMultiplier") + .HasColumnType("float"); + + b.Property("SpeedPenalty") + .HasColumnType("float"); + + b.Property("Spread") + .HasColumnType("float"); + + b.Property("Stackable") + .HasColumnType("tinyint(1)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("IsEnabled"); + + b.ToTable("game_items", (string)null); + }); + + modelBuilder.Entity("Server.Data.GameRecipe", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("EnergyCost") + .HasColumnType("int"); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("tinyint(1)") + .HasDefaultValue(true); + + b.Property("RareCost") + .HasColumnType("int"); + + b.Property("ResultItemId") + .HasColumnType("int"); + + b.Property("ScrapCost") + .HasColumnType("int"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("IsEnabled"); + + b.HasIndex("ResultItemId"); + + b.ToTable("game_recipes", (string)null); + }); + + modelBuilder.Entity("Server.Data.InventoryItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("Quantity") + .HasColumnType("int unsigned"); + + b.Property("SlotIndex") + .HasColumnType("int unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("CharacterId"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotIndex") + .IsUnique(); + + b.ToTable("inventories", (string)null); + }); + + modelBuilder.Entity("Server.Data.ItemTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemType") + .HasColumnType("tinyint unsigned"); + + b.Property("MaxStack") + .HasColumnType("int unsigned"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Rarity") + .HasColumnType("tinyint unsigned"); + + b.Property("StatsJson") + .HasColumnType("json"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Weight") + .HasColumnType("int unsigned"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("item_templates", (string)null); + }); + + modelBuilder.Entity("Server.Data.MatchHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("DamageDealt") + .HasColumnType("int"); + + b.Property("DamageTaken") + .HasColumnType("int"); + + b.Property("Deaths") + .HasColumnType("int"); + + b.Property("EloAfter") + .HasColumnType("int"); + + b.Property("EloChange") + .HasColumnType("int"); + + b.Property("EnergyCollected") + .HasColumnType("int"); + + b.Property("ItemsCrafted") + .HasColumnType("int"); + + b.Property("Kills") + .HasColumnType("int"); + + b.Property("MatchDurationSeconds") + .HasColumnType("int"); + + b.Property("MatchId") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Placement") + .HasColumnType("int"); + + b.Property("PlayedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("RareCollected") + .HasColumnType("int"); + + b.Property("Result") + .HasColumnType("int"); + + b.Property("ScrapCollected") + .HasColumnType("int"); + + b.Property("SurvivalTimeSeconds") + .HasColumnType("int"); + + b.Property("TotalPlayers") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("MatchId"); + + b.HasIndex("PlayedAt"); + + b.ToTable("match_history", (string)null); + }); + + modelBuilder.Entity("Server.Data.PlayerStats", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Deaths") + .HasColumnType("int"); + + b.Property("Elo") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1000); + + b.Property("Extractions") + .HasColumnType("int"); + + b.Property("ItemsCrafted") + .HasColumnType("int"); + + b.Property("Kills") + .HasColumnType("int"); + + b.Property("LongestSurvivalSeconds") + .HasColumnType("int"); + + b.Property("Losses") + .HasColumnType("int"); + + b.Property("MatchesPlayed") + .HasColumnType("int"); + + b.Property("TotalDamageDealt") + .HasColumnType("bigint"); + + b.Property("TotalDamageTaken") + .HasColumnType("bigint"); + + b.Property("TotalEnergyCollected") + .HasColumnType("bigint"); + + b.Property("TotalPlayTimeSeconds") + .HasColumnType("bigint"); + + b.Property("TotalRareCollected") + .HasColumnType("bigint"); + + b.Property("TotalScrapCollected") + .HasColumnType("bigint"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Wins") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AccountId") + .IsUnique(); + + b.ToTable("player_stats", (string)null); + }); + + modelBuilder.Entity("Server.Data.Session", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("CreatedIp") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ExpiresAt") + .HasColumnType("datetime(6)"); + + b.Property("RevokedAt") + .HasColumnType("datetime(6)"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("UserAgent") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("sessions", (string)null); + }); + + modelBuilder.Entity("Server.Data.Zone", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("MaxX") + .HasColumnType("double"); + + b.Property("MaxY") + .HasColumnType("double"); + + b.Property("MaxZ") + .HasColumnType("double"); + + b.Property("MinX") + .HasColumnType("double"); + + b.Property("MinY") + .HasColumnType("double"); + + b.Property("MinZ") + .HasColumnType("double"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("zones", (string)null); + }); + + modelBuilder.Entity("Server.Data.Character", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany("Characters") + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.Zone", "Zone") + .WithMany() + .HasForeignKey("ZoneId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Account"); + + b.Navigation("Zone"); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.HasOne("Server.Data.Character", "Character") + .WithMany() + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") + .WithMany() + .HasForeignKey("ItemTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Character"); + + b.Navigation("ItemTemplate"); + }); + + modelBuilder.Entity("Server.Data.GameRecipe", b => + { + b.HasOne("Server.Data.GameItem", "ResultItem") + .WithMany() + .HasForeignKey("ResultItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ResultItem"); + }); + + 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.MatchHistory", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany() + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.PlayerStats", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithOne() + .HasForeignKey("Server.Data.PlayerStats", "AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.Session", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany("Sessions") + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Navigation("Characters"); + + b.Navigation("Sessions"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Migrations/20251204143006_AddVoidScavengersEntities.cs b/Migrations/20251204143006_AddVoidScavengersEntities.cs new file mode 100644 index 0000000..aa4bc48 --- /dev/null +++ b/Migrations/20251204143006_AddVoidScavengersEntities.cs @@ -0,0 +1,118 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + /// + public partial class AddVoidScavengersEntities : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "game_items", + columns: table => new + { + Id = table.Column(type: "int", nullable: false), + Name = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Category = table.Column(type: "int", nullable: false), + CraftCost = table.Column(type: "int", nullable: false), + Description = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + LootValue = table.Column(type: "int", nullable: false), + Stackable = table.Column(type: "tinyint(1)", nullable: false), + IsEnabled = table.Column(type: "tinyint(1)", nullable: false, defaultValue: true), + Damage = table.Column(type: "int", nullable: false), + FireRate = table.Column(type: "float", nullable: false), + ProjectileSpeed = table.Column(type: "float", nullable: false), + Range = table.Column(type: "float", nullable: false), + AmmoType = table.Column(type: "int", nullable: false), + PelletCount = table.Column(type: "int", nullable: false), + Spread = table.Column(type: "float", nullable: false), + ExplosionRadius = table.Column(type: "float", nullable: false), + HarvestMultiplier = table.Column(type: "float", nullable: false), + ScanRadius = table.Column(type: "float", nullable: false), + ScanCooldown = table.Column(type: "float", nullable: false), + ShieldHealth = table.Column(type: "int", nullable: false), + ShieldDuration = table.Column(type: "float", nullable: false), + HealAmount = table.Column(type: "int", nullable: false), + ShieldBoostDuration = table.Column(type: "float", nullable: false), + DamageReduction = table.Column(type: "float", nullable: false), + SpeedBoostDuration = table.Column(type: "float", nullable: false), + SpeedMultiplier = table.Column(type: "float", nullable: false), + HealthBonus = table.Column(type: "int", nullable: false), + SpeedPenalty = table.Column(type: "float", nullable: false), + DashDistance = table.Column(type: "float", nullable: false), + DashCooldown = table.Column(type: "float", nullable: false), + CreatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)"), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)") + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn) + }, + constraints: table => + { + table.PrimaryKey("PK_game_items", x => x.Id); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "game_recipes", + columns: table => new + { + Id = table.Column(type: "int", nullable: false), + ResultItemId = table.Column(type: "int", nullable: false), + IsEnabled = table.Column(type: "tinyint(1)", nullable: false, defaultValue: true), + ScrapCost = table.Column(type: "int", nullable: false), + EnergyCost = table.Column(type: "int", nullable: false), + RareCost = table.Column(type: "int", nullable: false), + CreatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)"), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)") + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn) + }, + constraints: table => + { + table.PrimaryKey("PK_game_recipes", x => x.Id); + table.ForeignKey( + name: "FK_game_recipes_game_items_ResultItemId", + column: x => x.ResultItemId, + principalTable: "game_items", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_game_items_Category", + table: "game_items", + column: "Category"); + + migrationBuilder.CreateIndex( + name: "IX_game_items_IsEnabled", + table: "game_items", + column: "IsEnabled"); + + migrationBuilder.CreateIndex( + name: "IX_game_recipes_IsEnabled", + table: "game_recipes", + column: "IsEnabled"); + + migrationBuilder.CreateIndex( + name: "IX_game_recipes_ResultItemId", + table: "game_recipes", + column: "ResultItemId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "game_recipes"); + + migrationBuilder.DropTable( + name: "game_items"); + } + } +} diff --git a/Migrations/GameDbContextModelSnapshot.cs b/Migrations/GameDbContextModelSnapshot.cs index 100842e..32ee711 100644 --- a/Migrations/GameDbContextModelSnapshot.cs +++ b/Migrations/GameDbContextModelSnapshot.cs @@ -210,6 +210,168 @@ namespace SystemRevivalServer.Migrations b.ToTable("equipment", (string)null); }); + modelBuilder.Entity("Server.Data.GameItem", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("AmmoType") + .HasColumnType("int"); + + b.Property("Category") + .HasColumnType("int"); + + b.Property("CraftCost") + .HasColumnType("int"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Damage") + .HasColumnType("int"); + + b.Property("DamageReduction") + .HasColumnType("float"); + + b.Property("DashCooldown") + .HasColumnType("float"); + + b.Property("DashDistance") + .HasColumnType("float"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ExplosionRadius") + .HasColumnType("float"); + + b.Property("FireRate") + .HasColumnType("float"); + + b.Property("HarvestMultiplier") + .HasColumnType("float"); + + b.Property("HealAmount") + .HasColumnType("int"); + + b.Property("HealthBonus") + .HasColumnType("int"); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("tinyint(1)") + .HasDefaultValue(true); + + b.Property("LootValue") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PelletCount") + .HasColumnType("int"); + + b.Property("ProjectileSpeed") + .HasColumnType("float"); + + b.Property("Range") + .HasColumnType("float"); + + b.Property("ScanCooldown") + .HasColumnType("float"); + + b.Property("ScanRadius") + .HasColumnType("float"); + + b.Property("ShieldBoostDuration") + .HasColumnType("float"); + + b.Property("ShieldDuration") + .HasColumnType("float"); + + b.Property("ShieldHealth") + .HasColumnType("int"); + + b.Property("SpeedBoostDuration") + .HasColumnType("float"); + + b.Property("SpeedMultiplier") + .HasColumnType("float"); + + b.Property("SpeedPenalty") + .HasColumnType("float"); + + b.Property("Spread") + .HasColumnType("float"); + + b.Property("Stackable") + .HasColumnType("tinyint(1)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("IsEnabled"); + + b.ToTable("game_items", (string)null); + }); + + modelBuilder.Entity("Server.Data.GameRecipe", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("EnergyCost") + .HasColumnType("int"); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("tinyint(1)") + .HasDefaultValue(true); + + b.Property("RareCost") + .HasColumnType("int"); + + b.Property("ResultItemId") + .HasColumnType("int"); + + b.Property("ScrapCost") + .HasColumnType("int"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("IsEnabled"); + + b.HasIndex("ResultItemId"); + + b.ToTable("game_recipes", (string)null); + }); + modelBuilder.Entity("Server.Data.InventoryItem", b => { b.Property("Id") @@ -591,6 +753,17 @@ namespace SystemRevivalServer.Migrations b.Navigation("ItemTemplate"); }); + modelBuilder.Entity("Server.Data.GameRecipe", b => + { + b.HasOne("Server.Data.GameItem", "ResultItem") + .WithMany() + .HasForeignKey("ResultItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ResultItem"); + }); + modelBuilder.Entity("Server.Data.InventoryItem", b => { b.HasOne("Server.Data.Character", "Character") diff --git a/Program.cs b/Program.cs index 6fecc78..628d236 100644 --- a/Program.cs +++ b/Program.cs @@ -58,6 +58,9 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddControllers(); + // Health checks builder.Services.AddHealthChecks() .AddCheck("mysql", tags: new[] { "ready" }); @@ -181,5 +184,5 @@ app.Lifetime.ApplicationStopping.Register(() => // ---- (Optional) acquire a dev zone on startup ---- // var leases = app.Services.GetRequiredService(); // _ = leases.TryAcquireAsync(zoneId: 1); - +app.MapControllers(); await app.RunAsync(); diff --git a/data/GameDbContext.cs b/data/GameDbContext.cs index 697b492..372c9b9 100644 --- a/data/GameDbContext.cs +++ b/data/GameDbContext.cs @@ -16,6 +16,8 @@ public sealed class GameDbContext : DbContext public DbSet Equipment => Set(); public DbSet PlayerStats => Set(); public DbSet MatchHistory => Set(); + public DbSet GameItems => Set(); + public DbSet GameRecipes => Set(); protected override void OnModelCreating(ModelBuilder b) { diff --git a/data/entities/GameItem.cs b/data/entities/GameItem.cs new file mode 100644 index 0000000..c55a0a0 --- /dev/null +++ b/data/entities/GameItem.cs @@ -0,0 +1,84 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Server.Data; + +/// +/// Database-backed item definition for Void Scavengers +/// +public sealed class GameItem +{ + public int Id { get; set; } + public string Name { get; set; } = ""; + public ItemCategory Category { get; set; } + public int CraftCost { get; set; } + public string Description { get; set; } = ""; + public int LootValue { get; set; } + public bool Stackable { get; set; } + public bool IsEnabled { get; set; } = true; + + // Weapon stats (JSON or individual columns) + public int Damage { get; set; } + public float FireRate { get; set; } + public float ProjectileSpeed { get; set; } + public float Range { get; set; } + public int AmmoType { get; set; } + public int PelletCount { get; set; } = 1; + public float Spread { get; set; } + public float ExplosionRadius { get; set; } + + // Tool stats + public float HarvestMultiplier { get; set; } = 1f; + public float ScanRadius { get; set; } + public float ScanCooldown { get; set; } + public int ShieldHealth { get; set; } + public float ShieldDuration { get; set; } + + // Consumable stats + public int HealAmount { get; set; } + public float ShieldBoostDuration { get; set; } + public float DamageReduction { get; set; } + public float SpeedBoostDuration { get; set; } + public float SpeedMultiplier { get; set; } = 1f; + + // Armor stats + public int HealthBonus { get; set; } + public float SpeedPenalty { get; set; } + public float DashDistance { get; set; } + public float DashCooldown { get; set; } + + // Timestamps + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } +} + +public enum ItemCategory +{ + Resource = 0, + Weapon = 1, + Tool = 2, + Consumable = 3, + Armor = 4 +} + +public sealed class GameItemConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder e) + { + e.ToTable("game_items"); + e.HasKey(x => x.Id); + // Not auto-generated - we want specific IDs + e.Property(x => x.Id).ValueGeneratedNever(); + + e.Property(x => x.Name).HasMaxLength(64).IsRequired(); + e.Property(x => x.Description).HasMaxLength(256); + e.Property(x => x.IsEnabled).HasDefaultValue(true); + + e.HasIndex(x => x.Category); + e.HasIndex(x => x.IsEnabled); + + e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") + .ValueGeneratedOnAddOrUpdate(); + } +} diff --git a/data/entities/GameRecipe.cs b/data/entities/GameRecipe.cs new file mode 100644 index 0000000..4c37af9 --- /dev/null +++ b/data/entities/GameRecipe.cs @@ -0,0 +1,49 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Server.Data; + +/// +/// Database-backed crafting recipe for Void Scavengers +/// +public sealed class GameRecipe +{ + public int Id { get; set; } + public int ResultItemId { get; set; } + public bool IsEnabled { get; set; } = true; + + // Resource costs + public int ScrapCost { get; set; } + public int EnergyCost { get; set; } + public int RareCost { get; set; } + + // Timestamps + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + + // Navigation + public GameItem? ResultItem { get; set; } +} + +public sealed class GameRecipeConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder e) + { + e.ToTable("game_recipes"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedNever(); + + e.HasIndex(x => x.ResultItemId); + e.HasIndex(x => x.IsEnabled); + + e.HasOne(x => x.ResultItem) + .WithMany() + .HasForeignKey(x => x.ResultItemId) + .OnDelete(DeleteBehavior.Cascade); + + e.Property(x => x.IsEnabled).HasDefaultValue(true); + e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") + .ValueGeneratedOnAddOrUpdate(); + } +}