using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
namespace GameServer.Dungeon;
///
/// Dungeon Generator V3 - Uses the DungeonBuilder system
/// Supports: BuilderRoomTemplates, TileTemplates, ObjectTemplates, DungeonPalettes
///
public class DungeonGeneratorV3
{
// ============================================================
// CONFIGURATION - Set these to control logging verbosity
// ============================================================
///
/// Enable verbose logging to trace tile selection decisions.
/// Set to true to debug tile/template selection issues.
///
public static bool VerboseLogging { get; set; } = false;
///
/// Log every single tile placement (WARNING: extremely verbose for large dungeons)
///
public static bool LogEveryTile { get; set; } = false;
///
/// Enable socket-based tile matching. When true, tiles are selected based on
/// compatibility with neighboring tiles' sockets.
///
public static bool UseSocketMatching { get; set; } = true;
// ============================================================
// DEPENDENCIES
// ============================================================
private readonly GameDbContext _db;
private readonly Random _rng;
private readonly int _seed;
private readonly int _tier;
///
/// JSON options for case-insensitive deserialization.
/// JavaScript saves with lowercase: {"sheetId":3,"frameIndex":273}
/// C# classes use PascalCase: SheetId, FrameIndex
/// Also handles enum serialization as strings (Open, Closed, Custom)
///
private static readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() }
};
// ============================================================
// SOCKET MATCHING DATA
// ============================================================
///
/// Cache of parsed socket configurations for each TileTemplate.
/// Key = TileTemplate.Id, Value = parsed SocketConfiguration
///
private Dictionary _templateSocketConfigs = new();
///
/// Track which template was placed at each position for socket matching.
/// Key = "x,y", Value = TileTemplate.Id
///
private Dictionary _placedTemplates = new();
///
/// Lookup TileTemplate by (sheetId, frameIndex) for room stamping.
/// Key = "sheetId:frameIndex", Value = TileTemplate
///
private Dictionary _tileTemplatesBySprite = new();
// ============================================================
// PALETTE & TEMPLATES
// ============================================================
// 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)
{
Log($" 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
});
}
Log($" Generation complete: {rooms.Count} rooms, {layout.TileDetails.Count} tiles, {layout.Objects.Count} objects, {layout.TileMapSheets.Count} sheets");
return layout;
}
///
/// Load a dungeon palette and its associated templates.
///
/// Priority order:
/// 1. Specific palette by ID (if provided)
/// 2. Random palette matching biome (if provided)
/// 3. Random palette from all enabled palettes
/// 4. Fall back to loading all enabled templates (no palette)
///
private async Task LoadPaletteAsync(int? paletteId, string? biome)
{
Log($"--- Loading Palette ---");
// Try to load specific palette by ID
if (paletteId.HasValue)
{
_palette = await _db.DungeonPalettes.FindAsync(paletteId.Value);
if (_palette != null)
{
Log($"Loaded palette by ID: {_palette.Id} - '{_palette.Name}'");
}
else
{
Log($"WARNING: Palette ID {paletteId} not found!");
}
}
// Or find one by biome
if (_palette == null && !string.IsNullOrEmpty(biome))
{
var biomePalettes = await _db.DungeonPalettes
.Where(p => p.IsEnabled && p.Biome == biome)
.ToListAsync();
Log($"Found {biomePalettes.Count} palettes for biome '{biome}'");
if (biomePalettes.Count > 0)
{
// Randomly select from matching biome palettes
_palette = biomePalettes[_rng.Next(biomePalettes.Count)];
Log($"Randomly selected palette: {_palette.Id} - '{_palette.Name}'");
}
}
// Or randomly select from ALL enabled palettes (true dynamic selection)
if (_palette == null)
{
var allPalettes = await _db.DungeonPalettes
.Where(p => p.IsEnabled)
.ToListAsync();
Log($"Found {allPalettes.Count} total enabled palettes");
// List all available palettes for debugging
foreach (var p in allPalettes)
{
LogVerbose($" - Palette {p.Id}: '{p.Name}' (Biome: {p.Biome ?? "none"}, Enabled: {p.IsEnabled})");
}
if (allPalettes.Count > 0)
{
// Randomly select any enabled palette
_palette = allPalettes[_rng.Next(allPalettes.Count)];
Log($"Randomly selected palette: {_palette.Id} - '{_palette.Name}' (Biome: {_palette.Biome ?? "none"})");
}
else
{
Log($"WARNING: No enabled palettes found in database!");
}
}
if (_palette != null)
{
Log($"--- Applying Palette Settings ---");
Log($"Palette: '{_palette.Name}'");
Log($" Biome: {_palette.Biome ?? "none"}");
Log($" Rooms: {_palette.MinRooms}-{_palette.MaxRooms}");
Log($" Room Size: {_palette.MinRoomWidth}-{_palette.MaxRoomWidth} x {_palette.MinRoomHeight}-{_palette.MaxRoomHeight}");
Log($" Corridor Width: {_palette.MinCorridorWidth}-{_palette.MaxCorridorWidth}");
Log($" Densities: Decor={_palette.DecorationDensity}%, Trap={_palette.TrapDensity}%, Container={_palette.ContainerDensity}%");
// 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
{
Log($"No palette found - loading ALL enabled templates");
await LoadAllTemplatesAsync();
}
}
///
/// Load templates specified in the palette's JSON arrays.
///
/// Palette stores template IDs as JSON arrays:
/// - FloorTemplateIdsJson: [1, 2, 3]
/// - WallTemplateIdsJson: [4, 5]
/// - RoomTemplateIdsJson: [10, 11]
///
private async Task LoadTemplatesFromPaletteAsync()
{
if (_palette == null) return;
Log($"--- Loading Templates from Palette ---");
// 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);
Log($"Palette template IDs:");
Log($" Floor IDs: [{string.Join(", ", floorIds)}]");
Log($" Wall IDs: [{string.Join(", ", wallIds)}]");
Log($" Door IDs: [{string.Join(", ", doorIds)}]");
Log($" Decoration IDs: [{string.Join(", ", decorIds)}]");
Log($" Container IDs: [{string.Join(", ", containerIds)}]");
Log($" Trap IDs: [{string.Join(", ", trapIds)}]");
Log($" Room IDs: [{string.Join(", ", roomIds)}]");
// 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();
Log($"Loaded {_floorTemplates.Count} floor templates");
}
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();
Log($"Loaded {_wallTemplates.Count} wall templates");
}
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();
Log($"Loaded {_roomTemplates.Count} room templates from palette IDs: [{string.Join(",", roomIds)}]");
}
else
{
Log($" Palette has no room template IDs configured");
}
CategorizeRoomTemplates();
LogTemplateStats();
ParseSocketConfigurations();
BuildSpriteToTemplateLookup();
}
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();
ParseSocketConfigurations();
BuildSpriteToTemplateLookup();
}
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;
}
}
}
/// Log summary of loaded templates
private void LogTemplateStats()
{
Log($"--- Template Summary ---");
Log($" Floor templates: {_floorTemplates.Count}");
Log($" Wall templates: {_wallTemplates.Count}");
Log($" Door templates: {_doorTemplates.Count}");
Log($" Decoration templates: {_decorationTemplates.Count}");
Log($" Container templates: {_containerTemplates.Count}");
Log($" Trap templates: {_trapTemplates.Count}");
Log($" Room templates: {_roomTemplates.Count}");
Log($" - Entrance: {_entranceRooms.Count}");
Log($" - Exit: {_exitRooms.Count}");
Log($" - Boss: {_bossRooms.Count}");
Log($" - Treasure: {_treasureRooms.Count}");
Log($" - Normal: {_normalRooms.Count}");
}
///
/// Load all tile sheets and tile definitions from database.
/// Builds lookup dictionaries for fast tile resolution.
///
private async Task LoadTileDataAsync()
{
Log($"--- Loading Tile Data ---");
// 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;
Log($"Sheet {sheet.Id}: '{sheet.Name}' ({sheet.SheetWidth}x{sheet.SheetHeight}, TileSize: {sheet.TileWidth}x{sheet.TileHeight})");
if (sheet.Tiles != null)
{
foreach (var tile in sheet.Tiles)
{
tile.TileMapSheet = sheet;
_tileDefinitions[tile.Id] = tile;
LogVerbose($" - TileDef {tile.Id}: Frame={tile.FrameIndex}, Walkable={tile.IsWalkable}, Name='{tile.Name}'");
}
Log($" -> {sheet.Tiles.Count} tile definitions");
}
}
Log($"Total: {_tileDefinitions.Count} tile definitions from {sheets.Count} sheets");
// Log walkable vs non-walkable summary
var walkable = _tileDefinitions.Values.Count(t => t.IsWalkable);
var nonWalkable = _tileDefinitions.Values.Count(t => !t.IsWalkable);
Log($" Walkable: {walkable}, Non-walkable: {nonWalkable}");
}
private async Task> GenerateRoomsAsync(DungeonLayoutV2 layout)
{
var rooms = new List();
int targetRooms = _rng.Next(_minRooms, _maxRooms + 1);
Log($"--- 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,
RoomType.Boss => _bossRooms,
RoomType.Treasure => _treasureRooms,
_ => _normalRooms
};
// NOTE: We intentionally do NOT fallback to other templates here.
// If no templates exist for this room type, we generate a procedural room.
// This prevents tiny entrance rooms being used everywhere.
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 PlaceObjectsAsync(DungeonLayoutV2 layout, List rooms)
{
Log($" 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,
MobDefinitionId = spawn.MobDefinitionId,
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;
Log($" 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();
}
}
private async Task StampRoomTemplateAsync(DungeonLayoutV2 layout, DungeonRoomV2 room, BuilderRoomTemplate template)
{
Log($" Stamping room template '{template.Name}' at ({room.X},{room.Y})");
var jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
// Parse and place tiles from TileGridJson (new format from visual editor)
if (!string.IsNullOrEmpty(template.TileGridJson))
{
try
{
var tiles = JsonSerializer.Deserialize>(template.TileGridJson, jsonOptions);
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)
{
// Ensure the sheet is loaded for client rendering
EnsureSheetLoaded(t.SheetId);
// Use IsWalkable from the tile placement data (set by room editor)
// This is the primary source of truth for walkability
bool isWalkable = t.IsWalkable;
int templateId = t.TemplateId ?? 0;
// If no templateId provided, try to find one by sprite lookup (legacy support)
if (templateId == 0)
{
var tileTemplate = FindTemplateBySprite(t.SheetId, t.FrameIndex);
if (tileTemplate != null)
{
templateId = tileTemplate.Id;
// Only override isWalkable if not explicitly set in placement
// (legacy data won't have IsWalkable set)
}
}
layout.Tiles[worldX, worldY] = templateId > 0 ? templateId : 1; // Non-zero to indicate tile is placed
layout.Walkable[worldX, worldY] = isWalkable;
// Track placement for socket matching if we found a template
if (templateId > 0)
{
_placedTemplates[$"{worldX},{worldY}"] = templateId;
}
layout.TileDetails.Add(new PlacedTile
{
X = worldX,
Y = worldY,
TileDefinitionId = 0, // No TileDefinition - using template directly
SheetId = t.SheetId,
FrameIndex = t.FrameIndex,
Layer = 0
});
}
}
}
}
catch (Exception ex)
{
Log($" Error parsing TileGridJson: {ex.Message}");
}
}
// Parse and handle connection points
if (!string.IsNullOrEmpty(template.ConnectionPointsJson))
{
try
{
var connections = JsonSerializer.Deserialize>(template.ConnectionPointsJson, jsonOptions);
if (connections != null)
{
foreach (var conn in connections)
{
int worldX = room.X + conn.X;
int worldY = room.Y + conn.Y;
if (worldX >= 0 && worldX < MapWidth && worldY >= 0 && worldY < MapHeight)
{
// Connection points must be walkable for corridors to connect
layout.Walkable[worldX, worldY] = true;
// Store connection point info for corridor generation
room.ConnectionPoints.Add(new ConnectionPoint
{
X = worldX,
Y = worldY,
Direction = conn.Direction ?? "north"
});
LogVerbose($" Connection point at ({worldX},{worldY}) facing {conn.Direction ?? "north"}");
}
}
}
}
catch (Exception ex)
{
Log($" Error parsing ConnectionPointsJson: {ex.Message}");
}
}
// Place objects from ObjectPlacementsJson
if (!string.IsNullOrEmpty(template.ObjectPlacementsJson))
{
try
{
var objects = JsonSerializer.Deserialize>(template.ObjectPlacementsJson, jsonOptions);
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, _jsonOptions);
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,
MobDefinitionId = spawn.MobDefinitionId,
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)
{
Log($" 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;
// Clear tile so FillFloorTiles can place a floor tile here
// This handles walls that get carved through for corridors
layout.Tiles[x, cy] = 0;
// Remove any existing tile details at this position
layout.TileDetails.RemoveAll(t => t.X == x && t.Y == cy);
// Clear from placed templates tracking
_placedTemplates.Remove($"{x},{cy}");
}
}
}
}
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;
// Clear tile so FillFloorTiles can place a floor tile here
layout.Tiles[cx, y] = 0;
// Remove any existing tile details at this position
layout.TileDetails.RemoveAll(t => t.X == cx && t.Y == y);
// Clear from placed templates tracking
_placedTemplates.Remove($"{cx},{y}");
}
}
}
}
///
/// Fill all walkable cells with floor tiles.
///
/// For each walkable cell without a tile:
/// 1. Call SelectFloorTile to get appropriate template (with socket matching)
/// 2. Parse TilesJson from template and add to TileDetails
///
private void FillFloorTiles(DungeonLayoutV2 layout)
{
Log($"--- Filling Floor Tiles ---");
Log($"Floor templates available: {_floorTemplates.Count}");
Log($"Socket matching: {(UseSocketMatching ? "ENABLED" : "DISABLED")}");
// Clear placement tracking for socket matching
_placedTemplates.Clear();
// Log detailed template info for debugging
foreach (var t in _floorTemplates)
{
LogTileTemplate(t, "Floor");
}
bool loggedFirst = false;
int tileCount = 0;
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 result = SelectFloorTemplate(x, y, layout);
if (result != null)
{
if (!loggedFirst)
{
loggedFirst = true;
Log($"First selected floor: Template='{result.Value.TemplateName}', Sheet={result.Value.SheetId}, Frame={result.Value.FrameIndex}");
}
layout.Tiles[x, y] = result.Value.TemplateId; // Use template ID for tracking
layout.TileDetails.Add(new PlacedTile
{
X = x,
Y = y,
TileDefinitionId = 0, // No TileDefinition - using template directly
SheetId = result.Value.SheetId,
FrameIndex = result.Value.FrameIndex,
Layer = 0
});
tileCount++;
if (LogEveryTile)
{
Log($" Floor ({x},{y}): Template='{result.Value.TemplateName}', Sheet={result.Value.SheetId}, Frame={result.Value.FrameIndex}");
}
}
}
}
}
Log($"Placed {tileCount} floor tiles");
}
///
/// Result of selecting a tile template - contains all info needed for placement.
///
private struct TemplateSelectionResult
{
public int TemplateId;
public string TemplateName;
public int SheetId;
public int FrameIndex;
}
///
/// Select a floor template for the given position.
/// Returns the template's tile placement info directly from TilesJson.
///
private TemplateSelectionResult? SelectFloorTemplate(int x, int y, DungeonLayoutV2 layout)
{
if (_floorTemplates.Count == 0)
{
LogVerbose($"SelectFloorTemplate({x},{y}): No floor templates available!");
return null;
}
// Get socket-compatible templates (already sorted by score, best first)
var compatibleTemplates = GetCompatibleTemplates(_floorTemplates, x, y, layout);
// Get the best templates (those with the highest score)
var bestTemplates = GetTopScoredTemplates(compatibleTemplates, x, y, layout);
// Shuffle only among the best templates by weight
var shuffledTemplates = ShuffleByWeight(bestTemplates);
foreach (var template in shuffledTemplates)
{
var result = TryParseTemplateTile(template, x, y, "Floor", compatibleTemplates.Count, _floorTemplates.Count);
if (result != null)
{
// Track placement for socket matching
_placedTemplates[$"{x},{y}"] = template.Id;
if (!UsedFloorTemplates.Contains(template.Name))
UsedFloorTemplates.Add(template.Name);
return result;
}
}
Log($"SelectFloorTemplate({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates had valid TilesJson!");
return null;
}
///
/// Try to parse a template's TilesJson to get tile placement info.
/// Returns null if TilesJson is missing or invalid.
///
private TemplateSelectionResult? TryParseTemplateTile(TileTemplate template, int x, int y, string tileType, int compatibleCount, int totalCount)
{
LogVerbose($"Select{tileType}Template({x},{y}): Trying template '{template.Name}' (ID={template.Id}) [Compatible: {compatibleCount}/{totalCount}]");
if (string.IsNullOrEmpty(template.TilesJson))
{
LogVerbose($" -> TilesJson is empty/null");
return null;
}
LogVerbose($" Parsing TilesJson: {template.TilesJson}");
try
{
var tiles = JsonSerializer.Deserialize>(template.TilesJson, _jsonOptions);
if (tiles == null || tiles.Count == 0)
{
LogVerbose($" -> Deserialized to NULL or EMPTY!");
return null;
}
var first = tiles[0];
LogVerbose($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}");
// Ensure the sheet is tracked for client rendering
EnsureSheetLoaded(first.SheetId);
return new TemplateSelectionResult
{
TemplateId = template.Id,
TemplateName = template.Name,
SheetId = first.SheetId,
FrameIndex = first.FrameIndex
};
}
catch (Exception ex)
{
LogVerbose($" -> ERROR parsing TilesJson: {ex.Message}");
return null;
}
}
///
/// Ensure a tile sheet is loaded and tracked for client rendering.
///
private void EnsureSheetLoaded(int sheetId)
{
if (!_tileSheets.ContainsKey(sheetId))
{
var sheet = _db.TileMapSheets.Find(sheetId);
if (sheet != null)
{
_tileSheets[sheetId] = sheet;
LogVerbose($" -> Loaded TileMapSheet {sheetId}: '{sheet.Name}'");
}
else
{
Log($" -> WARNING: TileMapSheet {sheetId} not found in database!");
}
}
}
///
/// Place wall tiles around walkable areas.
/// Walls are placed on non-walkable cells adjacent to walkable cells.
///
private void PlaceWallTiles(DungeonLayoutV2 layout)
{
Log($"--- Placing Wall Tiles ---");
Log($"Wall templates available: {_wallTemplates.Count}");
Log($"Socket matching: {(UseSocketMatching ? "ENABLED" : "DISABLED")}");
// Clear placement tracking for socket matching (separate from floor tiles)
_placedTemplates.Clear();
// Log detailed template info for debugging
foreach (var t in _wallTemplates)
{
LogTileTemplate(t, "Wall");
}
int wallCount = 0;
// 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 result = SelectWallTemplate(x, y, layout);
if (result != null)
{
layout.Tiles[x, y] = result.Value.TemplateId;
layout.TileDetails.Add(new PlacedTile
{
X = x,
Y = y,
TileDefinitionId = 0, // No TileDefinition - using template directly
SheetId = result.Value.SheetId,
FrameIndex = result.Value.FrameIndex,
Layer = 0
});
wallCount++;
if (LogEveryTile)
{
Log($" Wall ({x},{y}): Template='{result.Value.TemplateName}', Sheet={result.Value.SheetId}, Frame={result.Value.FrameIndex}");
}
}
}
}
}
Log($"Placed {wallCount} wall tiles");
}
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;
}
///
/// Select a wall template for the given position.
/// Returns the template's tile placement info directly from TilesJson.
///
private TemplateSelectionResult? SelectWallTemplate(int x, int y, DungeonLayoutV2 layout)
{
if (_wallTemplates.Count == 0)
{
LogVerbose($"SelectWallTemplate({x},{y}): No wall templates available!");
return null;
}
// Get socket-compatible templates (already sorted by score, best first)
var compatibleTemplates = GetCompatibleTemplates(_wallTemplates, x, y, layout);
// Get the best templates (those with the highest score)
var bestTemplates = GetTopScoredTemplates(compatibleTemplates, x, y, layout);
// Shuffle only among the best templates by weight
var shuffledTemplates = ShuffleByWeight(bestTemplates);
foreach (var template in shuffledTemplates)
{
var result = TryParseTemplateTile(template, x, y, "Wall", compatibleTemplates.Count, _wallTemplates.Count);
if (result != null)
{
// Track placement for socket matching
_placedTemplates[$"{x},{y}"] = template.Id;
if (!UsedWallTemplates.Contains(template.Name))
UsedWallTemplates.Add(template.Name);
return result;
}
}
Log($"SelectWallTemplate({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates had valid TilesJson!");
return null;
}
///
/// Shuffle templates weighted by their Weight property.
/// Higher weight = more likely to appear earlier in the list.
///
private List ShuffleByWeight(List templates)
{
var result = new List();
var remaining = templates.ToList();
while (remaining.Count > 0)
{
var totalWeight = remaining.Sum(t => t.Weight);
if (totalWeight == 0) break;
var roll = _rng.Next(totalWeight);
var cumulative = 0;
for (int i = 0; i < remaining.Count; i++)
{
cumulative += remaining[i].Weight;
if (roll < cumulative)
{
result.Add(remaining[i]);
remaining.RemoveAt(i);
break;
}
}
}
return result;
}
///
/// Get templates with the highest socket score from a pre-sorted list.
/// If no templates have Custom socket matches, returns all compatible templates.
///
private List GetTopScoredTemplates(List sortedTemplates, int x, int y, DungeonLayoutV2 layout)
{
if (sortedTemplates.Count == 0) return sortedTemplates;
// Calculate scores (templates should already be sorted by score from GetCompatibleTemplates)
var scores = sortedTemplates
.Select(t => new { Template = t, Score = CalculateSocketScore(t, x, y, layout) })
.ToList();
var topScore = scores.Max(s => s.Score);
// If top score is from Custom matches (10+), only return those
// Otherwise return all (they're all equally generic matches)
if (topScore >= 10)
{
var topTemplates = scores.Where(s => s.Score >= 10).Select(s => s.Template).ToList();
LogVerbose($" Filtering to {topTemplates.Count} templates with Custom socket matches (score >= 10)");
return topTemplates;
}
return sortedTemplates;
}
// ============================================================
// SOCKET MATCHING METHODS
// ============================================================
///
/// Parse and cache socket configurations for all loaded templates.
/// Call this after loading templates.
///
private void ParseSocketConfigurations()
{
_templateSocketConfigs.Clear();
var allTemplates = _floorTemplates
.Concat(_wallTemplates)
.Concat(_doorTemplates);
int parsed = 0;
foreach (var template in allTemplates)
{
var config = ParseSocketConfig(template);
if (config != null)
{
_templateSocketConfigs[template.Id] = config;
parsed++;
}
}
Log($"Parsed socket configurations for {parsed} templates");
}
///
/// Build a lookup of TileTemplates by their sprite (sheetId:frameIndex).
/// Used when stamping room templates to get tile properties.
///
private void BuildSpriteToTemplateLookup()
{
_tileTemplatesBySprite.Clear();
var allTemplates = _floorTemplates
.Concat(_wallTemplates)
.Concat(_doorTemplates);
foreach (var template in allTemplates)
{
if (string.IsNullOrEmpty(template.TilesJson)) continue;
try
{
var tiles = JsonSerializer.Deserialize>(template.TilesJson, _jsonOptions);
if (tiles?.Count > 0)
{
var first = tiles[0];
var key = $"{first.SheetId}:{first.FrameIndex}";
// Only store if not already present (first template wins)
if (!_tileTemplatesBySprite.ContainsKey(key))
{
_tileTemplatesBySprite[key] = template;
}
}
}
catch { /* ignore parse errors */ }
}
Log($"Built sprite->template lookup with {_tileTemplatesBySprite.Count} entries");
}
///
/// Find a TileTemplate by sheetId and frameIndex.
/// Returns null if no matching template exists.
///
private TileTemplate? FindTemplateBySprite(int sheetId, int frameIndex)
{
var key = $"{sheetId}:{frameIndex}";
return _tileTemplatesBySprite.TryGetValue(key, out var template) ? template : null;
}
///
/// Parse a template's socket configuration from JSON or legacy fields.
///
private SocketConfiguration? ParseSocketConfig(TileTemplate template)
{
// Try new JSON format first
if (!string.IsNullOrEmpty(template.SocketConfigJson))
{
try
{
var config = JsonSerializer.Deserialize(template.SocketConfigJson, _jsonOptions);
if (config != null)
{
LogVerbose($" Template {template.Id} '{template.Name}': Parsed SocketConfigJson");
return config;
}
}
catch (Exception ex)
{
Log($" WARNING: Failed to parse SocketConfigJson for template {template.Id}: {ex.Message}");
}
}
// Fall back to legacy socket fields
var legacyConfig = SocketConfiguration.CreateDefault(template.Width, template.Height);
// Set first socket of each edge from legacy fields
if (legacyConfig.North.Count > 0)
{
legacyConfig.North[0].Type = template.SocketN;
if (template.SocketN == SocketType.Custom)
legacyConfig.North[0].CustomName = template.SocketCustom?.ToLower();
}
if (legacyConfig.East.Count > 0)
{
legacyConfig.East[0].Type = template.SocketE;
if (template.SocketE == SocketType.Custom)
legacyConfig.East[0].CustomName = template.SocketCustom?.ToLower();
}
if (legacyConfig.South.Count > 0)
{
legacyConfig.South[0].Type = template.SocketS;
if (template.SocketS == SocketType.Custom)
legacyConfig.South[0].CustomName = template.SocketCustom?.ToLower();
}
if (legacyConfig.West.Count > 0)
{
legacyConfig.West[0].Type = template.SocketW;
if (template.SocketW == SocketType.Custom)
legacyConfig.West[0].CustomName = template.SocketCustom?.ToLower();
}
return legacyConfig;
}
///
/// Check if a template can be placed at (x,y) based on neighboring tiles' sockets.
///
/// For a 1x1 template at (x,y):
/// - Check North socket against South socket of template at (x, y-1)
/// - Check East socket against West socket of template at (x+1, y)
/// - Check South socket against North socket of template at (x, y+1)
/// - Check West socket against East socket of template at (x-1, y)
///
/// Returns true if all present neighbors have compatible sockets.
///
private bool IsSocketCompatible(TileTemplate template, int x, int y, DungeonLayoutV2 layout)
{
if (!UseSocketMatching) return true;
if (!_templateSocketConfigs.TryGetValue(template.Id, out var config)) return true;
// Check North neighbor (our North socket vs their South socket)
if (y > 0 && _placedTemplates.TryGetValue($"{x},{y-1}", out var northTemplateId))
{
if (_templateSocketConfigs.TryGetValue(northTemplateId, out var northConfig))
{
var ourSocket = config.North.FirstOrDefault();
var theirSocket = northConfig.South.FirstOrDefault();
if (ourSocket != null && theirSocket != null && !SocketConfiguration.CanConnect(ourSocket, theirSocket))
{
return false;
}
}
}
// Check South neighbor (our South socket vs their North socket)
if (y < layout.Height - 1 && _placedTemplates.TryGetValue($"{x},{y+1}", out var southTemplateId))
{
if (_templateSocketConfigs.TryGetValue(southTemplateId, out var southConfig))
{
var ourSocket = config.South.FirstOrDefault();
var theirSocket = southConfig.North.FirstOrDefault();
if (ourSocket != null && theirSocket != null && !SocketConfiguration.CanConnect(ourSocket, theirSocket))
{
return false;
}
}
}
// Check East neighbor (our East socket vs their West socket)
if (x < layout.Width - 1 && _placedTemplates.TryGetValue($"{x+1},{y}", out var eastTemplateId))
{
if (_templateSocketConfigs.TryGetValue(eastTemplateId, out var eastConfig))
{
var ourSocket = config.East.FirstOrDefault();
var theirSocket = eastConfig.West.FirstOrDefault();
if (ourSocket != null && theirSocket != null && !SocketConfiguration.CanConnect(ourSocket, theirSocket))
{
return false;
}
}
}
// Check West neighbor (our West socket vs their East socket)
if (x > 0 && _placedTemplates.TryGetValue($"{x-1},{y}", out var westTemplateId))
{
if (_templateSocketConfigs.TryGetValue(westTemplateId, out var westConfig))
{
var ourSocket = config.West.FirstOrDefault();
var theirSocket = westConfig.East.FirstOrDefault();
if (ourSocket != null && theirSocket != null)
{
var canConnect = SocketConfiguration.CanConnect(ourSocket, theirSocket);
if (!canConnect && VerboseLogging)
{
LogVerbose($" Socket mismatch at ({x},{y}): Template {template.Id} West={ourSocket.Type}:{ourSocket.CustomName ?? "null"} vs Neighbor({x-1},{y}) Template {westTemplateId} East={theirSocket.Type}:{theirSocket.CustomName ?? "null"}");
}
if (!canConnect) return false;
}
}
}
else if (x > 0 && VerboseLogging)
{
// No placed template at west neighbor - this shouldn't happen in row-by-row filling
LogVerbose($" No placed template found at West neighbor ({x-1},{y}) when checking ({x},{y})");
}
return true;
}
///
/// Calculate a socket compatibility score for a template at a given position.
/// Higher score = better match.
///
/// Scoring:
/// - Custom socket match: +10 points per edge
/// - Open/Closed match: +1 point per edge
/// - No neighbor to check: +0 points
///
/// This prioritizes templates that match Custom sockets over generic Open/Closed.
///
private int CalculateSocketScore(TileTemplate template, int x, int y, DungeonLayoutV2 layout)
{
if (!_templateSocketConfigs.TryGetValue(template.Id, out var config)) return 0;
int score = 0;
// Check West neighbor (most important for left-to-right filling)
if (x > 0 && _placedTemplates.TryGetValue($"{x-1},{y}", out var westTemplateId))
{
if (_templateSocketConfigs.TryGetValue(westTemplateId, out var westConfig))
{
var ourSocket = config.West.FirstOrDefault();
var theirSocket = westConfig.East.FirstOrDefault();
if (ourSocket != null && theirSocket != null && SocketConfiguration.CanConnect(ourSocket, theirSocket))
{
// Custom matches are worth more
if (ourSocket.Type == SocketType.Custom && theirSocket.Type == SocketType.Custom)
score += 10;
else
score += 1;
}
}
}
// Check North neighbor
if (y > 0 && _placedTemplates.TryGetValue($"{x},{y-1}", out var northTemplateId))
{
if (_templateSocketConfigs.TryGetValue(northTemplateId, out var northConfig))
{
var ourSocket = config.North.FirstOrDefault();
var theirSocket = northConfig.South.FirstOrDefault();
if (ourSocket != null && theirSocket != null && SocketConfiguration.CanConnect(ourSocket, theirSocket))
{
if (ourSocket.Type == SocketType.Custom && theirSocket.Type == SocketType.Custom)
score += 10;
else
score += 1;
}
}
}
// Check South neighbor (if already placed, e.g., from room templates)
if (_placedTemplates.TryGetValue($"{x},{y+1}", out var southTemplateId))
{
if (_templateSocketConfigs.TryGetValue(southTemplateId, out var southConfig))
{
var ourSocket = config.South.FirstOrDefault();
var theirSocket = southConfig.North.FirstOrDefault();
if (ourSocket != null && theirSocket != null && SocketConfiguration.CanConnect(ourSocket, theirSocket))
{
if (ourSocket.Type == SocketType.Custom && theirSocket.Type == SocketType.Custom)
score += 10;
else
score += 1;
}
}
}
// Check East neighbor (if already placed, e.g., from room templates)
if (_placedTemplates.TryGetValue($"{x+1},{y}", out var eastTemplateId))
{
if (_templateSocketConfigs.TryGetValue(eastTemplateId, out var eastConfig))
{
var ourSocket = config.East.FirstOrDefault();
var theirSocket = eastConfig.West.FirstOrDefault();
if (ourSocket != null && theirSocket != null && SocketConfiguration.CanConnect(ourSocket, theirSocket))
{
if (ourSocket.Type == SocketType.Custom && theirSocket.Type == SocketType.Custom)
score += 10;
else
score += 1;
}
}
}
return score;
}
///
/// Get all templates from a list that are socket-compatible at position (x,y).
/// Templates are sorted by socket match quality - Custom matches are prioritized.
///
private List GetCompatibleTemplates(List templates, int x, int y, DungeonLayoutV2 layout)
{
if (!UseSocketMatching) return templates;
// Filter to compatible templates
var compatible = templates.Where(t => IsSocketCompatible(t, x, y, layout)).ToList();
if (compatible.Count == 0)
{
LogVerbose($" No socket-compatible templates at ({x},{y}), using all {templates.Count} templates");
return templates; // Fallback to all if none match
}
// Score and sort by socket match quality (highest first)
var scored = compatible
.Select(t => new { Template = t, Score = CalculateSocketScore(t, x, y, layout) })
.OrderByDescending(x => x.Score)
.ToList();
// Log the top matches
if (VerboseLogging && scored.Count > 0)
{
var topScore = scored[0].Score;
var topMatches = scored.Where(s => s.Score == topScore).ToList();
LogVerbose($" Socket-compatible: {compatible.Count}/{templates.Count} templates at ({x},{y}), top score={topScore} ({topMatches.Count} templates)");
}
// Return templates sorted by score (best matches first)
return scored.Select(s => s.Template).ToList();
}
// ============================================================
// LOGGING HELPERS
// ============================================================
/// Always log this message
private void Log(string message)
{
Console.WriteLine($"[DungeonGenV3] {message}");
}
/// Only log if VerboseLogging is enabled
private void LogVerbose(string message)
{
if (VerboseLogging)
{
Console.WriteLine($"[DungeonGenV3] {message}");
}
}
///
/// Log detailed information about a TileTemplate.
/// Shows how the template will resolve to an actual tile.
///
private void LogTileTemplate(TileTemplate t, string category)
{
Log($" {category} Template {t.Id}: '{t.Name}'");
Log($" Category={t.Category}, Biome={t.Biome ?? "any"}, Tags={t.Tags ?? "none"}");
Log($" Weight={t.Weight}, Walkable={t.IsWalkable}, BlocksMovement={t.BlocksMovement}");
Log($" PrimaryTileDefinitionId={t.PrimaryTileDefinitionId?.ToString() ?? "NULL"}");
if (!string.IsNullOrEmpty(t.TilesJson))
{
Log($" TilesJson={t.TilesJson}");
try
{
var tiles = JsonSerializer.Deserialize>(t.TilesJson, _jsonOptions);
if (tiles?.Count > 0)
{
var first = tiles[0];
Log($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}");
}
}
catch (Exception ex)
{
Log($" -> ERROR: {ex.Message}");
}
}
else
{
Log($" TilesJson=EMPTY");
}
}
}
// 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; }
}
public class RoomTilePlacement
{
public int X { get; set; }
public int Y { get; set; }
public int SheetId { get; set; }
public int FrameIndex { get; set; }
public int? TemplateId { get; set; } // TileTemplate ID (new format)
public bool IsWalkable { get; set; } = true; // Whether this tile is walkable (new format)
}
public class BuilderConnectionPoint
{
public int X { get; set; }
public int Y { get; set; }
public string? Direction { get; set; } // north, south, east, west
public int Width { get; set; } = 1;
}
public class ConnectionPoint
{
public int X { get; set; }
public int Y { get; set; }
public string Direction { get; set; } = "north";
public int Width { get; set; }
}
public 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; }
public int Layer { get; set; }
}