using DataServer.Data;
using DataServer.Data.Entities;
using DataServer.Data.Enums;
using GameServer.Dungeon;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Server.Networking;
using Server.Networking.Messages;
namespace GameServer.World;
public sealed partial class WorldHandler
{
private sealed class WorldNpcInteractRequest
{
public int NpcId { get; set; }
}
private sealed class WorldNpcDialogSelectRequest
{
public int NpcId { get; set; }
public int OptionId { get; set; }
}
private sealed class WorldNpcShopActionRequest
{
public int NpcId { get; set; }
public string Action { get; set; } = "buy";
public int SlotIndex { get; set; }
public int Quantity { get; set; } = 1;
}
///
/// Find the NPC in the player's current zone simulation.
///
private NpcInstance? FindWorldNpc(WorldSessionState s, int npcId)
{
var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ);
if (!_activeZones.TryGetValue(zoneKey, out var zoneSim)) return null;
return zoneSim.Npcs.TryGetValue(npcId, out var npc) ? npc : null;
}
private async Task HandleWorldNpcInteract(IConnection conn, WorldSessionState s, ReadOnlyMemory payload, CancellationToken ct)
{
var req = WorldInputParser.Parse(payload);
if (req == null) return;
var npc = FindWorldNpc(s, req.NpcId);
if (npc == null)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new
{
success = false,
error = "npc_not_found"
}, ct);
return;
}
// Check distance (NPC must be within interaction range)
float dist = MathF.Sqrt(MathF.Pow(npc.X - s.X, 2) + MathF.Pow(npc.Y - s.Y, 2));
if (dist > 128f) // ~4 tiles
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new
{
success = false,
error = "too_far"
}, ct);
return;
}
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new
{
success = true,
npc = new
{
id = npc.Id,
definitionId = npc.DefinitionId,
name = npc.Name,
canShop = npc.CanShop,
hasDialog = npc.HasDialog,
isKillable = npc.IsKillable,
behavior = npc.BehaviorMode.ToString().ToLower(),
onAttackBehavior = npc.OnAttackBehavior.ToString().ToLower(),
shopId = npc.ShopId,
dialogTreeId = npc.DialogTreeId
}
}, ct);
if (npc.HasDialog && npc.DialogTreeId.HasValue)
{
await SendWorldNpcDialogNodeAsync(conn, s, npc, null, ct);
}
if (npc.CanShop && npc.ShopId.HasValue)
{
await SendWorldNpcShopStateAsync(conn, npc.ShopId.Value, ct);
}
}
private async Task HandleWorldNpcDialogSelect(IConnection conn, WorldSessionState s, ReadOnlyMemory payload, CancellationToken ct)
{
var req = WorldInputParser.Parse(payload);
if (req == null) return;
var npc = FindWorldNpc(s, req.NpcId);
if (npc == null || !npc.HasDialog || !npc.DialogTreeId.HasValue)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new
{
success = false,
error = "npc_dialog_unavailable"
}, ct);
return;
}
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
var option = await db.DungeonNpcDialogOptions
.Include(o => o.Node)
.FirstOrDefaultAsync(o => o.Id == req.OptionId, ct);
if (option == null || option.Node == null || option.Node.DialogTreeId != npc.DialogTreeId.Value)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new
{
success = false,
error = "invalid_option"
}, ct);
return;
}
var (conditionMet, conditionError) = await EvaluateWorldDialogConditionAsync(db, s.CharacterId, option, ct);
if (!conditionMet)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new
{
success = false,
error = conditionError ?? "condition_failed"
}, ct);
return;
}
if (option.ConsumeConditionItem &&
option.ConditionType == NpcDialogConditionType.HasItem &&
int.TryParse(option.ConditionValue, out var consumeItemDefId))
{
await ConsumeWorldCharacterItemAsync(db, s.CharacterId, consumeItemDefId, Math.Max(1, option.ConditionQuantity), ct);
}
var nextNode = option.NextNodeId.HasValue
? await db.DungeonNpcDialogNodes.FirstOrDefaultAsync(n => n.Id == option.NextNodeId.Value && n.DialogTreeId == npc.DialogTreeId.Value, ct)
: null;
if (nextNode != null)
{
await ApplyWorldDialogRewardsAsync(db, s.CharacterId, nextNode, ct);
await SendWorldNpcDialogNodeAsync(conn, s, npc, nextNode.Id, ct);
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new
{
success = true,
npcId = npc.Id,
nextNodeId = nextNode.Id,
isTerminal = nextNode.IsTerminal
}, ct);
return;
}
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new
{
success = true,
npcId = npc.Id,
nextNodeId = (int?)null,
isTerminal = true
}, ct);
}
private async Task HandleWorldNpcShopAction(IConnection conn, WorldSessionState s, ReadOnlyMemory payload, CancellationToken ct)
{
var req = WorldInputParser.Parse(payload);
if (req == null) return;
var npc = FindWorldNpc(s, req.NpcId);
if (npc == null || !npc.CanShop || !npc.ShopId.HasValue)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "npc_shop_unavailable"
}, ct);
return;
}
if (string.Equals(req.Action, "sell", StringComparison.OrdinalIgnoreCase))
{
await HandleWorldNpcShopSellAsync(conn, s, npc, req, ct);
return;
}
if (!string.Equals(req.Action, "buy", StringComparison.OrdinalIgnoreCase))
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "unsupported_shop_action"
}, ct);
return;
}
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
var shopItem = await db.DungeonNpcShopItems
.Include(si => si.ItemDefinition)
.FirstOrDefaultAsync(si => si.ShopId == npc.ShopId.Value && si.SlotIndex == req.SlotIndex, ct);
if (shopItem == null || shopItem.ItemDefinition == null)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "shop_item_not_found"
}, ct);
return;
}
var quantity = Math.Max(1, req.Quantity);
if (!shopItem.Restocks)
{
quantity = Math.Min(quantity, shopItem.Quantity);
if (quantity <= 0)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "out_of_stock"
}, ct);
return;
}
}
var totalPrice = shopItem.PriceGold * quantity;
var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId, ct);
if (character == null)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "character_not_found"
}, ct);
return;
}
if (character.Gold < totalPrice)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "not_enough_gold",
requiredGold = totalPrice,
currentGold = character.Gold
}, ct);
return;
}
var added = await AddWorldItemToInventoryAsync(db, s.CharacterId, shopItem.ItemDefinitionId, quantity, ct);
if (!added)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = false,
error = "inventory_full"
}, ct);
return;
}
character.Gold -= totalPrice;
if (!shopItem.Restocks)
{
shopItem.Quantity = Math.Max(0, shopItem.Quantity - quantity);
}
await db.SaveChangesAsync(ct);
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new
{
success = true,
npcId = npc.Id,
action = "buy",
itemDefinitionId = shopItem.ItemDefinitionId,
quantity,
totalPrice,
remainingGold = character.Gold,
remainingStock = shopItem.Quantity
}, ct);
// Re-send updated shop state
await SendWorldNpcShopStateAsync(conn, npc.ShopId.Value, ct);
}
// ---- World NPC Helpers ----
private async Task SendWorldNpcDialogNodeAsync(IConnection conn, WorldSessionState s, NpcInstance npc, int? nodeId, CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
DungeonNpcDialogNode? node;
if (nodeId.HasValue)
{
node = await db.DungeonNpcDialogNodes
.FirstOrDefaultAsync(n => n.Id == nodeId.Value && n.DialogTreeId == npc.DialogTreeId, ct);
}
else
{
node = await db.DungeonNpcDialogNodes
.FirstOrDefaultAsync(n => n.DialogTreeId == npc.DialogTreeId && n.IsRoot, ct);
}
if (node == null)
{
await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_DIALOG_RESULT, new
{
success = false,
error = "dialog_node_not_found",
npcId = npc.Id
}, ct);
return;
}
var options = await db.DungeonNpcDialogOptions
.Where(o => o.NodeId == node.Id)
.OrderBy(o => o.SortOrder)
.ToListAsync(ct);
var filtered = new List