Tile Change

This commit is contained in:
dingo
2026-01-09 16:49:50 -05:00
parent 5feb284dc0
commit b6f4a7e555
+161 -320
View File
@@ -938,39 +938,23 @@ public class DungeonGeneratorV3
if (worldX >= 0 && worldX < MapWidth && worldY >= 0 && worldY < MapHeight) if (worldX >= 0 && worldX < MapWidth && worldY >= 0 && worldY < MapHeight)
{ {
// Find or create tile definition // Ensure the sheet is loaded for client rendering
var tileDef = _tileDefinitions.Values EnsureSheetLoaded(t.SheetId);
.FirstOrDefault(td => td.TileMapSheetId == t.SheetId && td.FrameIndex == t.FrameIndex);
if (tileDef != null) // Room template tiles are assumed walkable (they define the room interior)
// Walls will be placed around them by PlaceWallTiles
layout.Tiles[worldX, worldY] = 1; // Non-zero to indicate tile is placed
layout.Walkable[worldX, worldY] = true;
layout.TileDetails.Add(new PlacedTile
{ {
layout.Tiles[worldX, worldY] = tileDef.Id; X = worldX,
layout.Walkable[worldX, worldY] = tileDef.IsWalkable; Y = worldY,
TileDefinitionId = 0, // No TileDefinition - using template directly
layout.TileDetails.Add(new PlacedTile SheetId = t.SheetId,
{ FrameIndex = t.FrameIndex,
X = worldX, Layer = 0
Y = worldY, });
TileDefinitionId = tileDef.Id,
SheetId = t.SheetId,
FrameIndex = t.FrameIndex,
Layer = 0
});
}
else
{
// No tile definition, just mark walkable and store sheet/frame
layout.Walkable[worldX, worldY] = true;
layout.TileDetails.Add(new PlacedTile
{
X = worldX,
Y = worldY,
TileDefinitionId = 0,
SheetId = t.SheetId,
FrameIndex = t.FrameIndex,
Layer = 0
});
}
} }
} }
} }
@@ -1201,8 +1185,8 @@ public class DungeonGeneratorV3
/// Fill all walkable cells with floor tiles. /// Fill all walkable cells with floor tiles.
/// ///
/// For each walkable cell without a tile: /// For each walkable cell without a tile:
/// 1. Call SelectFloorTile to get appropriate tile (with socket matching) /// 1. Call SelectFloorTile to get appropriate template (with socket matching)
/// 2. Set layout.Tiles and add to TileDetails /// 2. Parse TilesJson from template and add to TileDetails
/// </summary> /// </summary>
private void FillFloorTiles(DungeonLayoutV2 layout) private void FillFloorTiles(DungeonLayoutV2 layout)
{ {
@@ -1219,9 +1203,8 @@ public class DungeonGeneratorV3
LogTileTemplate(t, "Floor"); LogTileTemplate(t, "Floor");
} }
TileDefinition? firstSelectedTile = null; bool loggedFirst = false;
int tileCount = 0; int tileCount = 0;
int fallbackCount = 0;
for (int y = 0; y < MapHeight; y++) for (int y = 0; y < MapHeight; y++)
{ {
@@ -1230,210 +1213,151 @@ public class DungeonGeneratorV3
// Only fill walkable cells that don't have tiles yet // Only fill walkable cells that don't have tiles yet
if (layout.Walkable[x, y] && layout.Tiles[x, y] == 0) if (layout.Walkable[x, y] && layout.Tiles[x, y] == 0)
{ {
var tile = SelectFloorTile(x, y, layout, out bool usedFallback); var result = SelectFloorTemplate(x, y, layout);
if (tile != null) if (result != null)
{ {
if (firstSelectedTile == null) if (!loggedFirst)
{ {
firstSelectedTile = tile; loggedFirst = true;
Log($"First selected floor tile: ID={tile.Id}, Name='{tile.Name}', Sheet={tile.TileMapSheetId}, Frame={tile.FrameIndex}"); Log($"First selected floor: Template='{result.Value.TemplateName}', Sheet={result.Value.SheetId}, Frame={result.Value.FrameIndex}");
} }
layout.Tiles[x, y] = tile.Id; layout.Tiles[x, y] = result.Value.TemplateId; // Use template ID for tracking
layout.TileDetails.Add(new PlacedTile layout.TileDetails.Add(new PlacedTile
{ {
X = x, X = x,
Y = y, Y = y,
TileDefinitionId = tile.Id, TileDefinitionId = 0, // No TileDefinition - using template directly
SheetId = tile.TileMapSheetId, SheetId = result.Value.SheetId,
FrameIndex = tile.FrameIndex, FrameIndex = result.Value.FrameIndex,
Layer = 0 Layer = 0
}); });
tileCount++; tileCount++;
if (usedFallback) fallbackCount++;
if (LogEveryTile) if (LogEveryTile)
{ {
Log($" Floor ({x},{y}): TileDef={tile.Id}, Sheet={tile.TileMapSheetId}, Frame={tile.FrameIndex}{(usedFallback ? " [FALLBACK]" : "")}"); Log($" Floor ({x},{y}): Template='{result.Value.TemplateName}', Sheet={result.Value.SheetId}, Frame={result.Value.FrameIndex}");
} }
} }
} }
} }
} }
Log($"Placed {tileCount} floor tiles ({fallbackCount} used fallback)"); Log($"Placed {tileCount} floor tiles");
} }
/// <summary> /// <summary>
/// Select a floor tile for the given position. /// Result of selecting a tile template - contains all info needed for placement.
///
/// SELECTION PROCESS (with socket matching):
/// 1. If _floorTemplates has templates:
/// a. Filter to socket-compatible templates (if UseSocketMatching)
/// b. Try each template in weighted order until one resolves to a TileDefinition
/// c. Try template.PrimaryTileDefinitionId first
/// d. If no PrimaryTileDefinitionId, parse template.TilesJson
/// e. Track placed template for future socket matching
/// 2. FALLBACK: Return first walkable TileDefinition (ordered by ID)
/// </summary> /// </summary>
private TileDefinition? SelectFloorTile(int x, int y, DungeonLayoutV2 layout, out bool usedFallback) private struct TemplateSelectionResult
{ {
usedFallback = false; public int TemplateId;
public string TemplateName;
// First try to use floor templates public int SheetId;
if (_floorTemplates.Count > 0) public int FrameIndex;
{
// Get socket-compatible templates
var compatibleTemplates = GetCompatibleTemplates(_floorTemplates, x, y, layout);
// Shuffle templates by weight, then try each until one resolves
var shuffledTemplates = ShuffleByWeight(compatibleTemplates);
foreach (var template in shuffledTemplates)
{
var tileDef = TryResolveFloorTemplate(template, x, y, compatibleTemplates.Count);
if (tileDef != null)
{
// Track placement for socket matching
_placedTemplates[$"{x},{y}"] = template.Id;
if (!UsedFloorTemplates.Contains(template.Name))
UsedFloorTemplates.Add(template.Name);
return tileDef;
}
}
// No template resolved - log warning
Log($"SelectFloorTile({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates could resolve to a TileDefinition!");
}
// FALLBACK: use the FIRST walkable tile consistently (not random)
usedFallback = true;
var walkableTiles = _tileDefinitions.Values.Where(t => t.IsWalkable).OrderBy(t => t.Id).ToList();
if (walkableTiles.Count > 0)
{
LogVerbose($"SelectFloorTile({x},{y}): FALLBACK TileDef {walkableTiles[0].Id} '{walkableTiles[0].Name}'");
return walkableTiles[0];
}
LogVerbose($"SelectFloorTile({x},{y}): No walkable tiles found!");
return _tileDefinitions.Values.FirstOrDefault();
} }
/// <summary> /// <summary>
/// Try to resolve a floor template to a TileDefinition. /// Select a floor template for the given position.
/// Returns null if the template cannot be resolved. /// Returns the template's tile placement info directly from TilesJson.
/// </summary> /// </summary>
private TileDefinition? TryResolveFloorTemplate(TileTemplate template, int x, int y, int compatibleCount) private TemplateSelectionResult? SelectFloorTemplate(int x, int y, DungeonLayoutV2 layout)
{ {
LogVerbose($"SelectFloorTile({x},{y}): Trying template '{template.Name}' (ID={template.Id}) [Compatible: {compatibleCount}/{_floorTemplates.Count}]"); if (_floorTemplates.Count == 0)
// Method 1: Try PrimaryTileDefinitionId first
if (template.PrimaryTileDefinitionId.HasValue)
{ {
LogVerbose($" Trying PrimaryTileDefinitionId: {template.PrimaryTileDefinitionId.Value}"); LogVerbose($"SelectFloorTemplate({x},{y}): No floor templates available!");
if (_tileDefinitions.TryGetValue(template.PrimaryTileDefinitionId.Value, out var tileDef)) return null;
{
LogVerbose($" -> Found TileDef {tileDef.Id} '{tileDef.Name}'");
return tileDef;
}
LogVerbose($" -> NOT FOUND in _tileDefinitions!");
} }
// Method 2: Try to parse TilesJson for the template // Get socket-compatible templates
if (!string.IsNullOrEmpty(template.TilesJson)) var compatibleTemplates = GetCompatibleTemplates(_floorTemplates, x, y, layout);
{
LogVerbose($" Trying TilesJson: {template.TilesJson}");
try
{
var tiles = JsonSerializer.Deserialize<List<TemplateTilePlacement>>(template.TilesJson, _jsonOptions);
if (tiles == null)
{
LogVerbose($" -> Deserialized to NULL!");
}
else if (tiles.Count == 0)
{
LogVerbose($" -> Deserialized to EMPTY list!");
}
else
{
var first = tiles[0];
LogVerbose($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}");
var match = _tileDefinitions.Values
.FirstOrDefault(t => t.TileMapSheetId == first.SheetId && t.FrameIndex == first.FrameIndex);
if (match != null)
{
LogVerbose($" -> Match: TileDef {match.Id} '{match.Name}'");
return match;
}
else
{
LogVerbose($" -> No TileDefinition for Sheet={first.SheetId}, Frame={first.FrameIndex}");
}
}
}
catch (Exception ex)
{
LogVerbose($" -> ERROR parsing TilesJson: {ex.Message}");
}
}
else
{
LogVerbose($" TilesJson is empty/null");
}
return null; // Could not resolve this template // Shuffle templates by weight, then try each until one has valid TilesJson
} var shuffledTemplates = ShuffleByWeight(compatibleTemplates);
// Overload for backward compatibility (without layout parameter)
private TileDefinition? SelectFloorTile(int x, int y, out bool usedFallback)
{
// Create a minimal layout for compatibility
usedFallback = false;
if (_floorTemplates.Count > 0) foreach (var template in shuffledTemplates)
{ {
var template = SelectWeightedTemplate(_floorTemplates); var result = TryParseTemplateTile(template, x, y, "Floor", compatibleTemplates.Count, _floorTemplates.Count);
if (template != null) if (result != null)
{ {
if (template.PrimaryTileDefinitionId.HasValue) // Track placement for socket matching
{ _placedTemplates[$"{x},{y}"] = template.Id;
if (_tileDefinitions.TryGetValue(template.PrimaryTileDefinitionId.Value, out var tileDef))
{
if (!UsedFloorTemplates.Contains(template.Name))
UsedFloorTemplates.Add(template.Name);
return tileDef;
}
}
if (!string.IsNullOrEmpty(template.TilesJson)) if (!UsedFloorTemplates.Contains(template.Name))
{ UsedFloorTemplates.Add(template.Name);
try
{ return result;
var tiles = JsonSerializer.Deserialize<List<TemplateTilePlacement>>(template.TilesJson, _jsonOptions);
if (tiles?.Count > 0)
{
var first = tiles[0];
var match = _tileDefinitions.Values
.FirstOrDefault(t => t.TileMapSheetId == first.SheetId && t.FrameIndex == first.FrameIndex);
if (match != null)
{
if (!UsedFloorTemplates.Contains(template.Name))
UsedFloorTemplates.Add(template.Name);
return match;
}
}
}
catch { }
}
} }
} }
usedFallback = true; Log($"SelectFloorTemplate({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates had valid TilesJson!");
var walkableTiles = _tileDefinitions.Values.Where(t => t.IsWalkable).OrderBy(t => t.Id).ToList(); return null;
return walkableTiles.FirstOrDefault() ?? _tileDefinitions.Values.FirstOrDefault(); }
/// <summary>
/// Try to parse a template's TilesJson to get tile placement info.
/// Returns null if TilesJson is missing or invalid.
/// </summary>
private TemplateSelectionResult? TryParseTemplateTile(TileTemplate template, int x, int y, string tileType, int compatibleCount, int totalCount)
{
LogVerbose($"Select{tileType}Template({x},{y}): Trying template '{template.Name}' (ID={template.Id}) [Compatible: {compatibleCount}/{totalCount}]");
if (string.IsNullOrEmpty(template.TilesJson))
{
LogVerbose($" -> TilesJson is empty/null");
return null;
}
LogVerbose($" Parsing TilesJson: {template.TilesJson}");
try
{
var tiles = JsonSerializer.Deserialize<List<TemplateTilePlacement>>(template.TilesJson, _jsonOptions);
if (tiles == null || tiles.Count == 0)
{
LogVerbose($" -> Deserialized to NULL or EMPTY!");
return null;
}
var first = tiles[0];
LogVerbose($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}");
// Ensure the sheet is tracked for client rendering
EnsureSheetLoaded(first.SheetId);
return new TemplateSelectionResult
{
TemplateId = template.Id,
TemplateName = template.Name,
SheetId = first.SheetId,
FrameIndex = first.FrameIndex
};
}
catch (Exception ex)
{
LogVerbose($" -> ERROR parsing TilesJson: {ex.Message}");
return null;
}
}
/// <summary>
/// Ensure a tile sheet is loaded and tracked for client rendering.
/// </summary>
private void EnsureSheetLoaded(int sheetId)
{
if (!_tileSheets.ContainsKey(sheetId))
{
var sheet = _db.TileMapSheets.Find(sheetId);
if (sheet != null)
{
_tileSheets[sheetId] = sheet;
LogVerbose($" -> Loaded TileMapSheet {sheetId}: '{sheet.Name}'");
}
else
{
Log($" -> WARNING: TileMapSheet {sheetId} not found in database!");
}
}
} }
/// <summary> /// <summary>
@@ -1456,7 +1380,6 @@ public class DungeonGeneratorV3
} }
int wallCount = 0; int wallCount = 0;
int fallbackCount = 0;
// Find cells adjacent to walkable that aren't walkable themselves // Find cells adjacent to walkable that aren't walkable themselves
for (int y = 0; y < MapHeight; y++) for (int y = 0; y < MapHeight; y++)
@@ -1465,20 +1388,25 @@ public class DungeonGeneratorV3
{ {
if (!layout.Walkable[x, y] && HasAdjacentWalkable(layout, x, y) && layout.Tiles[x, y] == 0) if (!layout.Walkable[x, y] && HasAdjacentWalkable(layout, x, y) && layout.Tiles[x, y] == 0)
{ {
var tile = SelectWallTile(x, y, layout); var result = SelectWallTemplate(x, y, layout);
if (tile != null) if (result != null)
{ {
layout.Tiles[x, y] = tile.Id; layout.Tiles[x, y] = result.Value.TemplateId;
layout.TileDetails.Add(new PlacedTile layout.TileDetails.Add(new PlacedTile
{ {
X = x, X = x,
Y = y, Y = y,
TileDefinitionId = tile.Id, TileDefinitionId = 0, // No TileDefinition - using template directly
SheetId = tile.TileMapSheetId, SheetId = result.Value.SheetId,
FrameIndex = tile.FrameIndex, FrameIndex = result.Value.FrameIndex,
Layer = 0 Layer = 0
}); });
wallCount++; wallCount++;
if (LogEveryTile)
{
Log($" Wall ({x},{y}): Template='{result.Value.TemplateName}', Sheet={result.Value.SheetId}, Frame={result.Value.FrameIndex}");
}
} }
} }
} }
@@ -1503,55 +1431,39 @@ public class DungeonGeneratorV3
} }
/// <summary> /// <summary>
/// Select a wall tile for the given position. /// Select a wall template for the given position.
/// /// Returns the template's tile placement info directly from TilesJson.
/// SELECTION PROCESS (with socket matching):
/// 1. If _wallTemplates has templates:
/// a. Filter to socket-compatible templates (if UseSocketMatching)
/// b. Try each template in weighted order until one resolves to a TileDefinition
/// c. Try template.PrimaryTileDefinitionId first
/// d. If no PrimaryTileDefinitionId, parse template.TilesJson
/// e. Track placed template for future socket matching
/// 2. FALLBACK: Return first non-walkable TileDefinition
/// </summary> /// </summary>
private TileDefinition? SelectWallTile(int x, int y, DungeonLayoutV2 layout) private TemplateSelectionResult? SelectWallTemplate(int x, int y, DungeonLayoutV2 layout)
{ {
if (_wallTemplates.Count > 0) if (_wallTemplates.Count == 0)
{ {
// Get socket-compatible templates LogVerbose($"SelectWallTemplate({x},{y}): No wall templates available!");
var compatibleTemplates = GetCompatibleTemplates(_wallTemplates, x, y, layout); return null;
// Shuffle templates by weight, then try each until one resolves
var shuffledTemplates = ShuffleByWeight(compatibleTemplates);
foreach (var template in shuffledTemplates)
{
var tileDef = TryResolveTemplate(template, x, y, compatibleTemplates.Count);
if (tileDef != null)
{
// Track placement for socket matching
_placedTemplates[$"{x},{y}"] = template.Id;
if (!UsedWallTemplates.Contains(template.Name))
UsedWallTemplates.Add(template.Name);
return tileDef;
}
}
// No template resolved - log warning
Log($"SelectWallTile({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates could resolve to a TileDefinition!");
} }
// FALLBACK: use the FIRST non-walkable tile consistently // Get socket-compatible templates
var wallTiles = _tileDefinitions.Values.Where(t => !t.IsWalkable).OrderBy(t => t.Id).ToList(); var compatibleTemplates = GetCompatibleTemplates(_wallTemplates, x, y, layout);
if (wallTiles.Count > 0)
// Shuffle templates by weight, then try each until one has valid TilesJson
var shuffledTemplates = ShuffleByWeight(compatibleTemplates);
foreach (var template in shuffledTemplates)
{ {
LogVerbose($"SelectWallTile({x},{y}): FALLBACK TileDef {wallTiles[0].Id} '{wallTiles[0].Name}'"); var result = TryParseTemplateTile(template, x, y, "Wall", compatibleTemplates.Count, _wallTemplates.Count);
return wallTiles[0]; if (result != null)
{
// Track placement for socket matching
_placedTemplates[$"{x},{y}"] = template.Id;
if (!UsedWallTemplates.Contains(template.Name))
UsedWallTemplates.Add(template.Name);
return result;
}
} }
LogVerbose($"SelectWallTile({x},{y}): No non-walkable tiles found!"); Log($"SelectWallTemplate({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates had valid TilesJson!");
return null; return null;
} }
@@ -1567,6 +1479,8 @@ public class DungeonGeneratorV3
while (remaining.Count > 0) while (remaining.Count > 0)
{ {
var totalWeight = remaining.Sum(t => t.Weight); var totalWeight = remaining.Sum(t => t.Weight);
if (totalWeight == 0) break;
var roll = _rng.Next(totalWeight); var roll = _rng.Next(totalWeight);
var cumulative = 0; var cumulative = 0;
@@ -1585,72 +1499,6 @@ public class DungeonGeneratorV3
return result; return result;
} }
/// <summary>
/// Try to resolve a template to a TileDefinition.
/// Returns null if the template cannot be resolved.
/// </summary>
private TileDefinition? TryResolveTemplate(TileTemplate template, int x, int y, int compatibleCount)
{
LogVerbose($"SelectWallTile({x},{y}): Trying template '{template.Name}' (ID={template.Id}) [Compatible: {compatibleCount}/{_wallTemplates.Count}]");
// Method 1: Try PrimaryTileDefinitionId first
if (template.PrimaryTileDefinitionId.HasValue)
{
LogVerbose($" Trying PrimaryTileDefinitionId: {template.PrimaryTileDefinitionId.Value}");
if (_tileDefinitions.TryGetValue(template.PrimaryTileDefinitionId.Value, out var tileDef))
{
LogVerbose($" -> Found TileDef {tileDef.Id} '{tileDef.Name}'");
return tileDef;
}
LogVerbose($" -> NOT FOUND in _tileDefinitions!");
}
// Method 2: Try to parse TilesJson for the template
if (!string.IsNullOrEmpty(template.TilesJson))
{
LogVerbose($" Trying TilesJson: {template.TilesJson}");
try
{
var tiles = JsonSerializer.Deserialize<List<TemplateTilePlacement>>(template.TilesJson, _jsonOptions);
if (tiles == null)
{
LogVerbose($" -> Deserialized to NULL!");
}
else if (tiles.Count == 0)
{
LogVerbose($" -> Deserialized to EMPTY list!");
}
else
{
var first = tiles[0];
LogVerbose($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}");
var match = _tileDefinitions.Values
.FirstOrDefault(t => t.TileMapSheetId == first.SheetId && t.FrameIndex == first.FrameIndex);
if (match != null)
{
LogVerbose($" -> Match: TileDef {match.Id} '{match.Name}'");
return match;
}
else
{
LogVerbose($" -> No TileDefinition for Sheet={first.SheetId}, Frame={first.FrameIndex}");
}
}
}
catch (Exception ex)
{
LogVerbose($" -> ERROR parsing TilesJson: {ex.Message}");
}
}
else
{
LogVerbose($" TilesJson is empty/null");
}
return null; // Could not resolve this template
}
// ============================================================ // ============================================================
// SOCKET MATCHING METHODS // SOCKET MATCHING METHODS
// ============================================================ // ============================================================
@@ -1884,13 +1732,6 @@ public class DungeonGeneratorV3
{ {
var first = tiles[0]; var first = tiles[0];
Log($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}"); Log($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}");
var match = _tileDefinitions.Values
.FirstOrDefault(td => td.TileMapSheetId == first.SheetId && td.FrameIndex == first.FrameIndex);
if (match != null)
Log($" -> Resolves to TileDef {match.Id}: '{match.Name}' (Walkable={match.IsWalkable})");
else
Log($" -> WARNING: No TileDefinition for Sheet={first.SheetId}, Frame={first.FrameIndex}!");
} }
} }
catch (Exception ex) catch (Exception ex)