2358 lines
91 KiB
C#
2358 lines
91 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 int _activeFamilyId = 1;
|
|
|
|
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();
|
|
|
|
// Legacy tag-based socket system (kept for fallback)
|
|
private Dictionary<int, Dictionary<string, string>> _tileSockets = new();
|
|
private Dictionary<int, Dictionary<string, HashSet<string>>> _tileSocketTypes = new();
|
|
|
|
// =========================================================================
|
|
// NEW COLUMN-BASED SOCKET SYSTEM
|
|
// =========================================================================
|
|
|
|
/// <summary>
|
|
/// Simple struct to hold socket data for a tile from database columns
|
|
/// </summary>
|
|
private struct TileSocketInfo
|
|
{
|
|
public SocketType N, E, S, W;
|
|
public string? NCustom, ECustom, SCustom, WCustom;
|
|
|
|
public string GetSocketId(string dir) => dir.ToUpperInvariant() switch
|
|
{
|
|
"N" => N == SocketType.Custom ? $"Custom:{NCustom}" : N.ToString(),
|
|
"E" => E == SocketType.Custom ? $"Custom:{ECustom}" : E.ToString(),
|
|
"S" => S == SocketType.Custom ? $"Custom:{SCustom}" : S.ToString(),
|
|
"W" => W == SocketType.Custom ? $"Custom:{WCustom}" : W.ToString(),
|
|
_ => "Closed"
|
|
};
|
|
|
|
public bool IsAllOpen => N == SocketType.Open && E == SocketType.Open &&
|
|
S == SocketType.Open && W == SocketType.Open;
|
|
|
|
public bool IsAllClosed => N == SocketType.Closed && E == SocketType.Closed &&
|
|
S == SocketType.Closed && W == SocketType.Closed;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Column-based socket cache - maps tile ID to socket info
|
|
/// </summary>
|
|
private Dictionary<int, TileSocketInfo> _tileSocketsStrict = new();
|
|
|
|
/// <summary>
|
|
/// Whether to use strict column-based sockets (true) or legacy tag-based (false)
|
|
/// </summary>
|
|
private bool _useStrictSockets = false;
|
|
|
|
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 RoomTemplate? SelectHallwayTemplate(HashSet<string> requiredTags, string direction)
|
|
{
|
|
if (_hallwayTemplates.Count == 0) return null;
|
|
|
|
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 { }
|
|
}
|
|
|
|
if (!supports) continue;
|
|
|
|
if (score > bestScore)
|
|
{
|
|
best = t;
|
|
bestScore = score;
|
|
}
|
|
}
|
|
|
|
return best;
|
|
}
|
|
|
|
private bool TryStampHallwayRun(
|
|
DungeonLayoutV2 layout,
|
|
RoomTemplate hallway,
|
|
int x1,
|
|
int y1,
|
|
int x2,
|
|
int y2,
|
|
int fallbackFloorId,
|
|
int fallbackSheetId,
|
|
int fallbackFrameIndex)
|
|
{
|
|
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;
|
|
|
|
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;
|
|
|
|
if (layout.IsWalkable(wx, wy)) continue;
|
|
|
|
int tileId = p.TileDefinitionId;
|
|
var tileDef = _tileDefinitions.GetValueOrDefault(tileId);
|
|
if (tileDef == null)
|
|
{
|
|
tileId = fallbackFloorId;
|
|
tileDef = _tileDefinitions.GetValueOrDefault(tileId);
|
|
}
|
|
|
|
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;
|
|
|
|
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()
|
|
{
|
|
await LoadTemplatesAsync();
|
|
|
|
var layout = new DungeonLayoutV2
|
|
{
|
|
Seed = _seed,
|
|
Tier = _tier,
|
|
Width = MapWidth,
|
|
Height = MapHeight,
|
|
TileSize = _tileSize
|
|
};
|
|
|
|
layout.Tiles = new int[MapWidth, MapHeight];
|
|
layout.Walkable = new bool[MapWidth, MapHeight];
|
|
layout.TileDetails = new List<PlacedTile>();
|
|
|
|
int roomCount = _rng.Next(MinRooms, MaxRooms + 1);
|
|
var rooms = new List<DungeonRoomV2>();
|
|
int attempts = 0;
|
|
int maxAttempts = roomCount * 30;
|
|
|
|
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})");
|
|
}
|
|
|
|
while (rooms.Count < roomCount && attempts < maxAttempts)
|
|
{
|
|
attempts++;
|
|
|
|
RoomType type = DetermineNextRoomType(rooms, roomCount);
|
|
|
|
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");
|
|
|
|
var bossRoom = rooms.FirstOrDefault(r => r.Type == RoomType.Boss);
|
|
if (bossRoom == null && rooms.Count > 1)
|
|
{
|
|
rooms[^1].Type = RoomType.Boss;
|
|
}
|
|
|
|
var entranceRoom = rooms.FirstOrDefault(r => r.Type == RoomType.Entrance) ?? rooms[0];
|
|
rooms = rooms.OrderBy(r => Distance(entranceRoom, r)).ToList();
|
|
|
|
var connected = new HashSet<int> { 0 };
|
|
Console.WriteLine($"[DungeonGenV2] Connecting {rooms.Count} rooms...");
|
|
|
|
for (int i = 1; i < rooms.Count; i++)
|
|
{
|
|
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}");
|
|
}
|
|
|
|
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]);
|
|
}
|
|
}
|
|
|
|
layout.SpawnPoint = new DungeonPoint(entranceRoom.CenterX, entranceRoom.CenterY);
|
|
|
|
GenerateSpawns(rooms, layout);
|
|
|
|
layout.Rooms = rooms.Cast<DungeonRoom>().ToList();
|
|
|
|
GenerateAutoWalls(layout);
|
|
|
|
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}, Hallway={_hallwayTemplates.Count}");
|
|
|
|
_tileDefinitions = new Dictionary<int, TileDefinition>();
|
|
|
|
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;
|
|
|
|
_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)");
|
|
}
|
|
|
|
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;
|
|
_tileDefinitions[tile.Id] = tile;
|
|
}
|
|
|
|
Console.WriteLine($"[DungeonGenV2] Loaded {_defaultSheet.Tiles.Count} tiles from default sheet '{_defaultSheet.Name}'");
|
|
}
|
|
|
|
Console.WriteLine($"[DungeonGenV2] Total tile definitions merged: {_tileDefinitions.Count}");
|
|
|
|
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}");
|
|
|
|
// =========================================================================
|
|
// BUILD COLUMN-BASED SOCKET CACHE
|
|
// =========================================================================
|
|
_tileSocketsStrict = _tileDefinitions.Values.ToDictionary(
|
|
t => t.Id,
|
|
t => new TileSocketInfo
|
|
{
|
|
N = t.SocketN,
|
|
E = t.SocketE,
|
|
S = t.SocketS,
|
|
W = t.SocketW,
|
|
NCustom = t.SocketNCustom,
|
|
ECustom = t.SocketECustom,
|
|
SCustom = t.SocketSCustom,
|
|
WCustom = t.SocketWCustom
|
|
}
|
|
);
|
|
|
|
Console.WriteLine($"[DungeonGenV2] Built strict socket cache for {_tileSocketsStrict.Count} tiles");
|
|
|
|
// Log socket distribution
|
|
var openCount = _tileSocketsStrict.Values.Count(s => s.IsAllOpen);
|
|
var closedCount = _tileSocketsStrict.Values.Count(s => s.IsAllClosed);
|
|
var mixedCount = _tileSocketsStrict.Count - openCount - closedCount;
|
|
Console.WriteLine($"[DungeonGenV2] Socket distribution: AllOpen={openCount}, AllClosed={closedCount}, Mixed={mixedCount}");
|
|
Console.WriteLine($"[DungeonGenV2] Socket distribution: AllOpen={openCount}, AllClosed={closedCount}, Mixed={mixedCount}");
|
|
|
|
// Determine if we should use strict sockets
|
|
// Use strict if we have tiles with non-default socket configurations
|
|
_useStrictSockets = openCount > 0 || mixedCount > 0;
|
|
Console.WriteLine($"[DungeonGenV2] Using strict socket matching: {_useStrictSockets}");
|
|
|
|
// Validate floor tile configuration
|
|
if (_useStrictSockets)
|
|
{
|
|
ValidateTileSocketConfiguration();
|
|
}
|
|
}
|
|
else
|
|
{
|
|
_tagIndex = null;
|
|
_tileTags = new Dictionary<int, HashSet<string>>();
|
|
_tileSocketTypes = new Dictionary<int, Dictionary<string, HashSet<string>>>();
|
|
_tileSocketsStrict = new Dictionary<int, TileSocketInfo>();
|
|
_useStrictSockets = false;
|
|
|
|
Console.WriteLine($"[DungeonGenV2] WARNING: No tile definitions available; tag index/caches not built.");
|
|
}
|
|
|
|
ChooseDungeonFamilyFromSheet();
|
|
}
|
|
|
|
// =========================================================================
|
|
// STRICT SOCKET MATCHING METHODS (Column-based)
|
|
// =========================================================================
|
|
|
|
/// <summary>
|
|
/// Check if a neighbor cell has an actually placed tile (not just marked walkable)
|
|
/// This is critical because CarveBasicRoom marks cells walkable BEFORE placing tiles
|
|
/// </summary>
|
|
private bool HasPlacedTile(DungeonLayoutV2 layout, int x, int y)
|
|
{
|
|
if (x < 0 || x >= layout.Width || y < 0 || y >= layout.Height)
|
|
return false;
|
|
return layout.Tiles[x, y] > 0; // Actually has a tile ID assigned
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get socket ID for a tile edge using column-based system
|
|
/// </summary>
|
|
private string GetSocketIdStrict(int tileId, string edge)
|
|
{
|
|
if (!_tileSocketsStrict.TryGetValue(tileId, out var sockets))
|
|
return "Closed"; // Unknown tile = Closed
|
|
|
|
return sockets.GetSocketId(edge);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Check if two tile edges are compatible using strict column-based matching
|
|
/// </summary>
|
|
private bool AreSocketsCompatibleStrict(int tileAId, string edgeA, int tileBId, string edgeB)
|
|
{
|
|
var socketA = GetSocketIdStrict(tileAId, edgeA);
|
|
var socketB = GetSocketIdStrict(tileBId, edgeB);
|
|
|
|
// STRICT: Must match exactly
|
|
return socketA.Equals(socketB, StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Check if a tile is compatible with all placed neighbors using strict matching
|
|
/// Uses HasPlacedTile to only check neighbors that actually have tiles assigned
|
|
/// </summary>
|
|
private bool IsCompatibleWithNeighborsStrict(DungeonLayoutV2 layout, int x, int y, int tileId)
|
|
{
|
|
// Check North neighbor (their S edge vs our N edge)
|
|
if (y > 0 && HasPlacedTile(layout, x, y - 1))
|
|
{
|
|
int neighborId = layout.Tiles[x, y - 1];
|
|
if (!AreSocketsCompatibleStrict(tileId, "N", neighborId, "S"))
|
|
return false;
|
|
}
|
|
|
|
// Check South neighbor (their N edge vs our S edge)
|
|
if (y < layout.Height - 1 && HasPlacedTile(layout, x, y + 1))
|
|
{
|
|
int neighborId = layout.Tiles[x, y + 1];
|
|
if (!AreSocketsCompatibleStrict(tileId, "S", neighborId, "N"))
|
|
return false;
|
|
}
|
|
|
|
// Check West neighbor (their E edge vs our W edge)
|
|
if (x > 0 && HasPlacedTile(layout, x - 1, y))
|
|
{
|
|
int neighborId = layout.Tiles[x - 1, y];
|
|
if (!AreSocketsCompatibleStrict(tileId, "W", neighborId, "E"))
|
|
return false;
|
|
}
|
|
|
|
// Check East neighbor (their W edge vs our E edge)
|
|
if (x < layout.Width - 1 && HasPlacedTile(layout, x + 1, y))
|
|
{
|
|
int neighborId = layout.Tiles[x + 1, y];
|
|
if (!AreSocketsCompatibleStrict(tileId, "E", neighborId, "W"))
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Build required socket types from neighbors using strict matching
|
|
/// Uses HasPlacedTile to only consider neighbors that actually have tiles assigned
|
|
/// </summary>
|
|
private Dictionary<string, string> GetRequiredSocketsStrict(DungeonLayoutV2 layout, int x, int y)
|
|
{
|
|
var required = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
|
|
|
// North neighbor's S edge determines our N requirement
|
|
if (y > 0 && HasPlacedTile(layout, x, y - 1))
|
|
{
|
|
required["N"] = GetSocketIdStrict(layout.Tiles[x, y - 1], "S");
|
|
}
|
|
|
|
// South neighbor's N edge determines our S requirement
|
|
if (y < layout.Height - 1 && HasPlacedTile(layout, x, y + 1))
|
|
{
|
|
required["S"] = GetSocketIdStrict(layout.Tiles[x, y + 1], "N");
|
|
}
|
|
|
|
// West neighbor's E edge determines our W requirement
|
|
if (x > 0 && HasPlacedTile(layout, x - 1, y))
|
|
{
|
|
required["W"] = GetSocketIdStrict(layout.Tiles[x - 1, y], "E");
|
|
}
|
|
|
|
// East neighbor's W edge determines our E requirement
|
|
if (x < layout.Width - 1 && HasPlacedTile(layout, x + 1, y))
|
|
{
|
|
required["E"] = GetSocketIdStrict(layout.Tiles[x + 1, y], "W");
|
|
}
|
|
|
|
return required;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Check if a tile satisfies strict socket requirements
|
|
/// </summary>
|
|
private bool SatisfiesSocketRequirementsStrict(int tileId, Dictionary<string, string> required)
|
|
{
|
|
foreach (var (edge, reqSocket) in required)
|
|
{
|
|
var tileSocket = GetSocketIdStrict(tileId, edge);
|
|
if (!tileSocket.Equals(reqSocket, StringComparison.OrdinalIgnoreCase))
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Pick a random floor tile using strict socket matching
|
|
/// </summary>
|
|
private TileDefinition? PickRandomFloorTileStrict(
|
|
DungeonLayoutV2 layout,
|
|
int x, int y,
|
|
int familyId,
|
|
double varianceChance = 0.25)
|
|
{
|
|
var required = GetRequiredSocketsStrict(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 => SatisfiesSocketRequirementsStrict(t.Id, required))
|
|
.ToList();
|
|
|
|
var variance = _tileDefinitions.Values
|
|
.Where(t => t.Type == TileType.Floor)
|
|
.Where(t => HasTag(t, varianceTag))
|
|
.Where(t => SatisfiesSocketRequirementsStrict(t.Id, required))
|
|
.ToList();
|
|
|
|
if (primary.Count == 0 && variance.Count == 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
bool pickVariance = _rng.NextDouble() < varianceChance;
|
|
var pool = pickVariance ? variance : primary;
|
|
if (pool.Count == 0) pool = pickVariance ? primary : variance;
|
|
|
|
return pool[_rng.Next(pool.Count)];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Validate tile socket configuration on startup
|
|
/// </summary>
|
|
private void ValidateTileSocketConfiguration()
|
|
{
|
|
var floors = _tileDefinitions.Values.Where(t => t.Type == TileType.Floor).ToList();
|
|
|
|
int allOpenCount = 0;
|
|
int allClosedCount = 0;
|
|
int mixedCount = 0;
|
|
|
|
foreach (var tile in floors)
|
|
{
|
|
if (!_tileSocketsStrict.TryGetValue(tile.Id, out var sockets))
|
|
{
|
|
Console.WriteLine($"[Socket] WARNING: Floor tile {tile.Id} '{tile.Name}' has no socket info!");
|
|
continue;
|
|
}
|
|
|
|
if (sockets.IsAllOpen) allOpenCount++;
|
|
else if (sockets.IsAllClosed) allClosedCount++;
|
|
else mixedCount++;
|
|
|
|
if (sockets.IsAllClosed)
|
|
{
|
|
Console.WriteLine($"[Socket] WARNING: Floor tile {tile.Id} '{tile.Name}' has ALL Closed sockets - cannot connect!");
|
|
}
|
|
}
|
|
|
|
Console.WriteLine($"[Socket] Floor tile validation: {allOpenCount} all-open, {allClosedCount} all-closed, {mixedCount} mixed");
|
|
|
|
if (allOpenCount == 0)
|
|
{
|
|
Console.WriteLine($"[Socket] WARNING: No floor tiles with Open sockets - dungeon generation may fail!");
|
|
}
|
|
}
|
|
|
|
private RoomType DetermineNextRoomType(List<DungeonRoomV2> existing, int targetCount)
|
|
{
|
|
bool hasBoss = existing.Any(r => r.Type == RoomType.Boss);
|
|
bool hasTreasure = existing.Any(r => r.Type == RoomType.Treasure);
|
|
|
|
if (!hasBoss && existing.Count >= targetCount - 2)
|
|
return RoomType.Boss;
|
|
|
|
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)
|
|
{
|
|
var templates = type switch
|
|
{
|
|
RoomType.Entrance => _entranceTemplates,
|
|
RoomType.Exit or RoomType.Boss => _bossTemplates.Concat(_exitTemplates).ToList(),
|
|
RoomType.Treasure => _treasureTemplates,
|
|
_ => _normalTemplates
|
|
};
|
|
|
|
if (templates.Count == 0)
|
|
{
|
|
return PlaceFallbackRoom(layout, existing, type, preferX, preferY);
|
|
}
|
|
|
|
var template = SelectWeightedTemplate(templates);
|
|
if (template == null)
|
|
{
|
|
return PlaceFallbackRoom(layout, existing, type, preferX, preferY);
|
|
}
|
|
|
|
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)
|
|
};
|
|
|
|
if (existing.Any(r => room.Intersects(r, padding: 3)))
|
|
{
|
|
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;
|
|
}
|
|
|
|
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;
|
|
|
|
var tileDef = _tileDefinitions.GetValueOrDefault(p.TileDefinitionId);
|
|
|
|
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 { }
|
|
}
|
|
|
|
if (!string.IsNullOrEmpty(template.ConnectionPointsJson))
|
|
{
|
|
try
|
|
{
|
|
var connections = JsonSerializer.Deserialize<List<ConnectionPoint>>(template.ConnectionPointsJson);
|
|
if (connections != null)
|
|
{
|
|
room.ConnectionPoints = connections;
|
|
}
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
if (room.ConnectionPoints.Count == 0)
|
|
{
|
|
room.ConnectionPoints = new List<ConnectionPoint>
|
|
{
|
|
new() { X = room.Width / 2, Y = 0, Direction = "north", Width = 3 },
|
|
new() { X = room.Width / 2, Y = room.Height - 1, Direction = "south", Width = 3 },
|
|
new() { X = 0, Y = room.Height / 2, Direction = "west", Width = 3 },
|
|
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 (!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)))
|
|
{
|
|
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)
|
|
{
|
|
int familyId = _activeFamilyId;
|
|
string primaryTag = $"TileBaseCore_{familyId}";
|
|
string varianceTag = $"TileBase_{familyId}";
|
|
|
|
// Get all floor tiles in this family
|
|
var primaryTiles = _tileDefinitions.Values
|
|
.Where(t => t.Type == TileType.Floor && HasTag(t, primaryTag))
|
|
.ToList();
|
|
var varianceTiles = _tileDefinitions.Values
|
|
.Where(t => t.Type == TileType.Floor && HasTag(t, varianceTag))
|
|
.ToList();
|
|
|
|
// Separate all-Open tiles from pattern tiles (those with Custom sockets)
|
|
var allOpenPrimary = primaryTiles
|
|
.Where(t => _tileSocketsStrict.TryGetValue(t.Id, out var s) && s.IsAllOpen)
|
|
.ToList();
|
|
var allOpenVariance = varianceTiles
|
|
.Where(t => _tileSocketsStrict.TryGetValue(t.Id, out var s) && s.IsAllOpen)
|
|
.ToList();
|
|
|
|
// Pattern tiles should only be used when we can verify all 4 constraints are satisfiable
|
|
var patternPrimary = primaryTiles
|
|
.Where(t => _tileSocketsStrict.TryGetValue(t.Id, out var s) && !s.IsAllOpen)
|
|
.ToList();
|
|
var patternVariance = varianceTiles
|
|
.Where(t => _tileSocketsStrict.TryGetValue(t.Id, out var s) && !s.IsAllOpen)
|
|
.ToList();
|
|
|
|
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;
|
|
|
|
// Mark as walkable
|
|
if (layout.Walkable != null)
|
|
layout.Walkable[x, y] = true;
|
|
|
|
// Remove any existing tile
|
|
layout.TileDetails.RemoveAll(t => t.X == x && t.Y == y);
|
|
|
|
TileDefinition? chosen = null;
|
|
|
|
if (_useStrictSockets)
|
|
{
|
|
// Build requirements from neighbors that already have tiles
|
|
var requirements = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
|
|
|
if (y > 0 && HasPlacedTile(layout, x, y - 1))
|
|
requirements["N"] = GetSocketIdStrict(layout.Tiles[x, y - 1], "S");
|
|
if (x > 0 && HasPlacedTile(layout, x - 1, y))
|
|
requirements["W"] = GetSocketIdStrict(layout.Tiles[x - 1, y], "E");
|
|
|
|
// Check if any requirement is a Custom socket type
|
|
bool hasCustomRequirement = requirements.Values
|
|
.Any(r => r.StartsWith("Custom:", StringComparison.OrdinalIgnoreCase));
|
|
|
|
// If we have Custom requirements, we MUST find a matching tile
|
|
// Otherwise, prefer all-Open tiles to avoid creating unsatisfiable constraints
|
|
|
|
Func<TileDefinition, bool> satisfiesReqs = t => {
|
|
foreach (var (edge, reqSocket) in requirements)
|
|
{
|
|
var tileSocket = GetSocketIdStrict(t.Id, edge);
|
|
if (!tileSocket.Equals(reqSocket, StringComparison.OrdinalIgnoreCase))
|
|
return false;
|
|
}
|
|
return true;
|
|
};
|
|
|
|
if (hasCustomRequirement)
|
|
{
|
|
// Must match the Custom requirement exactly
|
|
var compatiblePrimary = primaryTiles.Where(satisfiesReqs).ToList();
|
|
var compatibleVariance = varianceTiles.Where(satisfiesReqs).ToList();
|
|
|
|
bool wantVariance = _rng.NextDouble() < 0.25;
|
|
if (wantVariance && compatibleVariance.Count > 0)
|
|
chosen = compatibleVariance[_rng.Next(compatibleVariance.Count)];
|
|
else if (compatiblePrimary.Count > 0)
|
|
chosen = compatiblePrimary[_rng.Next(compatiblePrimary.Count)];
|
|
else if (compatibleVariance.Count > 0)
|
|
chosen = compatibleVariance[_rng.Next(compatibleVariance.Count)];
|
|
}
|
|
else
|
|
{
|
|
// No Custom requirements - strongly prefer all-Open tiles
|
|
// This prevents pattern tiles from spreading and creating unsatisfiable constraints
|
|
var compatibleOpenPrimary = allOpenPrimary.Where(satisfiesReqs).ToList();
|
|
var compatibleOpenVariance = allOpenVariance.Where(satisfiesReqs).ToList();
|
|
|
|
bool wantVariance = _rng.NextDouble() < 0.25;
|
|
|
|
if (wantVariance && compatibleOpenVariance.Count > 0)
|
|
chosen = compatibleOpenVariance[_rng.Next(compatibleOpenVariance.Count)];
|
|
else if (compatibleOpenPrimary.Count > 0)
|
|
chosen = compatibleOpenPrimary[_rng.Next(compatibleOpenPrimary.Count)];
|
|
else if (compatibleOpenVariance.Count > 0)
|
|
chosen = compatibleOpenVariance[_rng.Next(compatibleOpenVariance.Count)];
|
|
|
|
// Only fall back to pattern tiles if no Open tiles work
|
|
// This should be rare and indicates a tile configuration issue
|
|
if (chosen == null)
|
|
{
|
|
var compatiblePatternPrimary = patternPrimary.Where(satisfiesReqs).ToList();
|
|
var compatiblePatternVariance = patternVariance.Where(satisfiesReqs).ToList();
|
|
|
|
if (wantVariance && compatiblePatternVariance.Count > 0)
|
|
chosen = compatiblePatternVariance[_rng.Next(compatiblePatternVariance.Count)];
|
|
else if (compatiblePatternPrimary.Count > 0)
|
|
chosen = compatiblePatternPrimary[_rng.Next(compatiblePatternPrimary.Count)];
|
|
else if (compatiblePatternVariance.Count > 0)
|
|
chosen = compatiblePatternVariance[_rng.Next(compatiblePatternVariance.Count)];
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// Legacy: just pick any floor tile
|
|
var pool = _rng.NextDouble() < 0.25 ? varianceTiles : primaryTiles;
|
|
if (pool.Count == 0) pool = varianceTiles.Count > 0 ? varianceTiles : primaryTiles;
|
|
if (pool.Count > 0)
|
|
chosen = pool[_rng.Next(pool.Count)];
|
|
}
|
|
|
|
// Fallback to any floor tile
|
|
if (chosen == null)
|
|
chosen = _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor);
|
|
|
|
int floorId = chosen?.Id ?? 1;
|
|
layout.Tiles[x, y] = floorId;
|
|
|
|
if (floorId > 0 && chosen != null)
|
|
{
|
|
layout.TileDetails.Add(new PlacedTile
|
|
{
|
|
X = x,
|
|
Y = y,
|
|
TileDefinitionId = floorId,
|
|
SheetId = chosen.TileMapSheetId,
|
|
FrameIndex = chosen.FrameIndex,
|
|
Layer = 0
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// Repair pass to fix any remaining mismatches
|
|
RepairRoomFloorSockets(layout, room);
|
|
}
|
|
|
|
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>
|
|
/// Enhanced repair pass with constraint relaxation:
|
|
/// 1. First tries to find perfect match satisfying all constraints
|
|
/// 2. If impossible, scores tiles by how many constraints they satisfy
|
|
/// 3. Prefers Open sockets over Custom when requirements conflict
|
|
/// 4. Falls back to all-Open tile to break impossible patterns
|
|
/// Runs multiple iterations until stable.
|
|
/// </summary>
|
|
private void RepairRoomFloorSockets(DungeonLayoutV2 layout, DungeonRoomV2 room)
|
|
{
|
|
if (!_useStrictSockets) return;
|
|
|
|
int familyId = _activeFamilyId;
|
|
int maxIterations = 15; // Increased for more complex patterns
|
|
|
|
// Pre-cache tiles in this family
|
|
var familyTiles = _tileDefinitions.Values
|
|
.Where(t => t.Type == TileType.Floor)
|
|
.Where(t => HasTag(t, $"TileBaseCore_{familyId}") || HasTag(t, $"TileBase_{familyId}"))
|
|
.ToList();
|
|
|
|
// Find the fallback all-Open tile once
|
|
var allOpenTile = familyTiles
|
|
.Where(t => _tileSocketsStrict.TryGetValue(t.Id, out var s) && s.IsAllOpen)
|
|
.FirstOrDefault();
|
|
|
|
if (allOpenTile == null)
|
|
{
|
|
Console.WriteLine($"[Socket] WARNING: No all-Open fallback tile in family {familyId}!");
|
|
return;
|
|
}
|
|
|
|
for (int iteration = 0; iteration < maxIterations; iteration++)
|
|
{
|
|
int repairCount = 0;
|
|
int relaxedCount = 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;
|
|
|
|
if (!HasPlacedTile(layout, x, y))
|
|
continue;
|
|
|
|
int currentTileId = layout.Tiles[x, y];
|
|
|
|
// Build requirements from ALL 4 neighbors
|
|
var requirements = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
|
|
|
if (y > 0 && HasPlacedTile(layout, x, y - 1))
|
|
requirements["N"] = GetSocketIdStrict(layout.Tiles[x, y - 1], "S");
|
|
|
|
if (y < MapHeight - 1 && HasPlacedTile(layout, x, y + 1))
|
|
requirements["S"] = GetSocketIdStrict(layout.Tiles[x, y + 1], "N");
|
|
|
|
if (x > 0 && HasPlacedTile(layout, x - 1, y))
|
|
requirements["W"] = GetSocketIdStrict(layout.Tiles[x - 1, y], "E");
|
|
|
|
if (x < MapWidth - 1 && HasPlacedTile(layout, x + 1, y))
|
|
requirements["E"] = GetSocketIdStrict(layout.Tiles[x + 1, y], "W");
|
|
|
|
// Check if current tile satisfies all requirements
|
|
int currentScore = ScoreSocketMatch(currentTileId, requirements);
|
|
|
|
if (currentScore == requirements.Count)
|
|
continue; // Perfect match, skip
|
|
|
|
// Find best matching tile
|
|
TileDefinition? replacement = null;
|
|
int bestScore = currentScore;
|
|
bool bestIsAllOpen = false;
|
|
|
|
foreach (var candidate in familyTiles)
|
|
{
|
|
int score = ScoreSocketMatch(candidate.Id, requirements);
|
|
bool isAllOpen = _tileSocketsStrict.TryGetValue(candidate.Id, out var s) && s.IsAllOpen;
|
|
|
|
// Prefer higher scores, break ties by preferring all-Open
|
|
if (score > bestScore || (score == bestScore && isAllOpen && !bestIsAllOpen))
|
|
{
|
|
bestScore = score;
|
|
replacement = candidate;
|
|
bestIsAllOpen = isAllOpen;
|
|
}
|
|
}
|
|
|
|
// If no tile can satisfy even one requirement, use all-Open fallback
|
|
if (replacement == null || bestScore < requirements.Count)
|
|
{
|
|
// Check if all-Open would cause fewer conflicts
|
|
int allOpenScore = ScoreSocketMatchRelaxed(allOpenTile.Id, requirements);
|
|
if (allOpenScore >= bestScore)
|
|
{
|
|
replacement = allOpenTile;
|
|
relaxedCount++;
|
|
}
|
|
}
|
|
|
|
if (replacement == null || replacement.Id == currentTileId)
|
|
continue;
|
|
|
|
// Replace the tile
|
|
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
|
|
});
|
|
|
|
repairCount++;
|
|
}
|
|
}
|
|
|
|
Console.WriteLine($"[Socket] Repair iteration {iteration + 1}: {repairCount} tiles fixed ({relaxedCount} relaxed to all-Open)");
|
|
|
|
if (repairCount == 0)
|
|
break; // Stable, we're done
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Score how well a tile matches socket requirements (strict matching)
|
|
/// </summary>
|
|
private int ScoreSocketMatch(int tileId, Dictionary<string, string> requirements)
|
|
{
|
|
int score = 0;
|
|
foreach (var (edge, reqSocket) in requirements)
|
|
{
|
|
var tileSocket = GetSocketIdStrict(tileId, edge);
|
|
if (tileSocket.Equals(reqSocket, StringComparison.OrdinalIgnoreCase))
|
|
score++;
|
|
}
|
|
return score;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Score socket match with relaxed rules:
|
|
/// - Open ↔ Open = match
|
|
/// - Open ↔ Custom:X = partial match (0.5 points - allows Open tiles to "heal" pattern boundaries)
|
|
/// - Custom:X ↔ Custom:X = match
|
|
/// </summary>
|
|
private int ScoreSocketMatchRelaxed(int tileId, Dictionary<string, string> requirements)
|
|
{
|
|
int score = 0;
|
|
foreach (var (edge, reqSocket) in requirements)
|
|
{
|
|
var tileSocket = GetSocketIdStrict(tileId, edge);
|
|
|
|
if (tileSocket.Equals(reqSocket, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
score += 2; // Perfect match
|
|
}
|
|
else if (tileSocket.Equals("Open", StringComparison.OrdinalIgnoreCase) &&
|
|
reqSocket.StartsWith("Custom:", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
score += 1; // Partial match - Open can "absorb" custom patterns
|
|
}
|
|
else if (reqSocket.Equals("Open", StringComparison.OrdinalIgnoreCase) &&
|
|
tileSocket.StartsWith("Custom:", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
score += 1; // Partial match - Custom can connect to Open
|
|
}
|
|
}
|
|
return score;
|
|
}
|
|
|
|
private List<string> BuildRequiredSocketTags_AllDirs(DungeonLayoutV2 layout, int x, int y)
|
|
{
|
|
var req = new List<string>();
|
|
|
|
if (y > 0 && HasPlacedTile(layout, x, y - 1))
|
|
{
|
|
int nid = layout.Tiles[x, y - 1];
|
|
var r = GetRequiredSocketTagFromNeighbor(nid, neighborEdgeFacingUs: "S", ourDir: "N");
|
|
if (r != null) req.Add(r);
|
|
}
|
|
|
|
if (y < MapHeight - 1 && HasPlacedTile(layout, x, y + 1))
|
|
{
|
|
int sid = layout.Tiles[x, y + 1];
|
|
var r = GetRequiredSocketTagFromNeighbor(sid, neighborEdgeFacingUs: "N", ourDir: "S");
|
|
if (r != null) req.Add(r);
|
|
}
|
|
|
|
if (x > 0 && HasPlacedTile(layout, x - 1, y))
|
|
{
|
|
int wid = layout.Tiles[x - 1, y];
|
|
var r = GetRequiredSocketTagFromNeighbor(wid, neighborEdgeFacingUs: "E", ourDir: "W");
|
|
if (r != null) req.Add(r);
|
|
}
|
|
|
|
if (x < MapWidth - 1 && HasPlacedTile(layout, 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;
|
|
}
|
|
|
|
private TileDefinition? PickRandomFloorTile_AllDirs(
|
|
DungeonLayoutV2 layout,
|
|
int x, int y,
|
|
int familyId,
|
|
double varianceChance = 0.25)
|
|
{
|
|
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))
|
|
.Where(t => CompatibleWithAllNeighbors(layout, x, y, t))
|
|
.ToList();
|
|
|
|
var variance = _tileDefinitions.Values
|
|
.Where(t => t.Type == TileType.Floor)
|
|
.Where(t => HasTag(t, varianceTag))
|
|
.Where(t => HasAllTags(t, requiredSocketTags))
|
|
.Where(t => CompatibleWithAllNeighbors(layout, x, y, t))
|
|
.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 bool CompatibleWithAllNeighbors(
|
|
DungeonLayoutV2 layout, int x, int y, TileDefinition t)
|
|
{
|
|
if (y > 0 && HasPlacedTile(layout, x, y - 1))
|
|
if (!EdgeSocketsCompatible(t.Id, "N", layout.Tiles[x, y - 1], "S"))
|
|
return false;
|
|
|
|
if (y < layout.Height - 1 && HasPlacedTile(layout, x, y + 1))
|
|
if (!EdgeSocketsCompatible(t.Id, "S", layout.Tiles[x, y + 1], "N"))
|
|
return false;
|
|
|
|
if (x > 0 && HasPlacedTile(layout, x - 1, y))
|
|
if (!EdgeSocketsCompatible(t.Id, "W", layout.Tiles[x - 1, y], "E"))
|
|
return false;
|
|
|
|
if (x < layout.Width - 1 && HasPlacedTile(layout, x + 1, y))
|
|
if (!EdgeSocketsCompatible(t.Id, "E", layout.Tiles[x + 1, y], "W"))
|
|
return false;
|
|
|
|
return true;
|
|
}
|
|
|
|
|
|
private async Task ConnectRoomsAsync(DungeonLayoutV2 layout, DungeonRoomV2 a, DungeonRoomV2 b)
|
|
{
|
|
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));
|
|
}
|
|
|
|
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";
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
int familyId = _activeFamilyId;
|
|
|
|
// Corridors must use all-Open tiles to connect properly with any room tile
|
|
TileDefinition? floorTile = null;
|
|
|
|
if (_useStrictSockets)
|
|
{
|
|
// For corridors, we need tiles with ALL sockets Open so they can connect to anything
|
|
floorTile = _tileDefinitions.Values
|
|
.Where(t => t.Type == TileType.Floor)
|
|
.Where(t => HasTag(t, $"TileBaseCore_{familyId}") || HasTag(t, $"TileBase_{familyId}"))
|
|
.Where(t => {
|
|
if (!_tileSocketsStrict.TryGetValue(t.Id, out var sockets)) return false;
|
|
return sockets.IsAllOpen;
|
|
})
|
|
.OrderBy(_ => _rng.Next())
|
|
.FirstOrDefault();
|
|
|
|
Console.WriteLine($"[DungeonGenV2][Corridors] Found all-Open tile: {floorTile?.Id} '{floorTile?.Name}'");
|
|
}
|
|
|
|
// Fallback to any floor tile with all-Open sockets
|
|
floorTile ??= _tileDefinitions.Values
|
|
.Where(t => t.Type == TileType.Floor)
|
|
.Where(t => {
|
|
if (!_tileSocketsStrict.TryGetValue(t.Id, out var sockets)) return false;
|
|
return sockets.IsAllOpen;
|
|
})
|
|
.FirstOrDefault();
|
|
|
|
// Last resort fallback
|
|
floorTile ??= _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}");
|
|
|
|
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);
|
|
|
|
if (_rng.Next(2) == 0)
|
|
{
|
|
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);
|
|
|
|
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
|
|
{
|
|
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);
|
|
|
|
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 void ClearConnectionPoint(DungeonLayoutV2 layout, int x, int y, int width, string direction, int floorId, int sheetId, int frameIndex)
|
|
{
|
|
int depth = 5;
|
|
int halfWidth = Math.Max(width, 2);
|
|
|
|
Console.WriteLine($"[DungeonGenV2] Clearing connection at ({x},{y}) direction={direction} width={width}");
|
|
int clearedCount = 0;
|
|
|
|
for (int d = -depth; d <= depth; d++)
|
|
{
|
|
for (int w = -halfWidth; w <= halfWidth; w++)
|
|
{
|
|
int cx, cy;
|
|
|
|
switch (direction.ToLower())
|
|
{
|
|
case "north":
|
|
case "south":
|
|
cx = x + w;
|
|
cy = y + d;
|
|
break;
|
|
case "east":
|
|
case "west":
|
|
default:
|
|
cx = x + d;
|
|
cy = y + w;
|
|
break;
|
|
}
|
|
|
|
if (cx >= 0 && cx < MapWidth && cy >= 0 && cy < MapHeight)
|
|
{
|
|
bool hadTile = layout.Tiles[cx, cy] != 0;
|
|
bool wasBlocked = layout.Walkable != null && !layout.Walkable[cx, cy];
|
|
|
|
layout.TileDetails.RemoveAll(t => t.X == cx && t.Y == cy);
|
|
|
|
layout.Tiles[cx, cy] = floorId;
|
|
if (layout.Walkable != null)
|
|
{
|
|
layout.Walkable[cx, cy] = true;
|
|
}
|
|
|
|
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;
|
|
if (x >= 0 && x < MapWidth && ty >= 0 && ty < MapHeight && !layout.IsWalkable(x, ty))
|
|
{
|
|
layout.TileDetails.RemoveAll(t => t.X == x && t.Y == ty);
|
|
layout.Tiles[x, ty] = floorId;
|
|
|
|
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;
|
|
if (tx >= 0 && tx < MapWidth && y >= 0 && y < MapHeight && !layout.IsWalkable(tx, y))
|
|
{
|
|
layout.TileDetails.RemoveAll(t => t.X == tx && t.Y == y);
|
|
layout.Tiles[tx, y] = floorId;
|
|
|
|
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>
|
|
/// Generate walls around floor tiles with 2-tile depth (face + top/cap)
|
|
///
|
|
/// Wall Tag System:
|
|
/// - Cardinal walls: wall_north, wall_south, wall_east, wall_west (facing direction)
|
|
/// - Top/cap tiles: wall_north_top, wall_south_top, etc. (above face tiles)
|
|
/// - Outer corners: corner_ne, corner_nw, corner_se, corner_sw
|
|
/// - Inner corners: inner_ne, inner_nw, inner_se, inner_sw (for L-shaped rooms)
|
|
/// - Each corner also has _top variant
|
|
/// - void modifier: for tiles facing pure void/outside
|
|
///
|
|
/// Socket Configuration (walls should use these):
|
|
/// - Walls use Custom:WallH (horizontal connection) and Custom:WallV (vertical)
|
|
/// - Wall tops connect to face tiles via Custom:WallTop
|
|
/// - Wall faces connect to floor via Open or Custom:Floor
|
|
/// </summary>
|
|
private void GenerateAutoWalls(DungeonLayoutV2 layout)
|
|
{
|
|
int familyId = _activeFamilyId;
|
|
|
|
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");
|
|
|
|
// Helper to check tags
|
|
bool TileHasTag(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 get family-specific wall, fallback to any wall with that tag
|
|
TileDefinition? GetWallByTag(string tag, bool requireFamily = false)
|
|
{
|
|
// First try family-specific
|
|
var familyWall = wallTiles.FirstOrDefault(t =>
|
|
TileHasTag(t, tag) && TileHasTag(t, $"WallFamily_{familyId}"));
|
|
if (familyWall != null) return familyWall;
|
|
|
|
if (requireFamily) return null;
|
|
|
|
// Fallback to any wall with that tag
|
|
return wallTiles.FirstOrDefault(t => TileHasTag(t, tag));
|
|
}
|
|
|
|
// === FACE TILES (adjacent to floor) ===
|
|
var wallNorthFace = GetWallByTag("wall_north") ?? GetWallByTag("north") ?? wallTiles[0];
|
|
var wallSouthFace = GetWallByTag("wall_south") ?? GetWallByTag("south") ?? wallTiles[0];
|
|
var wallEastFace = GetWallByTag("wall_east") ?? GetWallByTag("east") ?? wallTiles[0];
|
|
var wallWestFace = GetWallByTag("wall_west") ?? GetWallByTag("west") ?? wallTiles[0];
|
|
|
|
// === TOP/CAP TILES (one tile further from floor) ===
|
|
var wallNorthTop = GetWallByTag("wall_north_top") ?? wallNorthFace;
|
|
var wallSouthTop = GetWallByTag("wall_south_top") ?? wallSouthFace;
|
|
var wallEastTop = GetWallByTag("wall_east_top") ?? wallEastFace;
|
|
var wallWestTop = GetWallByTag("wall_west_top") ?? wallWestFace;
|
|
|
|
// === OUTER CORNER FACE TILES ===
|
|
var cornerNEFace = GetWallByTag("corner_ne") ?? wallTiles[0];
|
|
var cornerNWFace = GetWallByTag("corner_nw") ?? wallTiles[0];
|
|
var cornerSEFace = GetWallByTag("corner_se") ?? wallTiles[0];
|
|
var cornerSWFace = GetWallByTag("corner_sw") ?? wallTiles[0];
|
|
|
|
// Void variants (corners that face pure void on two sides)
|
|
var cornerNEVoid = GetWallByTag("corner_ne_void") ?? wallTiles.FirstOrDefault(t => TileHasTag(t, "corner_ne") && TileHasTag(t, "void"));
|
|
var cornerNWVoid = GetWallByTag("corner_nw_void") ?? wallTiles.FirstOrDefault(t => TileHasTag(t, "corner_nw") && TileHasTag(t, "void"));
|
|
var cornerSEVoid = GetWallByTag("corner_se_void") ?? wallTiles.FirstOrDefault(t => TileHasTag(t, "corner_se") && TileHasTag(t, "void"));
|
|
var cornerSWVoid = GetWallByTag("corner_sw_void") ?? wallTiles.FirstOrDefault(t => TileHasTag(t, "corner_sw") && TileHasTag(t, "void"));
|
|
|
|
// === OUTER CORNER TOP TILES ===
|
|
var cornerNETop = GetWallByTag("corner_ne_top") ?? cornerNEFace;
|
|
var cornerNWTop = GetWallByTag("corner_nw_top") ?? cornerNWFace;
|
|
var cornerSETop = GetWallByTag("corner_se_top") ?? cornerSEFace;
|
|
var cornerSWTop = GetWallByTag("corner_sw_top") ?? cornerSWFace;
|
|
|
|
// === INNER CORNER TILES (for L-shaped room interiors) ===
|
|
var innerNEFace = GetWallByTag("inner_ne") ?? cornerNEFace;
|
|
var innerNWFace = GetWallByTag("inner_nw") ?? cornerNWFace;
|
|
var innerSEFace = GetWallByTag("inner_se") ?? cornerSEFace;
|
|
var innerSWFace = GetWallByTag("inner_sw") ?? cornerSWFace;
|
|
|
|
var innerNETop = GetWallByTag("inner_ne_top") ?? innerNEFace;
|
|
var innerNWTop = GetWallByTag("inner_nw_top") ?? innerNWFace;
|
|
var innerSETop = GetWallByTag("inner_se_top") ?? innerSEFace;
|
|
var innerSWTop = GetWallByTag("inner_sw_top") ?? innerSWFace;
|
|
|
|
// Helper functions
|
|
TileDefinition PickCornerFace(string corner, bool preferVoid)
|
|
{
|
|
return corner.ToLowerInvariant() switch
|
|
{
|
|
"ne" => (preferVoid ? cornerNEVoid : null) ?? cornerNEFace,
|
|
"nw" => (preferVoid ? cornerNWVoid : null) ?? cornerNWFace,
|
|
"se" => (preferVoid ? cornerSEVoid : null) ?? cornerSEFace,
|
|
"sw" => (preferVoid ? cornerSWVoid : null) ?? cornerSWFace,
|
|
_ => cornerNWFace
|
|
};
|
|
}
|
|
|
|
TileDefinition PickCornerTop(string corner)
|
|
{
|
|
return corner.ToLowerInvariant() switch
|
|
{
|
|
"ne" => cornerNETop,
|
|
"nw" => cornerNWTop,
|
|
"se" => cornerSETop,
|
|
"sw" => cornerSWTop,
|
|
_ => cornerNWTop
|
|
};
|
|
}
|
|
|
|
TileDefinition PickInnerCornerFace(string corner)
|
|
{
|
|
return corner.ToLowerInvariant() switch
|
|
{
|
|
"ne" => innerNEFace,
|
|
"nw" => innerNWFace,
|
|
"se" => innerSEFace,
|
|
"sw" => innerSWFace,
|
|
_ => innerNWFace
|
|
};
|
|
}
|
|
|
|
Console.WriteLine($"[DungeonGenV2] Wall mapping: N={wallNorthFace.Id}, S={wallSouthFace.Id}, E={wallEastFace.Id}, W={wallWestFace.Id}");
|
|
Console.WriteLine($"[DungeonGenV2] Wall tops: N={wallNorthTop.Id}, S={wallSouthTop.Id}, E={wallEastTop.Id}, W={wallWestTop.Id}");
|
|
|
|
// Track placed walls for the second pass
|
|
var wallPositions = new List<(int X, int Y, TileDefinition FaceTile, TileDefinition? TopTile, int TopOffsetX, int TopOffsetY)>();
|
|
|
|
// Helper to check tile types
|
|
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 IsFloorAt(int wx, int wy)
|
|
{
|
|
if (wx < 0 || wx >= MapWidth || wy < 0 || wy >= MapHeight) return false;
|
|
return layout.IsWalkable(wx, wy);
|
|
}
|
|
|
|
bool IsVoidAt(int wx, int wy)
|
|
{
|
|
if (wx < 0 || wx >= MapWidth || wy < 0 || wy >= MapHeight) return true;
|
|
if (layout.IsWalkable(wx, wy)) return false;
|
|
return !IsWallAt(wx, wy) && layout.Tiles[wx, wy] == 0;
|
|
}
|
|
|
|
// === PASS 1: Place wall FACE tiles adjacent to floors ===
|
|
for (int x = 0; x < MapWidth; x++)
|
|
{
|
|
for (int y = 0; y < MapHeight; y++)
|
|
{
|
|
// Skip if already has a tile
|
|
if (layout.Tiles[x, y] != 0) continue;
|
|
|
|
bool floorN = IsFloorAt(x, y - 1);
|
|
bool floorS = IsFloorAt(x, y + 1);
|
|
bool floorE = IsFloorAt(x + 1, y);
|
|
bool floorW = IsFloorAt(x - 1, y);
|
|
|
|
// Only place walls adjacent to floors
|
|
if (!floorN && !floorS && !floorE && !floorW) continue;
|
|
|
|
bool voidN = IsVoidAt(x, y - 1);
|
|
bool voidS = IsVoidAt(x, y + 1);
|
|
bool voidE = IsVoidAt(x + 1, y);
|
|
bool voidW = IsVoidAt(x - 1, y);
|
|
|
|
TileDefinition faceTile;
|
|
TileDefinition? topTile = null;
|
|
int topOffsetX = 0, topOffsetY = 0;
|
|
|
|
// Determine wall type based on adjacent floors
|
|
if (floorN && floorW)
|
|
{
|
|
// Inner corner - floor to NW
|
|
faceTile = PickInnerCornerFace("se");
|
|
topTile = innerSETop;
|
|
topOffsetY = 1; // Top is SOUTH of face (away from floor)
|
|
}
|
|
else if (floorN && floorE)
|
|
{
|
|
faceTile = PickInnerCornerFace("sw");
|
|
topTile = innerSWTop;
|
|
topOffsetY = 1;
|
|
}
|
|
else if (floorS && floorW)
|
|
{
|
|
faceTile = PickInnerCornerFace("ne");
|
|
topTile = innerNETop;
|
|
topOffsetY = -1; // Top is NORTH of face
|
|
}
|
|
else if (floorS && floorE)
|
|
{
|
|
faceTile = PickInnerCornerFace("nw");
|
|
topTile = innerNWTop;
|
|
topOffsetY = -1;
|
|
}
|
|
else if (floorS)
|
|
{
|
|
// Wall facing south (floor is to south)
|
|
faceTile = wallNorthFace;
|
|
topTile = wallNorthTop;
|
|
topOffsetY = -1; // Top is north of face (away from floor)
|
|
}
|
|
else if (floorN)
|
|
{
|
|
// Wall facing north (floor is to north)
|
|
faceTile = wallSouthFace;
|
|
topTile = wallSouthTop;
|
|
topOffsetY = 1; // Top is south of face
|
|
}
|
|
else if (floorE)
|
|
{
|
|
// Wall facing east
|
|
faceTile = wallWestFace;
|
|
topTile = wallWestTop;
|
|
topOffsetX = -1;
|
|
}
|
|
else // floorW
|
|
{
|
|
// Wall facing west
|
|
faceTile = wallEastFace;
|
|
topTile = wallEastTop;
|
|
topOffsetX = 1;
|
|
}
|
|
|
|
wallPositions.Add((x, y, faceTile, topTile, topOffsetX, topOffsetY));
|
|
}
|
|
}
|
|
|
|
// === PASS 2: Place outer corners (diagonal floor adjacency) ===
|
|
for (int x = 1; x < MapWidth - 1; x++)
|
|
{
|
|
for (int y = 1; y < MapHeight - 1; y++)
|
|
{
|
|
if (layout.Tiles[x, y] != 0) continue;
|
|
if (IsFloorAt(x, y)) continue;
|
|
|
|
bool floorNE = IsFloorAt(x + 1, y - 1);
|
|
bool floorNW = IsFloorAt(x - 1, y - 1);
|
|
bool floorSE = IsFloorAt(x + 1, y + 1);
|
|
bool floorSW = IsFloorAt(x - 1, y + 1);
|
|
|
|
// Skip if no diagonal floor
|
|
if (!floorNE && !floorNW && !floorSE && !floorSW) continue;
|
|
|
|
// Skip if already handled by cardinal adjacency
|
|
bool floorN = IsFloorAt(x, y - 1);
|
|
bool floorS = IsFloorAt(x, y + 1);
|
|
bool floorE = IsFloorAt(x + 1, y);
|
|
bool floorW = IsFloorAt(x - 1, y);
|
|
if (floorN || floorS || floorE || floorW) continue;
|
|
|
|
bool voidN = IsVoidAt(x, y - 1);
|
|
bool voidS = IsVoidAt(x, y + 1);
|
|
bool voidE = IsVoidAt(x + 1, y);
|
|
bool voidW = IsVoidAt(x - 1, y);
|
|
|
|
TileDefinition faceTile;
|
|
TileDefinition? topTile = null;
|
|
int topOffsetX = 0, topOffsetY = 0;
|
|
|
|
if (floorSE)
|
|
{
|
|
faceTile = PickCornerFace("nw", preferVoid: voidN && voidW);
|
|
topTile = cornerNWTop;
|
|
topOffsetX = -1; topOffsetY = -1;
|
|
}
|
|
else if (floorSW)
|
|
{
|
|
faceTile = PickCornerFace("ne", preferVoid: voidN && voidE);
|
|
topTile = cornerNETop;
|
|
topOffsetX = 1; topOffsetY = -1;
|
|
}
|
|
else if (floorNE)
|
|
{
|
|
faceTile = PickCornerFace("sw", preferVoid: voidS && voidW);
|
|
topTile = cornerSWTop;
|
|
topOffsetX = -1; topOffsetY = 1;
|
|
}
|
|
else // floorNW
|
|
{
|
|
faceTile = PickCornerFace("se", preferVoid: voidS && voidE);
|
|
topTile = cornerSETop;
|
|
topOffsetX = 1; topOffsetY = 1;
|
|
}
|
|
|
|
wallPositions.Add((x, y, faceTile, topTile, topOffsetX, topOffsetY));
|
|
}
|
|
}
|
|
|
|
// === PASS 3: Actually place all wall tiles ===
|
|
var placedWalls = new HashSet<(int, int)>();
|
|
int faceCount = 0, topCount = 0;
|
|
|
|
foreach (var (x, y, faceTile, topTile, topOffsetX, topOffsetY) in wallPositions)
|
|
{
|
|
// Place face tile
|
|
if (!placedWalls.Contains((x, y)))
|
|
{
|
|
layout.Tiles[x, y] = faceTile.Id;
|
|
if (layout.Walkable != null)
|
|
layout.Walkable[x, y] = false;
|
|
|
|
layout.TileDetails.Add(new PlacedTile
|
|
{
|
|
X = x,
|
|
Y = y,
|
|
TileDefinitionId = faceTile.Id,
|
|
SheetId = faceTile.TileMapSheetId,
|
|
FrameIndex = faceTile.FrameIndex,
|
|
Layer = 2
|
|
});
|
|
|
|
placedWalls.Add((x, y));
|
|
faceCount++;
|
|
}
|
|
|
|
// Place top tile (if we have one and the position is valid)
|
|
if (topTile != null)
|
|
{
|
|
int topX = x + topOffsetX;
|
|
int topY = y + topOffsetY;
|
|
|
|
if (topX >= 0 && topX < MapWidth && topY >= 0 && topY < MapHeight)
|
|
{
|
|
// Only place if the position is empty (void)
|
|
if (layout.Tiles[topX, topY] == 0 && !placedWalls.Contains((topX, topY)))
|
|
{
|
|
layout.Tiles[topX, topY] = topTile.Id;
|
|
if (layout.Walkable != null)
|
|
layout.Walkable[topX, topY] = false;
|
|
|
|
layout.TileDetails.Add(new PlacedTile
|
|
{
|
|
X = topX,
|
|
Y = topY,
|
|
TileDefinitionId = topTile.Id,
|
|
SheetId = topTile.TileMapSheetId,
|
|
FrameIndex = topTile.FrameIndex,
|
|
Layer = 3 // Top tiles on higher layer
|
|
});
|
|
|
|
placedWalls.Add((topX, topY));
|
|
topCount++;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
Console.WriteLine($"[DungeonGenV2] Generated {faceCount} wall faces, {topCount} wall tops");
|
|
}
|
|
|
|
|
|
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)
|
|
{
|
|
// Helper to check if a position is valid for spawning (must be walkable floor)
|
|
bool IsValidSpawnPosition(int x, int y)
|
|
{
|
|
if (x < 0 || x >= MapWidth || y < 0 || y >= MapHeight)
|
|
return false;
|
|
|
|
// Must be walkable
|
|
if (!layout.IsWalkable(x, y))
|
|
return false;
|
|
|
|
// Must have a floor tile (not wall, not empty)
|
|
int tileId = layout.Tiles[x, y];
|
|
if (tileId == 0)
|
|
return false;
|
|
|
|
if (_tileDefinitions.TryGetValue(tileId, out var tileDef))
|
|
{
|
|
// Only spawn on Floor or FloorDecor tiles
|
|
return tileDef.Type == TileType.Floor || tileDef.Type == TileType.FloorDecor;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
// Find a valid spawn position within a room, with retries
|
|
(int x, int y)? FindValidSpawnPosition(DungeonRoomV2 room, int maxAttempts = 20)
|
|
{
|
|
for (int attempt = 0; attempt < maxAttempts; attempt++)
|
|
{
|
|
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));
|
|
|
|
if (IsValidSpawnPosition(x, y))
|
|
return (x, y);
|
|
}
|
|
|
|
// Fallback: scan the room for any valid position
|
|
for (int x = room.X; x < room.X + room.Width; x++)
|
|
{
|
|
for (int y = room.Y; y < room.Y + room.Height; y++)
|
|
{
|
|
if (IsValidSpawnPosition(x, y))
|
|
return (x, y);
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
foreach (var room in rooms)
|
|
{
|
|
if (room.Type == RoomType.Entrance) continue;
|
|
|
|
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++)
|
|
{
|
|
var pos = FindValidSpawnPosition(room);
|
|
if (pos == null)
|
|
{
|
|
Console.WriteLine($"[DungeonGenV2] WARNING: Could not find valid spawn position in room at ({room.X},{room.Y})");
|
|
continue;
|
|
}
|
|
|
|
layout.MobSpawns.Add(new DungeonMobSpawn
|
|
{
|
|
Id = layout.MobSpawns.Count + 1,
|
|
X = pos.Value.x,
|
|
Y = pos.Value.y,
|
|
MobType = room.Type == RoomType.Boss ? DungeonMobSpawnType.Boss : DungeonMobSpawnType.Normal,
|
|
RoomIndex = rooms.IndexOf(room)
|
|
});
|
|
}
|
|
|
|
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++)
|
|
{
|
|
var pos = FindValidSpawnPosition(room);
|
|
if (pos == null)
|
|
{
|
|
Console.WriteLine($"[DungeonGenV2] WARNING: Could not find valid chest position in room at ({room.X},{room.Y})");
|
|
continue;
|
|
}
|
|
|
|
layout.ChestSpawns.Add(new DungeonChestSpawn
|
|
{
|
|
Id = layout.ChestSpawns.Count + 1,
|
|
X = pos.Value.x,
|
|
Y = pos.Value.y,
|
|
ChestType = room.Type == RoomType.Boss ? DungeonChestType.Boss : DungeonChestType.Normal,
|
|
RoomIndex = rooms.IndexOf(room)
|
|
});
|
|
}
|
|
}
|
|
|
|
layout.TotalMobs = layout.MobSpawns.Count;
|
|
layout.TotalChests = layout.ChestSpawns.Count;
|
|
Console.WriteLine($"[DungeonGenV2] Generated {layout.TotalMobs} mob spawns, {layout.TotalChests} chest spawns");
|
|
}
|
|
|
|
private static Dictionary<string, HashSet<string>> ParseSocketTypes(HashSet<string> tags)
|
|
{
|
|
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;
|
|
|
|
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
|
|
{
|
|
var parts = cleaned.Split('_', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
|
if (parts.Length == 2)
|
|
{
|
|
left = parts[0];
|
|
type = parts[1];
|
|
}
|
|
}
|
|
|
|
if (left.Length < "Socket".Length + 1) continue;
|
|
|
|
var dir = left.Substring("Socket".Length);
|
|
if (!(dir is "N" or "E" or "S" or "W")) continue;
|
|
|
|
map[dir].Add(string.IsNullOrWhiteSpace(type) ? "" : type);
|
|
}
|
|
|
|
return map;
|
|
}
|
|
|
|
private TileDefinition? PickRandomFloorTile(
|
|
DungeonLayoutV2 layout,
|
|
int x, int y,
|
|
int familyId,
|
|
double varianceChance = 0.25)
|
|
{
|
|
var requiredSocketTags = BuildRequiredSocketTags(layout, x, y);
|
|
|
|
bool requiresTyped = requiredSocketTags.Any(t => t.Contains('='));
|
|
|
|
string primaryTag = $"TileBaseCore_{familyId}";
|
|
string varianceTag = $"TileBase_{familyId}";
|
|
|
|
List<TileDefinition> primary = _tileDefinitions.Values
|
|
.Where(t => t.Type == TileType.Floor)
|
|
.Where(t => HasTag(t, primaryTag))
|
|
.Where(t => HasAllTags(t, requiredSocketTags))
|
|
.Where(t => CompatibleWithPlacedNeighbors(layout, x, y, t))
|
|
.ToList();
|
|
|
|
List<TileDefinition> variance = _tileDefinitions.Values
|
|
.Where(t => t.Type == TileType.Floor)
|
|
.Where(t => HasTag(t, varianceTag))
|
|
.Where(t => HasAllTags(t, requiredSocketTags))
|
|
.Where(t => CompatibleWithPlacedNeighbors(layout, x, y, t))
|
|
.ToList();
|
|
|
|
if (primary.Count == 0 && variance.Count == 0)
|
|
{
|
|
if (requiresTyped)
|
|
return null;
|
|
|
|
primary = _tileDefinitions.Values
|
|
.Where(t => t.Type == TileType.Floor)
|
|
.Where(t => HasTag(t, primaryTag))
|
|
.Where(t => CompatibleWithPlacedNeighbors(layout, x, y, t))
|
|
.ToList();
|
|
|
|
variance = _tileDefinitions.Values
|
|
.Where(t => t.Type == TileType.Floor)
|
|
.Where(t => HasTag(t, varianceTag))
|
|
.Where(t => CompatibleWithPlacedNeighbors(layout, x, y, t))
|
|
.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[_rng.Next(pool.Count)];
|
|
}
|
|
|
|
|
|
private bool CompatibleWithPlacedNeighbors(DungeonLayoutV2 layout, int x, int y, TileDefinition t)
|
|
{
|
|
if (y > 0 && HasPlacedTile(layout, x, y - 1))
|
|
{
|
|
int nId = layout.Tiles[x, y - 1];
|
|
if (!EdgeSocketsCompatible(t.Id, "N", nId, "S"))
|
|
return false;
|
|
}
|
|
|
|
if (x > 0 && HasPlacedTile(layout, x - 1, y))
|
|
{
|
|
int wId = layout.Tiles[x - 1, y];
|
|
if (!EdgeSocketsCompatible(t.Id, "W", wId, "E"))
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
private static string OppDir(string dir) => dir switch
|
|
{
|
|
"N" => "S",
|
|
"S" => "N",
|
|
"E" => "W",
|
|
"W" => "E",
|
|
_ => dir
|
|
};
|
|
|
|
private bool NeighborRequiresTyped(int neighborTileId, string neighborDir)
|
|
{
|
|
if (!_tileSocketTypes.TryGetValue(neighborTileId, out var sockets)) return false;
|
|
if (!sockets.TryGetValue(neighborDir, out var types)) return false;
|
|
|
|
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;
|
|
|
|
var typed = types.FirstOrDefault(t => !string.IsNullOrEmpty(t));
|
|
if (!string.IsNullOrEmpty(typed))
|
|
return $"Socket{ourDir}={typed}";
|
|
|
|
if (types.Contains(""))
|
|
return $"Socket{ourDir}";
|
|
|
|
return null;
|
|
}
|
|
|
|
private List<string> BuildRequiredSocketTags(DungeonLayoutV2 layout, int x, int y)
|
|
{
|
|
var req = new List<string>();
|
|
|
|
if (y > 0 && HasPlacedTile(layout, x, y - 1))
|
|
{
|
|
int nid = layout.Tiles[x, y - 1];
|
|
var r = GetRequiredSocketTagFromNeighbor(nid, neighborEdgeFacingUs: "S", ourDir: "N");
|
|
if (r != null) req.Add(r);
|
|
}
|
|
|
|
if (x > 0 && HasPlacedTile(layout, 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
|
|
};
|
|
|
|
private void ChooseDungeonFamilyFromSheet()
|
|
{
|
|
if (_tileDefinitions.Count == 0) { _activeFamilyId = 1; return; }
|
|
|
|
var families = new HashSet<int>();
|
|
|
|
foreach (var t in _tileDefinitions.Values)
|
|
{
|
|
if (t.Type != TileType.Floor) continue;
|
|
if (!_tileTags.TryGetValue(t.Id, out var tags)) continue;
|
|
|
|
foreach (var tag in tags)
|
|
{
|
|
if (tag.StartsWith("TileBaseCore_", StringComparison.OrdinalIgnoreCase) &&
|
|
int.TryParse(tag.Substring("TileBaseCore_".Length), out var fam))
|
|
{
|
|
families.Add(fam);
|
|
}
|
|
}
|
|
}
|
|
|
|
_activeFamilyId = families.Count > 0 ? families.ElementAt(_rng.Next(families.Count)) : 1;
|
|
Console.WriteLine($"[DungeonGenV2] Chosen dungeon tile familyId={_activeFamilyId}");
|
|
}
|
|
|
|
private bool EdgeSocketsCompatible(int aId, string aEdge, int bId, string bEdge)
|
|
{
|
|
// If using strict column-based sockets, delegate to that
|
|
if (_useStrictSockets)
|
|
{
|
|
return AreSocketsCompatibleStrict(aId, aEdge, bId, bEdge);
|
|
}
|
|
|
|
// Legacy tag-based socket compatibility
|
|
if (!_tileSocketTypes.TryGetValue(aId, out var aMap)) return true;
|
|
if (!_tileSocketTypes.TryGetValue(bId, out var bMap)) return true;
|
|
|
|
aMap.TryGetValue(aEdge, out var aTypes);
|
|
bMap.TryGetValue(bEdge, out var bTypes);
|
|
|
|
aTypes ??= new HashSet<string>();
|
|
bTypes ??= new HashSet<string>();
|
|
|
|
bool aMissing = aTypes.Count == 0 && !aMap.ContainsKey(aEdge);
|
|
bool bMissing = bTypes.Count == 0 && !bMap.ContainsKey(bEdge);
|
|
|
|
bool aClosed = aTypes.Contains("Closed");
|
|
bool bClosed = bTypes.Contains("Closed");
|
|
|
|
if (aClosed && bClosed) return true;
|
|
if (aClosed || bClosed) return false;
|
|
if (aMissing || bMissing) return false;
|
|
|
|
bool aTyped = aTypes.Any(t => !string.IsNullOrEmpty(t) && t != "Closed");
|
|
bool bTyped = bTypes.Any(t => !string.IsNullOrEmpty(t) && t != "Closed");
|
|
|
|
if (aTyped || bTyped)
|
|
{
|
|
var aTypedSet = aTypes.Where(t => !string.IsNullOrEmpty(t) && t != "Closed").ToHashSet(StringComparer.OrdinalIgnoreCase);
|
|
var bTypedSet = bTypes.Where(t => !string.IsNullOrEmpty(t) && t != "Closed").ToHashSet(StringComparer.OrdinalIgnoreCase);
|
|
return aTypedSet.Overlaps(bTypedSet);
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|