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); // Populate TileMapSheets for client rendering foreach (var sheet in _tileSheets.Values) { layout.TileMapSheets.Add(new TileMapSheetInfo { Id = sheet.Id, CdnPath = sheet.CdnPath ?? "", TileWidth = sheet.TileWidth, TileHeight = sheet.TileHeight, SheetWidth = sheet.SheetWidth, SheetHeight = sheet.SheetHeight, Columns = sheet.Columns }); } Console.WriteLine($"[DungeonGenV3] Generation complete: {rooms.Count} rooms, {layout.TileDetails.Count} tiles, {layout.Objects.Count} objects, {layout.TileMapSheets.Count} sheets"); 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; } }