From 7de9bd2761dcca9f86bd7938500d2e58be02efc2 Mon Sep 17 00:00:00 2001 From: dingo Date: Sun, 4 Jan 2026 21:35:42 -0500 Subject: [PATCH] Refresh fix, Dungeon Builder v2 --- Game/Dungeon/DungeonGeneratorV3.cs | 1225 +++++++++++++++++++++ Game/Dungeon/DungeonHandler.cs | 72 +- Game/Dungeon/DungeonLayoutV2.cs | 71 +- Game/Dungeon/DungeonRoomV2.cs | 97 +- Game/Dungeon/LootService.cs | 11 +- Services/Admin/Pages/Api.cshtml.cs | 39 +- Services/Admin/Pages/Recipes/Index.cshtml | 9 +- Services/Admin/Pages/Server/Index.cshtml | 102 ++ 8 files changed, 1559 insertions(+), 67 deletions(-) create mode 100644 Game/Dungeon/DungeonGeneratorV3.cs diff --git a/Game/Dungeon/DungeonGeneratorV3.cs b/Game/Dungeon/DungeonGeneratorV3.cs new file mode 100644 index 0000000..f146e04 --- /dev/null +++ b/Game/Dungeon/DungeonGeneratorV3.cs @@ -0,0 +1,1225 @@ +using DataServer.Data; +using DataServer.Data.Entities; +using Microsoft.EntityFrameworkCore; +using System.Text.Json; + +namespace Server.Game.Dungeon; + +/// +/// Dungeon Generator V3 - Uses the DungeonBuilder system +/// Supports: BuilderRoomTemplates, TileTemplates, ObjectTemplates, DungeonPalettes +/// +public class DungeonGeneratorV3 +{ + private readonly GameDbContext _db; + private readonly Random _rng; + private readonly int _seed; + private readonly int _tier; + + // Palette-based configuration + private DungeonPalette? _palette; + private List _floorTemplates = new(); + private List _wallTemplates = new(); + private List _doorTemplates = new(); + private List _decorationTemplates = new(); + private List _containerTemplates = new(); + private List _trapTemplates = new(); + private List _roomTemplates = new(); + + // Categorized room templates + private List _entranceRooms = new(); + private List _exitRooms = new(); + private List _bossRooms = new(); + private List _treasureRooms = new(); + private List _normalRooms = new(); + + // Tile data cache + private Dictionary _tileDefinitions = new(); + private Dictionary _tileSheets = new(); + + // Generation parameters (from palette or defaults) + private int _minRooms = 5; + private int _maxRooms = 12; + private int _minRoomWidth = 6; + private int _maxRoomWidth = 16; + private int _minRoomHeight = 6; + private int _maxRoomHeight = 16; + private int _corridorWidth = 3; + private int _decorationDensity = 30; + private int _trapDensity = 10; + private int _containerDensity = 20; + + // Map dimensions (tier-scaled) + private int MapWidth => 60 + (_tier * 12); + private int MapHeight => 60 + (_tier * 12); + + // Tracking for results + public List UsedFloorTemplates { get; } = new(); + public List UsedWallTemplates { get; } = new(); + public List UsedObjectTemplates { get; } = new(); + public List UsedRoomTemplates { get; } = new(); + + public DungeonGeneratorV3(GameDbContext db, int seed, int tier = 1) + { + _db = db; + _seed = seed; + _rng = new Random(seed); + _tier = Math.Max(1, tier); + } + + /// + /// Generate a dungeon using the specified palette or auto-select based on tier + /// + public async Task GenerateAsync(int? paletteId = null, string? biome = null) + { + Console.WriteLine($"[DungeonGenV3] Starting generation: seed={_seed}, tier={_tier}, palette={paletteId}, biome={biome}"); + + // Load palette and templates (auto-selects if no palette/biome specified) + await LoadPaletteAsync(paletteId, biome); + await LoadTileDataAsync(); + + // Create layout + var layout = new DungeonLayoutV2(MapWidth, MapHeight); + layout.Seed = _seed; + layout.Tier = _tier; + + // Initialize all cells as walls + for (int y = 0; y < MapHeight; y++) + { + for (int x = 0; x < MapWidth; x++) + { + layout.Walkable[x, y] = false; + layout.Tiles[x, y] = 0; + } + } + + // Generate rooms + var rooms = await GenerateRoomsAsync(layout); + layout.Rooms.AddRange(rooms); + + // Connect rooms with corridors + ConnectRooms(layout, rooms); + + // Fill floor tiles + FillFloorTiles(layout); + + // Place wall tiles + PlaceWallTiles(layout); + + // Place objects (decorations, containers, traps) + await PlaceObjectsAsync(layout, rooms); + + // Set spawn points + SetSpawnPoints(layout, rooms); + + Console.WriteLine($"[DungeonGenV3] Generation complete: {rooms.Count} rooms, {layout.TileDetails.Count} tiles, {layout.Objects.Count} objects"); + + return layout; + } + + private async Task LoadPaletteAsync(int? paletteId, string? biome) + { + // Try to load specific palette by ID + if (paletteId.HasValue) + { + _palette = await _db.DungeonPalettes.FindAsync(paletteId.Value); + if (_palette != null) + { + Console.WriteLine($"[DungeonGenV3] Using specified palette: {_palette.Name}"); + } + } + + // Or find one by biome + if (_palette == null && !string.IsNullOrEmpty(biome)) + { + var biomePalettes = await _db.DungeonPalettes + .Where(p => p.IsEnabled && p.Biome == biome) + .ToListAsync(); + + if (biomePalettes.Count > 0) + { + // Randomly select from matching biome palettes + _palette = biomePalettes[_rng.Next(biomePalettes.Count)]; + Console.WriteLine($"[DungeonGenV3] Randomly selected palette '{_palette.Name}' from biome '{biome}'"); + } + } + + // Or randomly select from ALL enabled palettes (true dynamic selection) + if (_palette == null) + { + var allPalettes = await _db.DungeonPalettes + .Where(p => p.IsEnabled) + .ToListAsync(); + + if (allPalettes.Count > 0) + { + // Randomly select any enabled palette + _palette = allPalettes[_rng.Next(allPalettes.Count)]; + Console.WriteLine($"[DungeonGenV3] Randomly selected palette: {_palette.Name} (biome: {_palette.Biome ?? "none"})"); + } + } + + if (_palette != null) + { + Console.WriteLine($"[DungeonGenV3] Using palette: {_palette.Name}"); + + // Apply palette generation parameters + _minRooms = _palette.MinRooms; + _maxRooms = _palette.MaxRooms; + _minRoomWidth = _palette.MinRoomWidth; + _maxRoomWidth = _palette.MaxRoomWidth; + _minRoomHeight = _palette.MinRoomHeight; + _maxRoomHeight = _palette.MaxRoomHeight; + _corridorWidth = _rng.Next(_palette.MinCorridorWidth, _palette.MaxCorridorWidth + 1); + _decorationDensity = _palette.DecorationDensity; + _trapDensity = _palette.TrapDensity; + _containerDensity = _palette.ContainerDensity; + + // Load templates from palette + await LoadTemplatesFromPaletteAsync(); + } + else + { + Console.WriteLine($"[DungeonGenV3] No palette found, loading all enabled templates"); + await LoadAllTemplatesAsync(); + } + } + + private async Task LoadTemplatesFromPaletteAsync() + { + if (_palette == null) return; + + // Parse template ID arrays + var floorIds = ParseIds(_palette.FloorTemplateIdsJson); + var wallIds = ParseIds(_palette.WallTemplateIdsJson); + var doorIds = ParseIds(_palette.DoorTemplateIdsJson); + var decorIds = ParseIds(_palette.DecorationIdsJson); + var containerIds = ParseIds(_palette.ContainerIdsJson); + var trapIds = ParseIds(_palette.TrapIdsJson); + var roomIds = ParseIds(_palette.RoomTemplateIdsJson); + + // Load tile templates + if (floorIds.Any()) + { + _floorTemplates = await _db.TileTemplates + .Where(t => floorIds.Contains(t.Id) && t.IsEnabled) + .Where(t => t.MinTier <= _tier && (t.MaxTier == 0 || t.MaxTier >= _tier)) + .ToListAsync(); + } + + if (wallIds.Any()) + { + _wallTemplates = await _db.TileTemplates + .Where(t => wallIds.Contains(t.Id) && t.IsEnabled) + .Where(t => t.MinTier <= _tier && (t.MaxTier == 0 || t.MaxTier >= _tier)) + .ToListAsync(); + } + + if (doorIds.Any()) + { + _doorTemplates = await _db.TileTemplates + .Where(t => doorIds.Contains(t.Id) && t.IsEnabled) + .ToListAsync(); + } + + // Load object templates + if (decorIds.Any()) + { + _decorationTemplates = await _db.ObjectTemplates + .Where(o => decorIds.Contains(o.Id) && o.IsEnabled) + .Where(o => o.MinTier <= _tier && (o.MaxTier == 0 || o.MaxTier >= _tier)) + .ToListAsync(); + } + + if (containerIds.Any()) + { + _containerTemplates = await _db.ObjectTemplates + .Where(o => containerIds.Contains(o.Id) && o.IsEnabled) + .ToListAsync(); + } + + if (trapIds.Any()) + { + _trapTemplates = await _db.ObjectTemplates + .Where(o => trapIds.Contains(o.Id) && o.IsEnabled) + .Where(o => o.MinTier <= _tier && (o.MaxTier == 0 || o.MaxTier >= _tier)) + .ToListAsync(); + } + + // Load room templates + if (roomIds.Any()) + { + _roomTemplates = await _db.BuilderRoomTemplates + .Where(r => roomIds.Contains(r.Id) && r.IsEnabled) + .Where(r => r.MinTier <= _tier && (r.MaxTier == 0 || r.MaxTier >= _tier)) + .ToListAsync(); + } + + CategorizeRoomTemplates(); + LogTemplateStats(); + } + + private async Task LoadAllTemplatesAsync() + { + // Load all enabled templates for the current tier + _floorTemplates = await _db.TileTemplates + .Where(t => t.IsEnabled && t.Category == TileTemplateCategory.Floor) + .Where(t => t.MinTier <= _tier && (t.MaxTier == 0 || t.MaxTier >= _tier)) + .ToListAsync(); + + _wallTemplates = await _db.TileTemplates + .Where(t => t.IsEnabled && t.Category == TileTemplateCategory.Wall) + .Where(t => t.MinTier <= _tier && (t.MaxTier == 0 || t.MaxTier >= _tier)) + .ToListAsync(); + + _doorTemplates = await _db.TileTemplates + .Where(t => t.IsEnabled && t.Category == TileTemplateCategory.Door) + .ToListAsync(); + + _decorationTemplates = await _db.ObjectTemplates + .Where(o => o.IsEnabled && (o.Type == ObjectTemplateType.Decoration || o.Type == ObjectTemplateType.Furniture)) + .Where(o => o.MinTier <= _tier && (o.MaxTier == 0 || o.MaxTier >= _tier)) + .ToListAsync(); + + _containerTemplates = await _db.ObjectTemplates + .Where(o => o.IsEnabled && o.Type == ObjectTemplateType.Container) + .Where(o => o.MinTier <= _tier && (o.MaxTier == 0 || o.MaxTier >= _tier)) + .ToListAsync(); + + _trapTemplates = await _db.ObjectTemplates + .Where(o => o.IsEnabled && (o.Type == ObjectTemplateType.Trap || o.Type == ObjectTemplateType.Hazard)) + .Where(o => o.MinTier <= _tier && (o.MaxTier == 0 || o.MaxTier >= _tier)) + .ToListAsync(); + + _roomTemplates = await _db.BuilderRoomTemplates + .Where(r => r.IsEnabled) + .Where(r => r.MinTier <= _tier && (r.MaxTier == 0 || r.MaxTier >= _tier)) + .ToListAsync(); + + CategorizeRoomTemplates(); + LogTemplateStats(); + } + + private void CategorizeRoomTemplates() + { + foreach (var room in _roomTemplates) + { + switch (room.Type) + { + case RoomType.Entrance: + _entranceRooms.Add(room); + break; + case RoomType.Exit: + _exitRooms.Add(room); + break; + case RoomType.Boss: + _bossRooms.Add(room); + break; + case RoomType.Treasure: + _treasureRooms.Add(room); + break; + default: + _normalRooms.Add(room); + break; + } + } + } + + private void LogTemplateStats() + { + Console.WriteLine($"[DungeonGenV3] Loaded templates:"); + Console.WriteLine($" - Floor: {_floorTemplates.Count}"); + Console.WriteLine($" - Wall: {_wallTemplates.Count}"); + Console.WriteLine($" - Door: {_doorTemplates.Count}"); + Console.WriteLine($" - Decoration: {_decorationTemplates.Count}"); + Console.WriteLine($" - Container: {_containerTemplates.Count}"); + Console.WriteLine($" - Trap: {_trapTemplates.Count}"); + Console.WriteLine($" - Rooms: {_roomTemplates.Count} (Entrance:{_entranceRooms.Count}, Exit:{_exitRooms.Count}, Boss:{_bossRooms.Count}, Treasure:{_treasureRooms.Count}, Normal:{_normalRooms.Count})"); + } + + private async Task LoadTileDataAsync() + { + // Load all tile sheets with their tiles + var sheets = await _db.TileMapSheets + .Include(s => s.Tiles) + .Where(s => s.IsEnabled) + .ToListAsync(); + + foreach (var sheet in sheets) + { + _tileSheets[sheet.Id] = sheet; + if (sheet.Tiles != null) + { + foreach (var tile in sheet.Tiles) + { + tile.TileMapSheet = sheet; + _tileDefinitions[tile.Id] = tile; + } + } + } + + Console.WriteLine($"[DungeonGenV3] Loaded {_tileDefinitions.Count} tile definitions from {sheets.Count} sheets"); + } + + private async Task> GenerateRoomsAsync(DungeonLayoutV2 layout) + { + var rooms = new List(); + int targetRooms = _rng.Next(_minRooms, _maxRooms + 1); + + Console.WriteLine($"[DungeonGenV3] Generating {targetRooms} rooms"); + + // Place entrance room first + var entrance = await PlaceRoomAsync(layout, rooms, RoomType.Entrance, MapWidth / 4, MapHeight / 2); + if (entrance != null) rooms.Add(entrance); + + // Place exit room on opposite side + var exit = await PlaceRoomAsync(layout, rooms, RoomType.Exit, 3 * MapWidth / 4, MapHeight / 2); + if (exit != null) rooms.Add(exit); + + // Fill with other rooms + int attempts = 0; + while (rooms.Count < targetRooms && attempts < targetRooms * 10) + { + attempts++; + + var roomType = ChooseRoomType(rooms, targetRooms); + int x = _rng.Next(4, MapWidth - 20); + int y = _rng.Next(4, MapHeight - 20); + + var room = await PlaceRoomAsync(layout, rooms, roomType, x, y); + if (room != null) + { + rooms.Add(room); + } + } + + return rooms; + } + + private RoomType ChooseRoomType(List existing, int target) + { + bool hasBoss = existing.Any(r => r.Type == RoomType.Boss); + bool hasTreasure = existing.Any(r => r.Type == RoomType.Treasure); + + // Ensure we have a boss room + if (!hasBoss && existing.Count >= target - 2) + return RoomType.Boss; + + int roll = _rng.Next(100); + + if (roll < 8 && !hasBoss && _bossRooms.Count > 0) return RoomType.Boss; + if (roll < 20 && _treasureRooms.Count > 0) return RoomType.Treasure; + + return RoomType.Normal; + } + + private async Task PlaceRoomAsync(DungeonLayoutV2 layout, List existing, RoomType type, int preferX, int preferY) + { + // Select template based on room type + var templates = type switch + { + RoomType.Entrance => _entranceRooms, + RoomType.Exit => _exitRooms.Count > 0 ? _exitRooms : _bossRooms, + RoomType.Boss => _bossRooms, + RoomType.Treasure => _treasureRooms, + _ => _normalRooms + }; + + BuilderRoomTemplate? template = null; + int roomWidth, roomHeight; + + if (templates.Count > 0) + { + // Use weighted selection + template = SelectWeightedTemplate(templates); + roomWidth = template.Width; + roomHeight = template.Height; + + if (!UsedRoomTemplates.Contains(template.Name)) + UsedRoomTemplates.Add(template.Name); + } + else + { + // Generate random room dimensions + roomWidth = _rng.Next(_minRoomWidth, _maxRoomWidth + 1); + roomHeight = _rng.Next(_minRoomHeight, _maxRoomHeight + 1); + } + + // Find valid position + int x = Math.Clamp(preferX - roomWidth / 2, 2, MapWidth - roomWidth - 2); + int y = Math.Clamp(preferY - roomHeight / 2, 2, MapHeight - roomHeight - 2); + + var room = new DungeonRoomV2(x, y, roomWidth, roomHeight) + { + Type = type, + TemplateId = template?.Id ?? 0, + TemplateName = template?.Name ?? $"Procedural {type}" + }; + + // Check for overlaps + if (existing.Any(r => room.Intersects(r, padding: 3))) + { + // Try random positions + for (int attempt = 0; attempt < 15; attempt++) + { + x = _rng.Next(2, MapWidth - roomWidth - 2); + y = _rng.Next(2, MapHeight - roomHeight - 2); + room = new DungeonRoomV2(x, y, roomWidth, roomHeight) + { + Type = type, + TemplateId = template?.Id ?? 0, + TemplateName = template?.Name ?? $"Procedural {type}" + }; + + if (!existing.Any(r => room.Intersects(r, padding: 3))) + break; + } + + if (existing.Any(r => room.Intersects(r, padding: 3))) + return null; + } + + // Stamp template or carve procedural room + if (template != null) + { + await StampRoomTemplateAsync(layout, room, template); + } + else + { + CarveProceduralRoom(layout, room); + } + + // Set connection points + if (template != null && !string.IsNullOrEmpty(template.ConnectionPointsJson)) + { + try + { + room.ConnectionPoints = JsonSerializer.Deserialize>(template.ConnectionPointsJson) ?? new(); + } + catch { } + } + + if (room.ConnectionPoints.Count == 0) + { + room.ConnectionPoints = CreateDefaultConnectionPoints(room); + } + + return room; + } + + private async Task StampRoomTemplateAsync(DungeonLayoutV2 layout, DungeonRoomV2 room, BuilderRoomTemplate template) + { + Console.WriteLine($"[DungeonGenV3] Stamping room template '{template.Name}' at ({room.X},{room.Y})"); + + // Parse and place tiles from TileGridJson (new format from visual editor) + if (!string.IsNullOrEmpty(template.TileGridJson)) + { + try + { + var tiles = JsonSerializer.Deserialize>(template.TileGridJson); + if (tiles != null) + { + foreach (var t in tiles) + { + int worldX = room.X + t.X; + int worldY = room.Y + t.Y; + + if (worldX >= 0 && worldX < MapWidth && worldY >= 0 && worldY < MapHeight) + { + // Find or create tile definition + var tileDef = _tileDefinitions.Values + .FirstOrDefault(td => td.TileMapSheetId == t.SheetId && td.FrameIndex == t.FrameIndex); + + if (tileDef != null) + { + layout.Tiles[worldX, worldY] = tileDef.Id; + layout.Walkable[worldX, worldY] = tileDef.IsWalkable; + + layout.TileDetails.Add(new PlacedTile + { + X = worldX, + Y = worldY, + TileDefinitionId = tileDef.Id, + SheetId = t.SheetId, + FrameIndex = t.FrameIndex, + Layer = 0 + }); + } + else + { + // No tile definition, just mark walkable and store sheet/frame + layout.Walkable[worldX, worldY] = true; + layout.TileDetails.Add(new PlacedTile + { + X = worldX, + Y = worldY, + TileDefinitionId = 0, + SheetId = t.SheetId, + FrameIndex = t.FrameIndex, + Layer = 0 + }); + } + } + } + } + } + catch (Exception ex) + { + Console.WriteLine($"[DungeonGenV3] Error parsing TileGridJson: {ex.Message}"); + } + } + + // Place objects from ObjectPlacementsJson + if (!string.IsNullOrEmpty(template.ObjectPlacementsJson)) + { + try + { + var objects = JsonSerializer.Deserialize>(template.ObjectPlacementsJson); + if (objects != null) + { + foreach (var obj in objects) + { + int worldX = room.X + obj.X; + int worldY = room.Y + obj.Y; + + var objTemplate = await _db.ObjectTemplates.FindAsync(obj.ObjectTemplateId); + if (objTemplate != null) + { + layout.Objects.Add(new PlacedObject + { + X = worldX, + Y = worldY, + ObjectTemplateId = objTemplate.Id, + Name = objTemplate.Name, + Type = objTemplate.Type.ToString(), + SpriteSheetId = objTemplate.SpriteSheetId ?? 0, + FrameIndex = objTemplate.FrameIndex, + BlocksMovement = objTemplate.BlocksMovement, + IsInteractable = objTemplate.IsInteractable + }); + + if (objTemplate.BlocksMovement) + { + layout.Walkable[worldX, worldY] = false; + } + + if (!UsedObjectTemplates.Contains(objTemplate.Name)) + UsedObjectTemplates.Add(objTemplate.Name); + } + } + } + } + catch { } + } + + // Handle mob spawns from template + if (!string.IsNullOrEmpty(template.MobSpawnsJson)) + { + try + { + var spawns = JsonSerializer.Deserialize>(template.MobSpawnsJson); + if (spawns != null) + { + foreach (var spawn in spawns) + { + room.MobSpawns.Add(new RoomMobSpawn + { + X = room.X + spawn.X, + Y = room.Y + spawn.Y, + Type = spawn.Type, + Count = spawn.Count + }); + } + } + } + catch { } + } + + // Set player spawn if entrance room + if (template.PlayerSpawnX.HasValue && template.PlayerSpawnY.HasValue) + { + room.PlayerSpawnX = room.X + template.PlayerSpawnX.Value; + room.PlayerSpawnY = room.Y + template.PlayerSpawnY.Value; + } + + // Set exit portal if exit room + if (template.ExitPortalX.HasValue && template.ExitPortalY.HasValue) + { + room.ExitX = room.X + template.ExitPortalX.Value; + room.ExitY = room.Y + template.ExitPortalY.Value; + } + } + + private void CarveProceduralRoom(DungeonLayoutV2 layout, DungeonRoomV2 room) + { + Console.WriteLine($"[DungeonGenV3] Carving procedural room at ({room.X},{room.Y}) size {room.Width}x{room.Height}"); + + // Carve floor + for (int y = room.Y; y < room.Y + room.Height; y++) + { + for (int x = room.X; x < room.X + room.Width; x++) + { + if (x >= 0 && x < MapWidth && y >= 0 && y < MapHeight) + { + layout.Walkable[x, y] = true; + } + } + } + } + + private List CreateDefaultConnectionPoints(DungeonRoomV2 room) + { + return new List + { + new() { X = room.Width / 2, Y = 0, Direction = "north", Width = _corridorWidth }, + new() { X = room.Width / 2, Y = room.Height - 1, Direction = "south", Width = _corridorWidth }, + new() { X = 0, Y = room.Height / 2, Direction = "west", Width = _corridorWidth }, + new() { X = room.Width - 1, Y = room.Height / 2, Direction = "east", Width = _corridorWidth } + }; + } + + private void ConnectRooms(DungeonLayoutV2 layout, List rooms) + { + if (rooms.Count < 2) return; + + // Connect rooms in sequence (MST-like) + var connected = new HashSet { 0 }; + var unconnected = new HashSet(Enumerable.Range(1, rooms.Count - 1)); + + while (unconnected.Count > 0) + { + int bestFrom = -1, bestTo = -1; + double bestDist = double.MaxValue; + + foreach (var from in connected) + { + foreach (var to in unconnected) + { + var dist = Distance(rooms[from], rooms[to]); + if (dist < bestDist) + { + bestDist = dist; + bestFrom = from; + bestTo = to; + } + } + } + + if (bestFrom >= 0 && bestTo >= 0) + { + CarveCorridor(layout, rooms[bestFrom], rooms[bestTo]); + connected.Add(bestTo); + unconnected.Remove(bestTo); + } + else + { + break; + } + } + } + + private double Distance(DungeonRoomV2 a, DungeonRoomV2 b) + { + int ax = a.X + a.Width / 2; + int ay = a.Y + a.Height / 2; + int bx = b.X + b.Width / 2; + int by = b.Y + b.Height / 2; + return Math.Sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by)); + } + + private void CarveCorridor(DungeonLayoutV2 layout, DungeonRoomV2 from, DungeonRoomV2 to) + { + int x1 = from.X + from.Width / 2; + int y1 = from.Y + from.Height / 2; + int x2 = to.X + to.Width / 2; + int y2 = to.Y + to.Height / 2; + + // L-shaped corridor + if (_rng.Next(2) == 0) + { + CarveHorizontalCorridor(layout, x1, x2, y1); + CarveVerticalCorridor(layout, y1, y2, x2); + } + else + { + CarveVerticalCorridor(layout, y1, y2, x1); + CarveHorizontalCorridor(layout, x1, x2, y2); + } + } + + private void CarveHorizontalCorridor(DungeonLayoutV2 layout, int x1, int x2, int y) + { + int minX = Math.Min(x1, x2); + int maxX = Math.Max(x1, x2); + int halfWidth = _corridorWidth / 2; + + for (int x = minX; x <= maxX; x++) + { + for (int dy = -halfWidth; dy <= halfWidth; dy++) + { + int cy = y + dy; + if (x >= 0 && x < MapWidth && cy >= 0 && cy < MapHeight) + { + layout.Walkable[x, cy] = true; + } + } + } + } + + private void CarveVerticalCorridor(DungeonLayoutV2 layout, int y1, int y2, int x) + { + int minY = Math.Min(y1, y2); + int maxY = Math.Max(y1, y2); + int halfWidth = _corridorWidth / 2; + + for (int y = minY; y <= maxY; y++) + { + for (int dx = -halfWidth; dx <= halfWidth; dx++) + { + int cx = x + dx; + if (cx >= 0 && cx < MapWidth && y >= 0 && y < MapHeight) + { + layout.Walkable[cx, y] = true; + } + } + } + } + + private void FillFloorTiles(DungeonLayoutV2 layout) + { + Console.WriteLine($"[DungeonGenV3] Filling floor tiles with {_floorTemplates.Count} templates"); + + for (int y = 0; y < MapHeight; y++) + { + for (int x = 0; x < MapWidth; x++) + { + // Only fill walkable cells that don't have tiles yet + if (layout.Walkable[x, y] && layout.Tiles[x, y] == 0) + { + var tile = SelectFloorTile(x, y); + if (tile != null) + { + layout.Tiles[x, y] = tile.Id; + layout.TileDetails.Add(new PlacedTile + { + X = x, + Y = y, + TileDefinitionId = tile.Id, + SheetId = tile.TileMapSheetId, + FrameIndex = tile.FrameIndex, + Layer = 0 + }); + } + } + } + } + } + + private TileDefinition? SelectFloorTile(int x, int y) + { + // First try to use floor templates + if (_floorTemplates.Count > 0) + { + var template = SelectWeightedTemplate(_floorTemplates); + if (template != null && template.PrimaryTileDefinitionId.HasValue) + { + if (_tileDefinitions.TryGetValue(template.PrimaryTileDefinitionId.Value, out var tileDef)) + { + if (!UsedFloorTemplates.Contains(template.Name)) + UsedFloorTemplates.Add(template.Name); + return tileDef; + } + } + + // Try to parse TilesJson for the template + if (template != null && !string.IsNullOrEmpty(template.TilesJson)) + { + try + { + var tiles = JsonSerializer.Deserialize>(template.TilesJson); + if (tiles?.Count > 0) + { + var first = tiles[0]; + // Find matching tile definition + var match = _tileDefinitions.Values + .FirstOrDefault(t => t.TileMapSheetId == first.SheetId && t.FrameIndex == first.FrameIndex); + if (match != null) + { + if (!UsedFloorTemplates.Contains(template.Name)) + UsedFloorTemplates.Add(template.Name); + return match; + } + } + } + catch { } + } + } + + // Fallback to any walkable tile + var walkableTiles = _tileDefinitions.Values.Where(t => t.IsWalkable).ToList(); + if (walkableTiles.Count > 0) + { + return walkableTiles[_rng.Next(walkableTiles.Count)]; + } + + return _tileDefinitions.Values.FirstOrDefault(); + } + + private void PlaceWallTiles(DungeonLayoutV2 layout) + { + Console.WriteLine($"[DungeonGenV3] Placing wall tiles with {_wallTemplates.Count} templates"); + + // Find cells adjacent to walkable that aren't walkable themselves + for (int y = 0; y < MapHeight; y++) + { + for (int x = 0; x < MapWidth; x++) + { + if (!layout.Walkable[x, y] && HasAdjacentWalkable(layout, x, y) && layout.Tiles[x, y] == 0) + { + var tile = SelectWallTile(x, y, layout); + if (tile != null) + { + layout.Tiles[x, y] = tile.Id; + layout.TileDetails.Add(new PlacedTile + { + X = x, + Y = y, + TileDefinitionId = tile.Id, + SheetId = tile.TileMapSheetId, + FrameIndex = tile.FrameIndex, + Layer = 0 + }); + } + } + } + } + } + + private bool HasAdjacentWalkable(DungeonLayoutV2 layout, int x, int y) + { + int[] dx = { 0, 1, 0, -1, 1, 1, -1, -1 }; + int[] dy = { -1, 0, 1, 0, -1, 1, 1, -1 }; + + for (int i = 0; i < 8; i++) + { + int nx = x + dx[i]; + int ny = y + dy[i]; + if (nx >= 0 && nx < MapWidth && ny >= 0 && ny < MapHeight && layout.Walkable[nx, ny]) + return true; + } + return false; + } + + private TileDefinition? SelectWallTile(int x, int y, DungeonLayoutV2 layout) + { + if (_wallTemplates.Count > 0) + { + var template = SelectWeightedTemplate(_wallTemplates); + if (template != null && template.PrimaryTileDefinitionId.HasValue) + { + if (_tileDefinitions.TryGetValue(template.PrimaryTileDefinitionId.Value, out var tileDef)) + { + if (!UsedWallTemplates.Contains(template.Name)) + UsedWallTemplates.Add(template.Name); + return tileDef; + } + } + } + + // Fallback to any non-walkable tile + var wallTiles = _tileDefinitions.Values.Where(t => !t.IsWalkable).ToList(); + if (wallTiles.Count > 0) + { + return wallTiles[_rng.Next(wallTiles.Count)]; + } + + return null; + } + + private async Task PlaceObjectsAsync(DungeonLayoutV2 layout, List rooms) + { + Console.WriteLine($"[DungeonGenV3] Placing objects (decor:{_decorationDensity}%, trap:{_trapDensity}%, container:{_containerDensity}%)"); + + foreach (var room in rooms) + { + // Skip entrance/exit for traps + bool canHaveTraps = room.Type != RoomType.Entrance; + + // Calculate target counts based on room size and density + int floorTiles = room.Width * room.Height; + int decorTarget = (floorTiles * _decorationDensity) / 1000; + int trapTarget = canHaveTraps ? (floorTiles * _trapDensity) / 1000 : 0; + int containerTarget = (floorTiles * _containerDensity) / 1000; + + // Place decorations + for (int i = 0; i < decorTarget && _decorationTemplates.Count > 0; i++) + { + var pos = FindValidObjectPosition(layout, room); + if (pos.HasValue) + { + var obj = SelectWeightedTemplate(_decorationTemplates); + PlaceObject(layout, pos.Value.x, pos.Value.y, obj); + } + } + + // Place containers (chests, etc.) + for (int i = 0; i < containerTarget && _containerTemplates.Count > 0; i++) + { + var pos = FindValidObjectPosition(layout, room); + if (pos.HasValue) + { + var obj = SelectWeightedTemplate(_containerTemplates); + PlaceObject(layout, pos.Value.x, pos.Value.y, obj); + } + } + + // Place traps + for (int i = 0; i < trapTarget && _trapTemplates.Count > 0; i++) + { + var pos = FindValidObjectPosition(layout, room); + if (pos.HasValue) + { + var obj = SelectWeightedTemplate(_trapTemplates); + PlaceObject(layout, pos.Value.x, pos.Value.y, obj); + } + } + } + } + + private (int x, int y)? FindValidObjectPosition(DungeonLayoutV2 layout, DungeonRoomV2 room) + { + for (int attempt = 0; attempt < 20; attempt++) + { + int x = room.X + _rng.Next(1, room.Width - 1); + int y = room.Y + _rng.Next(1, room.Height - 1); + + if (x >= 0 && x < MapWidth && y >= 0 && y < MapHeight && + layout.Walkable[x, y] && + !layout.Objects.Any(o => o.X == x && o.Y == y)) + { + return (x, y); + } + } + return null; + } + + private void PlaceObject(DungeonLayoutV2 layout, int x, int y, ObjectTemplate? obj) + { + if (obj == null) return; + + // Determine if it's a trap based on type + bool isTrap = obj.Type == ObjectTemplateType.Trap || obj.Type == ObjectTemplateType.Hazard; + + layout.Objects.Add(new PlacedObject + { + X = x, + Y = y, + ObjectTemplateId = obj.Id, + Name = obj.Name, + Type = obj.Type.ToString(), + SpriteSheetId = obj.SpriteSheetId ?? 0, + FrameIndex = obj.FrameIndex, + BlocksMovement = obj.BlocksMovement, + IsInteractable = obj.IsInteractable, + IsTrap = isTrap, + TrapDamage = obj.Damage, + LootTableId = obj.LootTableId + }); + + if (obj.BlocksMovement) + { + layout.Walkable[x, y] = false; + } + + if (!UsedObjectTemplates.Contains(obj.Name)) + UsedObjectTemplates.Add(obj.Name); + } + + private void SetSpawnPoints(DungeonLayoutV2 layout, List rooms) + { + // Find entrance room for player spawn + var entrance = rooms.FirstOrDefault(r => r.Type == RoomType.Entrance); + if (entrance != null) + { + if (entrance.PlayerSpawnX.HasValue && entrance.PlayerSpawnY.HasValue) + { + layout.PlayerSpawnX = entrance.PlayerSpawnX.Value; + layout.PlayerSpawnY = entrance.PlayerSpawnY.Value; + } + else + { + layout.PlayerSpawnX = entrance.X + entrance.Width / 2; + layout.PlayerSpawnY = entrance.Y + entrance.Height / 2; + } + + // Set legacy SpawnPoint too + layout.SpawnPoint = new DungeonPoint { X = layout.PlayerSpawnX, Y = layout.PlayerSpawnY }; + } + + // Find exit room for portal + var exit = rooms.FirstOrDefault(r => r.Type == RoomType.Exit); + if (exit != null) + { + if (exit.ExitX.HasValue && exit.ExitY.HasValue) + { + layout.ExitX = exit.ExitX.Value; + layout.ExitY = exit.ExitY.Value; + } + else + { + layout.ExitX = exit.X + exit.Width / 2; + layout.ExitY = exit.Y + exit.Height / 2; + } + } + + int mobId = 0; + int roomIndex = 0; + + // Collect mob spawns from all rooms + foreach (var room in rooms) + { + // Add spawns from template - convert RoomMobSpawn to DungeonMobSpawn + foreach (var spawn in room.MobSpawns) + { + var mobType = spawn.Type?.ToLower() switch + { + "boss" => DungeonMobSpawnType.Boss, + "elite" => DungeonMobSpawnType.Elite, + _ => DungeonMobSpawnType.Normal + }; + + for (int i = 0; i < spawn.Count; i++) + { + layout.MobSpawns.Add(new DungeonMobSpawn + { + Id = mobId++, + X = spawn.X, + Y = spawn.Y, + MobType = mobType, + RoomIndex = roomIndex, + IsAlive = true + }); + } + } + + // Add procedural spawns for rooms without template spawns + if (room.MobSpawns.Count == 0 && room.Type != RoomType.Entrance) + { + int mobCount = room.Type switch + { + RoomType.Boss => 1, + RoomType.Treasure => _rng.Next(1, 3), + _ => _rng.Next(2, 5) + }; + + var mobType = room.Type == RoomType.Boss ? DungeonMobSpawnType.Boss : DungeonMobSpawnType.Normal; + + for (int i = 0; i < mobCount; i++) + { + int mx = room.X + _rng.Next(1, room.Width - 1); + int my = room.Y + _rng.Next(1, room.Height - 1); + + layout.MobSpawns.Add(new DungeonMobSpawn + { + Id = mobId++, + X = mx, + Y = my, + MobType = mobType, + RoomIndex = roomIndex, + IsAlive = true + }); + } + } + + roomIndex++; + } + + layout.TotalMobs = layout.MobSpawns.Count; + + Console.WriteLine($"[DungeonGenV3] Spawn points: Player=({layout.PlayerSpawnX},{layout.PlayerSpawnY}), Exit=({layout.ExitX},{layout.ExitY}), Mobs={layout.MobSpawns.Count}"); + } + + // Helper methods + + private T? SelectWeightedTemplate(List templates) where T : class + { + if (templates.Count == 0) return null; + if (templates.Count == 1) return templates[0]; + + // Get weight property via reflection or assume equal weights + int totalWeight = 0; + var weights = new List(); + + foreach (var t in templates) + { + int weight = 100; + var weightProp = t.GetType().GetProperty("Weight"); + if (weightProp != null) + { + weight = (int)(weightProp.GetValue(t) ?? 100); + } + weights.Add(weight); + totalWeight += weight; + } + + int roll = _rng.Next(totalWeight); + int cumulative = 0; + + for (int i = 0; i < templates.Count; i++) + { + cumulative += weights[i]; + if (roll < cumulative) + return templates[i]; + } + + return templates[^1]; + } + + private List ParseIds(string? json) + { + if (string.IsNullOrEmpty(json)) return new List(); + try + { + return JsonSerializer.Deserialize>(json) ?? new List(); + } + catch + { + return new List(); + } + } + + // JSON helper classes + private class RoomTilePlacement + { + public int X { get; set; } + public int Y { get; set; } + public int SheetId { get; set; } + public int FrameIndex { get; set; } + } + + private class TemplateTilePlacement + { + public int X { get; set; } + public int Y { get; set; } + public int SheetId { get; set; } + public int FrameIndex { get; set; } + public int? TileDefId { get; set; } + } +} + +// Extended classes for DungeonLayoutV2 if not already defined +public class PlacedObject +{ + public int X { get; set; } + public int Y { get; set; } + public int ObjectTemplateId { get; set; } + public string Name { get; set; } = ""; + public string Type { get; set; } = ""; + public int SpriteSheetId { get; set; } + public int FrameIndex { get; set; } + public bool BlocksMovement { get; set; } + public bool IsInteractable { get; set; } + public bool IsTrap { get; set; } + public int TrapDamage { get; set; } + public int? LootTableId { get; set; } +} diff --git a/Game/Dungeon/DungeonHandler.cs b/Game/Dungeon/DungeonHandler.cs index 03e66d0..9ea848f 100644 --- a/Game/Dungeon/DungeonHandler.cs +++ b/Game/Dungeon/DungeonHandler.cs @@ -670,16 +670,16 @@ public sealed partial class DungeonHandler : IClientMessageHandler using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - var generator = new DungeonGeneratorV2(db, seed, tier); + var generator = new DungeonGeneratorV3(db, seed, tier); layoutV2 = await generator.GenerateAsync(); layout = layoutV2; // V2 extends V1, use directly - _log.LogInformation("Generated dungeon with V2 generator - {RoomCount} rooms, {TileCount} visual tiles", + _log.LogInformation("Generated dungeon with V3 generator - {RoomCount} rooms, {TileCount} visual tiles", layoutV2.Rooms.Count, layoutV2.TileDetails?.Count ?? 0); } catch (Exception ex) { - _log.LogWarning(ex, "V2 dungeon generator failed, falling back to V1"); + _log.LogWarning(ex, "V3 dungeon generator failed, falling back to V1"); layout = DungeonGenerator.Generate(seed, tier); } @@ -744,6 +744,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler // Build visual tile data if V2 layout available object? tileSheets = null; object? visualTiles = null; + object? placedObjects = null; _log.LogInformation("LayoutV2 is null: {IsNull}, TileDetails count: {Count}", instance.LayoutV2 == null, instance.LayoutV2?.TileDetails?.Count ?? 0); @@ -775,8 +776,28 @@ public sealed partial class DungeonHandler : IClientMessageHandler fy = t.FlipY }).ToArray(); - _log.LogInformation("Sending {SheetCount} sheets, {TileCount} visual tiles to client", - instance.LayoutV2.TileMapSheets.Count, instance.LayoutV2.TileDetails.Count); + // V3: Include placed objects (decorations, containers, traps) + if (instance.LayoutV2.Objects?.Count > 0) + { + placedObjects = instance.LayoutV2.Objects.Select(o => new + { + x = o.X, + y = o.Y, + id = o.ObjectTemplateId, + name = o.Name, + type = o.Type, + sheetId = o.SpriteSheetId, + frame = o.FrameIndex, + blocks = o.BlocksMovement, + interact = o.IsInteractable, + trap = o.IsTrap, + damage = o.TrapDamage, + loot = o.LootTableId + }).ToArray(); + } + + _log.LogInformation("Sending {SheetCount} sheets, {TileCount} visual tiles, {ObjectCount} objects to client", + instance.LayoutV2.TileMapSheets.Count, instance.LayoutV2.TileDetails.Count, instance.LayoutV2.Objects?.Count ?? 0); } await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new @@ -820,9 +841,10 @@ public sealed partial class DungeonHandler : IClientMessageHandler y = p.Y, type = p.Type.ToString().ToLower() }), - // V2 visual tile data + // V3 visual tile data tileSheets, - visualTiles + visualTiles, + placedObjects }, ct); } @@ -2152,16 +2174,16 @@ public sealed partial class DungeonHandler : IClientMessageHandler using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - var generator = new DungeonGeneratorV2(db, seed, tier); + var generator = new DungeonGeneratorV3(db, seed, tier); layoutV2 = await generator.GenerateAsync(); layout = layoutV2; // V2 extends V1, use directly - _log.LogInformation("Generated dungeon with V2 generator - {RoomCount} rooms, {TileCount} visual tiles", + _log.LogInformation("Generated dungeon with V3 generator - {RoomCount} rooms, {TileCount} visual tiles", layoutV2.Rooms.Count, layoutV2.TileDetails?.Count ?? 0); } catch (Exception ex) { - _log.LogWarning(ex, "V2 dungeon generator failed, falling back to V1"); + _log.LogWarning(ex, "V3 dungeon generator failed, falling back to V1"); layout = DungeonGenerator.Generate(seed, tier); } @@ -2323,6 +2345,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler // Build visual tile data if V2 layout available object? tileSheets = null; object? visualTiles = null; + object? placedObjects = null; if (instance.LayoutV2 != null && instance.LayoutV2.TileDetails.Count > 0) { @@ -2350,8 +2373,28 @@ public sealed partial class DungeonHandler : IClientMessageHandler fy = t.FlipY }).ToArray(); - _log.LogInformation("Sending {SheetCount} sheets, {TileCount} visual tiles to client", - instance.LayoutV2.TileMapSheets.Count, instance.LayoutV2.TileDetails.Count); + // V3: Include placed objects (decorations, containers, traps) + if (instance.LayoutV2.Objects?.Count > 0) + { + placedObjects = instance.LayoutV2.Objects.Select(o => new + { + x = o.X, + y = o.Y, + id = o.ObjectTemplateId, + name = o.Name, + type = o.Type, + sheetId = o.SpriteSheetId, + frame = o.FrameIndex, + blocks = o.BlocksMovement, + interact = o.IsInteractable, + trap = o.IsTrap, + damage = o.TrapDamage, + loot = o.LootTableId + }).ToArray(); + } + + _log.LogInformation("Sending {SheetCount} sheets, {TileCount} visual tiles, {ObjectCount} objects to client", + instance.LayoutV2.TileMapSheets.Count, instance.LayoutV2.TileDetails.Count, instance.LayoutV2.Objects?.Count ?? 0); } await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new @@ -2402,9 +2445,10 @@ public sealed partial class DungeonHandler : IClientMessageHandler y = p.Y, type = p.Type.ToString().ToLower() }), - // V2 visual tile data + // V3 visual tile data tileSheets, - visualTiles + visualTiles, + placedObjects }, ct); _log.LogInformation("Player {Name} (Level {Level}) joined dungeon {Id}", diff --git a/Game/Dungeon/DungeonLayoutV2.cs b/Game/Dungeon/DungeonLayoutV2.cs index 2b437e2..f6671b8 100644 --- a/Game/Dungeon/DungeonLayoutV2.cs +++ b/Game/Dungeon/DungeonLayoutV2.cs @@ -18,6 +18,33 @@ public class DungeonLayoutV2 : DungeonLayout /// public List TileMapSheets { get; set; } = new(); + /// + /// Placed objects (decorations, containers, traps) + /// + public List Objects { get; set; } = new(); + + /// + /// Player spawn position + /// + public int PlayerSpawnX { get; set; } + public int PlayerSpawnY { get; set; } + + /// + /// Exit portal position + /// + public int ExitX { get; set; } + public int ExitY { get; set; } + + public DungeonLayoutV2() : base() { } + + public DungeonLayoutV2(int width, int height) + { + Width = width; + Height = height; + Tiles = new int[width, height]; + Walkable = new bool[width, height]; + } + /// /// Build tile data optimized for client transmission /// @@ -31,6 +58,14 @@ public class DungeonLayoutV2 : DungeonLayout .Distinct() .ToList(); + // Also add sheets from direct SheetId references + var directSheetIds = TileDetails + .Where(t => t.SheetId > 0) + .Select(t => t.SheetId) + .Distinct(); + sheetIds.AddRange(directSheetIds); + sheetIds = sheetIds.Distinct().ToList(); + var sheets = tileDefinitions.Values .Where(t => sheetIds.Contains(t.TileMapSheetId)) .Select(t => t.TileMapSheet) @@ -76,7 +111,8 @@ public class DungeonLayoutV2 : DungeonLayout height = Height, tileSize = TileSize, tilesRLE = SerializeTilesRLE(), - spawn = new { x = SpawnPoint.X, y = SpawnPoint.Y }, + spawn = new { x = PlayerSpawnX > 0 ? PlayerSpawnX : SpawnPoint.X, y = PlayerSpawnY > 0 ? PlayerSpawnY : SpawnPoint.Y }, + exit = new { x = ExitX, y = ExitY }, rooms = Rooms.Select(r => new { x = r.X, y = r.Y, w = r.Width, h = r.Height, @@ -96,7 +132,23 @@ public class DungeonLayoutV2 : DungeonLayout type = c.ChestType.ToString(), roomIndex = c.RoomIndex }), - // New: Visual tile data + // Objects (decorations, containers, traps) + objects = Objects.Select(o => new + { + x = o.X, + y = o.Y, + id = o.ObjectTemplateId, + name = o.Name, + type = o.Type, + sheetId = o.SpriteSheetId, + frame = o.FrameIndex, + blocks = o.BlocksMovement, + interact = o.IsInteractable, + trap = o.IsTrap, + damage = o.TrapDamage, + loot = o.LootTableId + }), + // Tile sheets tileSheets = TileMapSheets.Select(s => new { id = s.Id, @@ -108,11 +160,14 @@ public class DungeonLayoutV2 : DungeonLayout cols = s.Columns, rows = s.Rows }), + // Visual tile details visualTiles = TileDetails.Select(t => new { x = t.X, y = t.Y, tid = t.TileDefinitionId, + sid = t.SheetId, + f = t.FrameIndex, l = t.Layer, r = t.Rotation, fx = t.FlipX, @@ -134,10 +189,12 @@ public class DungeonLayoutV2 : DungeonLayout height = Height, tileSize = TileSize, tilesRLE = SerializeTilesRLE(), - spawn = new { x = SpawnPoint.X, y = SpawnPoint.Y }, + spawn = new { x = PlayerSpawnX > 0 ? PlayerSpawnX : SpawnPoint.X, y = PlayerSpawnY > 0 ? PlayerSpawnY : SpawnPoint.Y }, + exit = new { x = ExitX, y = ExitY }, rooms = Rooms.Select(r => new { x = r.X, y = r.Y, w = r.Width, h = r.Height, type = r.Type.ToString() }), mobs = MobSpawns.Select(m => new { id = m.Id, x = m.X, y = m.Y, type = m.MobType.ToString() }), - chests = ChestSpawns.Select(c => new { id = c.Id, x = c.X, y = c.Y, type = c.ChestType.ToString() }) + chests = ChestSpawns.Select(c => new { id = c.Id, x = c.X, y = c.Y, type = c.ChestType.ToString() }), + objects = Objects.Select(o => new { x = o.X, y = o.Y, id = o.ObjectTemplateId, type = o.Type, blocks = o.BlocksMovement }) }); } @@ -163,6 +220,8 @@ public class DungeonLayoutV2 : DungeonLayout x = t.X, y = t.Y, tid = t.TileDefinitionId, + sid = t.SheetId, + f = t.FrameIndex, l = t.Layer, r = t.Rotation, fx = t.FlipX, @@ -170,6 +229,4 @@ public class DungeonLayoutV2 : DungeonLayout }) }); } -} - - +} \ No newline at end of file diff --git a/Game/Dungeon/DungeonRoomV2.cs b/Game/Dungeon/DungeonRoomV2.cs index a1de26f..8ea7aa0 100644 --- a/Game/Dungeon/DungeonRoomV2.cs +++ b/Game/Dungeon/DungeonRoomV2.cs @@ -1,48 +1,65 @@ -using DataServer.Data.Entities; -using Server.Game.Dungeon; +using DataServer.Data.Entities; -namespace Server.Game.Dungeon +namespace Server.Game.Dungeon; + +/// +/// Extended room with template info +/// +public class DungeonRoomV2 : DungeonRoom { - /// - /// Extended room with template info - /// - public class DungeonRoomV2 : DungeonRoom + public int? TemplateId { get; set; } + public string? TemplateName { get; set; } + public HashSet TemplateTags { get; set; } = new(StringComparer.OrdinalIgnoreCase); + public new RoomType Type { get; set; } = RoomType.Normal; + + /// Connection points parsed from template + public List ConnectionPoints { get; set; } = new(); + + /// Mob spawns from template (intermediate storage before conversion) + public List MobSpawns { get; set; } = new(); + + /// Player spawn position (for entrance rooms) + public int? PlayerSpawnX { get; set; } + public int? PlayerSpawnY { get; set; } + + /// Exit position (for exit rooms) + public int? ExitX { get; set; } + public int? ExitY { get; set; } + + public DungeonRoomV2(int x, int y, int width, int height) : base(x, y, width, height) { } + + /// Get the best connection point for a given direction + public ConnectionPoint? GetConnectionPoint(string direction) { - public int? TemplateId { get; set; } - public string? TemplateName { get; set; } - public HashSet TemplateTags { get; set; } = new(StringComparer.OrdinalIgnoreCase); - public new RoomType Type { get; set; } = RoomType.Normal; + // First try exact match + var exact = ConnectionPoints.FirstOrDefault(c => c.Direction.Equals(direction, StringComparison.OrdinalIgnoreCase)); + if (exact != null) return exact; - /// Connection points parsed from template - public List ConnectionPoints { get; set; } = new(); - - public DungeonRoomV2(int x, int y, int width, int height) : base(x, y, width, height) { } - - /// Get the best connection point for a given direction - public ConnectionPoint? GetConnectionPoint(string direction) + // No exact match - create a default one for this direction + return direction.ToLower() switch { - // First try exact match - var exact = ConnectionPoints.FirstOrDefault(c => c.Direction.Equals(direction, StringComparison.OrdinalIgnoreCase)); - if (exact != null) return exact; - - // No exact match - create a default one for this direction rather than using wrong direction - // This ensures the connection point is actually on the correct edge - return direction.ToLower() switch - { - "north" => new ConnectionPoint { X = Width / 2, Y = 0, Direction = "north", Width = 3 }, - "south" => new ConnectionPoint { X = Width / 2, Y = Height - 1, Direction = "south", Width = 3 }, - "east" => new ConnectionPoint { X = Width - 1, Y = Height / 2, Direction = "east", Width = 3 }, - "west" => new ConnectionPoint { X = 0, Y = Height / 2, Direction = "west", Width = 3 }, - _ => ConnectionPoints.FirstOrDefault() // Last resort fallback - }; - } - - /// Get world position of a connection point - public (int X, int Y) GetConnectionWorldPos(ConnectionPoint cp) - { - return (X + cp.X, Y + cp.Y); - } - + "north" => new ConnectionPoint { X = Width / 2, Y = 0, Direction = "north", Width = 3 }, + "south" => new ConnectionPoint { X = Width / 2, Y = Height - 1, Direction = "south", Width = 3 }, + "east" => new ConnectionPoint { X = Width - 1, Y = Height / 2, Direction = "east", Width = 3 }, + "west" => new ConnectionPoint { X = 0, Y = Height / 2, Direction = "west", Width = 3 }, + _ => ConnectionPoints.FirstOrDefault() + }; } + /// Get world position of a connection point + public (int X, int Y) GetConnectionWorldPos(ConnectionPoint cp) + { + return (X + cp.X, Y + cp.Y); + } +} + +/// +/// Mob spawn point within a room (intermediate type for template data) +/// +public class RoomMobSpawn +{ + public int X { get; set; } + public int Y { get; set; } + public string Type { get; set; } = "normal"; + public int Count { get; set; } = 1; } diff --git a/Game/Dungeon/LootService.cs b/Game/Dungeon/LootService.cs index e0cf94d..916a34b 100644 --- a/Game/Dungeon/LootService.cs +++ b/Game/Dungeon/LootService.cs @@ -41,7 +41,14 @@ public class LootService public async Task InitializeAsync() { if (_initialized) return; - + await RefreshCacheAsync(); + } + + /// + /// Refresh all loot-related caches (can be called on-demand from admin) + /// + public async Task RefreshCacheAsync() + { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); @@ -95,7 +102,7 @@ public class LootService _itemDefinitions = items.ToDictionary(i => i.Id); _initialized = true; - _log.LogInformation("LootService initialized: {Tables} tables, {Items} items, {Mappings} mob mappings", + _log.LogInformation("LootService cache refreshed: {Tables} tables, {Items} items, {Mappings} mob mappings", _lootTables.Count, _itemDefinitions.Count, mappings.Count); } diff --git a/Services/Admin/Pages/Api.cshtml.cs b/Services/Admin/Pages/Api.cshtml.cs index 1f0f90b..ed67a3e 100644 --- a/Services/Admin/Pages/Api.cshtml.cs +++ b/Services/Admin/Pages/Api.cshtml.cs @@ -7,10 +7,14 @@ namespace Server.Services.Admin.Pages; public class ApiModel : AdminPageModel { private readonly CraftingHandler _craftingHandler; + private readonly DungeonHandler? _dungeonHandler; + private readonly LootService? _lootService; - public ApiModel(CraftingHandler craftingHandler) + public ApiModel(CraftingHandler craftingHandler, DungeonHandler? dungeonHandler = null, LootService? lootService = null) { _craftingHandler = craftingHandler; + _dungeonHandler = dungeonHandler; + _lootService = lootService; } public IActionResult OnGet() @@ -21,20 +25,51 @@ public class ApiModel : AdminPageModel public async Task OnPostRefreshCacheAsync([FromQuery] string? type) { var refreshed = new List(); + var errors = new List(); try { - if (type == null || type.Equals("recipes", StringComparison.OrdinalIgnoreCase)) + // Refresh recipes + if (type == null || type.Equals("recipes", StringComparison.OrdinalIgnoreCase) || type.Equals("all", StringComparison.OrdinalIgnoreCase)) { await _craftingHandler.RefreshRecipeCacheAsync(); refreshed.Add("recipes"); } + // Refresh mobs (animations, sprites, definitions) + if (type == null || type.Equals("mobs", StringComparison.OrdinalIgnoreCase) || type.Equals("all", StringComparison.OrdinalIgnoreCase)) + { + if (_dungeonHandler != null) + { + await _dungeonHandler.RefreshMobCacheAsync(); + refreshed.Add("mobs"); + } + else + { + errors.Add("DungeonHandler not available for mob refresh"); + } + } + + // Refresh loot tables + if (type == null || type.Equals("loot", StringComparison.OrdinalIgnoreCase) || type.Equals("all", StringComparison.OrdinalIgnoreCase)) + { + if (_lootService != null) + { + await _lootService.RefreshCacheAsync(); + refreshed.Add("loot"); + } + else + { + errors.Add("LootService not available for loot refresh"); + } + } + return new JsonResult(new { success = true, message = "Cache refreshed", refreshed, + errors = errors.Count > 0 ? errors : null, timestamp = DateTime.UtcNow }); } diff --git a/Services/Admin/Pages/Recipes/Index.cshtml b/Services/Admin/Pages/Recipes/Index.cshtml index 915c418..3c5bdd9 100644 --- a/Services/Admin/Pages/Recipes/Index.cshtml +++ b/Services/Admin/Pages/Recipes/Index.cshtml @@ -5,6 +5,8 @@ ViewData["Title"] = "Recipes"; } +@Html.AntiForgeryToken() +
@@ -214,9 +216,12 @@ btn.innerHTML = ' Refreshing...'; try { - const response = await fetch('/admin/api/refresh-cache?type=recipes', { + const response = await fetch('/admin/api?handler=RefreshCache&type=recipes', { method: 'POST', - credentials: 'same-origin' + credentials: 'same-origin', + headers: { + 'RequestVerificationToken': document.querySelector('input[name="__RequestVerificationToken"]')?.value || '' + } }); const data = await response.json(); diff --git a/Services/Admin/Pages/Server/Index.cshtml b/Services/Admin/Pages/Server/Index.cshtml index 9d89133..c262755 100644 --- a/Services/Admin/Pages/Server/Index.cshtml +++ b/Services/Admin/Pages/Server/Index.cshtml @@ -114,6 +114,48 @@
+ + +
+

Cache Management

+

Refresh server caches without restarting. Use after adding/modifying game data.

+ +
+ + + + + + + +
+ + +
@@ -147,3 +189,63 @@ }
+ +@section Scripts { + +}