Trying GPT Dungeon idea

This commit is contained in:
dingo
2025-12-30 14:10:17 -05:00
parent c35a9b5034
commit 7483608bb5
2 changed files with 788 additions and 271 deletions
+473 -271
View File
@@ -17,6 +17,9 @@ public class DungeonGeneratorV2
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;
@@ -57,27 +60,37 @@ public class DungeonGeneratorV2
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();
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;
return floors.FirstOrDefault();
}
private RoomTemplate? SelectHallwayTemplate(HashSet<string> requiredTags, string direction)
@@ -388,6 +401,7 @@ public class DungeonGeneratorV2
.ToListAsync();
_tileDefinitions = tiles.ToDictionary(t => t.Id);
_tagIndex = new TileTagIndex(_tileDefinitions.Values);
_defaultSheet = tiles.FirstOrDefault()?.TileMapSheet;
Console.WriteLine($"[DungeonGenV2] Loaded {tiles.Count} tile definitions from templates");
}
@@ -920,157 +934,356 @@ public class DungeonGeneratorV2
/// <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 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)
if (_tagIndex == null)
{
Console.WriteLine("[DungeonGenV2] No wall tiles found - skipping auto-wall generation");
Console.WriteLine("[DungeonGenV2] TagIndex missing - skipping auto-wall generation");
return;
}
Console.WriteLine($"[DungeonGenV2] Found {wallTiles.Count} wall tiles for auto-wall generation");
foreach (var wt in wallTiles)
// We only place *structural* walls here (solid). Add a later pass if you want trim/decor replacement.
var biome = DefaultBiome;
bool InBounds(int x, int y) => x >= 0 && x < MapWidth && y >= 0 && y < MapHeight;
bool IsWallAt(int x, int y)
{
Console.WriteLine($" - {wt.Id}: {wt.Name} (tags: {wt.Tags ?? "none"})");
if (!InBounds(x, y)) return false;
var id = layout.Tiles[x, y];
if (id <= 0) return false;
return _tagIndex.IsKind(id, TileKind.Wall);
}
// 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)
bool IsOutsideAt(int x, int y)
{
if (string.IsNullOrWhiteSpace(t.Tags)) return false;
return t.Tags
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Any(s => s.Equals(tag, StringComparison.OrdinalIgnoreCase));
// "Outside" means: out of bounds OR not walkable AND not a wall
if (!InBounds(x, y)) return true;
if (layout.IsWalkable(x, y)) return false;
return !IsWallAt(x, y);
}
// 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.
// Index existing wall visuals so we can update/replace without duplicates
var wallDetailIndex = new Dictionary<(int X, int Y), int>();
for (int i = 0; i < layout.TileDetails.Count; i++)
{
@@ -1079,47 +1292,27 @@ public class DungeonGeneratorV2
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)
void PlaceWall(int x, int y, TileDefinition tdef)
{
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;
}
layout.Tiles[x, y] = tdef.Id;
if (layout.Walkable != null) layout.Walkable[x, y] = false;
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))
if (wallDetailIndex.TryGetValue((x, y), out var idx))
{
var d = layout.TileDetails[existingIdx];
var d = layout.TileDetails[idx];
d.TileDefinitionId = tdef.Id;
d.SheetId = tdef.TileMapSheetId;
d.FrameIndex = tdef.FrameIndex;
layout.TileDetails[existingIdx] = d;
d.Layer = 2;
layout.TileDetails[idx] = d;
}
else
{
wallDetailIndex[(wx, wy)] = layout.TileDetails.Count;
wallDetailIndex[(x, y)] = layout.TileDetails.Count;
layout.TileDetails.Add(new PlacedTile
{
X = wx,
Y = wy,
X = x,
Y = y,
TileDefinitionId = tdef.Id,
SheetId = tdef.TileMapSheetId,
FrameIndex = tdef.FrameIndex,
@@ -1128,12 +1321,92 @@ public class DungeonGeneratorV2
}
}
TileDefinition PickEdge(string dir, bool preferVoidVariant)
{
// Require: wall + edge + direction
// Prefer: solid
// Forbid: door/connector/decorative/trim by default
var required = new[] { "wall", "edge", dir };
var prefer = new[] { "solid", "stone" };
var forbid = preferVoidVariant
? new[] { "door", "doorway", "connector", "decorative", "trim" } // allow void/boundary variants if tagged, but don't force it
: new[] { "door", "doorway", "connector", "decorative", "trim", "void", "empty", "boundary" };
var t = _tagIndex!.FindBestWall(required, prefer: prefer, forbid: forbid, allowTrim: false, allowVoidBoundary: preferVoidVariant, biome: biome);
return t ?? _tileDefinitions.Values.First(td => td.Id > 0); // should never happen, but keeps you from crashing
}
TileDefinition PickCorner(string cornerTag, bool preferVoidVariant)
{
// Require: wall + corner_xx
var required = new[] { "wall", cornerTag };
var prefer = new[] { "solid", "stone" };
var forbid = preferVoidVariant
? new[] { "door", "doorway", "connector", "decorative", "trim" }
: new[] { "door", "doorway", "connector", "decorative", "trim", "void", "empty", "boundary" };
var t = _tagIndex!.FindBestWall(required, prefer: prefer, forbid: forbid, allowTrim: false, allowVoidBoundary: preferVoidVariant, biome: biome);
return t ?? PickEdge("north", preferVoidVariant: false);
}
// MAIN PASS: fill void cells adjacent to walkable with edge/corner walls
int placed = 0;
for (int x = 0; x < MapWidth; x++)
{
for (int y = 0; y < MapHeight; y++)
{
// Only place into empty/void cells
if (layout.Tiles[x, y] != 0) continue;
if (layout.IsWalkable(x, y)) continue;
bool floorN = InBounds(x, y - 1) && layout.IsWalkable(x, y - 1);
bool floorS = InBounds(x, y + 1) && layout.IsWalkable(x, y + 1);
bool floorE = InBounds(x + 1, y) && layout.IsWalkable(x + 1, y);
bool floorW = InBounds(x - 1, y) && layout.IsWalkable(x - 1, y);
if (!(floorN || floorS || floorE || floorW)) continue;
// Outside check for corner void 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);
TileDefinition wall;
// Corners first (interior corner based on two orthogonal floor neighbors)
if (floorN && floorW) wall = PickCorner("corner_nw", preferVoidVariant: (vS && vE));
else if (floorN && floorE) wall = PickCorner("corner_ne", preferVoidVariant: (vS && vW));
else if (floorS && floorW) wall = PickCorner("corner_sw", preferVoidVariant: (vN && vE));
else if (floorS && floorE) wall = PickCorner("corner_se", preferVoidVariant: (vN && vW));
else
{
// Edges
// NOTE: Direction tag semantics vary by tileset. This mapping assumes dir tag refers to the wall's "side"/edge.
// If your walls look flipped, swap these:
//
// If floor is NORTH of this void cell, the wall tile is on the SOUTH edge of the floor, and might be tagged "south".
// If floor is SOUTH of this void cell, the wall tile might be tagged "north".
//
if (floorS) wall = PickEdge("north", preferVoidVariant: false);
else if (floorN) wall = PickEdge("south", preferVoidVariant: false);
else if (floorE) wall = PickEdge("west", preferVoidVariant: false);
else wall = PickEdge("east", preferVoidVariant: false);
}
PlaceWall(x, y, wall);
placed++;
}
}
// DIAGONAL CAP PASS:
// Fill "bite marks" where void sees walkable only diagonally but has nearby wall support.
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.Tiles[x, y] != 0) continue;
if (layout.IsWalkable(x, y)) continue;
bool floorNE = layout.IsWalkable(x + 1, y - 1);
@@ -1146,101 +1419,30 @@ public class DungeonGeneratorV2
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.
if (!(wallN || wallS || wallE || wallW)) continue;
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)));
}
}
TileDefinition? cap = null;
// 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;
if (floorSE && (wallS || wallE)) cap = PickCorner("corner_se", preferVoidVariant: (vN && vW));
else if (floorSW && (wallS || wallW)) cap = PickCorner("corner_sw", preferVoidVariant: (vN && vE));
else if (floorNE && (wallN || wallE)) cap = PickCorner("corner_ne", preferVoidVariant: (vS && vW));
else if (floorNW && (wallN || wallW)) cap = PickCorner("corner_nw", preferVoidVariant: (vS && vE));
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))
if (cap != null)
{
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
});
PlaceWall(x, y, cap);
placed++;
}
}
}
Console.WriteLine($"[DungeonGenV2] Generated {wallPositions.Count} auto-walls");
Console.WriteLine($"[DungeonGenV2] Generated {placed} auto-walls (tag-driven)");
}
private RoomTemplate? SelectWeightedTemplate(List<RoomTemplate> templates)
{
if (templates.Count == 0) return null;
+315
View File
@@ -0,0 +1,315 @@
// DungeonGeneratorV2.TagDrivenTiles.cs
// Drop this file next to DungeonGeneratorV2 and wire in the 2 small call sites noted below.
// This adds a fast tag index + robust tile picking (and avoids "Void counted as Wall" issues when DB types are messy).
using DataServer.Data.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Server.Game.Dungeon
{
/// <summary>
/// Normalized tag info: supports comma/space separated tokens + key:value tags.
/// Examples:
/// - "biome:dungeon,corner_ne,north,wall" => Tokens={"corner_ne","north","wall"}, KV["biome"]="dungeon"
/// - "frame:10,sheet:3" => KV["frame"]="10", KV["sheet"]="3"
/// </summary>
internal sealed class TagInfo
{
public readonly HashSet<string> Tokens;
public readonly Dictionary<string, string> KV;
public TagInfo(HashSet<string> tokens, Dictionary<string, string> kv)
{
Tokens = tokens;
KV = kv;
}
public bool Has(string token) => Tokens.Contains(token);
public bool TryGet(string key, out string value) => KV.TryGetValue(key, out value);
}
internal static class TagParser
{
// Split on commas and whitespace. Your dataset is comma-delimited, but this makes it resilient.
private static readonly char[] _seps = new[] { ',', ' ', '\t', '\r', '\n' };
public static TagInfo Parse(string? tags)
{
var tokens = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var kv = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrWhiteSpace(tags))
return new TagInfo(tokens, kv);
foreach (var raw in tags.Split(_seps, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (string.IsNullOrWhiteSpace(raw)) continue;
var s = raw.Trim();
var idx = s.IndexOf(':');
if (idx > 0 && idx < s.Length - 1)
{
var k = s[..idx].Trim();
var v = s[(idx + 1)..].Trim();
if (k.Length > 0 && v.Length > 0)
kv[k] = v;
continue;
}
tokens.Add(s);
}
return new TagInfo(tokens, kv);
}
}
internal enum TileKind
{
Unknown = 0,
Void,
Floor,
Wall,
Door,
Decorative
}
/// <summary>
/// Builds a fast index over TileDefinitions using TAGS as truth (not DB TileType),
/// because your sample shows "Void" rows with Type=1 which can collide with "Wall".
/// </summary>
internal sealed class TileTagIndex
{
public readonly Dictionary<int, TagInfo> TagById = new();
public readonly Dictionary<int, TileKind> KindById = new();
public readonly List<TileDefinition> Floors = new();
public readonly List<TileDefinition> Walls = new();
public readonly List<TileDefinition> Doors = new();
public readonly List<TileDefinition> Decorative = new();
// Convenience: cached candidates for wall variants
private readonly List<TileDefinition> _solidWalls = new();
private readonly List<TileDefinition> _trimWalls = new();
private readonly List<TileDefinition> _voidWalls = new(); // wall-ish void boundary (if you ever want them)
public TileTagIndex(IEnumerable<TileDefinition> tiles)
{
foreach (var t in tiles)
{
var info = TagParser.Parse(t.Tags);
TagById[t.Id] = info;
var kind = Classify(t, info);
KindById[t.Id] = kind;
switch (kind)
{
case TileKind.Floor:
Floors.Add(t);
break;
case TileKind.Wall:
Walls.Add(t);
if (info.Has("trim")) _trimWalls.Add(t);
else _solidWalls.Add(t);
if (info.Has("void") || info.Has("boundary") || info.Has("empty")) _voidWalls.Add(t);
break;
case TileKind.Door:
Doors.Add(t);
break;
case TileKind.Decorative:
Decorative.Add(t);
break;
}
}
}
private static TileKind Classify(TileDefinition t, TagInfo info)
{
// Tag-driven classification (more reliable than DB enum when data is inconsistent).
// Priority: door > void > decorative > floor > wall.
if (info.Has("door") || info.Has("doorway") || info.Has("connector"))
return TileKind.Door;
if (info.Has("void") || info.Has("empty"))
return TileKind.Void;
if (info.Has("decorative") || info.Has("decor"))
return TileKind.Decorative;
// Your floor tiles consistently include "floor" and/or "walkable"
if (info.Has("floor") || info.Has("walkable") || t.IsWalkable)
return TileKind.Floor;
if (info.Has("wall") || info.Has("solid") || info.Has("boundary") || info.Has("trim"))
return TileKind.Wall;
return TileKind.Unknown;
}
public TagInfo Tags(TileDefinition t) => TagById.TryGetValue(t.Id, out var ti) ? ti : TagParser.Parse(t.Tags);
public bool IsKind(int tileId, TileKind kind) => KindById.TryGetValue(tileId, out var k) && k == kind;
public IEnumerable<TileDefinition> WallCandidates(bool allowTrim, bool allowVoidBoundary)
{
// Default: prefer solid walls; optionally allow trim.
// "allowVoidBoundary" is off by default; those are the void/boundary wall-ish tiles.
var list = new List<TileDefinition>(_solidWalls);
if (allowTrim) list.AddRange(_trimWalls);
if (allowVoidBoundary) list.AddRange(_voidWalls);
return list;
}
public TileDefinition? FindBestFloor(HashSet<string> requiredTokens, string? biome = null)
{
if (Floors.Count == 0) return null;
// Hard forbids for floors
static bool FloorForbid(TagInfo ti) =>
ti.Has("void") || ti.Has("boundary") || ti.Has("door") || ti.Has("doorway") || ti.Has("connector") ||
ti.Has("decorative") || ti.Has("trim") || ti.Has("wall");
TileDefinition? best = null;
int bestScore = int.MinValue;
foreach (var f in Floors)
{
var ti = Tags(f);
if (biome != null && ti.TryGet("biome", out var b) && !b.Equals(biome, StringComparison.OrdinalIgnoreCase))
continue;
if (FloorForbid(ti)) continue;
// Score:
// +100 per required token present (but ignore frame/sheet metadata)
// +10 for "stone" if required includes "stone" (already handled by required token)
// +2 for not being "edge" unless requested
int score = 0;
foreach (var req in requiredTokens)
{
// ignore metadata-like tokens
if (req.StartsWith("frame:", StringComparison.OrdinalIgnoreCase)) continue;
if (req.StartsWith("sheet:", StringComparison.OrdinalIgnoreCase)) continue;
if (req.StartsWith("biome:", StringComparison.OrdinalIgnoreCase)) continue;
if (ti.Has(req)) score += 100;
else score -= 50; // soft penalty; we still allow partial matches
}
// Prefer "plain" floor tiles unless you asked for edges.
if (!requiredTokens.Contains("edge")) score += ti.Has("edge") ? -5 : +2;
// Prefer walkable
if (f.IsWalkable) score += 5;
if (score > bestScore)
{
best = f;
bestScore = score;
}
}
return best ?? Floors[0];
}
/// <summary>
/// Find the best wall tile matching the requested features.
/// Typically you pass: corner_ne + (optional) void + (optional) trim/solid + (optional) north/east/west/south.
/// </summary>
public TileDefinition? FindBestWall(
IEnumerable<string> required,
IEnumerable<string>? prefer = null,
IEnumerable<string>? forbid = null,
bool allowTrim = false,
bool allowVoidBoundary = false,
string? biome = null)
{
var req = required?.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()).ToArray() ?? Array.Empty<string>();
var pref = prefer?.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()).ToArray() ?? Array.Empty<string>();
var forb = forbid?.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()).ToArray() ?? Array.Empty<string>();
var candidates = WallCandidates(allowTrim, allowVoidBoundary);
TileDefinition? best = null;
int bestScore = int.MinValue;
foreach (var w in candidates)
{
var ti = Tags(w);
if (biome != null && ti.TryGet("biome", out var b) && !b.Equals(biome, StringComparison.OrdinalIgnoreCase))
continue;
// Never pick doors/decoration as structural walls
if (ti.Has("door") || ti.Has("doorway") || ti.Has("connector") || ti.Has("decorative"))
continue;
// Forbid list
bool bad = false;
foreach (var f in forb)
{
if (ti.Has(f)) { bad = true; break; }
}
if (bad) continue;
int score = 0;
// Required: strong positive if present, strong negative if missing
foreach (var r in req)
{
if (ti.Has(r)) score += 200;
else score -= 200;
}
// Preferred: small bump
foreach (var p in pref)
{
if (ti.Has(p)) score += 20;
}
// Prefer "wall"+"solid" unless trim is explicitly wanted
if (!allowTrim) score += ti.Has("trim") ? -50 : +10;
score += ti.Has("solid") ? +10 : 0;
if (score > bestScore)
{
best = w;
bestScore = score;
}
}
return best;
}
public TileDefinition? FindBestDoor(string direction, string? biome = null)
{
if (Doors.Count == 0) return null;
var dir = direction.Trim().ToLowerInvariant();
TileDefinition? best = null;
int bestScore = int.MinValue;
foreach (var d in Doors)
{
var ti = Tags(d);
if (biome != null && ti.TryGet("biome", out var b) && !b.Equals(biome, StringComparison.OrdinalIgnoreCase))
continue;
int score = 0;
if (ti.Has("door")) score += 50;
if (ti.Has("doorway")) score += 20;
if (ti.Has(dir)) score += 40; // north/south etc
if (score > bestScore)
{
best = d;
bestScore = score;
}
}
return best;
}
}
}