Tile Change

This commit is contained in:
dingo
2026-01-09 16:49:50 -05:00
parent 5feb284dc0
commit b6f4a7e555
+109 -268
View File
@@ -938,34 +938,19 @@ 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] = tileDef.Id; layout.Tiles[worldX, worldY] = 1; // Non-zero to indicate tile is placed
layout.Walkable[worldX, worldY] = tileDef.IsWalkable;
layout.TileDetails.Add(new PlacedTile
{
X = worldX,
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.Walkable[worldX, worldY] = true;
layout.TileDetails.Add(new PlacedTile layout.TileDetails.Add(new PlacedTile
{ {
X = worldX, X = worldX,
Y = worldY, Y = worldY,
TileDefinitionId = 0, TileDefinitionId = 0, // No TileDefinition - using template directly
SheetId = t.SheetId, SheetId = t.SheetId,
FrameIndex = t.FrameIndex, FrameIndex = t.FrameIndex,
Layer = 0 Layer = 0
@@ -974,7 +959,6 @@ public class DungeonGeneratorV3
} }
} }
} }
}
catch (Exception ex) catch (Exception ex)
{ {
Log($" Error parsing TileGridJson: {ex.Message}"); Log($" Error parsing TileGridJson: {ex.Message}");
@@ -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,69 +1213,72 @@ 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;
public int SheetId;
public int FrameIndex;
}
// First try to use floor templates /// <summary>
if (_floorTemplates.Count > 0) /// Select a floor template for the given position.
/// Returns the template's tile placement info directly from TilesJson.
/// </summary>
private TemplateSelectionResult? SelectFloorTemplate(int x, int y, DungeonLayoutV2 layout)
{ {
if (_floorTemplates.Count == 0)
{
LogVerbose($"SelectFloorTemplate({x},{y}): No floor templates available!");
return null;
}
// Get socket-compatible templates // Get socket-compatible templates
var compatibleTemplates = GetCompatibleTemplates(_floorTemplates, x, y, layout); var compatibleTemplates = GetCompatibleTemplates(_floorTemplates, x, y, layout);
// Shuffle templates by weight, then try each until one resolves // Shuffle templates by weight, then try each until one has valid TilesJson
var shuffledTemplates = ShuffleByWeight(compatibleTemplates); var shuffledTemplates = ShuffleByWeight(compatibleTemplates);
foreach (var template in shuffledTemplates) foreach (var template in shuffledTemplates)
{ {
var tileDef = TryResolveFloorTemplate(template, x, y, compatibleTemplates.Count); var result = TryParseTemplateTile(template, x, y, "Floor", compatibleTemplates.Count, _floorTemplates.Count);
if (tileDef != null) if (result != null)
{ {
// Track placement for socket matching // Track placement for socket matching
_placedTemplates[$"{x},{y}"] = template.Id; _placedTemplates[$"{x},{y}"] = template.Id;
@@ -1300,140 +1286,78 @@ public class DungeonGeneratorV3
if (!UsedFloorTemplates.Contains(template.Name)) if (!UsedFloorTemplates.Contains(template.Name))
UsedFloorTemplates.Add(template.Name); UsedFloorTemplates.Add(template.Name);
return tileDef; return result;
} }
} }
// No template resolved - log warning Log($"SelectFloorTemplate({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates had valid TilesJson!");
Log($"SelectFloorTile({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates could resolve to a TileDefinition!"); return null;
}
// 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. /// Try to parse a template's TilesJson to get tile placement info.
/// Returns null if the template cannot be resolved. /// Returns null if TilesJson is missing or invalid.
/// </summary> /// </summary>
private TileDefinition? TryResolveFloorTemplate(TileTemplate template, int x, int y, int compatibleCount) private TemplateSelectionResult? TryParseTemplateTile(TileTemplate template, int x, int y, string tileType, int compatibleCount, int totalCount)
{ {
LogVerbose($"SelectFloorTile({x},{y}): Trying template '{template.Name}' (ID={template.Id}) [Compatible: {compatibleCount}/{_floorTemplates.Count}]"); LogVerbose($"Select{tileType}Template({x},{y}): Trying template '{template.Name}' (ID={template.Id}) [Compatible: {compatibleCount}/{totalCount}]");
// Method 1: Try PrimaryTileDefinitionId first if (string.IsNullOrEmpty(template.TilesJson))
if (template.PrimaryTileDefinitionId.HasValue)
{ {
LogVerbose($" Trying PrimaryTileDefinitionId: {template.PrimaryTileDefinitionId.Value}"); LogVerbose($" -> TilesJson is empty/null");
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 LogVerbose($" Parsing TilesJson: {template.TilesJson}");
if (!string.IsNullOrEmpty(template.TilesJson))
{
LogVerbose($" Trying TilesJson: {template.TilesJson}");
try try
{ {
var tiles = JsonSerializer.Deserialize<List<TemplateTilePlacement>>(template.TilesJson, _jsonOptions); var tiles = JsonSerializer.Deserialize<List<TemplateTilePlacement>>(template.TilesJson, _jsonOptions);
if (tiles == null) if (tiles == null || tiles.Count == 0)
{ {
LogVerbose($" -> Deserialized to NULL!"); LogVerbose($" -> Deserialized to NULL or EMPTY!");
return null;
} }
else if (tiles.Count == 0)
{
LogVerbose($" -> Deserialized to EMPTY list!");
}
else
{
var first = tiles[0]; var first = tiles[0];
LogVerbose($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}"); LogVerbose($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}");
var match = _tileDefinitions.Values // Ensure the sheet is tracked for client rendering
.FirstOrDefault(t => t.TileMapSheetId == first.SheetId && t.FrameIndex == first.FrameIndex); EnsureSheetLoaded(first.SheetId);
if (match != null)
return new TemplateSelectionResult
{ {
LogVerbose($" -> Match: TileDef {match.Id} '{match.Name}'"); TemplateId = template.Id,
return match; TemplateName = template.Name,
} SheetId = first.SheetId,
else FrameIndex = first.FrameIndex
{ };
LogVerbose($" -> No TileDefinition for Sheet={first.SheetId}, Frame={first.FrameIndex}");
}
}
} }
catch (Exception ex) catch (Exception ex)
{ {
LogVerbose($" -> ERROR parsing TilesJson: {ex.Message}"); 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 else
{ {
LogVerbose($" TilesJson is empty/null"); Log($" -> WARNING: TileMapSheet {sheetId} not found in database!");
}
return null; // Could not resolve this template
}
// 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)
{
var template = SelectWeightedTemplate(_floorTemplates);
if (template != null)
{
if (template.PrimaryTileDefinitionId.HasValue)
{
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))
{
try
{
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;
var walkableTiles = _tileDefinitions.Values.Where(t => t.IsWalkable).OrderBy(t => t.Id).ToList();
return walkableTiles.FirstOrDefault() ?? _tileDefinitions.Values.FirstOrDefault();
} }
/// <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,31 +1431,27 @@ 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)
{ {
LogVerbose($"SelectWallTemplate({x},{y}): No wall templates available!");
return null;
}
// Get socket-compatible templates // Get socket-compatible templates
var compatibleTemplates = GetCompatibleTemplates(_wallTemplates, x, y, layout); var compatibleTemplates = GetCompatibleTemplates(_wallTemplates, x, y, layout);
// Shuffle templates by weight, then try each until one resolves // Shuffle templates by weight, then try each until one has valid TilesJson
var shuffledTemplates = ShuffleByWeight(compatibleTemplates); var shuffledTemplates = ShuffleByWeight(compatibleTemplates);
foreach (var template in shuffledTemplates) foreach (var template in shuffledTemplates)
{ {
var tileDef = TryResolveTemplate(template, x, y, compatibleTemplates.Count); var result = TryParseTemplateTile(template, x, y, "Wall", compatibleTemplates.Count, _wallTemplates.Count);
if (tileDef != null) if (result != null)
{ {
// Track placement for socket matching // Track placement for socket matching
_placedTemplates[$"{x},{y}"] = template.Id; _placedTemplates[$"{x},{y}"] = template.Id;
@@ -1535,23 +1459,11 @@ public class DungeonGeneratorV3
if (!UsedWallTemplates.Contains(template.Name)) if (!UsedWallTemplates.Contains(template.Name))
UsedWallTemplates.Add(template.Name); UsedWallTemplates.Add(template.Name);
return tileDef; return result;
} }
} }
// No template resolved - log warning Log($"SelectWallTemplate({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates had valid TilesJson!");
Log($"SelectWallTile({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates could resolve to a TileDefinition!");
}
// FALLBACK: use the FIRST non-walkable tile consistently
var wallTiles = _tileDefinitions.Values.Where(t => !t.IsWalkable).OrderBy(t => t.Id).ToList();
if (wallTiles.Count > 0)
{
LogVerbose($"SelectWallTile({x},{y}): FALLBACK TileDef {wallTiles[0].Id} '{wallTiles[0].Name}'");
return wallTiles[0];
}
LogVerbose($"SelectWallTile({x},{y}): No non-walkable tiles found!");
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)