Refresh fix, Dungeon Builder v2

This commit is contained in:
dingo
2026-01-04 21:35:42 -05:00
parent 89e6684288
commit 7de9bd2761
8 changed files with 1559 additions and 67 deletions
File diff suppressed because it is too large Load Diff
+58 -14
View File
@@ -670,16 +670,16 @@ public sealed partial class DungeonHandler : IClientMessageHandler
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var generator = new DungeonGeneratorV2(db, seed, tier);
var generator = new DungeonGeneratorV3(db, seed, tier);
layoutV2 = await generator.GenerateAsync();
layout = layoutV2; // V2 extends V1, use directly
_log.LogInformation("Generated dungeon with V2 generator - {RoomCount} rooms, {TileCount} visual tiles",
_log.LogInformation("Generated dungeon with V3 generator - {RoomCount} rooms, {TileCount} visual tiles",
layoutV2.Rooms.Count, layoutV2.TileDetails?.Count ?? 0);
}
catch (Exception ex)
{
_log.LogWarning(ex, "V2 dungeon generator failed, falling back to V1");
_log.LogWarning(ex, "V3 dungeon generator failed, falling back to V1");
layout = DungeonGenerator.Generate(seed, tier);
}
@@ -744,6 +744,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler
// Build visual tile data if V2 layout available
object? tileSheets = null;
object? visualTiles = null;
object? placedObjects = null;
_log.LogInformation("LayoutV2 is null: {IsNull}, TileDetails count: {Count}",
instance.LayoutV2 == null, instance.LayoutV2?.TileDetails?.Count ?? 0);
@@ -775,8 +776,28 @@ public sealed partial class DungeonHandler : IClientMessageHandler
fy = t.FlipY
}).ToArray();
_log.LogInformation("Sending {SheetCount} sheets, {TileCount} visual tiles to client",
instance.LayoutV2.TileMapSheets.Count, instance.LayoutV2.TileDetails.Count);
// V3: Include placed objects (decorations, containers, traps)
if (instance.LayoutV2.Objects?.Count > 0)
{
placedObjects = instance.LayoutV2.Objects.Select(o => new
{
x = o.X,
y = o.Y,
id = o.ObjectTemplateId,
name = o.Name,
type = o.Type,
sheetId = o.SpriteSheetId,
frame = o.FrameIndex,
blocks = o.BlocksMovement,
interact = o.IsInteractable,
trap = o.IsTrap,
damage = o.TrapDamage,
loot = o.LootTableId
}).ToArray();
}
_log.LogInformation("Sending {SheetCount} sheets, {TileCount} visual tiles, {ObjectCount} objects to client",
instance.LayoutV2.TileMapSheets.Count, instance.LayoutV2.TileDetails.Count, instance.LayoutV2.Objects?.Count ?? 0);
}
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new
@@ -820,9 +841,10 @@ public sealed partial class DungeonHandler : IClientMessageHandler
y = p.Y,
type = p.Type.ToString().ToLower()
}),
// V2 visual tile data
// V3 visual tile data
tileSheets,
visualTiles
visualTiles,
placedObjects
}, ct);
}
@@ -2152,16 +2174,16 @@ public sealed partial class DungeonHandler : IClientMessageHandler
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var generator = new DungeonGeneratorV2(db, seed, tier);
var generator = new DungeonGeneratorV3(db, seed, tier);
layoutV2 = await generator.GenerateAsync();
layout = layoutV2; // V2 extends V1, use directly
_log.LogInformation("Generated dungeon with V2 generator - {RoomCount} rooms, {TileCount} visual tiles",
_log.LogInformation("Generated dungeon with V3 generator - {RoomCount} rooms, {TileCount} visual tiles",
layoutV2.Rooms.Count, layoutV2.TileDetails?.Count ?? 0);
}
catch (Exception ex)
{
_log.LogWarning(ex, "V2 dungeon generator failed, falling back to V1");
_log.LogWarning(ex, "V3 dungeon generator failed, falling back to V1");
layout = DungeonGenerator.Generate(seed, tier);
}
@@ -2323,6 +2345,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler
// Build visual tile data if V2 layout available
object? tileSheets = null;
object? visualTiles = null;
object? placedObjects = null;
if (instance.LayoutV2 != null && instance.LayoutV2.TileDetails.Count > 0)
{
@@ -2350,8 +2373,28 @@ public sealed partial class DungeonHandler : IClientMessageHandler
fy = t.FlipY
}).ToArray();
_log.LogInformation("Sending {SheetCount} sheets, {TileCount} visual tiles to client",
instance.LayoutV2.TileMapSheets.Count, instance.LayoutV2.TileDetails.Count);
// V3: Include placed objects (decorations, containers, traps)
if (instance.LayoutV2.Objects?.Count > 0)
{
placedObjects = instance.LayoutV2.Objects.Select(o => new
{
x = o.X,
y = o.Y,
id = o.ObjectTemplateId,
name = o.Name,
type = o.Type,
sheetId = o.SpriteSheetId,
frame = o.FrameIndex,
blocks = o.BlocksMovement,
interact = o.IsInteractable,
trap = o.IsTrap,
damage = o.TrapDamage,
loot = o.LootTableId
}).ToArray();
}
_log.LogInformation("Sending {SheetCount} sheets, {TileCount} visual tiles, {ObjectCount} objects to client",
instance.LayoutV2.TileMapSheets.Count, instance.LayoutV2.TileDetails.Count, instance.LayoutV2.Objects?.Count ?? 0);
}
await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new
@@ -2402,9 +2445,10 @@ public sealed partial class DungeonHandler : IClientMessageHandler
y = p.Y,
type = p.Type.ToString().ToLower()
}),
// V2 visual tile data
// V3 visual tile data
tileSheets,
visualTiles
visualTiles,
placedObjects
}, ct);
_log.LogInformation("Player {Name} (Level {Level}) joined dungeon {Id}",
+64 -7
View File
@@ -18,6 +18,33 @@ public class DungeonLayoutV2 : DungeonLayout
/// </summary>
public List<TileMapSheetInfo> TileMapSheets { get; set; } = new();
/// <summary>
/// Placed objects (decorations, containers, traps)
/// </summary>
public List<PlacedObject> Objects { get; set; } = new();
/// <summary>
/// Player spawn position
/// </summary>
public int PlayerSpawnX { get; set; }
public int PlayerSpawnY { get; set; }
/// <summary>
/// Exit portal position
/// </summary>
public int ExitX { get; set; }
public int ExitY { get; set; }
public DungeonLayoutV2() : base() { }
public DungeonLayoutV2(int width, int height)
{
Width = width;
Height = height;
Tiles = new int[width, height];
Walkable = new bool[width, height];
}
/// <summary>
/// Build tile data optimized for client transmission
/// </summary>
@@ -31,6 +58,14 @@ public class DungeonLayoutV2 : DungeonLayout
.Distinct()
.ToList();
// Also add sheets from direct SheetId references
var directSheetIds = TileDetails
.Where(t => t.SheetId > 0)
.Select(t => t.SheetId)
.Distinct();
sheetIds.AddRange(directSheetIds);
sheetIds = sheetIds.Distinct().ToList();
var sheets = tileDefinitions.Values
.Where(t => sheetIds.Contains(t.TileMapSheetId))
.Select(t => t.TileMapSheet)
@@ -76,7 +111,8 @@ public class DungeonLayoutV2 : DungeonLayout
height = Height,
tileSize = TileSize,
tilesRLE = SerializeTilesRLE(),
spawn = new { x = SpawnPoint.X, y = SpawnPoint.Y },
spawn = new { x = PlayerSpawnX > 0 ? PlayerSpawnX : SpawnPoint.X, y = PlayerSpawnY > 0 ? PlayerSpawnY : SpawnPoint.Y },
exit = new { x = ExitX, y = ExitY },
rooms = Rooms.Select(r => new
{
x = r.X, y = r.Y, w = r.Width, h = r.Height,
@@ -96,7 +132,23 @@ public class DungeonLayoutV2 : DungeonLayout
type = c.ChestType.ToString(),
roomIndex = c.RoomIndex
}),
// New: Visual tile data
// Objects (decorations, containers, traps)
objects = Objects.Select(o => new
{
x = o.X,
y = o.Y,
id = o.ObjectTemplateId,
name = o.Name,
type = o.Type,
sheetId = o.SpriteSheetId,
frame = o.FrameIndex,
blocks = o.BlocksMovement,
interact = o.IsInteractable,
trap = o.IsTrap,
damage = o.TrapDamage,
loot = o.LootTableId
}),
// Tile sheets
tileSheets = TileMapSheets.Select(s => new
{
id = s.Id,
@@ -108,11 +160,14 @@ public class DungeonLayoutV2 : DungeonLayout
cols = s.Columns,
rows = s.Rows
}),
// Visual tile details
visualTiles = TileDetails.Select(t => new
{
x = t.X,
y = t.Y,
tid = t.TileDefinitionId,
sid = t.SheetId,
f = t.FrameIndex,
l = t.Layer,
r = t.Rotation,
fx = t.FlipX,
@@ -134,10 +189,12 @@ public class DungeonLayoutV2 : DungeonLayout
height = Height,
tileSize = TileSize,
tilesRLE = SerializeTilesRLE(),
spawn = new { x = SpawnPoint.X, y = SpawnPoint.Y },
spawn = new { x = PlayerSpawnX > 0 ? PlayerSpawnX : SpawnPoint.X, y = PlayerSpawnY > 0 ? PlayerSpawnY : SpawnPoint.Y },
exit = new { x = ExitX, y = ExitY },
rooms = Rooms.Select(r => new { x = r.X, y = r.Y, w = r.Width, h = r.Height, type = r.Type.ToString() }),
mobs = MobSpawns.Select(m => new { id = m.Id, x = m.X, y = m.Y, type = m.MobType.ToString() }),
chests = ChestSpawns.Select(c => new { id = c.Id, x = c.X, y = c.Y, type = c.ChestType.ToString() })
chests = ChestSpawns.Select(c => new { id = c.Id, x = c.X, y = c.Y, type = c.ChestType.ToString() }),
objects = Objects.Select(o => new { x = o.X, y = o.Y, id = o.ObjectTemplateId, type = o.Type, blocks = o.BlocksMovement })
});
}
@@ -163,6 +220,8 @@ public class DungeonLayoutV2 : DungeonLayout
x = t.X,
y = t.Y,
tid = t.TileDefinitionId,
sid = t.SheetId,
f = t.FrameIndex,
l = t.Layer,
r = t.Rotation,
fx = t.FlipX,
@@ -170,6 +229,4 @@ public class DungeonLayoutV2 : DungeonLayout
})
});
}
}
}
+57 -40
View File
@@ -1,48 +1,65 @@
using DataServer.Data.Entities;
using Server.Game.Dungeon;
using DataServer.Data.Entities;
namespace Server.Game.Dungeon
namespace Server.Game.Dungeon;
/// <summary>
/// Extended room with template info
/// </summary>
public class DungeonRoomV2 : DungeonRoom
{
/// <summary>
/// Extended room with template info
/// </summary>
public class DungeonRoomV2 : DungeonRoom
public int? TemplateId { get; set; }
public string? TemplateName { get; set; }
public HashSet<string> TemplateTags { get; set; } = new(StringComparer.OrdinalIgnoreCase);
public new RoomType Type { get; set; } = RoomType.Normal;
/// <summary>Connection points parsed from template</summary>
public List<ConnectionPoint> ConnectionPoints { get; set; } = new();
/// <summary>Mob spawns from template (intermediate storage before conversion)</summary>
public List<RoomMobSpawn> MobSpawns { get; set; } = new();
/// <summary>Player spawn position (for entrance rooms)</summary>
public int? PlayerSpawnX { get; set; }
public int? PlayerSpawnY { get; set; }
/// <summary>Exit position (for exit rooms)</summary>
public int? ExitX { get; set; }
public int? ExitY { get; set; }
public DungeonRoomV2(int x, int y, int width, int height) : base(x, y, width, height) { }
/// <summary>Get the best connection point for a given direction</summary>
public ConnectionPoint? GetConnectionPoint(string direction)
{
public int? TemplateId { get; set; }
public string? TemplateName { get; set; }
public HashSet<string> TemplateTags { get; set; } = new(StringComparer.OrdinalIgnoreCase);
public new RoomType Type { get; set; } = RoomType.Normal;
// First try exact match
var exact = ConnectionPoints.FirstOrDefault(c => c.Direction.Equals(direction, StringComparison.OrdinalIgnoreCase));
if (exact != null) return exact;
/// <summary>Connection points parsed from template</summary>
public List<ConnectionPoint> ConnectionPoints { get; set; } = new();
public DungeonRoomV2(int x, int y, int width, int height) : base(x, y, width, height) { }
/// <summary>Get the best connection point for a given direction</summary>
public ConnectionPoint? GetConnectionPoint(string direction)
// No exact match - create a default one for this direction
return direction.ToLower() switch
{
// First try exact match
var exact = ConnectionPoints.FirstOrDefault(c => c.Direction.Equals(direction, StringComparison.OrdinalIgnoreCase));
if (exact != null) return exact;
// No exact match - create a default one for this direction rather than using wrong direction
// This ensures the connection point is actually on the correct edge
return direction.ToLower() switch
{
"north" => new ConnectionPoint { X = Width / 2, Y = 0, Direction = "north", Width = 3 },
"south" => new ConnectionPoint { X = Width / 2, Y = Height - 1, Direction = "south", Width = 3 },
"east" => new ConnectionPoint { X = Width - 1, Y = Height / 2, Direction = "east", Width = 3 },
"west" => new ConnectionPoint { X = 0, Y = Height / 2, Direction = "west", Width = 3 },
_ => ConnectionPoints.FirstOrDefault() // Last resort fallback
};
}
/// <summary>Get world position of a connection point</summary>
public (int X, int Y) GetConnectionWorldPos(ConnectionPoint cp)
{
return (X + cp.X, Y + cp.Y);
}
"north" => new ConnectionPoint { X = Width / 2, Y = 0, Direction = "north", Width = 3 },
"south" => new ConnectionPoint { X = Width / 2, Y = Height - 1, Direction = "south", Width = 3 },
"east" => new ConnectionPoint { X = Width - 1, Y = Height / 2, Direction = "east", Width = 3 },
"west" => new ConnectionPoint { X = 0, Y = Height / 2, Direction = "west", Width = 3 },
_ => ConnectionPoints.FirstOrDefault()
};
}
/// <summary>Get world position of a connection point</summary>
public (int X, int Y) GetConnectionWorldPos(ConnectionPoint cp)
{
return (X + cp.X, Y + cp.Y);
}
}
/// <summary>
/// Mob spawn point within a room (intermediate type for template data)
/// </summary>
public class RoomMobSpawn
{
public int X { get; set; }
public int Y { get; set; }
public string Type { get; set; } = "normal";
public int Count { get; set; } = 1;
}
+9 -2
View File
@@ -41,7 +41,14 @@ public class LootService
public async Task InitializeAsync()
{
if (_initialized) return;
await RefreshCacheAsync();
}
/// <summary>
/// Refresh all loot-related caches (can be called on-demand from admin)
/// </summary>
public async Task RefreshCacheAsync()
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
@@ -95,7 +102,7 @@ public class LootService
_itemDefinitions = items.ToDictionary(i => i.Id);
_initialized = true;
_log.LogInformation("LootService initialized: {Tables} tables, {Items} items, {Mappings} mob mappings",
_log.LogInformation("LootService cache refreshed: {Tables} tables, {Items} items, {Mappings} mob mappings",
_lootTables.Count, _itemDefinitions.Count, mappings.Count);
}
+37 -2
View File
@@ -7,10 +7,14 @@ namespace Server.Services.Admin.Pages;
public class ApiModel : AdminPageModel
{
private readonly CraftingHandler _craftingHandler;
private readonly DungeonHandler? _dungeonHandler;
private readonly LootService? _lootService;
public ApiModel(CraftingHandler craftingHandler)
public ApiModel(CraftingHandler craftingHandler, DungeonHandler? dungeonHandler = null, LootService? lootService = null)
{
_craftingHandler = craftingHandler;
_dungeonHandler = dungeonHandler;
_lootService = lootService;
}
public IActionResult OnGet()
@@ -21,20 +25,51 @@ public class ApiModel : AdminPageModel
public async Task<IActionResult> OnPostRefreshCacheAsync([FromQuery] string? type)
{
var refreshed = new List<string>();
var errors = new List<string>();
try
{
if (type == null || type.Equals("recipes", StringComparison.OrdinalIgnoreCase))
// Refresh recipes
if (type == null || type.Equals("recipes", StringComparison.OrdinalIgnoreCase) || type.Equals("all", StringComparison.OrdinalIgnoreCase))
{
await _craftingHandler.RefreshRecipeCacheAsync();
refreshed.Add("recipes");
}
// Refresh mobs (animations, sprites, definitions)
if (type == null || type.Equals("mobs", StringComparison.OrdinalIgnoreCase) || type.Equals("all", StringComparison.OrdinalIgnoreCase))
{
if (_dungeonHandler != null)
{
await _dungeonHandler.RefreshMobCacheAsync();
refreshed.Add("mobs");
}
else
{
errors.Add("DungeonHandler not available for mob refresh");
}
}
// Refresh loot tables
if (type == null || type.Equals("loot", StringComparison.OrdinalIgnoreCase) || type.Equals("all", StringComparison.OrdinalIgnoreCase))
{
if (_lootService != null)
{
await _lootService.RefreshCacheAsync();
refreshed.Add("loot");
}
else
{
errors.Add("LootService not available for loot refresh");
}
}
return new JsonResult(new
{
success = true,
message = "Cache refreshed",
refreshed,
errors = errors.Count > 0 ? errors : null,
timestamp = DateTime.UtcNow
});
}
+7 -2
View File
@@ -5,6 +5,8 @@
ViewData["Title"] = "Recipes";
}
@Html.AntiForgeryToken()
<div class="space-y-6">
<!-- Header -->
<div class="flex items-center justify-between">
@@ -214,9 +216,12 @@
btn.innerHTML = '<svg class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Refreshing...';
try {
const response = await fetch('/admin/api/refresh-cache?type=recipes', {
const response = await fetch('/admin/api?handler=RefreshCache&type=recipes', {
method: 'POST',
credentials: 'same-origin'
credentials: 'same-origin',
headers: {
'RequestVerificationToken': document.querySelector('input[name="__RequestVerificationToken"]')?.value || ''
}
});
const data = await response.json();
+102
View File
@@ -114,6 +114,48 @@
</div>
</div>
</div>
<!-- Cache Management -->
<div class="card p-6">
<h2 class="text-lg font-semibold text-white mb-4">Cache Management</h2>
<p class="text-sm text-gray-400 mb-4">Refresh server caches without restarting. Use after adding/modifying game data.</p>
<div class="grid grid-cols-2 md:grid-cols-4 gap-3" id="cacheButtons">
<button type="button" onclick="refreshCache('recipes')" class="btn btn-secondary flex flex-col items-center gap-1 py-3">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
</svg>
<span class="text-xs">Recipes</span>
</button>
<button type="button" onclick="refreshCache('mobs')" class="btn btn-secondary flex flex-col items-center gap-1 py-3">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
<span class="text-xs">Mobs</span>
</button>
<button type="button" onclick="refreshCache('loot')" class="btn btn-secondary flex flex-col items-center gap-1 py-3">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/>
</svg>
<span class="text-xs">Loot Tables</span>
</button>
<button type="button" onclick="refreshCache('all')" class="btn bg-purple-700 hover:bg-purple-600 text-white flex flex-col items-center gap-1 py-3">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
</svg>
<span class="text-xs">Refresh All</span>
</button>
</div>
<div id="cacheStatus" class="mt-4 hidden">
<div class="p-3 rounded-lg bg-gray-800 border border-gray-700">
<span id="cacheStatusText" class="text-gray-300"></span>
</div>
</div>
</div>
<!-- Recent Broadcasts -->
<div class="card p-6">
@@ -147,3 +189,63 @@
}
</div>
</div>
@section Scripts {
<script>
async function refreshCache(type) {
const statusDiv = document.getElementById('cacheStatus');
const statusText = document.getElementById('cacheStatusText');
const buttons = document.querySelectorAll('#cacheButtons button');
// Disable all buttons
buttons.forEach(btn => btn.disabled = true);
// Show loading
statusDiv.classList.remove('hidden');
statusText.innerHTML = '<span class="animate-pulse">Refreshing ' + type + ' cache...</span>';
statusDiv.querySelector('div').className = 'p-3 rounded-lg bg-blue-900/50 border border-blue-700';
try {
const token = document.querySelector('input[name="__RequestVerificationToken"]')?.value || '';
const response = await fetch('/admin/api?handler=RefreshCache&type=' + type, {
method: 'POST',
credentials: 'same-origin',
headers: {
'RequestVerificationToken': token
}
});
let data;
const text = await response.text();
try {
data = JSON.parse(text);
} catch (e) {
throw new Error('Invalid response from server: ' + text.substring(0, 100));
}
if (response.ok && data.success) {
statusText.innerHTML = '✓ Cache refreshed: ' + (data.refreshed || []).join(', ');
statusDiv.querySelector('div').className = 'p-3 rounded-lg bg-green-900/50 border border-green-700';
if (data.errors && data.errors.length > 0) {
statusText.innerHTML += '<br><span class="text-yellow-400">Warnings: ' + data.errors.join(', ') + '</span>';
}
} else {
statusText.innerHTML = '✗ Error: ' + (data.error || 'Unknown error');
statusDiv.querySelector('div').className = 'p-3 rounded-lg bg-red-900/50 border border-red-700';
}
} catch (err) {
statusText.innerHTML = '✗ Error: ' + err.message;
statusDiv.querySelector('div').className = 'p-3 rounded-lg bg-red-900/50 border border-red-700';
} finally {
// Re-enable buttons
buttons.forEach(btn => btn.disabled = false);
// Hide status after 5 seconds
setTimeout(() => {
statusDiv.classList.add('hidden');
}, 5000);
}
}
</script>
}