Breakdown DungeonHandler Monolith to sealed partials
This commit is contained in:
@@ -146,131 +146,6 @@ public sealed partial class DungeonHandler : IClientMessageHandler
|
||||
_log.LogInformation("DungeonHandler initialized on pod {PodId} with {MobCount} mob definitions", _podId, _mobDefinitions.Count);
|
||||
}
|
||||
|
||||
private async Task SubscribeToBroadcastChannelAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Subscribe to server:broadcast channel
|
||||
await _redis.Bus.SubscribeAsync("server:broadcast", (channel, message) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (message.IsNullOrEmpty) return;
|
||||
|
||||
var payload = JsonSerializer.Deserialize<BroadcastPayload>(message.ToString());
|
||||
if (payload == null) return;
|
||||
|
||||
_log.LogInformation("Received broadcast from Redis: [{Type}] {Message}", payload.Type, payload.Message);
|
||||
|
||||
// Send to all local player sessions
|
||||
foreach (var session in _playerSessions.Values)
|
||||
{
|
||||
_ = SendAsync(session.Connection, DungeonOpCodes.SERVER_BROADCAST, new
|
||||
{
|
||||
message = payload.Message,
|
||||
type = payload.Type
|
||||
}, CancellationToken.None);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.LogError(ex, "Error processing broadcast message");
|
||||
}
|
||||
});
|
||||
|
||||
// Subscribe to server:command channel for asset refresh, force reconnect, etc.
|
||||
await _redis.Bus.SubscribeAsync("server:command", (channel, message) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (message.IsNullOrEmpty) return;
|
||||
|
||||
var payload = JsonSerializer.Deserialize<CommandPayload>(message.ToString());
|
||||
if (payload == null) return;
|
||||
|
||||
_log.LogInformation("Received command from Redis: {Command}", payload.Command);
|
||||
|
||||
switch (payload.Command)
|
||||
{
|
||||
case "refresh_assets":
|
||||
// Queue asset refresh for all local players
|
||||
_broadcastService.QueueAssetRefresh();
|
||||
break;
|
||||
case "force_reconnect":
|
||||
// Could implement force disconnect here
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.LogError(ex, "Error processing command message");
|
||||
}
|
||||
});
|
||||
|
||||
_log.LogInformation("Subscribed to Redis broadcast channels");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.LogError(ex, "Failed to subscribe to Redis broadcast channels");
|
||||
}
|
||||
}
|
||||
|
||||
// Payload classes for Redis pub/sub
|
||||
private class BroadcastPayload
|
||||
{
|
||||
[System.Text.Json.Serialization.JsonPropertyName("type")]
|
||||
public string Type { get; set; } = "system";
|
||||
|
||||
[System.Text.Json.Serialization.JsonPropertyName("message")]
|
||||
public string Message { get; set; } = "";
|
||||
|
||||
[System.Text.Json.Serialization.JsonPropertyName("duration")]
|
||||
public int Duration { get; set; } = 10;
|
||||
|
||||
[System.Text.Json.Serialization.JsonPropertyName("timestamp")]
|
||||
public long Timestamp { get; set; }
|
||||
}
|
||||
|
||||
private class CommandPayload
|
||||
{
|
||||
[System.Text.Json.Serialization.JsonPropertyName("command")]
|
||||
public string Command { get; set; } = "";
|
||||
public long Timestamp { get; set; }
|
||||
}
|
||||
|
||||
private async Task LoadMobDefinitionsAsync()
|
||||
{
|
||||
await RefreshMobCacheAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refresh mob definitions cache. Call this after mobs are modified in admin.
|
||||
/// </summary>
|
||||
public async Task RefreshMobCacheAsync()
|
||||
{
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
|
||||
var mobs = await db.Set<DungeonMobDefinition>()
|
||||
.Where(m => m.IsEnabled)
|
||||
.ToListAsync();
|
||||
|
||||
if (mobs.Count == 0)
|
||||
{
|
||||
_log.LogCritical("Dungeon Mobs Table EMPTY");
|
||||
}
|
||||
|
||||
_mobDefinitions = mobs.ToDictionary(m => m.Id);
|
||||
|
||||
// Build sprite configs from animation assignments
|
||||
var spriteConfigBuilder = new MobSpriteConfigBuilder(db);
|
||||
_mobSpriteConfigs = await spriteConfigBuilder.BuildSpriteConfigsAsync(mobs.Select(m => m.Id));
|
||||
|
||||
// Count animation assignments for debugging
|
||||
var assignmentCount = await db.Set<MobAnimationAssignment>().CountAsync();
|
||||
_log.LogInformation("Refreshed mob cache: {MobCount} mobs, {AssignmentCount} animation assignments", mobs.Count, assignmentCount);
|
||||
}
|
||||
|
||||
public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
||||
{
|
||||
// Ensure initialized
|
||||
@@ -2163,380 +2038,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler
|
||||
var (_, _, _) = await AddLootToInventoryWithOverflowAsync(session, loot, 0);
|
||||
}
|
||||
|
||||
#region Loot Chest Handlers
|
||||
|
||||
/// <summary>
|
||||
/// Handle opening a loot chest
|
||||
/// </summary>
|
||||
private async Task HandleLootChestOpen(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
||||
{
|
||||
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
|
||||
var request = System.Text.Json.JsonSerializer.Deserialize<LootChestOpenRequest>(json);
|
||||
if (request == null) return;
|
||||
|
||||
if (!session.CurrentDungeonId.HasValue ||
|
||||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
|
||||
return;
|
||||
|
||||
if (!dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest))
|
||||
{
|
||||
await SendErrorAsync(connection, "Chest not found", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check ownership
|
||||
if (chest.OwnerCharacterId != session.CharacterId)
|
||||
{
|
||||
await SendErrorAsync(connection, "This chest doesn't belong to you", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check distance
|
||||
if (session.PlayerInstance != null)
|
||||
{
|
||||
float dist = MathF.Sqrt(
|
||||
MathF.Pow(session.PlayerInstance.X - chest.X, 2) +
|
||||
MathF.Pow(session.PlayerInstance.Y - chest.Y, 2));
|
||||
|
||||
if (dist > 96) // Interaction range
|
||||
{
|
||||
await SendErrorAsync(connection, "Too far from chest", ct);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
chest.IsOpen = true;
|
||||
|
||||
// Load item definitions for display
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
|
||||
var itemDefIds = chest.Items.Select(i => i.ItemDefinitionId).Distinct().ToList();
|
||||
var itemDefs = await db.Set<DungeonItemDefinition>()
|
||||
.Where(d => itemDefIds.Contains(d.Id))
|
||||
.ToDictionaryAsync(d => d.Id, ct);
|
||||
|
||||
// Build chest state
|
||||
var chestItems = new object?[100];
|
||||
foreach (var item in chest.Items)
|
||||
{
|
||||
if (itemDefs.TryGetValue(item.ItemDefinitionId, out var def))
|
||||
{
|
||||
chestItems[item.SlotIndex] = new
|
||||
{
|
||||
slotIndex = item.SlotIndex,
|
||||
definitionId = def.Id,
|
||||
name = def.Name,
|
||||
description = def.Description,
|
||||
type = def.Type.ToString(),
|
||||
rarity = def.Rarity.ToString(),
|
||||
quantity = item.Quantity,
|
||||
spritePath = def.SpritePath,
|
||||
tintColor = def.TintColor
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
await SendAsync(connection, DungeonOpCodes.LOOT_CHEST_STATE, new
|
||||
{
|
||||
chestId = chest.Id,
|
||||
gold = chest.Gold,
|
||||
items = chestItems,
|
||||
slots = 100
|
||||
}, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle taking a single item from loot chest
|
||||
/// </summary>
|
||||
private async Task HandleLootChestTakeItem(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
||||
{
|
||||
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
|
||||
var request = System.Text.Json.JsonSerializer.Deserialize<LootChestTakeItemRequest>(json);
|
||||
if (request == null) return;
|
||||
|
||||
if (!session.CurrentDungeonId.HasValue ||
|
||||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
|
||||
return;
|
||||
|
||||
if (!dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest))
|
||||
return;
|
||||
|
||||
if (chest.OwnerCharacterId != session.CharacterId)
|
||||
return;
|
||||
|
||||
// Find the item in chest
|
||||
var chestItem = chest.Items.FirstOrDefault(i => i.SlotIndex == request.SlotIndex);
|
||||
if (chestItem == null)
|
||||
{
|
||||
await SendErrorAsync(connection, "Item not found in chest", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
|
||||
// Get item definition
|
||||
var itemDef = await db.Set<DungeonItemDefinition>()
|
||||
.FirstOrDefaultAsync(d => d.Id == chestItem.ItemDefinitionId, ct);
|
||||
if (itemDef == null) return;
|
||||
|
||||
// Get player's current inventory
|
||||
var existingItems = await db.Set<DungeonCharacterItem>()
|
||||
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
|
||||
.ToListAsync(ct);
|
||||
|
||||
// Find an available slot
|
||||
var usedSlots = existingItems.Select(i => i.SlotIndex).ToHashSet();
|
||||
int targetSlot = request.TargetSlotIndex;
|
||||
|
||||
if (targetSlot < 0 || targetSlot >= 30 || usedSlots.Contains(targetSlot))
|
||||
{
|
||||
// Find first available slot
|
||||
targetSlot = -1;
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
if (!usedSlots.Contains(i))
|
||||
{
|
||||
targetSlot = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (targetSlot < 0)
|
||||
{
|
||||
await SendErrorAsync(connection, "Inventory full", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add to player inventory
|
||||
var newItem = new DungeonCharacterItem
|
||||
{
|
||||
CharacterId = session.CharacterId,
|
||||
ItemDefinitionId = chestItem.ItemDefinitionId,
|
||||
Quantity = chestItem.Quantity,
|
||||
SlotIndex = targetSlot
|
||||
};
|
||||
db.Set<DungeonCharacterItem>().Add(newItem);
|
||||
|
||||
// Update database chest item as taken
|
||||
var dbChestItem = await db.DeathChestItems
|
||||
.FirstOrDefaultAsync(i => i.DeathChestId == chest.DatabaseId &&
|
||||
i.SlotIndex == request.SlotIndex &&
|
||||
!i.IsTaken, ct);
|
||||
if (dbChestItem != null)
|
||||
{
|
||||
dbChestItem.IsTaken = true;
|
||||
dbChestItem.TakenAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
// Remove from runtime chest
|
||||
chest.Items.Remove(chestItem);
|
||||
|
||||
// Check if chest is now empty
|
||||
await CheckAndRemoveEmptyChestAsync(db, dungeon, chest, session, ct);
|
||||
|
||||
// Send updated states
|
||||
await HandleInventoryRequest(connection, session, ct);
|
||||
|
||||
// Only resend chest state if it still exists
|
||||
if (!chest.IsEmpty)
|
||||
{
|
||||
await HandleLootChestOpen(connection, session, payload, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle taking all items from loot chest
|
||||
/// </summary>
|
||||
private async Task HandleLootChestTakeAll(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
||||
{
|
||||
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
|
||||
var request = System.Text.Json.JsonSerializer.Deserialize<LootChestTakeAllRequest>(json);
|
||||
if (request == null) return;
|
||||
|
||||
if (!session.CurrentDungeonId.HasValue ||
|
||||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
|
||||
return;
|
||||
|
||||
if (!dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest))
|
||||
return;
|
||||
|
||||
if (chest.OwnerCharacterId != session.CharacterId)
|
||||
return;
|
||||
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
|
||||
// Get player's current inventory
|
||||
var existingItems = await db.Set<DungeonCharacterItem>()
|
||||
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
|
||||
.ToListAsync(ct);
|
||||
|
||||
var usedSlots = existingItems.Select(i => i.SlotIndex).ToHashSet();
|
||||
var itemsTaken = new List<LootChestItem>();
|
||||
var takenLoot = new List<LootDrop>();
|
||||
|
||||
// Try to take each item
|
||||
foreach (var chestItem in chest.Items.ToList())
|
||||
{
|
||||
// Find available slot
|
||||
int targetSlot = -1;
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
if (!usedSlots.Contains(i))
|
||||
{
|
||||
targetSlot = i;
|
||||
usedSlots.Add(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (targetSlot < 0)
|
||||
break; // Inventory full
|
||||
|
||||
// Get item definition for popup
|
||||
var itemDef = await db.Set<DungeonItemDefinition>()
|
||||
.FirstOrDefaultAsync(d => d.Id == chestItem.ItemDefinitionId, ct);
|
||||
|
||||
// Add to player inventory
|
||||
var newItem = new DungeonCharacterItem
|
||||
{
|
||||
CharacterId = session.CharacterId,
|
||||
ItemDefinitionId = chestItem.ItemDefinitionId,
|
||||
Quantity = chestItem.Quantity,
|
||||
SlotIndex = targetSlot
|
||||
};
|
||||
db.Set<DungeonCharacterItem>().Add(newItem);
|
||||
|
||||
// Update database chest item as taken
|
||||
var dbChestItem = await db.DeathChestItems
|
||||
.FirstOrDefaultAsync(i => i.DeathChestId == chest.DatabaseId &&
|
||||
i.SlotIndex == chestItem.SlotIndex &&
|
||||
!i.IsTaken, ct);
|
||||
if (dbChestItem != null)
|
||||
{
|
||||
dbChestItem.IsTaken = true;
|
||||
dbChestItem.TakenAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
itemsTaken.Add(chestItem);
|
||||
|
||||
if (itemDef != null)
|
||||
{
|
||||
takenLoot.Add(new LootDrop
|
||||
{
|
||||
ItemDefinitionId = chestItem.ItemDefinitionId,
|
||||
Item = itemDef,
|
||||
Quantity = chestItem.Quantity
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Take gold
|
||||
if (chest.Gold > 0)
|
||||
{
|
||||
var character = await db.DungeonCharacters.FindAsync(new object[] { session.CharacterId }, ct);
|
||||
if (character != null)
|
||||
{
|
||||
character.Gold += chest.Gold;
|
||||
|
||||
// Update database chest
|
||||
var dbChest = await db.DeathChests.FindAsync(new object[] { chest.DatabaseId }, ct);
|
||||
if (dbChest != null)
|
||||
{
|
||||
dbChest.GoldAmount = 0;
|
||||
}
|
||||
|
||||
chest.Gold = 0;
|
||||
}
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
// Remove taken items from runtime chest
|
||||
foreach (var item in itemsTaken)
|
||||
{
|
||||
chest.Items.Remove(item);
|
||||
}
|
||||
|
||||
// Send loot popup
|
||||
if (takenLoot.Count > 0)
|
||||
{
|
||||
await SendLootPopupAsync(session, takenLoot);
|
||||
}
|
||||
|
||||
// Check if chest is now empty
|
||||
await CheckAndRemoveEmptyChestAsync(db, dungeon, chest, session, ct);
|
||||
|
||||
// Send updated inventory
|
||||
await HandleInventoryRequest(connection, session, ct);
|
||||
|
||||
// If chest still has items, send updated state
|
||||
if (!chest.IsEmpty)
|
||||
{
|
||||
var openPayload = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(
|
||||
new LootChestOpenRequest { ChestId = request.ChestId });
|
||||
await HandleLootChestOpen(connection, session, openPayload, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle closing a loot chest
|
||||
/// </summary>
|
||||
private async Task HandleLootChestClose(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
||||
{
|
||||
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
|
||||
var request = System.Text.Json.JsonSerializer.Deserialize<LootChestCloseRequest>(json);
|
||||
if (request == null) return;
|
||||
|
||||
if (!session.CurrentDungeonId.HasValue ||
|
||||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
|
||||
return;
|
||||
|
||||
if (dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest))
|
||||
{
|
||||
if (chest.OwnerCharacterId == session.CharacterId)
|
||||
{
|
||||
chest.IsOpen = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check if a chest is empty and remove it if so
|
||||
/// </summary>
|
||||
private async Task CheckAndRemoveEmptyChestAsync(GameDbContext db, DungeonInstance dungeon, LootChestInstance chest, DungeonPlayerSession owner, CancellationToken ct)
|
||||
{
|
||||
if (chest.IsEmpty)
|
||||
{
|
||||
// Update database
|
||||
var dbChest = await db.DeathChests.FindAsync(new object[] { chest.DatabaseId }, ct);
|
||||
if (dbChest != null)
|
||||
{
|
||||
dbChest.IsEmpty = true;
|
||||
dbChest.EmptiedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
// Notify owner that chest is removed
|
||||
await SendAsync(owner.Connection, DungeonOpCodes.LOOT_CHEST_REMOVED, new
|
||||
{
|
||||
chestId = chest.Id
|
||||
}, ct);
|
||||
|
||||
// Remove from runtime
|
||||
dungeon.Simulation.LootChests.TryRemove(chest.Id, out _);
|
||||
|
||||
_log.LogInformation("Loot chest {ChestId} emptied and removed", chest.Id);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#if false // moved to DungeonHandler.Dungeons.cs
|
||||
#region Dungeon Browser Handlers
|
||||
|
||||
/// <summary>
|
||||
@@ -3208,6 +2710,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler
|
||||
}
|
||||
|
||||
#endregion
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Sends loot popup to client showing what they received
|
||||
@@ -4321,6 +3824,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler
|
||||
}
|
||||
}
|
||||
|
||||
#if false // moved to DungeonHandler.Crafting.cs
|
||||
#region Crafting
|
||||
|
||||
private async Task HandleCraftingSkillsRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
|
||||
@@ -4497,11 +4001,13 @@ public sealed partial class DungeonHandler : IClientMessageHandler
|
||||
}
|
||||
|
||||
#endregion
|
||||
#endif
|
||||
}
|
||||
|
||||
// Request/Input DTOs
|
||||
|
||||
|
||||
#if false // moved to DungeonHandler.Stash.cs and DungeonHandler.MobLoot.cs
|
||||
#region Stash System (VIP Feature)
|
||||
|
||||
public partial class DungeonHandler
|
||||
@@ -5013,3 +4519,4 @@ public partial class DungeonHandler
|
||||
|
||||
|
||||
#endregion
|
||||
#endif
|
||||
|
||||
Reference in New Issue
Block a user