Dungeon Builder

This commit is contained in:
dingo
2025-12-28 08:29:27 -05:00
parent 6e7609d6e5
commit 3d4607e591
3 changed files with 903 additions and 0 deletions
+552
View File
@@ -0,0 +1,552 @@
using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
namespace Server.Game.Dungeon;
/// <summary>
/// Procedural dungeon generator using room templates from database
/// Falls back to basic BSP generation if no templates available
/// </summary>
public class DungeonGeneratorV2
{
private readonly GameDbContext _db;
private readonly Random _rng;
private readonly int _seed;
private readonly int _tier;
private readonly int _tileSize = 32;
// Tier-based scaling
private int MinRooms => 5 + (_tier * 2);
private int MaxRooms => 8 + (_tier * 3);
private int MapWidth => 60 + (_tier * 15); // In tiles
private int MapHeight => 60 + (_tier * 15);
// Cached templates
private List<RoomTemplate> _entranceTemplates = new();
private List<RoomTemplate> _exitTemplates = new();
private List<RoomTemplate> _bossTemplates = new();
private List<RoomTemplate> _treasureTemplates = new();
private List<RoomTemplate> _normalTemplates = new();
private List<RoomTemplate> _hallwayTemplates = new();
// Tile definitions cache
private Dictionary<int, TileDefinition> _tileDefinitions = new();
private TileMapSheet? _defaultSheet;
public DungeonGeneratorV2(GameDbContext db, int seed, int tier)
{
_db = db;
_seed = seed;
_tier = Math.Max(1, tier);
_rng = new Random(seed);
}
public async Task<DungeonLayoutV2> GenerateAsync()
{
// Load templates from database
await LoadTemplatesAsync();
var layout = new DungeonLayoutV2
{
Seed = _seed,
Tier = _tier,
Width = MapWidth,
Height = MapHeight,
TileSize = _tileSize
};
// Initialize tile map with detailed tile info
// 0 = void/wall, positive = tile definition ID
layout.Tiles = new int[MapWidth, MapHeight];
layout.TileDetails = new List<PlacedTile>();
// Generate rooms
int roomCount = _rng.Next(MinRooms, MaxRooms + 1);
var rooms = new List<DungeonRoomV2>();
int attempts = 0;
int maxAttempts = roomCount * 30;
// Always place entrance first
var entrance = await PlaceRoomAsync(layout, rooms, RoomType.Entrance, 5, 5);
if (entrance != null) rooms.Add(entrance);
// Place other rooms
while (rooms.Count < roomCount && attempts < maxAttempts)
{
attempts++;
// Determine room type based on current room count
RoomType type = DetermineNextRoomType(rooms, roomCount);
// Try to place near existing room (for connectivity)
var baseRoom = rooms[_rng.Next(rooms.Count)];
int offsetX = _rng.Next(-20, 21);
int offsetY = _rng.Next(-20, 21);
int x = Math.Clamp(baseRoom.X + baseRoom.Width / 2 + offsetX, 2, MapWidth - 15);
int y = Math.Clamp(baseRoom.Y + baseRoom.Height / 2 + offsetY, 2, MapHeight - 15);
var newRoom = await PlaceRoomAsync(layout, rooms, type, x, y);
if (newRoom != null)
{
rooms.Add(newRoom);
}
}
// Ensure we have an exit/boss room
var bossRoom = rooms.FirstOrDefault(r => r.Type == RoomType.Boss);
if (bossRoom == null && rooms.Count > 1)
{
// Convert last room to boss
rooms[^1].Type = RoomType.Boss;
}
// Sort rooms by distance from entrance for corridor generation
var entranceRoom = rooms.FirstOrDefault(r => r.Type == RoomType.Entrance) ?? rooms[0];
rooms = rooms.OrderBy(r => Distance(entranceRoom, r)).ToList();
// Connect rooms with corridors
var connected = new HashSet<int> { 0 };
for (int i = 1; i < rooms.Count; i++)
{
// Find closest connected room
int closestIdx = connected.OrderBy(c => Distance(rooms[c], rooms[i])).First();
await ConnectRoomsAsync(layout, rooms[closestIdx], rooms[i]);
connected.Add(i);
}
// Add some extra connections for loops
for (int i = 0; i < rooms.Count / 4; i++)
{
int a = _rng.Next(rooms.Count);
int b = _rng.Next(rooms.Count);
if (a != b && Distance(rooms[a], rooms[b]) < 30)
{
await ConnectRoomsAsync(layout, rooms[a], rooms[b]);
}
}
// Set spawn point
layout.SpawnPoint = new DungeonPoint(entranceRoom.CenterX, entranceRoom.CenterY);
// Generate mob and chest spawns based on room templates
GenerateSpawns(rooms, layout);
// Store rooms
layout.Rooms = rooms.Cast<DungeonRoom>().ToList();
// Build tile data for client
layout.BuildClientTileData(_tileDefinitions, _defaultSheet);
return layout;
}
private async Task LoadTemplatesAsync()
{
var templates = await _db.RoomTemplates
.Where(r => r.IsEnabled)
.Where(r => r.MinTier <= _tier && (r.MaxTier == 0 || r.MaxTier >= _tier))
.ToListAsync();
_entranceTemplates = templates.Where(t => t.Type == RoomType.Entrance).ToList();
_exitTemplates = templates.Where(t => t.Type == RoomType.Exit).ToList();
_bossTemplates = templates.Where(t => t.Type == RoomType.Boss).ToList();
_treasureTemplates = templates.Where(t => t.Type == RoomType.Treasure).ToList();
_normalTemplates = templates.Where(t => t.Type == RoomType.Normal).ToList();
_hallwayTemplates = templates.Where(t => t.Type == RoomType.Hallway).ToList();
// Load tile definitions
var tileIds = templates
.Where(t => !string.IsNullOrEmpty(t.TileDataJson))
.SelectMany(t => {
try {
var placements = JsonSerializer.Deserialize<List<TilePlacement>>(t.TileDataJson!);
return placements?.Select(p => p.TileDefinitionId) ?? Enumerable.Empty<int>();
} catch { return Enumerable.Empty<int>(); }
})
.Distinct()
.ToList();
if (tileIds.Any())
{
var tiles = await _db.TileDefinitions
.Include(t => t.TileMapSheet)
.Where(t => tileIds.Contains(t.Id))
.ToListAsync();
_tileDefinitions = tiles.ToDictionary(t => t.Id);
_defaultSheet = tiles.FirstOrDefault()?.TileMapSheet;
}
// If no templates, load a default sheet for basic generation
if (_defaultSheet == null)
{
_defaultSheet = await _db.TileMapSheets
.Include(s => s.Tiles)
.FirstOrDefaultAsync(s => s.IsEnabled);
if (_defaultSheet?.Tiles != null)
{
foreach (var tile in _defaultSheet.Tiles)
{
_tileDefinitions[tile.Id] = tile;
}
}
}
}
private RoomType DetermineNextRoomType(List<DungeonRoomV2> existing, int targetCount)
{
// Ensure we have at least one of certain types
bool hasBoss = existing.Any(r => r.Type == RoomType.Boss);
bool hasTreasure = existing.Any(r => r.Type == RoomType.Treasure);
// If near the end and no boss, force boss
if (!hasBoss && existing.Count >= targetCount - 2)
return RoomType.Boss;
// Weighted random selection
int roll = _rng.Next(100);
if (roll < 5 && !hasBoss) return RoomType.Boss;
if (roll < 15 && !hasTreasure) return RoomType.Treasure;
if (roll < 25) return RoomType.Treasure;
return RoomType.Normal;
}
private async Task<DungeonRoomV2?> PlaceRoomAsync(DungeonLayoutV2 layout, List<DungeonRoomV2> existing, RoomType type, int preferX, int preferY)
{
// Get templates for this type
var templates = type switch
{
RoomType.Entrance => _entranceTemplates,
RoomType.Exit or RoomType.Boss => _bossTemplates.Concat(_exitTemplates).ToList(),
RoomType.Treasure => _treasureTemplates,
_ => _normalTemplates
};
// If no templates, use fallback generation
if (templates.Count == 0)
{
return PlaceFallbackRoom(layout, existing, type, preferX, preferY);
}
// Weighted random selection
var template = SelectWeightedTemplate(templates);
if (template == null)
{
return PlaceFallbackRoom(layout, existing, type, preferX, preferY);
}
// Try to place at preferred position
int x = Math.Clamp(preferX - template.Width / 2, 2, MapWidth - template.Width - 2);
int y = Math.Clamp(preferY - template.Height / 2, 2, MapHeight - template.Height - 2);
var room = new DungeonRoomV2(x, y, template.Width, template.Height)
{
Type = type,
TemplateId = template.Id,
TemplateName = template.Name
};
// Check overlap
if (existing.Any(r => room.Intersects(r, padding: 3)))
{
// Try random position
for (int attempt = 0; attempt < 10; attempt++)
{
x = _rng.Next(2, MapWidth - template.Width - 2);
y = _rng.Next(2, MapHeight - template.Height - 2);
room = new DungeonRoomV2(x, y, template.Width, template.Height)
{
Type = type,
TemplateId = template.Id,
TemplateName = template.Name
};
if (!existing.Any(r => room.Intersects(r, padding: 3)))
break;
}
if (existing.Any(r => room.Intersects(r, padding: 3)))
return null;
}
// Place tiles from template
if (!string.IsNullOrEmpty(template.TileDataJson))
{
try
{
var placements = JsonSerializer.Deserialize<List<TilePlacement>>(template.TileDataJson);
if (placements != null)
{
foreach (var p in placements)
{
int worldX = x + p.X;
int worldY = y + p.Y;
if (worldX >= 0 && worldX < MapWidth && worldY >= 0 && worldY < MapHeight)
{
layout.Tiles[worldX, worldY] = p.TileDefinitionId;
layout.TileDetails.Add(new PlacedTile
{
X = worldX,
Y = worldY,
TileDefinitionId = p.TileDefinitionId,
Layer = p.Layer,
Rotation = p.Rotation,
FlipX = p.FlipX,
FlipY = p.FlipY
});
}
}
}
}
catch { /* Invalid JSON, fall through to basic carve */ }
}
// If no tiles were placed, do basic carve
if (!layout.TileDetails.Any(t => t.X >= x && t.X < x + room.Width && t.Y >= y && t.Y < y + room.Height))
{
CarveBasicRoom(layout, room);
}
return room;
}
private DungeonRoomV2? PlaceFallbackRoom(DungeonLayoutV2 layout, List<DungeonRoomV2> existing, RoomType type, int preferX, int preferY)
{
int w = _rng.Next(6, 12);
int h = _rng.Next(6, 12);
int x = Math.Clamp(preferX - w / 2, 2, MapWidth - w - 2);
int y = Math.Clamp(preferY - h / 2, 2, MapHeight - h - 2);
var room = new DungeonRoomV2(x, y, w, h) { Type = type };
if (existing.Any(r => room.Intersects(r, padding: 3)))
{
// Try random positions
for (int attempt = 0; attempt < 20; attempt++)
{
x = _rng.Next(2, MapWidth - w - 2);
y = _rng.Next(2, MapHeight - h - 2);
room = new DungeonRoomV2(x, y, w, h) { Type = type };
if (!existing.Any(r => room.Intersects(r, padding: 3)))
break;
}
if (existing.Any(r => room.Intersects(r, padding: 3)))
return null;
}
CarveBasicRoom(layout, room);
return room;
}
private void CarveBasicRoom(DungeonLayoutV2 layout, DungeonRoomV2 room)
{
// Find floor tile from default sheet
var floorTile = _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor);
int floorId = floorTile?.Id ?? -1; // -1 means no visual tile, just walkable
for (int x = room.X; x < room.X + room.Width; x++)
{
for (int y = room.Y; y < room.Y + room.Height; y++)
{
if (x >= 0 && x < MapWidth && y >= 0 && y < MapHeight)
{
layout.Tiles[x, y] = floorId > 0 ? floorId : 1; // 1 = walkable but no visual
if (floorId > 0)
{
layout.TileDetails.Add(new PlacedTile
{
X = x, Y = y,
TileDefinitionId = floorId,
Layer = 0
});
}
}
}
}
}
private async Task ConnectRoomsAsync(DungeonLayoutV2 layout, DungeonRoomV2 a, DungeonRoomV2 b)
{
// Check for hallway templates
// For now, use basic corridor carving
int x = a.CenterX;
int y = a.CenterY;
int targetX = b.CenterX;
int targetY = b.CenterY;
var floorTile = _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor);
int floorId = floorTile?.Id ?? 1;
// L-shaped corridor
if (_rng.Next(2) == 0)
{
CarveHorizontalCorridor(layout, x, targetX, y, floorId);
CarveVerticalCorridor(layout, y, targetY, targetX, floorId);
}
else
{
CarveVerticalCorridor(layout, y, targetY, x, floorId);
CarveHorizontalCorridor(layout, x, targetX, targetY, floorId);
}
}
private void CarveHorizontalCorridor(DungeonLayoutV2 layout, int x1, int x2, int y, int floorId)
{
int minX = Math.Min(x1, x2);
int maxX = Math.Max(x1, x2);
for (int x = minX; x <= maxX; x++)
{
for (int dy = 0; dy < 2; dy++) // 2-tile wide corridor
{
int ty = y + dy;
if (x >= 0 && x < MapWidth && ty >= 0 && ty < MapHeight && layout.Tiles[x, ty] == 0)
{
layout.Tiles[x, ty] = floorId;
if (floorId > 1)
{
layout.TileDetails.Add(new PlacedTile { X = x, Y = ty, TileDefinitionId = floorId, Layer = 0 });
}
}
}
}
}
private void CarveVerticalCorridor(DungeonLayoutV2 layout, int y1, int y2, int x, int floorId)
{
int minY = Math.Min(y1, y2);
int maxY = Math.Max(y1, y2);
for (int y = minY; y <= maxY; y++)
{
for (int dx = 0; dx < 2; dx++) // 2-tile wide corridor
{
int tx = x + dx;
if (tx >= 0 && tx < MapWidth && y >= 0 && y < MapHeight && layout.Tiles[tx, y] == 0)
{
layout.Tiles[tx, y] = floorId;
if (floorId > 1)
{
layout.TileDetails.Add(new PlacedTile { X = tx, Y = y, TileDefinitionId = floorId, Layer = 0 });
}
}
}
}
}
private RoomTemplate? SelectWeightedTemplate(List<RoomTemplate> templates)
{
if (templates.Count == 0) return null;
int totalWeight = templates.Sum(t => t.Weight);
int roll = _rng.Next(totalWeight);
int cumulative = 0;
foreach (var t in templates)
{
cumulative += t.Weight;
if (roll < cumulative)
return t;
}
return templates[0];
}
private float Distance(DungeonRoom a, DungeonRoom b)
{
float dx = a.CenterX - b.CenterX;
float dy = a.CenterY - b.CenterY;
return MathF.Sqrt(dx * dx + dy * dy);
}
private void GenerateSpawns(List<DungeonRoomV2> rooms, DungeonLayoutV2 layout)
{
foreach (var room in rooms)
{
if (room.Type == RoomType.Entrance) continue;
// Mob spawns
int mobCount = room.Type switch
{
RoomType.Boss => 1,
RoomType.Treasure => _rng.Next(1, 3),
_ => _rng.Next(2, 5 + _tier)
};
for (int i = 0; i < mobCount; i++)
{
int x = room.X + 1 + _rng.Next(Math.Max(1, room.Width - 2));
int y = room.Y + 1 + _rng.Next(Math.Max(1, room.Height - 2));
layout.MobSpawns.Add(new DungeonMobSpawn
{
Id = layout.MobSpawns.Count + 1,
X = x, Y = y,
MobType = room.Type == RoomType.Boss ? DungeonMobSpawnType.Boss : DungeonMobSpawnType.Normal,
RoomIndex = rooms.IndexOf(room)
});
}
// Chest spawns
int chestCount = room.Type switch
{
RoomType.Treasure => _rng.Next(2, 4),
RoomType.Boss => 1,
_ => _rng.NextDouble() < 0.2 ? 1 : 0
};
for (int i = 0; i < chestCount; i++)
{
int x = room.X + 1 + _rng.Next(Math.Max(1, room.Width - 2));
int y = room.Y + 1 + _rng.Next(Math.Max(1, room.Height - 2));
layout.ChestSpawns.Add(new DungeonChestSpawn
{
Id = layout.ChestSpawns.Count + 1,
X = x, Y = y,
ChestType = room.Type == RoomType.Boss ? DungeonChestType.Boss : DungeonChestType.Normal,
RoomIndex = rooms.IndexOf(room)
});
}
}
layout.TotalMobs = layout.MobSpawns.Count;
layout.TotalChests = layout.ChestSpawns.Count;
}
}
/// <summary>
/// Extended room with template info
/// </summary>
public class DungeonRoomV2 : DungeonRoom
{
public int? TemplateId { get; set; }
public string? TemplateName { get; set; }
public new RoomType Type { get; set; } = RoomType.Normal;
public DungeonRoomV2(int x, int y, int width, int height) : base(x, y, width, height) { }
}
/// <summary>
/// Placed tile with details
/// </summary>
public class PlacedTile
{
public int X { get; set; }
public int Y { get; set; }
public int TileDefinitionId { get; set; }
public int Layer { get; set; }
public int Rotation { get; set; }
public bool FlipX { get; set; }
public bool FlipY { get; set; }
}
+188
View File
@@ -0,0 +1,188 @@
using DataServer.Data.Entities;
using System.Text.Json;
namespace Server.Game.Dungeon;
/// <summary>
/// Enhanced dungeon layout with full tile visual information
/// </summary>
public class DungeonLayoutV2 : DungeonLayout
{
/// <summary>
/// Detailed tile placements with visual info
/// </summary>
public List<PlacedTile> TileDetails { get; set; } = new();
/// <summary>
/// Tilemap sheet data for client rendering
/// </summary>
public List<TileMapSheetInfo> TileMapSheets { get; set; } = new();
/// <summary>
/// Build tile data optimized for client transmission
/// </summary>
public void BuildClientTileData(Dictionary<int, TileDefinition> tileDefinitions, TileMapSheet? defaultSheet)
{
// Collect all unique sheets used
var sheetIds = TileDetails
.Select(t => tileDefinitions.GetValueOrDefault(t.TileDefinitionId)?.TileMapSheetId)
.Where(id => id.HasValue)
.Select(id => id!.Value)
.Distinct()
.ToList();
var sheets = tileDefinitions.Values
.Where(t => sheetIds.Contains(t.TileMapSheetId))
.Select(t => t.TileMapSheet)
.Where(s => s != null)
.DistinctBy(s => s!.Id)
.ToList();
// Add default sheet if not already included
if (defaultSheet != null && !sheets.Any(s => s?.Id == defaultSheet.Id))
{
sheets.Add(defaultSheet);
}
foreach (var sheet in sheets)
{
if (sheet == null) continue;
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
});
}
}
/// <summary>
/// Serialize to JSON for client
/// Includes full tile visual data
/// </summary>
public new string ToJson()
{
return JsonSerializer.Serialize(new
{
seed = Seed,
tier = Tier,
width = Width,
height = Height,
tileSize = TileSize,
tilesRLE = SerializeTilesRLE(),
spawn = new { x = SpawnPoint.X, y = SpawnPoint.Y },
rooms = Rooms.Select(r => new
{
x = r.X, y = r.Y, w = r.Width, h = r.Height,
type = r.Type.ToString(),
templateId = (r as DungeonRoomV2)?.TemplateId,
templateName = (r as DungeonRoomV2)?.TemplateName
}),
mobs = MobSpawns.Select(m => new
{
id = m.Id, x = m.X, y = m.Y,
type = m.MobType.ToString(),
roomIndex = m.RoomIndex
}),
chests = ChestSpawns.Select(c => new
{
id = c.Id, x = c.X, y = c.Y,
type = c.ChestType.ToString(),
roomIndex = c.RoomIndex
}),
// New: Visual tile data
tileSheets = TileMapSheets.Select(s => new
{
id = s.Id,
path = s.CdnPath,
tileW = s.TileWidth,
tileH = s.TileHeight,
sheetW = s.SheetWidth,
sheetH = s.SheetHeight,
cols = s.Columns,
rows = s.Rows
}),
visualTiles = TileDetails.Select(t => new
{
x = t.X,
y = t.Y,
tid = t.TileDefinitionId,
l = t.Layer,
r = t.Rotation,
fx = t.FlipX,
fy = t.FlipY
})
});
}
/// <summary>
/// Lightweight JSON for initial dungeon state (no visual data, sent separately)
/// </summary>
public string ToLightJson()
{
return JsonSerializer.Serialize(new
{
seed = Seed,
tier = Tier,
width = Width,
height = Height,
tileSize = TileSize,
tilesRLE = SerializeTilesRLE(),
spawn = new { x = SpawnPoint.X, y = SpawnPoint.Y },
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() })
});
}
/// <summary>
/// Get visual tile data JSON (can be fetched separately for large dungeons)
/// </summary>
public string ToVisualTileJson()
{
return JsonSerializer.Serialize(new
{
sheets = TileMapSheets.Select(s => new
{
id = s.Id,
path = s.CdnPath,
tileW = s.TileWidth,
tileH = s.TileHeight,
sheetW = s.SheetWidth,
sheetH = s.SheetHeight,
cols = s.Columns
}),
tiles = TileDetails.Select(t => new
{
x = t.X,
y = t.Y,
tid = t.TileDefinitionId,
l = t.Layer,
r = t.Rotation,
fx = t.FlipX,
fy = t.FlipY
})
});
}
}
/// <summary>
/// Tilemap sheet info for client
/// </summary>
public class TileMapSheetInfo
{
public int Id { get; set; }
public string CdnPath { get; set; } = "";
public int TileWidth { get; set; }
public int TileHeight { get; set; }
public int SheetWidth { get; set; }
public int SheetHeight { get; set; }
public int Columns { get; set; }
public int Rows { get; set; }
}
+163
View File
@@ -0,0 +1,163 @@
using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
namespace Server.Game.Dungeon;
/// <summary>
/// Extension methods for visual tile data
/// </summary>
public static class DungeonVisualTileExtensions
{
/// <summary>
/// Build visual tile data for client from room templates used in the dungeon
/// </summary>
public static async Task<object?> BuildVisualTileDataAsync(this DungeonInstance instance, GameDbContext db)
{
var layout = instance.Simulation.Layout;
// Check if we have a V2 layout with tile details
if (layout is DungeonLayoutV2 layoutV2 && layoutV2.TileDetails.Count > 0)
{
return new
{
sheets = layoutV2.TileMapSheets.Select(s => new
{
id = s.Id,
path = s.CdnPath,
tileW = s.TileWidth,
tileH = s.TileHeight,
sheetW = s.SheetWidth,
sheetH = s.SheetHeight,
cols = s.Columns
}),
tiles = layoutV2.TileDetails.Select(t => new
{
x = t.X,
y = t.Y,
tid = t.TileDefinitionId,
l = t.Layer,
r = t.Rotation,
fx = t.FlipX,
fy = t.FlipY
})
};
}
// For V1 layouts, try to build visual data from room templates if any were used
// This is a fallback - in practice V2 generator should be used for visual tiles
// Get rooms that have template IDs (from V2 rooms stored in V1 layout)
var roomsWithTemplates = layout.Rooms
.OfType<DungeonRoomV2>()
.Where(r => r.TemplateId.HasValue)
.ToList();
if (roomsWithTemplates.Count == 0)
{
// No templates used, return null (client will use basic tilemap)
return null;
}
// Load templates and their tile data
var templateIds = roomsWithTemplates.Select(r => r.TemplateId!.Value).Distinct().ToList();
var templates = await db.RoomTemplates
.Where(t => templateIds.Contains(t.Id))
.ToListAsync();
// Collect all tile definition IDs
var allTileIds = new HashSet<int>();
foreach (var template in templates)
{
if (string.IsNullOrEmpty(template.TileDataJson)) continue;
try
{
var placements = JsonSerializer.Deserialize<List<TilePlacement>>(template.TileDataJson);
if (placements != null)
{
foreach (var p in placements)
{
allTileIds.Add(p.TileDefinitionId);
}
}
}
catch { /* Invalid JSON */ }
}
if (allTileIds.Count == 0)
{
return null;
}
// Load tile definitions with their sheets
var tileDefinitions = await db.TileDefinitions
.Include(t => t.TileMapSheet)
.Where(t => allTileIds.Contains(t.Id))
.ToDictionaryAsync(t => t.Id);
// Build sheets list
var sheets = tileDefinitions.Values
.Select(t => t.TileMapSheet)
.Where(s => s != null)
.DistinctBy(s => s!.Id)
.Select(s => new
{
id = s!.Id,
path = s.CdnPath,
tileW = s.TileWidth,
tileH = s.TileHeight,
sheetW = s.SheetWidth,
sheetH = s.SheetHeight,
cols = s.Columns
})
.ToList();
// Build tiles list
var tiles = new List<object>();
foreach (var room in roomsWithTemplates)
{
var template = templates.FirstOrDefault(t => t.Id == room.TemplateId);
if (template == null || string.IsNullOrEmpty(template.TileDataJson)) continue;
try
{
var placements = JsonSerializer.Deserialize<List<TilePlacement>>(template.TileDataJson);
if (placements == null) continue;
foreach (var p in placements)
{
var tileDef = tileDefinitions.GetValueOrDefault(p.TileDefinitionId);
if (tileDef == null) continue;
tiles.Add(new
{
x = room.X + p.X,
y = room.Y + p.Y,
tid = p.TileDefinitionId,
sid = tileDef.TileMapSheetId,
frame = tileDef.FrameIndex,
l = p.Layer,
r = p.Rotation,
fx = p.FlipX,
fy = p.FlipY
});
}
}
catch { /* Invalid JSON */ }
}
return new { sheets, tiles };
}
/// <summary>
/// Generate a dungeon using V2 generator with room templates
/// </summary>
public static async Task<DungeonLayoutV2> GenerateWithTemplatesAsync(GameDbContext db, int seed, int tier)
{
var generator = new DungeonGeneratorV2(db, seed, tier);
return await generator.GenerateAsync();
}
}