Stash system

This commit is contained in:
dingo
2025-12-26 17:06:29 -05:00
parent 1d3e4e5f90
commit 28b816553d
2 changed files with 424 additions and 3 deletions
+414 -3
View File
@@ -9,6 +9,7 @@ using DataServer.Data.Enums;
using Server.Networking;
using Server.Networking.Handling;
using Server.Networking.Messages;
using Server.Services;
using Server.Services.Auth;
namespace Server.Game.Dungeon;
@@ -17,12 +18,13 @@ namespace Server.Game.Dungeon;
/// Handles dungeon crawler game messages via the server's message router
/// Implements IClientMessageHandler for integration with existing infrastructure
/// </summary>
public sealed class DungeonHandler : IClientMessageHandler
public sealed partial class DungeonHandler : IClientMessageHandler
{
private readonly ILogger<DungeonHandler> _log;
private readonly ISessionRegistry _sessions;
private readonly IMessageSerializer _ser;
private readonly IServiceScopeFactory _scopeFactory;
private readonly IServerBroadcastService _broadcastService;
// Player state tracking (keyed by connection ID)
private readonly ConcurrentDictionary<Guid, DungeonPlayerSession> _playerSessions = new();
@@ -50,7 +52,8 @@ public sealed class DungeonHandler : IClientMessageHandler
IMessageSerializer ser,
IServiceScopeFactory scopeFactory,
LootService lootService,
CraftingHandler craftingHandler)
CraftingHandler craftingHandler,
IServerBroadcastService broadcastService)
{
_log = log;
_sessions = sessions;
@@ -58,6 +61,7 @@ public sealed class DungeonHandler : IClientMessageHandler
_scopeFactory = scopeFactory;
_lootService = lootService;
_craftingHandler = craftingHandler;
_broadcastService = broadcastService;
}
public IReadOnlyCollection<int> SupportedOpCodes => new[]
@@ -92,7 +96,11 @@ public sealed class DungeonHandler : IClientMessageHandler
// Crafting
DungeonOpCodes.CRAFTING_SKILLS_REQUEST,
DungeonOpCodes.CRAFTING_RECIPES_REQUEST,
DungeonOpCodes.CRAFTING_ATTEMPT
DungeonOpCodes.CRAFTING_ATTEMPT,
// Stash (VIP)
DungeonOpCodes.STASH_REQUEST,
DungeonOpCodes.STASH_DEPOSIT,
DungeonOpCodes.STASH_WITHDRAW
};
public async Task InitializeAsync()
@@ -265,6 +273,17 @@ public sealed class DungeonHandler : IClientMessageHandler
case DungeonOpCodes.CRAFTING_ATTEMPT:
await HandleCraftingAttempt(connection, session, payload, ct);
break;
// Stash (VIP Feature)
case DungeonOpCodes.STASH_REQUEST:
await HandleStashRequest(connection, session, ct);
break;
case DungeonOpCodes.STASH_DEPOSIT:
await HandleStashDeposit(connection, session, payload, ct);
break;
case DungeonOpCodes.STASH_WITHDRAW:
await HandleStashWithdraw(connection, session, payload, ct);
break;
}
}
catch (Exception ex)
@@ -739,6 +758,9 @@ public sealed class DungeonHandler : IClientMessageHandler
{
_currentTick++;
// Process pending broadcasts
ProcessPendingBroadcasts();
foreach (var (dungeonId, instance) in _dungeons)
{
try
@@ -840,6 +862,32 @@ public sealed class DungeonHandler : IClientMessageHandler
}
}
}
/// <summary>
/// Process pending server broadcasts and send to all connected players
/// </summary>
private void ProcessPendingBroadcasts()
{
var broadcasts = _broadcastService.GetPendingBroadcasts();
if (broadcasts.Count == 0) return;
foreach (var broadcast in broadcasts)
{
// Send to all connected player sessions
foreach (var session in _playerSessions.Values)
{
_ = SendAsync(session.Connection, DungeonOpCodes.SERVER_BROADCAST, new
{
message = broadcast.Message,
type = broadcast.Type
}, CancellationToken.None);
}
_log.LogInformation("Broadcast sent to {Count} players: [{Type}] {Message}",
_playerSessions.Count, broadcast.Type, broadcast.Message);
}
}
/// <summary>
/// Process loot when a mob dies - includes normal loot roll plus any carried player loot
/// </summary>
@@ -3166,3 +3214,366 @@ public class CraftingIngredientInput
[System.Text.Json.Serialization.JsonPropertyName("quantity")]
public int Quantity { get; set; }
}
#region Stash System (VIP Feature)
public partial class DungeonHandler
{
private const int STASH_SLOTS = 50; // Number of stash slots for VIP
/// <summary>
/// Handle request to view stash contents
/// </summary>
private async Task HandleStashRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Check VIP status
var account = await db.Accounts.FindAsync(new object[] { session.AccountId }, ct);
if (account == null || account.Role < AccountRole.Vip)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "vip_required",
message = "Stash is a VIP feature. Upgrade your account to access it!"
}, ct);
return;
}
// Get stash items
var stashItems = await db.DungeonStashItems
.Where(s => s.CharacterId == session.CharacterId)
.Include(s => s.Definition)
.OrderBy(s => s.SlotIndex)
.ToListAsync(ct);
await SendAsync(connection, DungeonOpCodes.STASH_STATE, new
{
slots = STASH_SLOTS,
items = stashItems.Select(s => new
{
id = s.Id,
slotIndex = s.SlotIndex,
itemDefinitionId = s.ItemDefinitionId,
quantity = s.Quantity,
storedAt = s.StoredAt,
definition = s.Definition == null ? null : new
{
id = s.Definition.Id,
name = s.Definition.Name,
description = s.Definition.Description,
type = s.Definition.Type.ToString(),
rarity = s.Definition.Rarity.ToString(),
spritePath = s.Definition.SpritePath,
stackable = s.Definition.Stackable,
maxStack = s.Definition.MaxStack
}
})
}, ct);
}
/// <summary>
/// Handle depositing an item from inventory to stash
/// </summary>
private async Task HandleStashDeposit(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Check VIP status
var account = await db.Accounts.FindAsync(new object[] { session.AccountId }, ct);
if (account == null || account.Role < AccountRole.Vip)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "vip_required",
message = "Stash is a VIP feature."
}, ct);
return;
}
// Must be in hub to use stash
if (session.State != PlayerState.InHub)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "not_in_hub",
message = "You must be in the hub to access your stash."
}, ct);
return;
}
var request = _ser.Deserialize<StashDepositRequest>(payload);
var inventorySlot = request.InventorySlot;
var quantity = request.Quantity > 0 ? request.Quantity : 1;
var targetSlot = request.TargetSlot;
// Find the inventory item
var invItem = await db.DungeonCharacterItems
.Include(i => i.ItemDefinition)
.FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.SlotIndex == inventorySlot && !i.IsEquipped, ct);
if (invItem == null)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "item_not_found",
message = "Item not found in inventory."
}, ct);
return;
}
// Find target slot
if (targetSlot < 0)
{
// Auto-find empty slot
var usedSlots = await db.DungeonStashItems
.Where(s => s.CharacterId == session.CharacterId)
.Select(s => s.SlotIndex)
.ToListAsync(ct);
for (int i = 0; i < STASH_SLOTS; i++)
{
if (!usedSlots.Contains(i))
{
targetSlot = i;
break;
}
}
if (targetSlot < 0)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "stash_full",
message = "Your stash is full!"
}, ct);
return;
}
}
// Validate quantity
quantity = Math.Min(quantity, invItem.Quantity);
// Check if stacking with existing stash item
DungeonStashItem? existingStash = null;
if (invItem.ItemDefinition?.Stackable == true)
{
existingStash = await db.DungeonStashItems
.Include(s => s.Definition)
.FirstOrDefaultAsync(s => s.CharacterId == session.CharacterId &&
s.ItemDefinitionId == invItem.ItemDefinitionId, ct);
}
if (existingStash != null && invItem.ItemDefinition?.Stackable == true)
{
// Stack with existing
var maxAdd = (invItem.ItemDefinition?.MaxStack ?? 99) - existingStash.Quantity;
var toAdd = Math.Min(quantity, maxAdd);
if (toAdd > 0)
{
existingStash.Quantity += toAdd;
invItem.Quantity -= toAdd;
if (invItem.Quantity <= 0)
db.DungeonCharacterItems.Remove(invItem);
}
}
else
{
// Create new stash entry
var stashItem = new DungeonStashItem
{
CharacterId = session.CharacterId,
ItemDefinitionId = invItem.ItemDefinitionId,
Quantity = quantity,
SlotIndex = targetSlot,
StoredAt = DateTime.UtcNow
};
db.DungeonStashItems.Add(stashItem);
invItem.Quantity -= quantity;
if (invItem.Quantity <= 0)
db.DungeonCharacterItems.Remove(invItem);
}
await db.SaveChangesAsync(ct);
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = true,
message = "Item deposited to stash."
}, ct);
// Send updated inventory and stash
await HandleInventoryRequest(connection, session, ct);
await HandleStashRequest(connection, session, ct);
}
/// <summary>
/// Handle withdrawing an item from stash to inventory
/// </summary>
private async Task HandleStashWithdraw(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Check VIP status
var account = await db.Accounts.FindAsync(new object[] { session.AccountId }, ct);
if (account == null || account.Role < AccountRole.Vip)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "vip_required",
message = "Stash is a VIP feature."
}, ct);
return;
}
// Must be in hub to use stash
if (session.State != PlayerState.InHub)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "not_in_hub",
message = "You must be in the hub to access your stash."
}, ct);
return;
}
var request = _ser.Deserialize<StashWithdrawRequest>(payload);
var stashSlot = request.StashSlot;
var quantity = request.Quantity > 0 ? request.Quantity : 1;
// Find the stash item
var stashItem = await db.DungeonStashItems
.Include(s => s.Definition)
.FirstOrDefaultAsync(s => s.CharacterId == session.CharacterId && s.SlotIndex == stashSlot, ct);
if (stashItem == null)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "item_not_found",
message = "Item not found in stash."
}, ct);
return;
}
// Validate quantity
quantity = Math.Min(quantity, stashItem.Quantity);
// Find empty inventory slot or stackable slot
var invItems = await db.DungeonCharacterItems
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
.Include(i => i.ItemDefinition)
.ToListAsync(ct);
// Check for stackable existing
DungeonCharacterItem? targetItem = null;
if (stashItem.Definition?.Stackable == true)
{
targetItem = invItems.FirstOrDefault(i =>
i.ItemDefinitionId == stashItem.ItemDefinitionId &&
i.Quantity < (i.ItemDefinition?.MaxStack ?? 99));
}
if (targetItem != null)
{
// Stack with existing
var maxAdd = (stashItem.Definition?.MaxStack ?? 99) - targetItem.Quantity;
var toAdd = Math.Min(quantity, maxAdd);
targetItem.Quantity += toAdd;
stashItem.Quantity -= toAdd;
if (stashItem.Quantity <= 0)
db.DungeonStashItems.Remove(stashItem);
}
else
{
// Find empty slot (starting from slot 0 for inventory)
var usedSlots = invItems.Select(i => i.SlotIndex).ToHashSet();
int emptySlot = -1;
for (int i = 0; i < 30; i++)
{
if (!usedSlots.Contains(i))
{
emptySlot = i;
break;
}
}
if (emptySlot < 0)
{
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = false,
error = "inventory_full",
message = "Your inventory is full!"
}, ct);
return;
}
// Create new inventory item
var newItem = new DungeonCharacterItem
{
CharacterId = session.CharacterId,
ItemDefinitionId = stashItem.ItemDefinitionId,
Quantity = quantity,
SlotIndex = emptySlot
};
db.DungeonCharacterItems.Add(newItem);
stashItem.Quantity -= quantity;
if (stashItem.Quantity <= 0)
db.DungeonStashItems.Remove(stashItem);
}
await db.SaveChangesAsync(ct);
await SendAsync(connection, DungeonOpCodes.STASH_RESULT, new
{
success = true,
message = "Item withdrawn from stash."
}, ct);
// Send updated inventory and stash
await HandleInventoryRequest(connection, session, ct);
await HandleStashRequest(connection, session, ct);
}
}
// Request DTOs for stash operations
public class StashDepositRequest
{
[System.Text.Json.Serialization.JsonPropertyName("inventorySlot")]
public int InventorySlot { get; set; }
[System.Text.Json.Serialization.JsonPropertyName("quantity")]
public int Quantity { get; set; } = 1;
[System.Text.Json.Serialization.JsonPropertyName("targetSlot")]
public int TargetSlot { get; set; } = -1;
}
public class StashWithdrawRequest
{
[System.Text.Json.Serialization.JsonPropertyName("stashSlot")]
public int StashSlot { get; set; }
[System.Text.Json.Serialization.JsonPropertyName("quantity")]
public int Quantity { get; set; } = 1;
}
#endregion
+10
View File
@@ -82,4 +82,14 @@ public static class DungeonOpCodes
public const int CRAFTING_SKILL_LEVELUP = 336; // Skill level increased
public const int RECIPE_DISCOVERED = 337; // New recipe learned
public const int RECIPE_SCROLL_USE = 338; // Use a recipe scroll
// Server Broadcast (600-609)
public const int SERVER_BROADCAST = 600;
// Stash (610-619) - VIP Feature
public const int STASH_REQUEST = 610; // Request stash contents
public const int STASH_STATE = 611; // Stash contents response
public const int STASH_DEPOSIT = 612; // Move item from inventory to stash
public const int STASH_WITHDRAW = 613; // Move item from stash to inventory
public const int STASH_RESULT = 614; // Result of deposit/withdraw operation
}