using DataServer.Data; using DataServer.Data.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System.Text; using System.Text.Json; namespace GameServer.Dungeon; /// /// Dungeon Generator VNext (first-pass implementation): /// - BSP room partitioning for macro structure /// - Random-walk corridor carving (2-4 tile width) /// - Tier-scaled size/room count and multi-boss support for tier 6+ /// public class DungeonGeneratorVNext { private readonly GameDbContext _db; private readonly int _seed; private readonly int _tier; private readonly Random _rng; private readonly ILogger? _logger; private DungeonPalette? _selectedPalette; private List _roomTemplates = new(); private readonly HashSet _usedRoomTemplateIds = new(); private readonly Dictionary> _templateMobSpawnsByRoom = new(); private readonly Dictionary<(int X, int Y), List> _templateTilesByCell = new(); private readonly Dictionary _tileDefinitionsById = new(); private readonly Dictionary _objectTemplatesById = new(); private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; public DungeonGeneratorVNext(GameDbContext db, int seed, int tier = 1, ILogger? logger = null) { _db = db; _seed = seed; _tier = Math.Max(1, tier); _rng = new Random(seed); _logger = logger; } private readonly record struct PartitionRect(int X, int Y, int Width, int Height) { public int CenterX => X + Width / 2; public int CenterY => Y + Height / 2; } public async Task GenerateAsync() { _usedRoomTemplateIds.Clear(); _templateMobSpawnsByRoom.Clear(); _templateTilesByCell.Clear(); _tileDefinitionsById.Clear(); _objectTemplatesById.Clear(); _selectedPalette = await SelectPaletteAsync(); await LoadRoomTemplatesAsync(); int size = 72 + (_tier * 8); if (_tier >= 6) size += (_tier - 5) * 12; int mapWidth = Math.Clamp(size, 64, 220); int mapHeight = Math.Clamp(size, 64, 220); int targetRooms = 10 + (_tier * 2); if (_tier >= 6) targetRooms += _tier; targetRooms = Math.Clamp(targetRooms, 12, 80); int minExpectedRooms = Math.Max(8, targetRooms / 2); var layout = new DungeonLayoutV2(mapWidth, mapHeight) { Seed = _seed, Tier = _tier, TileSize = 32 }; for (int x = 0; x < mapWidth; x++) { for (int y = 0; y < mapHeight; y++) { layout.Tiles[x, y] = 0; layout.Walkable![x, y] = false; } } var rooms = GenerateRooms(mapWidth, mapHeight, targetRooms); if (rooms.Count < minExpectedRooms) { rooms = GenerateFallbackRooms(mapWidth, mapHeight, targetRooms); } foreach (var room in rooms) { CarveRoom(layout, room); } ConnectRoomsWithRandomWalk(layout, rooms); AddLoopConnections(layout, rooms, Math.Max(2, rooms.Count / 4)); AssignRoomTypes(rooms); ApplyRoomTemplates(layout, rooms); GenerateSpawnsAndChests(layout, rooms); await BuildPaletteDrivenTileDetailsAsync(layout); layout.Rooms = rooms; var entrance = rooms.FirstOrDefault(r => r.Type == DungeonRoomType.Entrance) ?? rooms[0]; int spawnX = entrance.PlayerSpawnX ?? entrance.CenterX; int spawnY = entrance.PlayerSpawnY ?? entrance.CenterY; layout.SpawnPoint = new DungeonPoint(spawnX, spawnY); layout.PlayerSpawnX = spawnX; layout.PlayerSpawnY = spawnY; layout.TotalMobs = layout.MobSpawns.Count; layout.TotalChests = layout.ChestSpawns.Count; _logger?.LogInformation( "VNext generated seed {Seed}, tier {Tier}: {Width}x{Height}, rooms={RoomCount}, mobs={MobCount}, chests={ChestCount}, bosses={BossCount}", _seed, _tier, mapWidth, mapHeight, rooms.Count, layout.TotalMobs, layout.TotalChests, layout.MobSpawns.Count(m => m.MobType == DungeonMobSpawnType.Boss)); return layout; } private List GenerateRooms(int mapWidth, int mapHeight, int targetRooms) { var leaves = new List { new(2, 2, mapWidth - 4, mapHeight - 4) }; int minLeafSize = 16; int splitGuard = 0; while (leaves.Count < targetRooms * 2 && splitGuard++ < 4000) { int index = _rng.Next(leaves.Count); var leaf = leaves[index]; bool splitVertical = leaf.Width > leaf.Height; if (_rng.NextDouble() < 0.35) splitVertical = !splitVertical; if (splitVertical) { if (leaf.Width < minLeafSize * 2) continue; int splitX = _rng.Next(leaf.X + minLeafSize, leaf.X + leaf.Width - minLeafSize); var left = new PartitionRect(leaf.X, leaf.Y, splitX - leaf.X, leaf.Height); var right = new PartitionRect(splitX, leaf.Y, leaf.X + leaf.Width - splitX, leaf.Height); leaves[index] = left; leaves.Add(right); } else { if (leaf.Height < minLeafSize * 2) continue; int splitY = _rng.Next(leaf.Y + minLeafSize, leaf.Y + leaf.Height - minLeafSize); var top = new PartitionRect(leaf.X, leaf.Y, leaf.Width, splitY - leaf.Y); var bottom = new PartitionRect(leaf.X, splitY, leaf.Width, leaf.Y + leaf.Height - splitY); leaves[index] = top; leaves.Add(bottom); } } var rooms = new List(); int minRoom = 8; int maxRoom = 20; foreach (var leaf in leaves.OrderBy(_ => _rng.Next())) { if (rooms.Count >= targetRooms) break; int margin = 2; int maxW = Math.Max(minRoom, leaf.Width - margin * 2); int maxH = Math.Max(minRoom, leaf.Height - margin * 2); if (maxW < minRoom || maxH < minRoom) continue; int width = _rng.Next(minRoom, Math.Min(maxRoom, maxW) + 1); int height = _rng.Next(minRoom, Math.Min(maxRoom, maxH) + 1); int x = _rng.Next(leaf.X + 1, leaf.X + leaf.Width - width); int y = _rng.Next(leaf.Y + 1, leaf.Y + leaf.Height - height); var room = new DungeonRoom(x, y, width, height); if (rooms.Any(r => room.Intersects(r, 1))) continue; rooms.Add(room); } return rooms .OrderBy(r => r.X + r.Y) .ToList(); } private List GenerateFallbackRooms(int mapWidth, int mapHeight, int desiredCount) { var rooms = new List(); int count = Math.Clamp(desiredCount, 12, 80); int attempts = 0; while (rooms.Count < count && attempts++ < count * 60) { int maxRoom = Math.Min(24, 10 + _tier); int width = _rng.Next(8, maxRoom + 1); int height = _rng.Next(8, maxRoom + 1); if (width >= mapWidth - 4 || height >= mapHeight - 4) continue; int x = _rng.Next(2, mapWidth - width - 2); int y = _rng.Next(2, mapHeight - height - 2); var room = new DungeonRoom(x, y, width, height); if (rooms.Any(r => room.Intersects(r, 2))) continue; rooms.Add(room); } return rooms.OrderBy(r => r.X + r.Y).ToList(); } private async Task LoadRoomTemplatesAsync() { IQueryable query = _db.BuilderRoomTemplates .Where(r => r.IsEnabled) .Where(r => r.MinTier <= _tier && (r.MaxTier == 0 || r.MaxTier >= _tier)); var roomTemplateIds = ParseIds(_selectedPalette?.RoomTemplateIdsJson); if (roomTemplateIds.Count > 0) { query = query.Where(r => roomTemplateIds.Contains(r.Id)); } _roomTemplates = await query.ToListAsync(); // Palette might reference disabled/out-of-tier templates only; fallback to all tier-enabled. if (_roomTemplates.Count == 0 && roomTemplateIds.Count > 0) { _roomTemplates = await _db.BuilderRoomTemplates .Where(r => r.IsEnabled) .Where(r => r.MinTier <= _tier && (r.MaxTier == 0 || r.MaxTier >= _tier)) .ToListAsync(); } var defs = await _db.TileDefinitions .Where(t => t.IsEnabled) .ToListAsync(); foreach (var def in defs) { _tileDefinitionsById[def.Id] = def; } var objectTemplateIds = new HashSet(); foreach (var room in _roomTemplates) { if (string.IsNullOrWhiteSpace(room.ObjectPlacementsJson)) continue; try { var objects = JsonSerializer.Deserialize>(room.ObjectPlacementsJson, _jsonOptions); if (objects == null) continue; foreach (var obj in objects) { if (obj.ObjectTemplateId > 0) { objectTemplateIds.Add(obj.ObjectTemplateId); } } } catch { // Keep generation resilient if a room has malformed object placement JSON. } } if (objectTemplateIds.Count > 0) { var objectTemplates = await _db.ObjectTemplates .Where(o => o.IsEnabled && objectTemplateIds.Contains(o.Id)) .ToListAsync(); foreach (var template in objectTemplates) { _objectTemplatesById[template.Id] = template; } } _logger?.LogInformation( "VNext room templates loaded: {Count} templates (palette={PaletteId})", _roomTemplates.Count, _selectedPalette?.Id ?? 0); } private void CarveRoom(DungeonLayoutV2 layout, DungeonRoom room) { for (int x = room.X; x < room.X + room.Width; x++) { for (int y = room.Y; y < room.Y + room.Height; y++) { SetFloor(layout, x, y); } } } private void ConnectRoomsWithRandomWalk(DungeonLayoutV2 layout, List rooms) { if (rooms.Count < 2) return; var connected = new List { rooms[0] }; var unconnected = new HashSet(rooms.Skip(1)); while (unconnected.Count > 0) { DungeonRoom? bestFrom = null; DungeonRoom? bestTo = null; float bestDist = float.MaxValue; foreach (var from in connected) { foreach (var to in unconnected) { float dist = Distance(from.CenterX, from.CenterY, to.CenterX, to.CenterY); if (dist < bestDist) { bestDist = dist; bestFrom = from; bestTo = to; } } } if (bestFrom == null || bestTo == null) break; int width = _rng.Next(2, 5); CarveRandomWalkCorridor(layout, bestFrom.CenterX, bestFrom.CenterY, bestTo.CenterX, bestTo.CenterY, width); connected.Add(bestTo); unconnected.Remove(bestTo); } } private void AddLoopConnections(DungeonLayoutV2 layout, List rooms, int loopCount) { if (rooms.Count < 3) return; for (int i = 0; i < loopCount; i++) { var a = rooms[_rng.Next(rooms.Count)]; var b = rooms[_rng.Next(rooms.Count)]; if (ReferenceEquals(a, b)) continue; int width = _rng.Next(2, 5); CarveRandomWalkCorridor(layout, a.CenterX, a.CenterY, b.CenterX, b.CenterY, width); } } private void CarveRandomWalkCorridor(DungeonLayoutV2 layout, int startX, int startY, int endX, int endY, int width) { int x = startX; int y = startY; int guard = layout.Width * layout.Height * 2; while ((x != endX || y != endY) && guard-- > 0) { CarveBrush(layout, x, y, width); int dx = Math.Sign(endX - x); int dy = Math.Sign(endY - y); int stepX = 0; int stepY = 0; if (_rng.NextDouble() < 0.7) { if (Math.Abs(endX - x) >= Math.Abs(endY - y)) stepX = dx; else stepY = dy; } else { int roll = _rng.Next(4); if (roll == 0) stepX = 1; if (roll == 1) stepX = -1; if (roll == 2) stepY = 1; if (roll == 3) stepY = -1; } if (stepX == 0 && stepY == 0) { if (dx != 0) stepX = dx; else if (dy != 0) stepY = dy; } x = Math.Clamp(x + stepX, 1, layout.Width - 2); y = Math.Clamp(y + stepY, 1, layout.Height - 2); } CarveBrush(layout, endX, endY, width); } private void CarveBrush(DungeonLayoutV2 layout, int cx, int cy, int width) { int half = width / 2; for (int x = cx - half; x <= cx + half; x++) { for (int y = cy - half; y <= cy + half; y++) { SetFloor(layout, x, y); } } } private void SetFloor(DungeonLayoutV2 layout, int x, int y) { if (x < 1 || y < 1 || x >= layout.Width - 1 || y >= layout.Height - 1) return; layout.Tiles[x, y] = 1; layout.Walkable![x, y] = true; } private void AssignRoomTypes(List rooms) { if (rooms.Count == 0) return; int entranceIndex = rooms .Select((r, i) => (idx: i, score: r.X + r.Y)) .OrderBy(p => p.score) .Select(p => p.idx) .First(); rooms[entranceIndex].Type = DungeonRoomType.Entrance; int bossCount = GetRequiredBossCount(); var candidates = rooms .Select((r, i) => (room: r, idx: i)) .Where(p => p.idx != entranceIndex) .OrderByDescending(p => Distance(rooms[entranceIndex].CenterX, rooms[entranceIndex].CenterY, p.room.CenterX, p.room.CenterY)) .ToList(); if (candidates.Count == 0) { rooms[entranceIndex].Type = DungeonRoomType.Boss; return; } foreach (var room in rooms.Where(r => r.Type != DungeonRoomType.Entrance)) { room.Type = DungeonRoomType.Combat; } for (int i = 0; i < Math.Min(bossCount, candidates.Count); i++) { candidates[i].room.Type = DungeonRoomType.Boss; } int treasureCount = Math.Max(1, rooms.Count / 8); var treasureCandidates = rooms .Where(r => r.Type == DungeonRoomType.Combat) .OrderBy(_ => _rng.Next()) .Take(treasureCount); foreach (var room in treasureCandidates) { room.Type = DungeonRoomType.Treasure; } } private void ApplyRoomTemplates(DungeonLayoutV2 layout, List rooms) { if (_roomTemplates.Count == 0 || rooms.Count == 0) { return; } foreach (var room in rooms) { var candidates = GetTemplatesForRoomType(room.Type); if (candidates.Count == 0) continue; // Do not keep reusing the same template in a single dungeon. var availableCandidates = candidates .Where(t => !_usedRoomTemplateIds.Contains(t.Id)) .ToList(); if (availableCandidates.Count == 0) continue; // Each room independently rolls whether to be template-based or procedural. if (!ShouldUseTemplateForRoom(room.Type)) continue; var template = SelectWeightedRoomTemplate(availableCandidates); if (template == null) continue; _usedRoomTemplateIds.Add(template.Id); room.TemplateId = template.Id; room.TemplateName = template.Name; if (template.PlayerSpawnX.HasValue && template.PlayerSpawnY.HasValue) { room.PlayerSpawnX = room.X + template.PlayerSpawnX.Value; room.PlayerSpawnY = room.Y + template.PlayerSpawnY.Value; } if (template.ExitPortalX.HasValue && template.ExitPortalY.HasValue) { room.ExitX = room.X + template.ExitPortalX.Value; room.ExitY = room.Y + template.ExitPortalY.Value; layout.ExitX = room.ExitX.Value; layout.ExitY = room.ExitY.Value; } StampRoomTemplateTiles(layout, room, template); StampRoomTemplateObjects(layout, room, template); LoadTemplateMobSpawns(room, template); } } private bool ShouldUseTemplateForRoom(DungeonRoomType roomType) { // Leaves room generation mixed: some runs use few templates, some many. double chance = roomType switch { DungeonRoomType.Entrance => 0.45, DungeonRoomType.Boss => 0.45, DungeonRoomType.Treasure => 0.40, _ => 0.30 }; return _rng.NextDouble() < chance; } private List GetTemplatesForRoomType(DungeonRoomType roomType) { List candidates = roomType switch { DungeonRoomType.Entrance => _roomTemplates.Where(t => t.Type == RoomType.Entrance).ToList(), DungeonRoomType.Boss => _roomTemplates.Where(t => t.Type == RoomType.Boss).ToList(), DungeonRoomType.Treasure => _roomTemplates.Where(t => t.Type == RoomType.Treasure).ToList(), _ => _roomTemplates.Where(t => t.Type == RoomType.Normal || t.Type == RoomType.Hallway || t.Type == RoomType.Junction || t.Type == RoomType.Challenge || t.Type == RoomType.Secret || t.Type == RoomType.Shop || t.Type == RoomType.Shrine) .ToList() }; if (candidates.Count > 0) return candidates; // Fallback to any template for robustness. return _roomTemplates; } private BuilderRoomTemplate? SelectWeightedRoomTemplate(List templates) { if (templates.Count == 0) return null; if (templates.Count == 1) return templates[0]; int totalWeight = 0; var weights = new List(templates.Count); foreach (var template in templates) { int baseWeight = Math.Max(1, template.Weight); weights.Add(baseWeight); totalWeight += baseWeight; } 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 void StampRoomTemplateTiles(DungeonLayoutV2 layout, DungeonRoom room, BuilderRoomTemplate template) { if (string.IsNullOrWhiteSpace(template.TileGridJson)) return; try { var tiles = JsonSerializer.Deserialize>(template.TileGridJson, _jsonOptions); if (tiles == null || tiles.Count == 0) return; foreach (var tile in tiles) { int x = room.X + tile.X; int y = room.Y + tile.Y; if (x < 0 || y < 0 || x >= layout.Width || y >= layout.Height) continue; int layer = tile.Layer ?? 0; int tileDefinitionId = tile.TileDefinitionId ?? 0; int sheetId = tile.SheetId; int frameIndex = tile.FrameIndex; if (tileDefinitionId > 0 && _tileDefinitionsById.TryGetValue(tileDefinitionId, out var def)) { sheetId = def.TileMapSheetId; frameIndex = def.FrameIndex; } var placed = new PlacedTile { X = x, Y = y, TileDefinitionId = tileDefinitionId, SheetId = sheetId, FrameIndex = frameIndex, Layer = layer, Rotation = 0, FlipX = false, FlipY = false }; var key = (x, y); if (!_templateTilesByCell.TryGetValue(key, out var list)) { list = new List(); _templateTilesByCell[key] = list; } list.Add(placed); } } catch (Exception ex) { _logger?.LogWarning(ex, "VNext failed parsing TileGridJson for template {TemplateId}:{TemplateName}", template.Id, template.Name); } } private void LoadTemplateMobSpawns(DungeonRoom room, BuilderRoomTemplate template) { if (string.IsNullOrWhiteSpace(template.MobSpawnsJson)) return; try { var spawns = JsonSerializer.Deserialize>(template.MobSpawnsJson, _jsonOptions); if (spawns == null || spawns.Count == 0) return; _templateMobSpawnsByRoom[room] = spawns; } catch (Exception ex) { _logger?.LogWarning(ex, "VNext failed parsing MobSpawnsJson for template {TemplateId}:{TemplateName}", template.Id, template.Name); } } private void StampRoomTemplateObjects(DungeonLayoutV2 layout, DungeonRoom room, BuilderRoomTemplate template) { if (string.IsNullOrWhiteSpace(template.ObjectPlacementsJson)) return; try { var objects = JsonSerializer.Deserialize>(template.ObjectPlacementsJson, _jsonOptions); if (objects == null || objects.Count == 0) return; foreach (var obj in objects) { if (!_objectTemplatesById.TryGetValue(obj.ObjectTemplateId, out var objectTemplate)) { continue; } int worldX = room.X + obj.X; int worldY = room.Y + obj.Y; if (worldX < 0 || worldY < 0 || worldX >= layout.Width || worldY >= layout.Height) { continue; } layout.Objects.Add(new PlacedObject { X = worldX, Y = worldY, ObjectTemplateId = objectTemplate.Id, Name = objectTemplate.Name, Type = objectTemplate.Type.ToString(), SpriteSheetId = objectTemplate.SpriteSheetId ?? 0, FrameIndex = objectTemplate.FrameIndex, BlocksMovement = objectTemplate.BlocksMovement, IsInteractable = objectTemplate.IsInteractable, IsTrap = objectTemplate.Type == ObjectTemplateType.Trap || objectTemplate.Type == ObjectTemplateType.Hazard, TrapDamage = objectTemplate.Damage, LootTableId = objectTemplate.LootTableId, TriggeredByWalk = objectTemplate.TriggeredByWalk, InteractionType = objectTemplate.InteractionType.ToString(), MetadataJson = string.IsNullOrWhiteSpace(obj.OverridesJson) ? null : obj.OverridesJson }); if (objectTemplate.BlocksMovement) { layout.Walkable![worldX, worldY] = false; layout.Tiles[worldX, worldY] = 0; } } } catch (Exception ex) { _logger?.LogWarning(ex, "VNext failed parsing ObjectPlacementsJson for template {TemplateId}:{TemplateName}", template.Id, template.Name); } } private void GenerateSpawnsAndChests(DungeonLayoutV2 layout, List rooms) { layout.MobSpawns.Clear(); layout.ChestSpawns.Clear(); int mobId = 1; int chestId = 1; for (int i = 0; i < rooms.Count; i++) { var room = rooms[i]; if (room.Type == DungeonRoomType.Entrance) continue; bool hasTemplateMobs = _templateMobSpawnsByRoom.TryGetValue(room, out var templateSpawns) && templateSpawns != null && templateSpawns.Count > 0; if (hasTemplateMobs) { foreach (var spawn in templateSpawns!) { int count = Math.Max(1, spawn.Count); var mobType = spawn.Type?.ToLowerInvariant() switch { "boss" => DungeonMobSpawnType.Boss, "elite" => DungeonMobSpawnType.Elite, _ => DungeonMobSpawnType.Normal }; for (int c = 0; c < count; c++) { int spawnX = room.X + spawn.X; int spawnY = room.Y + spawn.Y; spawnX = Math.Clamp(spawnX, room.X + 1, room.X + room.Width - 2); spawnY = Math.Clamp(spawnY, room.Y + 1, room.Y + room.Height - 2); layout.MobSpawns.Add(new DungeonMobSpawn { Id = mobId++, X = spawnX, Y = spawnY, MobType = mobType, MobDefinitionId = spawn.MobDefinitionId, RoomIndex = i }); } } } else { int mobCount = room.Type switch { DungeonRoomType.Boss => 1, DungeonRoomType.Treasure => _rng.Next(1, 3), _ => _rng.Next(2, 5 + Math.Max(0, _tier / 2)) }; for (int m = 0; m < mobCount; m++) { var pos = RandomPointInRoom(room); layout.MobSpawns.Add(new DungeonMobSpawn { Id = mobId++, X = pos.x, Y = pos.y, MobType = room.Type == DungeonRoomType.Boss ? DungeonMobSpawnType.Boss : DungeonMobSpawnType.Normal, RoomIndex = i }); } } int chestCount = room.Type switch { DungeonRoomType.Boss => 1, DungeonRoomType.Treasure => _rng.Next(1, 3), _ => _rng.NextDouble() < 0.25 ? 1 : 0 }; for (int c = 0; c < chestCount; c++) { var pos = RandomPointInRoom(room); layout.ChestSpawns.Add(new DungeonChestSpawn { Id = chestId++, X = pos.x, Y = pos.y, ChestType = room.Type == DungeonRoomType.Boss ? DungeonChestType.Boss : DungeonChestType.Normal, RoomIndex = i }); } } int requiredBossCount = Math.Min(GetRequiredBossCount(), Math.Max(1, rooms.Count - 1)); int bossSpawnCount = layout.MobSpawns.Count(m => m.MobType == DungeonMobSpawnType.Boss); if (bossSpawnCount < requiredBossCount && rooms.Count > 1) { var entranceRoom = rooms.FirstOrDefault(r => r.Type == DungeonRoomType.Entrance) ?? rooms[0]; var candidateRooms = rooms .Select((room, idx) => (room, idx)) .Where(p => p.room.Type != DungeonRoomType.Entrance) .OrderByDescending(p => Distance(entranceRoom.CenterX, entranceRoom.CenterY, p.room.CenterX, p.room.CenterY)) .ToList(); foreach (var candidate in candidateRooms) { if (bossSpawnCount >= requiredBossCount) break; bool roomAlreadyHasBoss = layout.MobSpawns.Any(m => m.RoomIndex == candidate.idx && m.MobType == DungeonMobSpawnType.Boss); if (roomAlreadyHasBoss) continue; var pos = RandomPointInRoom(candidate.room); layout.MobSpawns.Add(new DungeonMobSpawn { Id = mobId++, X = pos.x, Y = pos.y, MobType = DungeonMobSpawnType.Boss, RoomIndex = candidate.idx }); candidate.room.Type = DungeonRoomType.Boss; bossSpawnCount++; } } if (bossSpawnCount == 0 && rooms.Count > 0) { int fallbackRoomIndex = rooms.FindIndex(r => r.Type != DungeonRoomType.Entrance); if (fallbackRoomIndex < 0) fallbackRoomIndex = 0; var pos = RandomPointInRoom(rooms[fallbackRoomIndex]); layout.MobSpawns.Add(new DungeonMobSpawn { Id = mobId, X = pos.x, Y = pos.y, MobType = DungeonMobSpawnType.Boss, RoomIndex = fallbackRoomIndex }); rooms[fallbackRoomIndex].Type = DungeonRoomType.Boss; } } private int GetRequiredBossCount() { if (_tier < 6) return 1; return Math.Clamp(1 + (_tier / 4), 2, 4); } private (int x, int y) RandomPointInRoom(DungeonRoom room) { int x = _rng.Next(room.X + 1, room.X + room.Width - 1); int y = _rng.Next(room.Y + 1, room.Y + room.Height - 1); return (x, y); } private async Task BuildPaletteDrivenTileDetailsAsync(DungeonLayoutV2 layout) { layout.TileDetails.Clear(); layout.TileMapSheets.Clear(); var tileContext = await BuildTileContextAsync(); if (tileContext.FloorCandidates.Count == 0 && tileContext.WallCandidates.Count == 0) { _logger?.LogWarning("VNext tile context had no palette candidates; using fallback tile placeholders."); BuildFallbackTileDetails(layout); return; } var usedSheetIds = new HashSet(); for (int y = 0; y < layout.Height; y++) { for (int x = 0; x < layout.Width; x++) { if (!layout.Walkable![x, y]) continue; if (TryGetTemplateBaseTile(x, y, out var templateBaseTile)) { layout.Tiles[x, y] = templateBaseTile.TileDefinitionId > 0 ? templateBaseTile.TileDefinitionId : layout.Tiles[x, y]; layout.TileDetails.Add(templateBaseTile); if (templateBaseTile.SheetId > 0) { usedSheetIds.Add(templateBaseTile.SheetId); } continue; } var floorDef = SelectFloorDefinition(tileContext); if (floorDef == null) continue; layout.Tiles[x, y] = floorDef.Id; usedSheetIds.Add(floorDef.TileMapSheetId); layout.TileDetails.Add(new PlacedTile { X = x, Y = y, TileDefinitionId = floorDef.Id, SheetId = floorDef.TileMapSheetId, FrameIndex = floorDef.FrameIndex, Layer = floorDef.RenderLayer, Rotation = 0, FlipX = false, FlipY = false }); } } var wallCells = new List<(int X, int Y)>(); for (int y = 0; y < layout.Height; y++) { for (int x = 0; x < layout.Width; x++) { if (layout.Walkable![x, y]) continue; if (!HasAdjacentWalkable(layout, x, y)) continue; wallCells.Add((x, y)); } } // Single-pass strict directional wall placement (exact 8-direction mask). foreach (var cell in wallCells) { int mask8 = ComputeEightDirectionMask(layout, cell.X, cell.Y); TileDefinition? wallDef = null; string? directionalBucket = ResolveDirectionalWallBucket(mask8); if (!string.IsNullOrEmpty(directionalBucket)) { wallDef = SelectWallDefinitionForBucket(tileContext, directionalBucket); } else { foreach (var fallbackBucket in ResolveDirectionalFallbackBuckets(mask8)) { wallDef = SelectWallDefinitionForBucket(tileContext, fallbackBucket); if (wallDef != null) { break; } } } if (wallDef == null) { continue; } if (TryGetTemplateBaseTile(cell.X, cell.Y, out var templateWallTile)) { layout.Tiles[cell.X, cell.Y] = templateWallTile.TileDefinitionId > 0 ? templateWallTile.TileDefinitionId : layout.Tiles[cell.X, cell.Y]; layout.TileDetails.RemoveAll(t => t.X == cell.X && t.Y == cell.Y && t.Layer == 0); layout.TileDetails.Add(templateWallTile); if (templateWallTile.SheetId > 0) { usedSheetIds.Add(templateWallTile.SheetId); } } else { UpsertWallTile(layout, cell.X, cell.Y, wallDef); usedSheetIds.Add(wallDef.TileMapSheetId); } } foreach (var kv in _templateTilesByCell) { foreach (var tile in kv.Value.Where(t => t.Layer > 0)) { if (tile.X < 0 || tile.Y < 0 || tile.X >= layout.Width || tile.Y >= layout.Height) { continue; } layout.TileDetails.Add(tile); if (tile.SheetId > 0) { usedSheetIds.Add(tile.SheetId); } } } foreach (int sheetId in usedSheetIds) { if (!tileContext.SheetsById.TryGetValue(sheetId, out var sheet)) continue; 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, Rows = sheet.Rows }); } } private void BuildFallbackTileDetails(DungeonLayoutV2 layout) { for (int y = 0; y < layout.Height; y++) { for (int x = 0; x < layout.Width; x++) { if (!layout.Walkable![x, y]) continue; layout.TileDetails.Add(new PlacedTile { X = x, Y = y, TileDefinitionId = 0, SheetId = 0, FrameIndex = 0, Layer = 0, Rotation = 0, FlipX = false, FlipY = false }); } } } private async Task BuildTileContextAsync() { var sheets = await _db.TileMapSheets .Where(s => s.IsEnabled) .ToListAsync(); var sheetsById = sheets.ToDictionary(s => s.Id); var palette = _selectedPalette ?? await SelectPaletteAsync(); _selectedPalette = palette; var allowedBucketIds = ParseIds(palette?.AllowedBucketIdsJson).ToHashSet(); var allTiles = await _db.TileDefinitions .Where(t => t.IsEnabled) .ToListAsync(); var links = await _db.TileDefinitionBuckets.ToListAsync(); var tileBuckets = new Dictionary>(); foreach (var link in links) { if (!tileBuckets.TryGetValue(link.TileDefinitionId, out var set)) { set = new HashSet(); tileBuckets[link.TileDefinitionId] = set; } set.Add(link.TileBucketId); } var buckets = await _db.TileBuckets .Where(b => b.IsEnabled) .ToListAsync(); var bucketNamesById = buckets.ToDictionary(b => b.Id, b => b.Name); var bucketIdsByName = buckets .GroupBy(b => NormalizeBucketKey(b.Name)) .ToDictionary(g => g.Key, g => g.First().Id); bool TileAllowedByPalette(TileDefinition t) { if (allowedBucketIds.Count == 0) return true; if (!tileBuckets.TryGetValue(t.Id, out var ids) || ids.Count == 0) return false; return ids.Overlaps(allowedBucketIds); } var floorCandidates = allTiles .Where(t => t.IsWalkable && t.Type != TileType.Wall && t.Type != TileType.WallDecor) .Where(TileAllowedByPalette) .ToList(); var wallCandidates = allTiles .Where(t => !t.IsWalkable || t.Type == TileType.Wall || t.Type == TileType.WallDecor) .Where(TileAllowedByPalette) .ToList(); var canonicalWallBucketIds = ResolveCanonicalWallBucketIds(bucketIdsByName, allowedBucketIds); var wallDefsByCanonicalBucket = new Dictionary>(StringComparer.OrdinalIgnoreCase); int ambiguousDirectionalCount = 0; foreach (var wallDef in wallCandidates) { if (!tileBuckets.TryGetValue(wallDef.Id, out var defBuckets) || defBuckets.Count == 0) continue; var directionalMatches = new List(); foreach (var kvp in canonicalWallBucketIds) { if (defBuckets.Contains(kvp.Value)) { directionalMatches.Add(kvp.Key); } } // Strict directional constraint: exactly one directional bucket per wall tile. if (directionalMatches.Count == 0) continue; if (directionalMatches.Count > 1) { ambiguousDirectionalCount++; continue; } string canonical = directionalMatches[0]; if (!wallDefsByCanonicalBucket.TryGetValue(canonical, out var defs)) { defs = new List(); wallDefsByCanonicalBucket[canonical] = defs; } defs.Add(wallDef); } _logger?.LogInformation( "VNext tile context: palette={PaletteId}, allowedBuckets={AllowedBuckets}, floorDefs={FloorDefs}, wallDefs={WallDefs}, resolvedWallBuckets={ResolvedBuckets}", palette?.Id ?? 0, allowedBucketIds.Count, floorCandidates.Count, wallCandidates.Count, wallDefsByCanonicalBucket.Count); if (ambiguousDirectionalCount > 0) { _logger?.LogWarning( "VNext tile context skipped {Count} wall definitions because they were assigned to multiple directional wall buckets.", ambiguousDirectionalCount); } return new TileBuildContext( sheetsById, floorCandidates, wallCandidates, wallDefsByCanonicalBucket, bucketNamesById); } private async Task SelectPaletteAsync() { var palettes = await _db.DungeonPalettes .Where(p => p.IsEnabled) .OrderBy(p => p.Id) .ToListAsync(); if (palettes.Count == 0) return null; return palettes[_rng.Next(palettes.Count)]; } private static List ParseIds(string? json) { if (string.IsNullOrWhiteSpace(json)) return new List(); try { return JsonSerializer.Deserialize>(json) ?? new List(); } catch { return new List(); } } private static Dictionary ResolveCanonicalWallBucketIds( Dictionary bucketIdsByName, HashSet allowedBucketIds) { var resolved = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var alias in WallBucketAliases) { foreach (var name in alias.Value) { if (!bucketIdsByName.TryGetValue(NormalizeBucketKey(name), out int id)) continue; if (allowedBucketIds.Count > 0 && !allowedBucketIds.Contains(id)) continue; resolved[alias.Key] = id; break; } } return resolved; } private TileDefinition? SelectFloorDefinition(TileBuildContext context) { if (context.FloorCandidates.Count == 0) return null; return context.FloorCandidates[_rng.Next(context.FloorCandidates.Count)]; } private TileDefinition? SelectWallDefinitionForBucket(TileBuildContext context, string canonicalBucketName) { if (!context.WallDefinitionsByCanonicalBucket.TryGetValue(canonicalBucketName, out var defs) || defs.Count == 0) { return null; } return defs[_rng.Next(defs.Count)]; } private static void PlaceWallTile(DungeonLayoutV2 layout, int x, int y, TileDefinition def) { layout.Tiles[x, y] = def.Id; layout.TileDetails.Add(new PlacedTile { X = x, Y = y, TileDefinitionId = def.Id, SheetId = def.TileMapSheetId, FrameIndex = def.FrameIndex, Layer = def.RenderLayer, Rotation = 0, FlipX = false, FlipY = false }); } private static void UpsertWallTile(DungeonLayoutV2 layout, int x, int y, TileDefinition def) { layout.TileDetails.RemoveAll(t => t.X == x && t.Y == y); PlaceWallTile(layout, x, y, def); } private bool TryGetTemplateBaseTile(int x, int y, out PlacedTile placedTile) { placedTile = default!; if (!_templateTilesByCell.TryGetValue((x, y), out var tiles) || tiles.Count == 0) { return false; } var baseTile = tiles .Where(t => t.Layer == 0) .OrderByDescending(t => t.TileDefinitionId > 0) .ThenByDescending(t => t.SheetId > 0) .FirstOrDefault(); if (baseTile == null) { return false; } placedTile = baseTile; return true; } private static bool HasAdjacentWalkable(DungeonLayoutV2 layout, int x, int y) { return IsWalkable(layout, x, y - 1) || // N IsWalkable(layout, x + 1, y - 1) || // NE IsWalkable(layout, x + 1, y) || // E IsWalkable(layout, x + 1, y + 1) || // SE IsWalkable(layout, x, y + 1) || // S IsWalkable(layout, x - 1, y + 1) || // SW IsWalkable(layout, x - 1, y) || // W IsWalkable(layout, x - 1, y - 1); // NW } private static int ComputeEightDirectionMask(DungeonLayoutV2 layout, int x, int y) { // Bit order N, NE, E, SE, S, SW, W, NW (MSB -> LSB). int n = IsWalkable(layout, x, y - 1) ? 1 : 0; int ne = IsWalkable(layout, x + 1, y - 1) ? 1 : 0; int e = IsWalkable(layout, x + 1, y) ? 1 : 0; int se = IsWalkable(layout, x + 1, y + 1) ? 1 : 0; int s = IsWalkable(layout, x, y + 1) ? 1 : 0; int sw = IsWalkable(layout, x - 1, y + 1) ? 1 : 0; int w = IsWalkable(layout, x - 1, y) ? 1 : 0; int nw = IsWalkable(layout, x - 1, y - 1) ? 1 : 0; return (n << 7) | (ne << 6) | (e << 5) | (se << 4) | (s << 3) | (sw << 2) | (w << 1) | nw; } private static bool IsWalkable(DungeonLayoutV2 layout, int x, int y) { if (x < 0 || y < 0 || x >= layout.Width || y >= layout.Height) return false; return layout.Walkable![x, y]; } private static string? ResolveDirectionalWallBucket(int mask8) { foreach (var mapping in DirectionalWallBucketMasks) { if (mapping.Value.Contains(mask8)) { return mapping.Key; } } return null; } private static string NormalizeBucketKey(string? value) { if (string.IsNullOrWhiteSpace(value)) { return string.Empty; } var sb = new StringBuilder(value.Length); foreach (char c in value) { if (char.IsLetterOrDigit(c)) { sb.Append(char.ToLowerInvariant(c)); } } return sb.ToString(); } private static IEnumerable ResolveDirectionalFallbackBuckets(int mask8) { // Bit order N, NE, E, SE, S, SW, W, NW. bool n = (mask8 & 0b1000_0000) != 0; bool e = (mask8 & 0b0010_0000) != 0; bool s = (mask8 & 0b0000_1000) != 0; bool w = (mask8 & 0b0000_0010) != 0; bool ne = (mask8 & 0b0100_0000) != 0; bool se = (mask8 & 0b0001_0000) != 0; bool sw = (mask8 & 0b0000_0100) != 0; bool nw = (mask8 & 0b0000_0001) != 0; // Prefer large corner profiles if adjacent cardinals exist. if (n && w) yield return "NWCornerLarge"; if (n && e) yield return "NECornerLarge"; if (s && e) yield return "SECornerLarge"; if (s && w) yield return "SWCornerLarge"; // Cardinal fallbacks for 3-way / complex masks. if (n) yield return "Wall_N"; if (e) yield return "Wall_E"; if (s) yield return "Wall_S"; if (w) yield return "Wall_W"; // If no cardinal bits exist, allow single-diagonal corners. if (!n && !e && !s && !w) { if (nw) yield return "NWCornerSingle"; if (ne) yield return "NECornerSingle"; if (se) yield return "SECornerSingle"; if (sw) yield return "SWCornerSingle"; } // Last-resort directional defaults to avoid untiled wall cells. yield return "Wall_N"; yield return "Wall_E"; yield return "Wall_S"; yield return "Wall_W"; } private sealed class TemplateTilePlacement { public int X { get; set; } public int Y { get; set; } public int SheetId { get; set; } public int FrameIndex { get; set; } public int? TileDefinitionId { get; set; } public int? Layer { get; set; } } private sealed class TemplateMobSpawn { public int X { get; set; } public int Y { get; set; } public int? MobDefinitionId { get; set; } public string? Type { get; set; } public int Count { get; set; } = 1; } private sealed record TileBuildContext( Dictionary SheetsById, List FloorCandidates, List WallCandidates, Dictionary> WallDefinitionsByCanonicalBucket, Dictionary BucketNamesById); private static readonly Dictionary WallBucketAliases = new(StringComparer.OrdinalIgnoreCase) { ["Wall_N"] = new[] { "wall_n", "walln", "north", "wall_north", "walltop" }, ["Wall_S"] = new[] { "wall_s", "walls", "south", "wall_south", "wallbottom", "wallbottm" }, ["Wall_E"] = new[] { "wall_e", "walle", "east", "wall_east", "wallsideleft" }, ["Wall_W"] = new[] { "wall_w", "wallw", "west", "wall_west", "wallsideright" }, ["NWCornerLarge"] = new[] { "nwcornerlarge", "wall_nwcornerlarge", "wall_nwnne" }, ["NECornerLarge"] = new[] { "necornerlarge", "wall_necornerlarge", "wall_nne" }, ["SECornerLarge"] = new[] { "secornerlarge", "wall_secornerlarge" }, ["SWCornerLarge"] = new[] { "swcornerlarge", "wall_swcornerlarge" }, ["NWCornerSingle"] = new[] { "nwcornersingle", "wall_nwcornersingle" }, ["NECornerSingle"] = new[] { "necornersingle", "wall_necornersingle" }, ["SECornerSingle"] = new[] { "secornersingle", "wall_secornersingle" }, ["SWCornerSingle"] = new[] { "swcornersingle", "wall_swcornersingle" } }; private static readonly KeyValuePair>[] DirectionalWallBucketMasks = { new("Wall_N", new HashSet { 128, 129, 192, 193 }), new("Wall_S", new HashSet { 8, 24, 12, 28 }), new("Wall_E", new HashSet { 32, 96, 48, 112 }), new("Wall_W", new HashSet { 2, 6, 3, 7 }), new("NWCornerLarge", new HashSet { 131 }), new("NECornerLarge", new HashSet { 224 }), new("SECornerLarge", new HashSet { 56 }), new("SWCornerLarge", new HashSet { 14 }), new("NWCornerSingle", new HashSet { 1 }), new("NECornerSingle", new HashSet { 64 }), new("SECornerSingle", new HashSet { 16 }), new("SWCornerSingle", new HashSet { 4 }) }; private static float Distance(int x1, int y1, int x2, int y2) { int dx = x2 - x1; int dy = y2 - y1; return MathF.Sqrt(dx * dx + dy * dy); } }