Files
systemrevivalserver/Game/Dungeon/DungeonGeneratorV2.cs
T
2025-12-31 13:43:56 -05:00

2252 lines
92 KiB
C#

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;
private TileTagIndex? _tagIndex;
private const string DefaultBiome = "dungeon";
// Corridor sizing (in tiles)
private const int MinCorridorWidth = 4;
private const int MaxCorridorWidth = 8;
// 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;
private Dictionary<string, List<TileDefinition>> _tileGroups = new();
private Dictionary<int, HashSet<string>> _tileTags = new();
private Dictionary<int, Dictionary<string, string>> _tileSockets = new();
private Dictionary<int, Dictionary<string, HashSet<string>>> _tileSocketTypes = new();
private static HashSet<string> ParseTags(string? tags)
{
if (string.IsNullOrWhiteSpace(tags)) return new HashSet<string>(StringComparer.OrdinalIgnoreCase);
return tags
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Where(s => !string.IsNullOrWhiteSpace(s))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
}
private static int CountOverlap(HashSet<string> a, HashSet<string> b)
{
if (a.Count == 0 || b.Count == 0) return 0;
int c = 0;
foreach (var t in a)
if (b.Contains(t)) c++;
return c;
}
//private TileDefinition? SelectBestFloorTileForTags(HashSet<string> requiredTags)
//{
// var floors = _tileDefinitions.Values.Where(t => t.Type == TileType.Floor).ToList();
// if (floors.Count == 0) return null;
// if (requiredTags.Count == 0)
// return floors[0];
// TileDefinition best = floors[0];
// int bestScore = -1;
// foreach (var f in floors)
// {
// var tags = ParseTags(f.Tags);
// int score = CountOverlap(requiredTags, tags);
// if (score > bestScore)
// {
// best = f;
// bestScore = score;
// }
// }
// return best;
//}
private TileDefinition? SelectBestFloorTileForTags(HashSet<string> requiredTags)
{
// If you want biome-aware floors later, pass biome from generator settings.
if (_tagIndex != null)
return _tagIndex.FindBestFloor(requiredTags, biome: DefaultBiome);
// Fallback to your old behavior if index isn't available for some reason
var floors = _tileDefinitions.Values.Where(t => t.Type == TileType.Floor).ToList();
return floors.FirstOrDefault();
}
private RoomTemplate? SelectHallwayTemplate(HashSet<string> requiredTags, string direction)
{
if (_hallwayTemplates.Count == 0) return null;
// Require a hallway to support the travel direction (and its opposite) via connection points.
// If template JSON is missing, we still allow it as a fallback.
static string Opp(string dir) => dir.ToLower() switch
{
"north" => "south",
"south" => "north",
"east" => "west",
"west" => "east",
_ => dir
};
var needA = direction.ToLower();
var needB = Opp(needA);
RoomTemplate? best = null;
int bestScore = -1;
foreach (var t in _hallwayTemplates)
{
int score = CountOverlap(requiredTags, ParseTags(t.Tags));
bool supports = true;
if (!string.IsNullOrEmpty(t.ConnectionPointsJson))
{
try
{
var cps = JsonSerializer.Deserialize<List<ConnectionPoint>>(t.ConnectionPointsJson);
if (cps != null)
{
supports = cps.Any(c => c.Direction.Equals(needA, StringComparison.OrdinalIgnoreCase))
&& cps.Any(c => c.Direction.Equals(needB, StringComparison.OrdinalIgnoreCase));
}
}
catch
{
// ignore parse failures
}
}
if (!supports) continue;
if (score > bestScore)
{
best = t;
bestScore = score;
}
}
return best;
}
private TileDefinition? PickRandomTile(HashSet<string> tags)
{
// Generate a cache key based on sorted tags (e.g., "dungeon,floor,stone")
string key = string.Join(",", tags.OrderBy(t => t));
if (!_tileGroups.ContainsKey(key))
{
// Find all matches, not just the single best one
var matches = _tileDefinitions.Values
.Where(t => tags.All(req => ParseTags(t.Tags).Contains(req)))
.ToList();
_tileGroups[key] = matches;
}
var candidates = _tileGroups[key];
if (candidates.Count == 0) return null;
// Return a random one from the list
return candidates[_rng.Next(candidates.Count)];
}
private bool TryStampHallwayRun(
DungeonLayoutV2 layout,
RoomTemplate hallway,
int x1,
int y1,
int x2,
int y2,
int fallbackFloorId,
int fallbackSheetId,
int fallbackFrameIndex)
{
// Only supports straight runs.
bool horizontal = y1 == y2;
bool vertical = x1 == x2;
if (!horizontal && !vertical) return false;
if (string.IsNullOrEmpty(hallway.TileDataJson)) return false;
List<TilePlacement>? placements;
try
{
placements = JsonSerializer.Deserialize<List<TilePlacement>>(hallway.TileDataJson);
}
catch
{
return false;
}
if (placements == null || placements.Count == 0) return false;
int step = horizontal ? Math.Max(1, hallway.Width) : Math.Max(1, hallway.Height);
int dir = horizontal ? Math.Sign(x2 - x1) : Math.Sign(y2 - y1);
if (dir == 0) dir = 1;
// Align hallway chunk to the corridor centerline.
int baseX = horizontal ? Math.Min(x1, x2) : x1 - (hallway.Width / 2);
int baseY = vertical ? Math.Min(y1, y2) : y1 - (hallway.Height / 2);
int end = horizontal ? Math.Max(x1, x2) : Math.Max(y1, y2);
for (int pos = horizontal ? Math.Min(x1, x2) : Math.Min(y1, y2);
pos <= end;
pos += step)
{
int originX = horizontal ? pos : baseX;
int originY = vertical ? pos : baseY;
foreach (var p in placements)
{
int wx = originX + p.X;
int wy = originY + p.Y;
if (wx < 0 || wx >= MapWidth || wy < 0 || wy >= MapHeight) continue;
// Stop stamping once we collide with an existing walkable area (usually a room).
if (layout.IsWalkable(wx, wy)) continue;
int tileId = p.TileDefinitionId;
var tileDef = _tileDefinitions.GetValueOrDefault(tileId);
if (tileDef == null)
{
tileId = fallbackFloorId;
tileDef = _tileDefinitions.GetValueOrDefault(tileId);
}
// Remove any previous visuals at this location.
layout.TileDetails.RemoveAll(t => t.X == wx && t.Y == wy);
layout.Tiles[wx, wy] = tileId;
if (layout.Walkable != null)
layout.Walkable[wx, wy] = tileDef?.IsWalkable ?? true;
// Add visual
if (tileId > 0)
{
layout.TileDetails.Add(new PlacedTile
{
X = wx,
Y = wy,
TileDefinitionId = tileId,
SheetId = tileDef?.TileMapSheetId ?? fallbackSheetId,
FrameIndex = tileDef?.FrameIndex ?? fallbackFrameIndex,
Layer = p.Layer,
Rotation = p.Rotation,
FlipX = p.FlipX,
FlipY = p.FlipY
});
}
}
}
return true;
}
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.Walkable = new bool[MapWidth, MapHeight]; // All false by default
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);
Console.WriteLine($"[DungeonGenV2] Placed entrance room: {entrance.TemplateName ?? "fallback"} at ({entrance.X},{entrance.Y})");
}
// 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);
Console.WriteLine($"[DungeonGenV2] Placed {type} room: {newRoom.TemplateName ?? "fallback"} at ({newRoom.X},{newRoom.Y})");
}
}
Console.WriteLine($"[DungeonGenV2] Placed {rooms.Count}/{roomCount} rooms after {attempts} attempts");
// 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 - entrance MUST be connected
var connected = new HashSet<int> { 0 };
Console.WriteLine($"[DungeonGenV2] Connecting {rooms.Count} rooms...");
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);
Console.WriteLine($"[DungeonGenV2] Connected room {i} ({rooms[i].Type}) to room {closestIdx}");
}
// 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();
// Auto-generate walls around floor tiles
GenerateAutoWalls(layout);
// Build tile data for client
layout.BuildClientTileData(_tileDefinitions, _defaultSheet);
Console.WriteLine($"[DungeonGenV2] Generation complete: {rooms.Count} rooms, {layout.TileDetails.Count} visual tiles, {layout.TileMapSheets.Count} sheets");
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();
// Console.WriteLine($"[DungeonGenV2] Loaded templates for tier {_tier}: Entrance={_entranceTemplates.Count}, Exit={_exitTemplates.Count}, Boss={_bossTemplates.Count}, Treasure={_treasureTemplates.Count}, Normal={_normalTemplates.Count}");
// // Load tile definitions from templates
// 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);
// _tagIndex = new TileTagIndex(_tileDefinitions.Values);
// _defaultSheet = tiles.FirstOrDefault()?.TileMapSheet;
// _tileTags = _tileDefinitions.Values.ToDictionary(t => t.Id, t => ParseTags(t.Tags));
// _tileSocketTypes = _tileDefinitions.Values.ToDictionary(
// t => t.Id,
// t => ParseSocketTypes(_tileTags[t.Id])
// );
// Console.WriteLine($"[DungeonGenV2] Loaded {tiles.Count} tile definitions from templates");
// }
// // Always load a default sheet for fallback 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)
// {
// tile.TileMapSheet = _defaultSheet; // Ensure navigation property is set
// _tileDefinitions[tile.Id] = tile;
// }
// Console.WriteLine($"[DungeonGenV2] Loaded {_defaultSheet.Tiles.Count} tiles from default sheet '{_defaultSheet.Name}'");
// }
// else
// {
// Console.WriteLine($"[DungeonGenV2] WARNING: No tilemap sheets found in database!");
// }
// }
// Console.WriteLine($"[DungeonGenV2] Total tile definitions: {_tileDefinitions.Count}");
//}
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();
Console.WriteLine($"[DungeonGenV2] Loaded templates for tier {_tier}: Entrance={_entranceTemplates.Count}, Exit={_exitTemplates.Count}, Boss={_bossTemplates.Count}, Treasure={_treasureTemplates.Count}, Normal={_normalTemplates.Count}, Hallway={_hallwayTemplates.Count}");
// Start clean each generation.
_tileDefinitions = new Dictionary<int, TileDefinition>();
// 1) Pull tile IDs referenced by templates (if any)
var templateTileIds = 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 (templateTileIds.Count > 0)
{
var templateTiles = await _db.TileDefinitions
.Include(t => t.TileMapSheet)
.Where(t => templateTileIds.Contains(t.Id))
.ToListAsync();
foreach (var tile in templateTiles)
_tileDefinitions[tile.Id] = tile;
// Pick a sheet for rendering defaults if we got one from template tiles
_defaultSheet = templateTiles.FirstOrDefault()?.TileMapSheet;
Console.WriteLine($"[DungeonGenV2] Loaded {templateTiles.Count} tile definitions referenced by templates");
}
else
{
Console.WriteLine($"[DungeonGenV2] No template tile references found (templates may be disabled or missing TileDataJson)");
}
// 2) Always load a default sheet for fallback generation (and merge its tiles)
if (_defaultSheet == null)
{
_defaultSheet = await _db.TileMapSheets
.Include(s => s.Tiles)
.FirstOrDefaultAsync(s => s.IsEnabled);
if (_defaultSheet == null)
Console.WriteLine($"[DungeonGenV2] WARNING: No enabled TileMapSheet found in database!");
}
if (_defaultSheet?.Tiles != null)
{
foreach (var tile in _defaultSheet.Tiles)
{
tile.TileMapSheet = _defaultSheet; // ensure nav prop set for client data building
_tileDefinitions[tile.Id] = tile; // merge/overwrite if already present
}
Console.WriteLine($"[DungeonGenV2] Loaded {_defaultSheet.Tiles.Count} tiles from default sheet '{_defaultSheet.Name}'");
}
Console.WriteLine($"[DungeonGenV2] Total tile definitions merged: {_tileDefinitions.Count}");
// 3) ALWAYS build indexes/caches after all tiles are merged
if (_tileDefinitions.Count > 0)
{
_tagIndex = new TileTagIndex(_tileDefinitions.Values);
_tileTags = _tileDefinitions.Values.ToDictionary(
t => t.Id,
t => ParseTags(t.Tags)
);
_tileSocketTypes = _tileDefinitions.Values.ToDictionary(
t => t.Id,
t => ParseSocketTypes(_tileTags[t.Id])
);
Console.WriteLine($"[DungeonGenV2] Built tag caches: tileTags={_tileTags.Count} socketTypes={_tileSocketTypes.Count}");
}
else
{
_tagIndex = null;
_tileTags = new Dictionary<int, HashSet<string>>();
_tileSocketTypes = new Dictionary<int, Dictionary<string, HashSet<string>>>();
Console.WriteLine($"[DungeonGenV2] WARNING: No tile definitions available; tag index/caches not built.");
}
}
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,
TemplateTags = ParseTags(template.Tags)
};
// 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,
TemplateTags = ParseTags(template.Tags)
};
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;
// Look up tile definition for sheet info and walkability
var tileDef = _tileDefinitions.GetValueOrDefault(p.TileDefinitionId);
// Set walkability based on tile definition
if (layout.Walkable != null && tileDef != null)
{
layout.Walkable[worldX, worldY] = tileDef.IsWalkable;
}
layout.TileDetails.Add(new PlacedTile
{
X = worldX,
Y = worldY,
TileDefinitionId = p.TileDefinitionId,
SheetId = tileDef?.TileMapSheetId ?? 0,
FrameIndex = tileDef?.FrameIndex ?? 0,
Layer = p.Layer,
Rotation = p.Rotation,
FlipX = p.FlipX,
FlipY = p.FlipY
});
}
}
}
}
catch { /* Invalid JSON, fall through to basic carve */ }
}
// Parse connection points from template
if (!string.IsNullOrEmpty(template.ConnectionPointsJson))
{
try
{
var connections = JsonSerializer.Deserialize<List<ConnectionPoint>>(template.ConnectionPointsJson);
if (connections != null)
{
room.ConnectionPoints = connections;
}
}
catch { /* Invalid JSON */ }
}
// If no connection points defined, create default ones on each edge
// These are positioned AT the room edge (not inside)
if (room.ConnectionPoints.Count == 0)
{
room.ConnectionPoints = new List<ConnectionPoint>
{
// North: center of top edge, Y=0 is top of room
new() { X = room.Width / 2, Y = 0, Direction = "north", Width = 3 },
// South: center of bottom edge
new() { X = room.Width / 2, Y = room.Height - 1, Direction = "south", Width = 3 },
// West: center of left edge
new() { X = 0, Y = room.Height / 2, Direction = "west", Width = 3 },
// East: center of right edge
new() { X = room.Width - 1, Y = room.Height / 2, Direction = "east", Width = 3 }
};
Console.WriteLine($"[DungeonGenV2] Created default connection points for room at ({x},{y})");
}
else
{
Console.WriteLine($"[DungeonGenV2] Room has {room.ConnectionPoints.Count} connection points from template");
foreach (var cp in room.ConnectionPoints)
{
Console.WriteLine($" - ({cp.X},{cp.Y}) direction={cp.Direction} width={cp.Width}");
}
}
// 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, TemplateTags = new HashSet<string>(StringComparer.OrdinalIgnoreCase) };
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, TemplateTags = new HashSet<string>(StringComparer.OrdinalIgnoreCase) };
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 = SelectBestFloorTileForTags(room.TemplateTags) ?? _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)
// {
// var floorTile = PickRandomTile(room.TemplateTags) ?? _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor);
// int floorId = floorTile?.Id ?? -1; // -1 means no visual tile, just walkable
// layout.Tiles[x, y] = floorId > 0 ? floorId : 1; // 1 = walkable but no visual
// // Set walkability - basic carved rooms are always walkable
// if (layout.Walkable != null)
// {
// layout.Walkable[x, y] = true;
// }
// if (floorId > 0 && floorTile != null)
// {
// layout.TileDetails.Add(new PlacedTile
// {
// X = x,
// Y = y,
// TileDefinitionId = floorId,
// SheetId = floorTile.TileMapSheetId,
// FrameIndex = floorTile.FrameIndex,
// Layer = 0
// });
// }
// }
// }
// }
//}
//private void CarveBasicRoom(DungeonLayoutV2 layout, DungeonRoomV2 room)
//{
// // 1) Decide which TileBase family to use for this room.
// // For now: default to family 1 unless the room tags explicitly choose another.
// // You can extend this to read "TileBaseFamily_2" etc. from room.TemplateTags.
// int familyId = 1;
// // 2) Optional: choose a single "primary" tile for the room to reduce speckle.
// // We'll still enforce sockets per-tile; if the chosen primary doesn't fit a spot,
// // we'll fall back to the general picker for that cell.
// TileDefinition? roomPrimary = PickRandomFloorTile(layout, room.X, room.Y, familyId, varianceChance: 0.0);
// 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)
// continue;
// // Always carve as walkable space.
// if (layout.Walkable != null)
// layout.Walkable[x, y] = true;
// // Remove any previous visuals at this location (safety, consistent with corridors)
// layout.TileDetails.RemoveAll(t => t.X == x && t.Y == y);
// // 3) Pick a tile using: TileBaseCore/TileBase variance + hard socket requirements from neighbors (N/W scan order)
// // 85% primary, 15% variance, BUT constrained by required socket tags.
// TileDefinition? floorTile = null;
// // Try room primary first most of the time to keep consistent "material"
// // (still must satisfy socket constraints for this cell).
// if (roomPrimary != null && SatisfiesSocketRequirements(layout, x, y, roomPrimary))
// {
// // Small variance chance to break up repetition
// if (_rng.NextDouble() < 0.15)
// floorTile = PickRandomFloorTile(layout, x, y, familyId, varianceChance: 1.0); // force variance pool
// else
// floorTile = roomPrimary;
// }
// else
// {
// floorTile = PickRandomFloorTile(layout, x, y, familyId, varianceChance: 0.15);
// }
// // Hard fallback: any floor
// floorTile ??= _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor);
// int floorId = floorTile?.Id ?? -1; // -1 means no visual tile, just walkable
// layout.Tiles[x, y] = floorId > 0 ? floorId : 1; // 1 = walkable but no visual
// if (floorId > 0 && floorTile != null)
// {
// layout.TileDetails.Add(new PlacedTile
// {
// X = x,
// Y = y,
// TileDefinitionId = floorId,
// SheetId = floorTile.TileMapSheetId,
// FrameIndex = floorTile.FrameIndex,
// Layer = 0
// });
// }
// }
// }
// // Optional but recommended: repair pass to fix E/S mismatches after scan-order placement.
// RepairRoomFloorSockets(layout, room);
//}
private void CarveBasicRoom(DungeonLayoutV2 layout, DungeonRoomV2 room)
{
// Toggle this if you want to silence per-cell spam quickly.
const bool VerboseFloorLogging = true;
// 1) Decide which TileBase family to use for this room.
int familyId = 2;
Console.WriteLine($"[DungeonGenV2][Floors] CarveBasicRoom START room=({room.X},{room.Y}) size=({room.Width}x{room.Height}) familyId={familyId} tags=[{string.Join(",", room.TemplateTags ?? new HashSet<string>())}]");
// 2) Choose a primary tile for the room (varianceChance=0 => strongly prefers core tiles).
// NOTE: This does NOT mean every tile will be the same; it's just a "material anchor".
TileDefinition? roomPrimary = PickRandomFloorTile(layout, room.X, room.Y, familyId, varianceChance: 0.0);
if (roomPrimary != null)
{
Console.WriteLine($"[DungeonGenV2][Floors] roomPrimary chosen id={roomPrimary.Id} name='{roomPrimary.Name}' sheet={roomPrimary.TileMapSheetId} frame={roomPrimary.FrameIndex} tags='{roomPrimary.Tags ?? ""}'");
}
else
{
Console.WriteLine($"[DungeonGenV2][Floors] roomPrimary chosen = null (will rely on per-cell picking)");
}
int placedCount = 0;
int primaryCount = 0;
int varianceCount = 0;
int perCellPickCount = 0;
int primaryRejectedBySockets = 0;
int fallbackAnyFloorCount = 0;
int forcedVariancePickNullCount = 0;
int cellPickNullCount = 0;
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)
{
if (VerboseFloorLogging)
Console.WriteLine($"[DungeonGenV2][Floors] skip OOB ({x},{y})");
continue;
}
// Always carve as walkable space.
if (layout.Walkable != null)
layout.Walkable[x, y] = true;
// Remove any previous visuals at this location
layout.TileDetails.RemoveAll(t => t.X == x && t.Y == y);
// Log neighborhood + required sockets (N/W scan-order)
var req = BuildRequiredSocketTags(layout, x, y);
if (VerboseFloorLogging)
{
int nId = (y > 0) ? layout.Tiles[x, y - 1] : -999;
int wId = (x > 0) ? layout.Tiles[x - 1, y] : -999;
string nInfo = (y > 0 && _tileDefinitions.TryGetValue(nId, out var nd))
? $"N=({x},{y - 1}) id={nId} '{nd.Name}' walk={layout.IsWalkable(x, y - 1)}"
: $"N=({x},{y - 1}) id={nId} walk={(y > 0 ? layout.IsWalkable(x, y - 1) : false)}";
string wInfo = (x > 0 && _tileDefinitions.TryGetValue(wId, out var wd))
? $"W=({x - 1},{y}) id={wId} '{wd.Name}' walk={layout.IsWalkable(x - 1, y)}"
: $"W=({x - 1},{y}) id={wId} walk={(x > 0 ? layout.IsWalkable(x - 1, y) : false)}";
Console.WriteLine($"[DungeonGenV2][Floors] cell=({x},{y}) reqSockets=[{string.Join(",", req)}] {nInfo} {wInfo}");
}
TileDefinition? chosen = null;
bool usedPrimary = false;
bool usedVariance = false;
// 3) 85% primary, 15% variance, constrained by required sockets.
// Important: The old behavior that "only uses one tile" happens if:
// - roomPrimary always fits and variance never succeeds (or isn't present)
// - or varianceChance logic never triggers/always returns same candidate list
// We'll log every decision so you can see why.
bool primaryFits = roomPrimary != null && SatisfiesSocketRequirements(layout, x, y, roomPrimary);
if (roomPrimary != null && !primaryFits)
primaryRejectedBySockets++;
// Roll for variance (we roll first, then attempt primary/variance accordingly)
double roll = _rng.NextDouble();
bool wantVariance = roll < 0.15;
if (VerboseFloorLogging)
Console.WriteLine($"[DungeonGenV2][Floors] cell=({x},{y}) roll={roll:0.000} wantVariance={wantVariance} primaryFits={primaryFits}");
if (primaryFits)
{
// If we want variance, try to pick variance; if that fails, use primary.
if (wantVariance)
{
chosen = PickRandomFloorTile(layout, x, y, familyId, varianceChance: 1.0); // force variance pool
if (chosen == null)
{
forcedVariancePickNullCount++;
if (VerboseFloorLogging)
Console.WriteLine($"[DungeonGenV2][Floors] cell=({x},{y}) forced variance returned NULL -> using roomPrimary");
chosen = roomPrimary;
usedPrimary = true;
}
else
{
usedVariance = true;
if (VerboseFloorLogging)
Console.WriteLine($"[DungeonGenV2][Floors] cell=({x},{y}) picked VARIANCE id={chosen.Id} '{chosen.Name}' tags='{chosen.Tags ?? ""}'");
}
}
else
{
chosen = roomPrimary;
usedPrimary = true;
if (VerboseFloorLogging)
Console.WriteLine($"[DungeonGenV2][Floors] cell=({x},{y}) used PRIMARY id={chosen.Id} '{chosen.Name}'");
}
}
else
{
// Primary doesn't fit or doesn't exist: do full per-cell pick (85/15 inside the picker)
chosen = PickRandomFloorTile(layout, x, y, familyId, varianceChance: 0.45);
perCellPickCount++;
if (chosen == null)
{
cellPickNullCount++;
if (VerboseFloorLogging)
Console.WriteLine($"[DungeonGenV2][Floors] cell=({x},{y}) per-cell pick returned NULL");
}
else
{
// classify
if (_tileTags.TryGetValue(chosen.Id, out var tags))
{
if (tags.Contains($"TileBaseCore_{familyId}")) usedPrimary = true;
else if (tags.Contains($"TileBase_{familyId}")) usedVariance = true;
}
if (VerboseFloorLogging)
Console.WriteLine($"[DungeonGenV2][Floors] cell=({x},{y}) per-cell picked id={chosen.Id} '{chosen.Name}' tags='{chosen.Tags ?? ""}'");
}
}
// Hard fallback: any floor
if (chosen == null)
{
fallbackAnyFloorCount++;
chosen = _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor);
if (VerboseFloorLogging)
Console.WriteLine($"[DungeonGenV2][Floors] cell=({x},{y}) HARD FALLBACK any-floor => {(chosen != null ? $"{chosen.Id} '{chosen.Name}'" : "NULL")}");
}
int floorId = chosen?.Id ?? -1;
layout.Tiles[x, y] = floorId > 0 ? floorId : 1;
if (floorId > 0 && chosen != null)
{
layout.TileDetails.Add(new PlacedTile
{
X = x,
Y = y,
TileDefinitionId = floorId,
SheetId = chosen.TileMapSheetId,
FrameIndex = chosen.FrameIndex,
Layer = 0
});
placedCount++;
if (usedPrimary) primaryCount++;
if (usedVariance) varianceCount++;
}
if (VerboseFloorLogging && chosen != null)
{
Console.WriteLine($"[DungeonGenV2][Floors] cell=({x},{y}) FINAL id={chosen.Id} '{chosen.Name}' primary={usedPrimary} variance={usedVariance}");
}
}
}
Console.WriteLine($"[DungeonGenV2][Floors] CarveBasicRoom END placed={placedCount} primary={primaryCount} variance={varianceCount} perCellPick={perCellPickCount} primaryRejectedBySockets={primaryRejectedBySockets} forcedVarNull={forcedVariancePickNullCount} perCellNull={cellPickNullCount} hardFallbackAnyFloor={fallbackAnyFloorCount}");
// Repair pass logs (you can also add verbosity inside RepairRoomFloorSockets if needed)
Console.WriteLine($"[DungeonGenV2][Floors] RepairRoomFloorSockets START room=({room.X},{room.Y}) size=({room.Width}x{room.Height})");
RepairRoomFloorSockets(layout, room);
Console.WriteLine($"[DungeonGenV2][Floors] RepairRoomFloorSockets END room=({room.X},{room.Y})");
}
/// <summary>
/// Returns true if the given tile satisfies the required socket tags derived from already-placed neighbors.
/// This uses the same neighbor logic as PickRandomFloorTile (typically N/W scan order).
/// </summary>
private bool SatisfiesSocketRequirements(DungeonLayoutV2 layout, int x, int y, TileDefinition candidate)
{
var required = BuildRequiredSocketTags(layout, x, y);
if (required.Count == 0) return true;
if (!_tileTags.TryGetValue(candidate.Id, out var tags)) return false;
foreach (var r in required)
if (!tags.Contains(r)) return false;
return true;
}
/// <summary>
/// Second-pass repair: ensures mutual socket compatibility with E/S neighbors too,
/// replacing tiles that don't agree. This makes the result look "locked in" rather than scan-order dependent.
/// </summary>
private void RepairRoomFloorSockets(DungeonLayoutV2 layout, DungeonRoomV2 room)
{
int familyId = 2;
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)
continue;
if (!layout.IsWalkable(x, y))
continue;
int id = layout.Tiles[x, y];
if (!_tileDefinitions.TryGetValue(id, out var cur))
continue;
// Build full constraints (N/E/S/W) based on existing neighbors
var required = BuildRequiredSocketTags_AllDirs(layout, x, y);
// If current tile already satisfies, keep it.
if (HasAllTags(cur, required))
continue;
// Try to find a better fitting tile from the same family
var replacement = PickRandomFloorTile_AllDirs(layout, x, y, familyId, varianceChance: 0.15);
if (replacement == null || replacement.Id == cur.Id)
continue;
// Apply replacement
layout.Tiles[x, y] = replacement.Id;
if (layout.Walkable != null)
layout.Walkable[x, y] = true;
layout.TileDetails.RemoveAll(t => t.X == x && t.Y == y);
layout.TileDetails.Add(new PlacedTile
{
X = x,
Y = y,
TileDefinitionId = replacement.Id,
SheetId = replacement.TileMapSheetId,
FrameIndex = replacement.FrameIndex,
Layer = 0
});
}
}
}
/// <summary>
/// Build required socket tags from ALL directions (N/E/S/W), used for repair.
/// Typed socket tags are respected (SocketN_Lava etc.).
/// </summary>
private List<string> BuildRequiredSocketTags_AllDirs(DungeonLayoutV2 layout, int x, int y)
{
var req = new List<string>();
// North neighbor => our N must match neighbor's S
if (y > 0 && layout.IsWalkable(x, y - 1))
{
int nid = layout.Tiles[x, y - 1];
var r = GetRequiredSocketTagFromNeighbor(nid, neighborEdgeFacingUs: "S", ourDir: "N");
if (r != null) req.Add(r);
}
// South neighbor => our S must match neighbor's N
if (y < MapHeight - 1 && layout.IsWalkable(x, y + 1))
{
int sid = layout.Tiles[x, y + 1];
var r = GetRequiredSocketTagFromNeighbor(sid, neighborEdgeFacingUs: "N", ourDir: "S");
if (r != null) req.Add(r);
}
// West neighbor => our W must match neighbor's E
if (x > 0 && layout.IsWalkable(x - 1, y))
{
int wid = layout.Tiles[x - 1, y];
var r = GetRequiredSocketTagFromNeighbor(wid, neighborEdgeFacingUs: "E", ourDir: "W");
if (r != null) req.Add(r);
}
// East neighbor => our E must match neighbor's W
if (x < MapWidth - 1 && layout.IsWalkable(x + 1, y))
{
int eid = layout.Tiles[x + 1, y];
var r = GetRequiredSocketTagFromNeighbor(eid, neighborEdgeFacingUs: "W", ourDir: "E");
if (r != null) req.Add(r);
}
return req;
}
/// <summary>
/// A stricter picker used by the repair pass: filters candidates using ALL-direction socket constraints.
/// </summary>
private TileDefinition? PickRandomFloorTile_AllDirs(
DungeonLayoutV2 layout,
int x, int y,
int familyId,
double varianceChance = 0.15)
{
var requiredSocketTags = BuildRequiredSocketTags_AllDirs(layout, x, y);
string primaryTag = $"TileBaseCore_{familyId}";
string varianceTag = $"TileBase_{familyId}";
var primary = _tileDefinitions.Values
.Where(t => t.Type == TileType.Floor)
.Where(t => HasTag(t, primaryTag))
.Where(t => HasAllTags(t, requiredSocketTags))
.ToList();
var variance = _tileDefinitions.Values
.Where(t => t.Type == TileType.Floor)
.Where(t => HasTag(t, varianceTag))
.Where(t => HasAllTags(t, requiredSocketTags))
.ToList();
if (primary.Count == 0 && variance.Count == 0)
return null;
bool pickVar = _rng.NextDouble() < varianceChance;
var pool = pickVar ? variance : primary;
if (pool.Count == 0) pool = pickVar ? primary : variance;
return pool.Count == 0 ? null : pool[_rng.Next(pool.Count)];
}
//private async Task ConnectRoomsAsync(DungeonLayoutV2 layout, DungeonRoomV2 a, DungeonRoomV2 b)
//{
// // Determine tag requirements for this connection.
// var requiredTags = new HashSet<string>(a.TemplateTags ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase);
// requiredTags.IntersectWith(b.TemplateTags ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase));
// if (requiredTags.Count == 0)
// {
// requiredTags = new HashSet<string>(a.TemplateTags ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase);
// requiredTags.UnionWith(b.TemplateTags ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase));
// }
// var floorTile = SelectBestFloorTileForTags(requiredTags) ?? _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor);
// int floorId = floorTile?.Id ?? 1;
// int sheetId = floorTile?.TileMapSheetId ?? 0;
// int frameIndex = floorTile?.FrameIndex ?? 0;
// // Determine best connection points based on relative positions
// string aDirection, bDirection;
// int deltaX = b.CenterX - a.CenterX;
// int deltaY = b.CenterY - a.CenterY;
// // Choose connection directions based on which room is where
// if (Math.Abs(deltaX) > Math.Abs(deltaY))
// {
// // Horizontal connection preferred
// aDirection = deltaX > 0 ? "east" : "west";
// bDirection = deltaX > 0 ? "west" : "east";
// }
// else
// {
// // Vertical connection preferred
// aDirection = deltaY > 0 ? "south" : "north";
// bDirection = deltaY > 0 ? "north" : "south";
// }
// // Get connection points (or fall back to edge center)
// var cpA = a.GetConnectionPoint(aDirection);
// var cpB = b.GetConnectionPoint(bDirection);
// Console.WriteLine($"[DungeonGenV2] Connecting {a.TemplateName ?? "room"} to {b.TemplateName ?? "room"}");
// Console.WriteLine($" A wants {aDirection}, got cp: {(cpA != null ? $"({cpA.X},{cpA.Y}) dir={cpA.Direction}" : "null")}");
// Console.WriteLine($" B wants {bDirection}, got cp: {(cpB != null ? $"({cpB.X},{cpB.Y}) dir={cpB.Direction}" : "null")}");
// int startX, startY, endX, endY;
// int corridorWidth = _rng.Next(MinCorridorWidth, MaxCorridorWidth + 1);
// if (cpA != null)
// {
// var (wx, wy) = a.GetConnectionWorldPos(cpA);
// startX = wx;
// startY = wy;
// corridorWidth = Math.Max(corridorWidth, cpA.Width);
// // Clear the connection point area (carve through template walls)
// ClearConnectionPoint(layout, wx, wy, cpA.Width, aDirection, floorId, sheetId, frameIndex);
// }
// else
// {
// startX = a.CenterX;
// startY = a.CenterY;
// }
// if (cpB != null)
// {
// var (wx, wy) = b.GetConnectionWorldPos(cpB);
// endX = wx;
// endY = wy;
// corridorWidth = Math.Max(corridorWidth, cpB.Width);
// // Clear the connection point area (carve through template walls)
// ClearConnectionPoint(layout, wx, wy, cpB.Width, bDirection, floorId, sheetId, frameIndex);
// }
// else
// {
// endX = b.CenterX;
// endY = b.CenterY;
// }
// // L-shaped corridor from connection point to connection point
// if (_rng.Next(2) == 0)
// {
// // Horizontal segment
// var hallH = SelectHallwayTemplate(requiredTags, startX <= endX ? "east" : "west");
// if (hallH == null || !TryStampHallwayRun(layout, hallH, startX, startY, endX, startY, floorId, sheetId, frameIndex))
// CarveHorizontalCorridor(layout, startX, endX, startY, floorId, sheetId, frameIndex, corridorWidth);
// // Vertical segment
// var hallV = SelectHallwayTemplate(requiredTags, startY <= endY ? "south" : "north");
// if (hallV == null || !TryStampHallwayRun(layout, hallV, endX, startY, endX, endY, floorId, sheetId, frameIndex))
// CarveVerticalCorridor(layout, startY, endY, endX, floorId, sheetId, frameIndex, corridorWidth);
// }
// else
// {
// // Vertical segment
// var hallV = SelectHallwayTemplate(requiredTags, startY <= endY ? "south" : "north");
// if (hallV == null || !TryStampHallwayRun(layout, hallV, startX, startY, startX, endY, floorId, sheetId, frameIndex))
// CarveVerticalCorridor(layout, startY, endY, startX, floorId, sheetId, frameIndex, corridorWidth);
// // Horizontal segment
// var hallH = SelectHallwayTemplate(requiredTags, startX <= endX ? "east" : "west");
// if (hallH == null || !TryStampHallwayRun(layout, hallH, startX, endY, endX, endY, floorId, sheetId, frameIndex))
// CarveHorizontalCorridor(layout, startX, endX, endY, floorId, sheetId, frameIndex, corridorWidth);
// }
//}
private async Task ConnectRoomsAsync(DungeonLayoutV2 layout, DungeonRoomV2 a, DungeonRoomV2 b)
{
// Determine tag requirements for this connection.
var requiredTags = new HashSet<string>(
a.TemplateTags ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase),
StringComparer.OrdinalIgnoreCase);
requiredTags.IntersectWith(b.TemplateTags ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase));
if (requiredTags.Count == 0)
{
requiredTags = new HashSet<string>(
a.TemplateTags ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase),
StringComparer.OrdinalIgnoreCase);
requiredTags.UnionWith(b.TemplateTags ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase));
}
// Decide best connection directions based on relative positions
string aDirection, bDirection;
int deltaX = b.CenterX - a.CenterX;
int deltaY = b.CenterY - a.CenterY;
if (Math.Abs(deltaX) > Math.Abs(deltaY))
{
aDirection = deltaX > 0 ? "east" : "west";
bDirection = deltaX > 0 ? "west" : "east";
}
else
{
aDirection = deltaY > 0 ? "south" : "north";
bDirection = deltaY > 0 ? "north" : "south";
}
// Get connection points (or fall back to edge center)
var cpA = a.GetConnectionPoint(aDirection);
var cpB = b.GetConnectionPoint(bDirection);
Console.WriteLine($"[DungeonGenV2] Connecting {a.TemplateName ?? "room"} to {b.TemplateName ?? "room"}");
Console.WriteLine($" A wants {aDirection}, got cp: {(cpA != null ? $"({cpA.X},{cpA.Y}) dir={cpA.Direction}" : "null")}");
Console.WriteLine($" B wants {bDirection}, got cp: {(cpB != null ? $"({cpB.X},{cpB.Y}) dir={cpB.Direction}" : "null")}");
int startX, startY, endX, endY;
int corridorWidth = _rng.Next(MinCorridorWidth, MaxCorridorWidth + 1);
if (cpA != null)
{
var (wx, wy) = a.GetConnectionWorldPos(cpA);
startX = wx;
startY = wy;
corridorWidth = Math.Max(corridorWidth, cpA.Width);
}
else
{
startX = a.CenterX;
startY = a.CenterY;
}
if (cpB != null)
{
var (wx, wy) = b.GetConnectionWorldPos(cpB);
endX = wx;
endY = wy;
corridorWidth = Math.Max(corridorWidth, cpB.Width);
}
else
{
endX = b.CenterX;
endY = b.CenterY;
}
// ---- NEW: pick a corridor floor tile via PickRandomFloorTile (family-aware) ----
// TODO: derive familyId from room tags if/when you add that convention
int familyId = 2;
// Pick based on start position (or midpoint � either is fine)
var floorTile =
PickRandomFloorTile(layout, startX, startY, familyId, varianceChance: 0.15)
?? _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor);
int floorId = floorTile?.Id ?? 1;
int sheetId = floorTile?.TileMapSheetId ?? 0;
int frameIndex = floorTile?.FrameIndex ?? 0;
Console.WriteLine($"[DungeonGenV2][Corridors] using floorId={floorId} '{floorTile?.Name}' familyId={familyId} sheet={sheetId} frame={frameIndex}");
// Clear the connection point area (carve through template walls)
// (Now uses the same chosen floor)
if (cpA != null) ClearConnectionPoint(layout, startX, startY, cpA.Width, aDirection, floorId, sheetId, frameIndex);
if (cpB != null) ClearConnectionPoint(layout, endX, endY, cpB.Width, bDirection, floorId, sheetId, frameIndex);
// L-shaped corridor from connection point to connection point
if (_rng.Next(2) == 0)
{
// Horizontal segment
var hallH = SelectHallwayTemplate(requiredTags, startX <= endX ? "east" : "west");
if (hallH == null || !TryStampHallwayRun(layout, hallH, startX, startY, endX, startY, floorId, sheetId, frameIndex))
CarveHorizontalCorridor(layout, startX, endX, startY, floorId, sheetId, frameIndex, corridorWidth);
// Vertical segment
var hallV = SelectHallwayTemplate(requiredTags, startY <= endY ? "south" : "north");
if (hallV == null || !TryStampHallwayRun(layout, hallV, endX, startY, endX, endY, floorId, sheetId, frameIndex))
CarveVerticalCorridor(layout, startY, endY, endX, floorId, sheetId, frameIndex, corridorWidth);
}
else
{
// Vertical segment
var hallV = SelectHallwayTemplate(requiredTags, startY <= endY ? "south" : "north");
if (hallV == null || !TryStampHallwayRun(layout, hallV, startX, startY, startX, endY, floorId, sheetId, frameIndex))
CarveVerticalCorridor(layout, startY, endY, startX, floorId, sheetId, frameIndex, corridorWidth);
// Horizontal segment
var hallH = SelectHallwayTemplate(requiredTags, startX <= endX ? "east" : "west");
if (hallH == null || !TryStampHallwayRun(layout, hallH, startX, endY, endX, endY, floorId, sheetId, frameIndex))
CarveHorizontalCorridor(layout, startX, endX, endY, floorId, sheetId, frameIndex, corridorWidth);
}
}
/// <summary>
/// Clear tiles at a connection point to allow corridor entry
/// This aggressively clears walls in both directions to ensure passage
/// </summary>
private void ClearConnectionPoint(DungeonLayoutV2 layout, int x, int y, int width, string direction, int floorId, int sheetId, int frameIndex)
{
int depth = 5; // How far to clear in each direction
int halfWidth = Math.Max(width, 2);
Console.WriteLine($"[DungeonGenV2] Clearing connection at ({x},{y}) direction={direction} width={width}");
int clearedCount = 0;
// Clear in a cross/plus pattern centered on the connection point
// This ensures we punch through walls regardless of direction
for (int d = -depth; d <= depth; d++)
{
for (int w = -halfWidth; w <= halfWidth; w++)
{
int cx, cy;
switch (direction.ToLower())
{
case "north":
case "south":
// Vertical corridor - d goes vertical, w goes horizontal
cx = x + w;
cy = y + d;
break;
case "east":
case "west":
default:
// Horizontal corridor - d goes horizontal, w goes vertical
cx = x + d;
cy = y + w;
break;
}
if (cx >= 0 && cx < MapWidth && cy >= 0 && cy < MapHeight)
{
// Track if we're actually changing something
bool hadTile = layout.Tiles[cx, cy] != 0;
bool wasBlocked = layout.Walkable != null && !layout.Walkable[cx, cy];
// Remove existing tile visuals
layout.TileDetails.RemoveAll(t => t.X == cx && t.Y == cy);
// Set as walkable floor
layout.Tiles[cx, cy] = floorId;
if (layout.Walkable != null)
{
layout.Walkable[cx, cy] = true;
}
// Add floor tile visual
if (floorId > 0 && sheetId > 0)
{
layout.TileDetails.Add(new PlacedTile
{
X = cx,
Y = cy,
TileDefinitionId = floorId,
SheetId = sheetId,
FrameIndex = frameIndex,
Layer = 0
});
}
if (hadTile && wasBlocked)
clearedCount++;
}
}
}
Console.WriteLine($"[DungeonGenV2] Cleared {clearedCount} wall tiles at connection");
}
private void CarveHorizontalCorridor(DungeonLayoutV2 layout, int x1, int x2, int y, int floorId, int sheetId, int frameIndex, int width = 2)
{
int minX = Math.Min(x1, x2);
int maxX = Math.Max(x1, x2);
for (int x = minX; x <= maxX; x++)
{
for (int dy = 0; dy < width; dy++)
{
int ty = y + dy - width / 2; // Center the corridor
if (x >= 0 && x < MapWidth && ty >= 0 && ty < MapHeight && !layout.IsWalkable(x, ty))
{
// Remove any existing visual (walls, void decorations, etc.)
layout.TileDetails.RemoveAll(t => t.X == x && t.Y == ty);
layout.Tiles[x, ty] = floorId;
// Set walkability for corridors
if (layout.Walkable != null)
{
layout.Walkable[x, ty] = true;
}
if (floorId > 0 && sheetId > 0)
{
layout.TileDetails.Add(new PlacedTile
{
X = x,
Y = ty,
TileDefinitionId = floorId,
SheetId = sheetId,
FrameIndex = frameIndex,
Layer = 0
});
}
}
}
}
}
private void CarveVerticalCorridor(DungeonLayoutV2 layout, int y1, int y2, int x, int floorId, int sheetId, int frameIndex, int width = 2)
{
int minY = Math.Min(y1, y2);
int maxY = Math.Max(y1, y2);
for (int y = minY; y <= maxY; y++)
{
for (int dx = 0; dx < width; dx++)
{
int tx = x + dx - width / 2; // Center the corridor
if (tx >= 0 && tx < MapWidth && y >= 0 && y < MapHeight && !layout.IsWalkable(tx, y))
{
// Remove any existing visual (walls, void decorations, etc.)
layout.TileDetails.RemoveAll(t => t.X == tx && t.Y == y);
layout.Tiles[tx, y] = floorId;
// Set walkability for corridors
if (layout.Walkable != null)
{
layout.Walkable[tx, y] = true;
}
if (floorId > 0 && sheetId > 0)
{
layout.TileDetails.Add(new PlacedTile
{
X = tx,
Y = y,
TileDefinitionId = floorId,
SheetId = sheetId,
FrameIndex = frameIndex,
Layer = 0
});
}
}
}
}
}
/// <summary>
/// Automatically generate wall tiles around floor tiles that border void
/// </summary>
private void GenerateAutoWalls(DungeonLayoutV2 layout)
{
// Find wall tiles for each direction
var wallTiles = _tileDefinitions.Values.Where(t => t.Type == TileType.Wall).ToList();
if (wallTiles.Count == 0)
{
Console.WriteLine("[DungeonGenV2] No wall tiles found - skipping auto-wall generation");
return;
}
Console.WriteLine($"[DungeonGenV2] Found {wallTiles.Count} wall tiles for auto-wall generation");
foreach (var wt in wallTiles)
{
Console.WriteLine($" - {wt.Id}: {wt.Name} (tags: {wt.Tags ?? "none"})");
}
// Helper to match tags.
// NOTE: Some of your data has tags separated by commas *and/or* whitespace (e.g. "corner_nw void"),
// so we split on both to be resilient.
bool HasTag(TileDefinition t, string tag)
{
if (string.IsNullOrWhiteSpace(t.Tags)) return false;
return t.Tags
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Any(s => s.Equals(tag, StringComparison.OrdinalIgnoreCase));
}
// Try to find directional walls by tags, fall back to first wall
var wallNorth = wallTiles.FirstOrDefault(t => HasTag(t, "north")) ?? wallTiles[0];
var wallSouth = wallTiles.FirstOrDefault(t => HasTag(t, "south")) ?? wallTiles[0];
var wallEast = wallTiles.FirstOrDefault(t => HasTag(t, "east")) ?? wallTiles[0];
var wallWest = wallTiles.FirstOrDefault(t => HasTag(t, "west")) ?? wallTiles[0];
// Corner tiles:
// - corner_* indicates which *quadrant of the tile contains the wall mass* (tile itself lives in void space)
// - many sets also include "void"-tagged corner variants meant specifically for outside/diagonal void corners.
var wallCornerNE = wallTiles.FirstOrDefault(t => HasTag(t, "corner_ne") && !HasTag(t, "void"))
?? wallTiles.FirstOrDefault(t => HasTag(t, "corner_ne"))
?? wallTiles[0];
var wallCornerNW = wallTiles.FirstOrDefault(t => HasTag(t, "corner_nw") && !HasTag(t, "void"))
?? wallTiles.FirstOrDefault(t => HasTag(t, "corner_nw"))
?? wallTiles[0];
var wallCornerSE = wallTiles.FirstOrDefault(t => HasTag(t, "corner_se") && !HasTag(t, "void"))
?? wallTiles.FirstOrDefault(t => HasTag(t, "corner_se"))
?? wallTiles[0];
var wallCornerSW = wallTiles.FirstOrDefault(t => HasTag(t, "corner_sw") && !HasTag(t, "void"))
?? wallTiles.FirstOrDefault(t => HasTag(t, "corner_sw"))
?? wallTiles[0];
// Prefer these when a corner tile borders void on TWO orthogonal sides (classic outside corner).
var wallCornerNEVoid = wallTiles.FirstOrDefault(t => HasTag(t, "corner_ne") && HasTag(t, "void"));
var wallCornerNWVoid = wallTiles.FirstOrDefault(t => HasTag(t, "corner_nw") && HasTag(t, "void"));
var wallCornerSEVoid = wallTiles.FirstOrDefault(t => HasTag(t, "corner_se") && HasTag(t, "void"));
var wallCornerSWVoid = wallTiles.FirstOrDefault(t => HasTag(t, "corner_sw") && HasTag(t, "void"));
TileDefinition PickCorner(string cornerTag, bool preferVoid)
{
// cornerTag is one of: corner_ne, corner_nw, corner_se, corner_sw
return cornerTag.ToLowerInvariant() switch
{
"corner_ne" => (preferVoid ? wallCornerNEVoid : null) ?? wallCornerNE,
"corner_nw" => (preferVoid ? wallCornerNWVoid : null) ?? wallCornerNW,
"corner_se" => (preferVoid ? wallCornerSEVoid : null) ?? wallCornerSE,
"corner_sw" => (preferVoid ? wallCornerSWVoid : null) ?? wallCornerSW,
_ => wallCornerNW
};
}
Console.WriteLine($"[DungeonGenV2] Wall tile mapping: N={wallNorth.Id}, S={wallSouth.Id}, E={wallEast.Id}, W={wallWest.Id}");
// Track positions that need walls
var wallPositions = new List<(int X, int Y, TileDefinition Tile)>();
// Check each void tile to see if it borders a floor
for (int x = 0; x < MapWidth; x++)
{
for (int y = 0; y < MapHeight; y++)
{
// Skip if not void
if (layout.Tiles[x, y] != 0) continue;
// Check neighbors for floor tiles (walkable)
bool hasFloorNorth = y > 0 && layout.IsWalkable(x, y - 1);
bool hasFloorSouth = y < MapHeight - 1 && layout.IsWalkable(x, y + 1);
bool hasFloorEast = x < MapWidth - 1 && layout.IsWalkable(x + 1, y);
bool hasFloorWest = x > 0 && layout.IsWalkable(x - 1, y);
// If any adjacent tile is floor, this should be a wall
if (hasFloorNorth || hasFloorSouth || hasFloorEast || hasFloorWest)
{
// Determine wall type based on which direction has floor
TileDefinition wallTile;
// Check for corners first.
// IMPORTANT: corner_* tags indicate the quadrant where the *wall mass* lives inside this tile.
// That quadrant matches the direction of the interior (walkable) corner.
// Example: if the interior is to the NW (diagonal floor at NW), use corner_nw.
// If this is an *outside* corner (the two orthogonal sides away from the interior are void),
// prefer a corner variant that includes the "void" tag.
bool outsideN = IsOutsideAt(x, y - 1);
bool outsideS = IsOutsideAt(x, y + 1);
bool outsideE = IsOutsideAt(x + 1, y);
bool outsideW = IsOutsideAt(x - 1, y);
if (hasFloorNorth && hasFloorWest)
wallTile = PickCorner("corner_nw", preferVoid: (outsideS && outsideE));
else if (hasFloorNorth && hasFloorEast)
wallTile = PickCorner("corner_ne", preferVoid: (outsideS && outsideW));
else if (hasFloorSouth && hasFloorWest)
wallTile = PickCorner("corner_sw", preferVoid: (outsideN && outsideE));
else if (hasFloorSouth && hasFloorEast)
wallTile = PickCorner("corner_se", preferVoid: (outsideN && outsideW));
else if (hasFloorSouth)
wallTile = wallNorth; // Wall is north of floor, so it's a north-facing wall
else if (hasFloorNorth)
wallTile = wallSouth;
else if (hasFloorEast)
wallTile = wallWest;
else
wallTile = wallEast;
wallPositions.Add((x, y, wallTile));
}
}
}
// Place wall tiles
foreach (var (x, y, tile) in wallPositions)
{
layout.Tiles[x, y] = tile.Id;
// Walls are not walkable
if (layout.Walkable != null)
{
layout.Walkable[x, y] = false;
}
layout.TileDetails.Add(new PlacedTile
{
X = x,
Y = y,
TileDefinitionId = tile.Id,
SheetId = tile.TileMapSheetId,
FrameIndex = tile.FrameIndex,
Layer = 2 // Walls on layer 2
});
}
// Index existing wall visuals so we can update/replace them without duplicating TileDetails entries.
var wallDetailIndex = new Dictionary<(int X, int Y), int>();
for (int i = 0; i < layout.TileDetails.Count; i++)
{
var d = layout.TileDetails[i];
if (d.Layer == 2)
wallDetailIndex[(d.X, d.Y)] = i;
}
// Void-corner fill pass: when corridors/walls are thicker, some corner "caps" end up as void tiles that
// only see walkable space diagonally. Fill those with the appropriate connected corner wall so we don't
// get little void bite-marks at corridor turns and room borders.
bool IsWallAt(int wx, int wy)
{
if (wx < 0 || wx >= MapWidth || wy < 0 || wy >= MapHeight) return false;
int tid = layout.Tiles[wx, wy];
if (tid == 0) return false;
return _tileDefinitions.TryGetValue(tid, out var td) && td.Type == TileType.Wall;
}
bool IsOutsideAt(int wx, int wy)
{
// "Outside"/"void" in your terminology: a tile that is NOT walkable and NOT a wall.
// This prevents treating floor as "void" while still recognizing unfilled space.
if (wx < 0 || wx >= MapWidth || wy < 0 || wy >= MapHeight) return true; // out of bounds counts as outside
if (layout.IsWalkable(wx, wy)) return false;
return !IsWallAt(wx, wy);
}
void PlaceWall(int wx, int wy, TileDefinition tdef)
{
layout.Tiles[wx, wy] = tdef.Id;
if (layout.Walkable != null) layout.Walkable[wx, wy] = false;
if (wallDetailIndex.TryGetValue((wx, wy), out var existingIdx))
{
var d = layout.TileDetails[existingIdx];
d.TileDefinitionId = tdef.Id;
d.SheetId = tdef.TileMapSheetId;
d.FrameIndex = tdef.FrameIndex;
layout.TileDetails[existingIdx] = d;
}
else
{
wallDetailIndex[(wx, wy)] = layout.TileDetails.Count;
layout.TileDetails.Add(new PlacedTile
{
X = wx,
Y = wy,
TileDefinitionId = tdef.Id,
SheetId = tdef.TileMapSheetId,
FrameIndex = tdef.FrameIndex,
Layer = 2
});
}
}
for (int x = 1; x < MapWidth - 1; x++)
{
for (int y = 1; y < MapHeight - 1; y++)
{
if (layout.Tiles[x, y] != 0) continue; // only fill void
// Don't overwrite walkable tiles (shouldn't happen because walkable implies non-zero, but safe).
if (layout.IsWalkable(x, y)) continue;
bool floorNE = layout.IsWalkable(x + 1, y - 1);
bool floorNW = layout.IsWalkable(x - 1, y - 1);
bool floorSE = layout.IsWalkable(x + 1, y + 1);
bool floorSW = layout.IsWalkable(x - 1, y + 1);
bool wallN = IsWallAt(x, y - 1);
bool wallS = IsWallAt(x, y + 1);
bool wallE = IsWallAt(x + 1, y);
bool wallW = IsWallAt(x - 1, y);
// Only fill if there's "supporting" wall structure nearby; prevents random diagonal filling.
// The diagonal walkable indicates the interior corner; the adjacent walls indicate we are on the border.
// Diagonal-walkable indicates the interior corner. Choose the corner wall variant that visually
// connects the two bordering wall runs (this tileset uses the opposite naming compared to the
// earlier assumption, so NW<->SE and NE<->SW).
// Outside-void corners: if the two orthogonal tiles away from the interior are void, prefer "void" corner variants.
bool vN = IsOutsideAt(x, y - 1);
bool vS = IsOutsideAt(x, y + 1);
bool vE = IsOutsideAt(x + 1, y);
bool vW = IsOutsideAt(x - 1, y);
if (floorSE && (wallS || wallE)) PlaceWall(x, y, PickCorner("corner_se", preferVoid: (vN && vW)));
else if (floorSW && (wallS || wallW)) PlaceWall(x, y, PickCorner("corner_sw", preferVoid: (vN && vE)));
else if (floorNE && (wallN || wallE)) PlaceWall(x, y, PickCorner("corner_ne", preferVoid: (vS && vW)));
else if (floorNW && (wallN || wallW)) PlaceWall(x, y, PickCorner("corner_nw", preferVoid: (vS && vE)));
}
}
// Corner fix-up pass: if a wall tile meets void on the outside but is adjacent to walkable
// only diagonally (common with thicker walls / multi-tile corridors), swap in the connected
// corner tile so the silhouette doesn't look "broken".
//
// Example: a boundary wall tile that is NW of a floor tile might not see floor South/East
// directly (those may be other wall tiles), but it *will* see floor at SE diagonally.
for (int x = 1; x < MapWidth - 1; x++)
{
for (int y = 1; y < MapHeight - 1; y++)
{
int id = layout.Tiles[x, y];
if (id == 0) continue;
if (!_tileDefinitions.TryGetValue(id, out var def)) continue;
if (def.Type != TileType.Wall) continue;
bool floorN = layout.IsWalkable(x, y - 1);
bool floorS = layout.IsWalkable(x, y + 1);
bool floorE = layout.IsWalkable(x + 1, y);
bool floorW = layout.IsWalkable(x - 1, y);
bool floorNE = layout.IsWalkable(x + 1, y - 1);
bool floorNW = layout.IsWalkable(x - 1, y - 1);
bool floorSE = layout.IsWalkable(x + 1, y + 1);
bool floorSW = layout.IsWalkable(x - 1, y + 1);
TileDefinition? replace = null;
// Choose connected outer corners using diagonal floor hints.
bool vN2 = IsOutsideAt(x, y - 1);
bool vS2 = IsOutsideAt(x, y + 1);
bool vE2 = IsOutsideAt(x + 1, y);
bool vW2 = IsOutsideAt(x - 1, y);
if (floorSE && !floorS && !floorE) replace = PickCorner("corner_se", preferVoid: (vN2 && vW2));
else if (floorSW && !floorS && !floorW) replace = PickCorner("corner_sw", preferVoid: (vN2 && vE2));
else if (floorNE && !floorN && !floorE) replace = PickCorner("corner_ne", preferVoid: (vS2 && vW2));
else if (floorNW && !floorN && !floorW) replace = PickCorner("corner_nw", preferVoid: (vS2 && vE2));
if (replace == null) continue;
if (replace.Id == id) continue;
layout.Tiles[x, y] = replace.Id;
if (layout.Walkable != null) layout.Walkable[x, y] = false;
// Update existing wall visual if present; otherwise add.
if (wallDetailIndex.TryGetValue((x, y), out var idx))
{
var d = layout.TileDetails[idx];
d.TileDefinitionId = replace.Id;
d.SheetId = replace.TileMapSheetId;
d.FrameIndex = replace.FrameIndex;
layout.TileDetails[idx] = d;
}
else
{
layout.TileDetails.Add(new PlacedTile
{
X = x,
Y = y,
TileDefinitionId = replace.Id,
SheetId = replace.TileMapSheetId,
FrameIndex = replace.FrameIndex,
Layer = 2
});
}
}
}
Console.WriteLine($"[DungeonGenV2] Generated {wallPositions.Count} auto-walls");
}
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;
}
private static Dictionary<string, HashSet<string>> ParseSocketTypes(HashSet<string> tags)
{
// dir -> set of types; "" means untyped
var map = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase)
{
["N"] = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
["E"] = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
["S"] = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
["W"] = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
};
foreach (var t in tags)
{
if (!t.StartsWith("Socket", StringComparison.OrdinalIgnoreCase))
continue;
// Support:
// SocketE
// SocketE=OuterBorder
// SocketE_OuterBorder
// SocketE:OuterBorder
var cleaned = t.Replace(":", "=", StringComparison.Ordinal);
string left = cleaned;
string type = "";
int eq = cleaned.IndexOf('=');
if (eq >= 0)
{
left = cleaned.Substring(0, eq);
type = cleaned.Substring(eq + 1).Trim();
}
else
{
// underscore typed form
var parts = cleaned.Split('_', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length == 2)
{
left = parts[0];
type = parts[1];
}
}
// left is "SocketN" / "SocketE"
if (left.Length < "Socket".Length + 1) continue;
var dir = left.Substring("Socket".Length); // "N" "E" "S" "W"
if (!(dir is "N" or "E" or "S" or "W")) continue;
// untyped stored as ""
map[dir].Add(string.IsNullOrWhiteSpace(type) ? "" : type);
}
return map;
}
private TileDefinition? PickRandomFloorTile(
DungeonLayoutV2 layout,
int x, int y,
int familyId,
double varianceChance = 0.15)
{
var requiredSocketTags = BuildRequiredSocketTags(layout, x, y);
string primaryTag = $"TileBaseCore_{familyId}";
string varianceTag = $"TileBase_{familyId}";
var primary = _tileDefinitions.Values
.Where(t => t.Type == TileType.Floor)
.Where(t => HasTag(t, primaryTag))
.Where(t => HasAllTags(t, requiredSocketTags))
.ToList();
var variance = _tileDefinitions.Values
.Where(t => t.Type == TileType.Floor)
.Where(t => HasTag(t, varianceTag))
.Where(t => HasAllTags(t, requiredSocketTags))
.ToList();
if (primary.Count == 0 && variance.Count == 0)
{
// Fallback: relax socket requirements (so you don't dead-end)
// You can also log this so you know your tileset is missing variants.
primary = _tileDefinitions.Values
.Where(t => t.Type == TileType.Floor && HasTag(t, primaryTag))
.ToList();
variance = _tileDefinitions.Values
.Where(t => t.Type == TileType.Floor && HasTag(t, varianceTag))
.ToList();
}
if (primary.Count == 0 && variance.Count == 0)
return _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor);
bool pickVar = _rng.NextDouble() < varianceChance;
var pool = pickVar ? variance : primary;
if (pool.Count == 0) pool = pickVar ? primary : variance;
return pool.Count == 0 ? null : pool[_rng.Next(pool.Count)];
}
private static string OppDir(string dir) => dir switch
{
"N" => "S",
"S" => "N",
"E" => "W",
"W" => "E",
_ => dir
};
private bool NeighborRequiresTyped(int neighborTileId, string neighborDir)
{
// neighborDir is the edge on the neighbor facing us (e.g. neighbor's "S" if it is north of us)
if (!_tileSocketTypes.TryGetValue(neighborTileId, out var sockets)) return false;
if (!sockets.TryGetValue(neighborDir, out var types)) return false;
// typed if it has any non-empty type
return types.Any(t => !string.IsNullOrEmpty(t));
}
private string? GetRequiredSocketTagFromNeighbor(int neighborTileId, string neighborEdgeFacingUs, string ourDir)
{
if (!_tileSocketTypes.TryGetValue(neighborTileId, out var sockets)) return null;
if (!sockets.TryGetValue(neighborEdgeFacingUs, out var types)) return null;
// If neighbor supports typed types on that edge, require a matching typed socket
var typed = types.FirstOrDefault(t => !string.IsNullOrEmpty(t));
if (!string.IsNullOrEmpty(typed))
return $"Socket{ourDir}={typed}";
// Otherwise require untyped
if (types.Contains(""))
return $"Socket{ourDir}";
// neighbor has no socket facing us => no requirement (or treat as mismatch)
return null;
}
private List<string> BuildRequiredSocketTags(DungeonLayoutV2 layout, int x, int y)
{
var req = new List<string>();
// North neighbor => our N must match neighbor's S
if (y > 0 && layout.IsWalkable(x, y - 1))
{
int nid = layout.Tiles[x, y - 1];
var r = GetRequiredSocketTagFromNeighbor(nid, neighborEdgeFacingUs: "S", ourDir: "N");
if (r != null) req.Add(r);
}
// West neighbor => our W must match neighbor's E
if (x > 0 && layout.IsWalkable(x - 1, y))
{
int wid = layout.Tiles[x - 1, y];
var r = GetRequiredSocketTagFromNeighbor(wid, neighborEdgeFacingUs: "E", ourDir: "W");
if (r != null) req.Add(r);
}
return req;
}
private bool HasAllTags(TileDefinition t, IEnumerable<string> required)
{
if (!_tileTags.TryGetValue(t.Id, out var tags)) return false;
foreach (var r in required)
if (!tags.Contains(r)) return false;
return true;
}
private bool HasTag(int tileId, string tag)
=> _tileTags.TryGetValue(tileId, out var tags) && tags.Contains(tag);
private bool HasTag(TileDefinition t, string tag)
=> _tileTags.TryGetValue(t.Id, out var tags) && tags.Contains(tag);
private static string Opp(string dir) => dir switch
{
"N" => "S",
"S" => "N",
"E" => "W",
"W" => "E",
_ => dir
};
}
/// <summary>
/// Extended room with template info
/// </summary>
public class DungeonRoomV2 : DungeonRoom
{
public int? TemplateId { get; set; }
public string? TemplateName { get; set; }
public HashSet<string> TemplateTags { get; set; } = new(StringComparer.OrdinalIgnoreCase);
public new RoomType Type { get; set; } = RoomType.Normal;
/// <summary>Connection points parsed from template</summary>
public List<ConnectionPoint> ConnectionPoints { get; set; } = new();
public DungeonRoomV2(int x, int y, int width, int height) : base(x, y, width, height) { }
/// <summary>Get the best connection point for a given direction</summary>
public ConnectionPoint? GetConnectionPoint(string direction)
{
// First try exact match
var exact = ConnectionPoints.FirstOrDefault(c => c.Direction.Equals(direction, StringComparison.OrdinalIgnoreCase));
if (exact != null) return exact;
// No exact match - create a default one for this direction rather than using wrong direction
// This ensures the connection point is actually on the correct edge
return direction.ToLower() switch
{
"north" => new ConnectionPoint { X = Width / 2, Y = 0, Direction = "north", Width = 3 },
"south" => new ConnectionPoint { X = Width / 2, Y = Height - 1, Direction = "south", Width = 3 },
"east" => new ConnectionPoint { X = Width - 1, Y = Height / 2, Direction = "east", Width = 3 },
"west" => new ConnectionPoint { X = 0, Y = Height / 2, Direction = "west", Width = 3 },
_ => ConnectionPoints.FirstOrDefault() // Last resort fallback
};
}
/// <summary>Get world position of a connection point</summary>
public (int X, int Y) GetConnectionWorldPos(ConnectionPoint cp)
{
return (X + cp.X, Y + cp.Y);
}
}
/// <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 SheetId { get; set; } // For client rendering
public int FrameIndex { get; set; } // Frame in the sheet
public int Layer { get; set; }
public int Rotation { get; set; }
public bool FlipX { get; set; }
public bool FlipY { get; set; }
}