From 14d74fa9ce5afab439f6bb34e1fc72ca63956699 Mon Sep 17 00:00:00 2001 From: dingo Date: Tue, 17 Feb 2026 11:18:55 -0500 Subject: [PATCH] World changes --- .claude/settings.local.json | 7 + Game/Dungeon/CombatCalculator.cs | 52 +- Game/Dungeon/DungeonSimulation.cs | 11 +- Game/Dungeon/MobAI.cs | 187 +++-- Game/Dungeon/PlayerInstance.cs | 4 +- Game/Shared/ICombatEnvironment.cs | 40 + Game/Shared/IPlayerTarget.cs | 43 + Game/World/WorldBroadcastService.cs | 24 +- Game/World/WorldChunkCache.cs | 58 +- Game/World/WorldHandler.Combat.cs | 331 ++++++++ Game/World/WorldHandler.Npcs.cs | 562 +++++++++++++ Game/World/WorldHandler.Objects.cs | 255 ++++++ Game/World/WorldHandler.cs | 365 ++++++++- Game/World/WorldMobSpawnTracker.cs | 229 ++++++ Game/World/WorldMovementService.cs | 49 +- Game/World/WorldPlayerCombatState.cs | 120 +++ Game/World/WorldPortalMetadata.cs | 11 + Game/World/WorldSessionState.cs | 1 + Game/World/WorldZoneSimulation.cs | 771 ++++++++++++++++++ Networking/Messages/OpCodes.cs | 45 + .../Admin/Pages/WorldEditor/Index.cshtml.cs | 16 +- data/entities/DungeonCharacter.cs | 1 + data/entities/WorldEntities.cs | 4 +- 23 files changed, 3029 insertions(+), 157 deletions(-) create mode 100644 .claude/settings.local.json create mode 100644 Game/Shared/ICombatEnvironment.cs create mode 100644 Game/Shared/IPlayerTarget.cs create mode 100644 Game/World/WorldHandler.Combat.cs create mode 100644 Game/World/WorldHandler.Npcs.cs create mode 100644 Game/World/WorldHandler.Objects.cs create mode 100644 Game/World/WorldMobSpawnTracker.cs create mode 100644 Game/World/WorldPlayerCombatState.cs create mode 100644 Game/World/WorldZoneSimulation.cs diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..00fc07d --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,7 @@ +{ + "permissions": { + "allow": [ + "Bash(dotnet build:*)" + ] + } +} diff --git a/Game/Dungeon/CombatCalculator.cs b/Game/Dungeon/CombatCalculator.cs index 6755ddf..7c5f0bf 100644 --- a/Game/Dungeon/CombatCalculator.cs +++ b/Game/Dungeon/CombatCalculator.cs @@ -1,4 +1,5 @@ using DataServer.Data.Entities; +using GameServer.Shared; namespace GameServer.Dungeon; @@ -11,7 +12,7 @@ public static class CombatCalculator /// Calculate damage dealt from player to mob /// public static DamageResult CalculatePlayerToMobDamage( - PlayerInstance player, + IPlayerTarget player, MobInstance mob, string damageTypeKey, int baseDamage) @@ -70,7 +71,7 @@ public static class CombatCalculator /// public static DamageResult CalculateMobToPlayerDamage( MobInstance mob, - PlayerInstance player, + IPlayerTarget player, string damageTypeKey, int baseDamage, Dictionary playerTotalResistances) @@ -148,7 +149,7 @@ public static class CombatCalculator /// Calculate player weapon damage range /// public static (int min, int max, string damageTypeKey) GetPlayerWeaponDamage( - PlayerInstance player, + IPlayerTarget player, DungeonItemDefinition? weapon) { if (weapon == null) @@ -191,6 +192,51 @@ public static class CombatCalculator return (true, null); } + + /// + /// Calculate damage dealt from player to player (PvP) + /// + public static DamageResult CalculatePlayerToPlayerDamage( + IPlayerTarget attacker, + IPlayerTarget defender, + string damageTypeKey, + int baseDamage) + { + // 1. Base damage modified by attacker stats + float damage = baseDamage; + if (damageTypeKey == "physical") + damage *= 1 + (attacker.Strength * 0.05f); + else + damage *= 1 + (attacker.Intelligence * 0.05f); + + // 2. Apply defender armor + float armorMitigation = defender.Armor / (float)(defender.Armor + 100); + damage *= (1 - armorMitigation); + + // 3. Apply defender resistances (capped at 75%) + float defenderResist = 0f; + if (defender.Resistances.TryGetValue(damageTypeKey, out float resist)) + defenderResist = Math.Min(resist, 0.75f); + if (defenderResist != 0) + damage *= (1 - defenderResist); + + // 4. Endurance reduction (capped at 50%) + float enduranceReduction = Math.Min(defender.Endurance / (float)(defender.Endurance + 100), 0.50f); + damage *= (1.0f - enduranceReduction); + + // 5. PvP damage reduction (30% global reduction to make fights last longer) + damage *= 0.7f; + + int finalDamage = Math.Max(1, (int)damage); + + return new DamageResult + { + FinalDamage = finalDamage, + WasResisted = defenderResist > 0, + WasWeakness = defenderResist < 0, + DamageTypeKey = damageTypeKey + }; + } } public class DamageResult diff --git a/Game/Dungeon/DungeonSimulation.cs b/Game/Dungeon/DungeonSimulation.cs index 1131707..ca53d1e 100644 --- a/Game/Dungeon/DungeonSimulation.cs +++ b/Game/Dungeon/DungeonSimulation.cs @@ -2,13 +2,14 @@ using System.Collections.Concurrent; using System.Text.Json; using DataServer.Data.Entities; using DataServer.Data.Enums; +using GameServer.Shared; namespace GameServer.Dungeon; /// /// Runtime simulation for an active dungeon instance /// -public partial class DungeonSimulation +public partial class DungeonSimulation : ICombatEnvironment { public DungeonLayout Layout { get; } public int Tier { get; } @@ -1887,6 +1888,14 @@ public partial class DungeonSimulation _pendingSummons.Add((mobDefinitionId, x, y, tier)); } + // ---- ICombatEnvironment implementation ---- + + IEnumerable ICombatEnvironment.GetAlivePlayers() + => Players.Values.Where(p => p.IsAlive); + + IPlayerTarget? ICombatEnvironment.GetPlayer(ulong characterId) + => Players.TryGetValue(characterId, out var p) ? p : null; + public int AllocateRuntimeMobId() { lock (_mobIdLock) diff --git a/Game/Dungeon/MobAI.cs b/Game/Dungeon/MobAI.cs index 8e46912..5d51faf 100644 --- a/Game/Dungeon/MobAI.cs +++ b/Game/Dungeon/MobAI.cs @@ -1,5 +1,6 @@ using DataServer.Data.Entities; using DataServer.Data.Enums; +using GameServer.Shared; namespace GameServer.Dungeon; @@ -13,7 +14,7 @@ public static class MobAI /// /// Main AI update - called each tick for each mob /// - public static void UpdateMob(MobInstance mob, DungeonSimulation sim, float deltaTime) + public static void UpdateMob(MobInstance mob, ICombatEnvironment env, float deltaTime) { if (!mob.IsAlive || mob.IsStunned) return; @@ -21,7 +22,7 @@ public static class MobAI UpdateCooldowns(mob, deltaTime); // Update status effects - UpdateStatusEffects(mob, sim, deltaTime); + UpdateStatusEffects(mob, env, deltaTime); // Check for phase transitions (for bosses) CheckPhaseTransition(mob); @@ -35,7 +36,7 @@ public static class MobAI mob.CastTimeRemaining -= deltaTime; if (mob.CastTimeRemaining <= 0) { - ExecuteAbility(mob, mob.CastingAbility, sim); + ExecuteAbility(mob, mob.CastingAbility, env); mob.CastingAbility = null; mob.State = MobState.Idle; mob.StateTime = 0; @@ -47,37 +48,37 @@ public static class MobAI switch (mob.Behavior) { case MobBehavior.Aggressive: - UpdateAggressive(mob, sim, deltaTime); + UpdateAggressive(mob, env, deltaTime); break; case MobBehavior.Defensive: - UpdateDefensive(mob, sim, deltaTime); + UpdateDefensive(mob, env, deltaTime); break; case MobBehavior.Ranged: - UpdateRanged(mob, sim, deltaTime); + UpdateRanged(mob, env, deltaTime); break; case MobBehavior.Skirmisher: - UpdateSkirmisher(mob, sim, deltaTime); + UpdateSkirmisher(mob, env, deltaTime); break; case MobBehavior.Tank: - UpdateTank(mob, sim, deltaTime); + UpdateTank(mob, env, deltaTime); break; case MobBehavior.Assassin: - UpdateAssassin(mob, sim, deltaTime); + UpdateAssassin(mob, env, deltaTime); break; case MobBehavior.Healer: - UpdateHealer(mob, sim, deltaTime); + UpdateHealer(mob, env, deltaTime); break; case MobBehavior.Patrol: - UpdatePatrol(mob, sim, deltaTime); + UpdatePatrol(mob, env, deltaTime); break; case MobBehavior.Pack: - UpdatePack(mob, sim, deltaTime); + UpdatePack(mob, env, deltaTime); break; case MobBehavior.Summoner: - UpdateSummoner(mob, sim, deltaTime); + UpdateSummoner(mob, env, deltaTime); break; default: - UpdateAggressive(mob, sim, deltaTime); + UpdateAggressive(mob, env, deltaTime); break; } } @@ -87,14 +88,14 @@ public static class MobAI /// /// Aggressive: Charges player on sight, melee attacks. Wanders when idle. /// - private static void UpdateAggressive(MobInstance mob, DungeonSimulation sim, float deltaTime) + private static void UpdateAggressive(MobInstance mob, ICombatEnvironment env, float deltaTime) { - var target = FindNearestPlayer(mob, sim); + var target = FindNearestPlayer(mob, env); if (target == null) { // No target - wander or return to spawn area - UpdateIdleWander(mob, sim, deltaTime); + UpdateIdleWander(mob, env, deltaTime); return; } @@ -104,7 +105,7 @@ public static class MobAI // Check leash range if (distFromSpawn > mob.Stats.LeashRange) { - ReturnToSpawn(mob, sim, deltaTime); + ReturnToSpawn(mob, env, deltaTime); return; } @@ -125,16 +126,16 @@ public static class MobAI // Chase mob.State = MobState.Chasing; mob.CurrentAnimation = mob.GetDirectionalAnimation("walk"); - MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, sim); + MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, env); } } /// /// Defensive: Only attacks if player comes close to spawn. Wanders near spawn. /// - private static void UpdateDefensive(MobInstance mob, DungeonSimulation sim, float deltaTime) + private static void UpdateDefensive(MobInstance mob, ICombatEnvironment env, float deltaTime) { - var target = FindNearestPlayer(mob, sim); + var target = FindNearestPlayer(mob, env); float distFromSpawn = GetDistance(mob.X, mob.Y, mob.SpawnX, mob.SpawnY); if (target != null) @@ -148,7 +149,7 @@ public static class MobAI // Don't stray too far from spawn if (distFromSpawn > mob.Stats.LeashRange * 0.5f) { - ReturnToSpawn(mob, sim, deltaTime); + ReturnToSpawn(mob, env, deltaTime); return; } @@ -164,7 +165,7 @@ public static class MobAI else { mob.State = MobState.Chasing; - MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 0.7f * deltaTime, sim); + MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 0.7f * deltaTime, env); } return; } @@ -172,19 +173,19 @@ public static class MobAI // No threat - wander near spawn mob.TargetId = null; - UpdateIdleWander(mob, sim, deltaTime, wanderRadius: 80f); + UpdateIdleWander(mob, env, deltaTime, wanderRadius: 80f); } /// /// Ranged: Keeps distance, fires projectiles /// - private static void UpdateRanged(MobInstance mob, DungeonSimulation sim, float deltaTime) + private static void UpdateRanged(MobInstance mob, ICombatEnvironment env, float deltaTime) { - var target = FindNearestPlayer(mob, sim); + var target = FindNearestPlayer(mob, env); if (target == null) { - UpdateIdleWander(mob, sim, deltaTime); + UpdateIdleWander(mob, env, deltaTime); return; } @@ -193,7 +194,7 @@ public static class MobAI if (distFromSpawn > mob.Stats.LeashRange) { - ReturnToSpawn(mob, sim, deltaTime); + ReturnToSpawn(mob, env, deltaTime); return; } @@ -209,14 +210,14 @@ public static class MobAI // Too close, back up mob.State = MobState.Kiting; mob.CurrentAnimation = mob.GetDirectionalAnimation("walk"); - MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, sim); + MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, env); } else if (distance > preferredRange * 1.3f && distance <= mob.Stats.LeashRange) { // Too far, move closer mob.State = MobState.Chasing; mob.CurrentAnimation = mob.GetDirectionalAnimation("walk"); - MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, sim); + MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, env); } else { @@ -229,13 +230,13 @@ public static class MobAI /// /// Skirmisher: Hit-and-run tactics /// - private static void UpdateSkirmisher(MobInstance mob, DungeonSimulation sim, float deltaTime) + private static void UpdateSkirmisher(MobInstance mob, ICombatEnvironment env, float deltaTime) { - var target = FindNearestPlayer(mob, sim); + var target = FindNearestPlayer(mob, env); if (target == null) { - UpdateIdleWander(mob, sim, deltaTime); + UpdateIdleWander(mob, env, deltaTime); return; } @@ -247,13 +248,13 @@ public static class MobAI { mob.State = MobState.Fleeing; mob.CurrentAnimation = mob.GetDirectionalAnimation("walk"); - MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * 1.3f * deltaTime, sim); + MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * 1.3f * deltaTime, env); return; } if (distFromSpawn > mob.Stats.LeashRange) { - ReturnToSpawn(mob, sim, deltaTime); + ReturnToSpawn(mob, env, deltaTime); return; } @@ -274,7 +275,7 @@ public static class MobAI else { mob.State = MobState.Chasing; - MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 1.2f * deltaTime, sim); + MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 1.2f * deltaTime, env); } } else @@ -282,20 +283,20 @@ public static class MobAI // Retreat phase mob.State = MobState.Kiting; mob.CurrentAnimation = mob.GetDirectionalAnimation("walk"); - MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, sim); + MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, env); } } /// /// Tank: Slow but tough, always moves toward target /// - private static void UpdateTank(MobInstance mob, DungeonSimulation sim, float deltaTime) + private static void UpdateTank(MobInstance mob, ICombatEnvironment env, float deltaTime) { - var target = FindNearestPlayer(mob, sim); + var target = FindNearestPlayer(mob, env); if (target == null) { - UpdateIdleWander(mob, sim, deltaTime, wanderRadius: 50f); + UpdateIdleWander(mob, env, deltaTime, wanderRadius: 50f); return; } @@ -304,7 +305,7 @@ public static class MobAI if (distFromSpawn > mob.Stats.LeashRange) { - ReturnToSpawn(mob, sim, deltaTime); + ReturnToSpawn(mob, env, deltaTime); return; } @@ -322,25 +323,24 @@ public static class MobAI mob.State = MobState.Chasing; mob.CurrentAnimation = mob.GetDirectionalAnimation("walk"); // Tanks move at 60% speed - MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 0.6f * deltaTime, sim); + MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 0.6f * deltaTime, env); } } /// /// Assassin: Targets lowest HP player, moves fast /// - private static void UpdateAssassin(MobInstance mob, DungeonSimulation sim, float deltaTime) + private static void UpdateAssassin(MobInstance mob, ICombatEnvironment env, float deltaTime) { // Target lowest HP player - var target = sim.Players.Values - .Where(p => p.IsAlive) + var target = env.GetAlivePlayers() .Where(p => GetDistance(mob.X, mob.Y, p.X, p.Y) <= mob.Stats.AggroRange) .OrderBy(p => p.Health / p.MaxHealth) .FirstOrDefault(); if (target == null) { - UpdateIdleWander(mob, sim, deltaTime); + UpdateIdleWander(mob, env, deltaTime); return; } @@ -349,7 +349,7 @@ public static class MobAI if (distFromSpawn > mob.Stats.LeashRange) { - ReturnToSpawn(mob, sim, deltaTime); + ReturnToSpawn(mob, env, deltaTime); return; } @@ -366,17 +366,17 @@ public static class MobAI mob.State = MobState.Chasing; mob.CurrentAnimation = mob.GetDirectionalAnimation("walk"); // Assassins move at 130% speed - MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 1.3f * deltaTime, sim); + MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed * 1.3f * deltaTime, env); } } /// /// Healer: Heals nearby mobs, stays back from combat /// - private static void UpdateHealer(MobInstance mob, DungeonSimulation sim, float deltaTime) + private static void UpdateHealer(MobInstance mob, ICombatEnvironment env, float deltaTime) { // Check for injured allies first - var injuredAlly = sim.Mobs.Values + var injuredAlly = env.Mobs.Values .Where(m => m.IsAlive && m.Id != mob.Id) .Where(m => GetDistance(mob.X, mob.Y, m.X, m.Y) <= 150f) .Where(m => m.HpPercent < 0.7f) @@ -402,7 +402,7 @@ public static class MobAI } // Otherwise, stay back from combat - var target = FindNearestPlayer(mob, sim); + var target = FindNearestPlayer(mob, env); if (target != null) { float distance = GetDistance(mob.X, mob.Y, target.X, target.Y); @@ -411,7 +411,7 @@ public static class MobAI if (distance < preferredRange) { mob.State = MobState.Kiting; - MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, sim); + MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, env); } else if (distance <= mob.Stats.AttackRange) { @@ -420,69 +420,69 @@ public static class MobAI } else { - UpdateIdleWander(mob, sim, deltaTime); + UpdateIdleWander(mob, env, deltaTime); } } /// /// Patrol: Walks a path, alerts others when seeing players /// - private static void UpdatePatrol(MobInstance mob, DungeonSimulation sim, float deltaTime) + private static void UpdatePatrol(MobInstance mob, ICombatEnvironment env, float deltaTime) { - var target = FindNearestPlayer(mob, sim); + var target = FindNearestPlayer(mob, env); if (target != null) { // Alert nearby mobs if (!mob.HasCalledForHelp) { - CallForHelp(mob, sim); + CallForHelp(mob, env); } // Then fight like aggressive - UpdateAggressive(mob, sim, deltaTime); + UpdateAggressive(mob, env, deltaTime); } else { mob.HasCalledForHelp = false; // Patrol - wander in a larger area - UpdateIdleWander(mob, sim, deltaTime, wanderRadius: 150f); + UpdateIdleWander(mob, env, deltaTime, wanderRadius: 150f); } } /// /// Pack: Calls nearby mobs when engaged /// - private static void UpdatePack(MobInstance mob, DungeonSimulation sim, float deltaTime) + private static void UpdatePack(MobInstance mob, ICombatEnvironment env, float deltaTime) { - var target = FindNearestPlayer(mob, sim); + var target = FindNearestPlayer(mob, env); if (target != null) { if (!mob.HasCalledForHelp) { - CallForHelp(mob, sim); + CallForHelp(mob, env); } - UpdateAggressive(mob, sim, deltaTime); + UpdateAggressive(mob, env, deltaTime); } else { mob.HasCalledForHelp = false; - UpdateIdleWander(mob, sim, deltaTime); + UpdateIdleWander(mob, env, deltaTime); } } /// /// Summoner: Stays back and summons minions /// - private static void UpdateSummoner(MobInstance mob, DungeonSimulation sim, float deltaTime) + private static void UpdateSummoner(MobInstance mob, ICombatEnvironment env, float deltaTime) { - var target = FindNearestPlayer(mob, sim); + var target = FindNearestPlayer(mob, env); if (target == null) { - UpdateIdleWander(mob, sim, deltaTime); + UpdateIdleWander(mob, env, deltaTime); return; } @@ -512,7 +512,7 @@ public static class MobAI if (distance < preferredRange * 0.5f) { mob.State = MobState.Kiting; - MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, sim); + MoveAwayFrom(mob, target.X, target.Y, mob.Stats.MoveSpeed * deltaTime, env); } else { @@ -528,7 +528,7 @@ public static class MobAI /// /// Wander around spawn area when no targets /// - private static void UpdateIdleWander(MobInstance mob, DungeonSimulation sim, float deltaTime, float wanderRadius = 0f) + private static void UpdateIdleWander(MobInstance mob, ICombatEnvironment env, float deltaTime, float wanderRadius = 0f) { // Use leash range if no wander radius specified if (wanderRadius <= 0) @@ -539,7 +539,7 @@ public static class MobAI // Too far from spawn? Return first if (distFromSpawn > wanderRadius) { - ReturnToSpawn(mob, sim, deltaTime); + ReturnToSpawn(mob, env, deltaTime); return; } @@ -572,7 +572,7 @@ public static class MobAI float targetY = mob.SpawnY + MathF.Sin(angle) * dist; // Check if target is walkable - if (sim.CanActorMoveTo(targetX, targetY)) + if (env.CanActorMoveTo(targetX, targetY)) { mob.WanderTargetX = targetX; mob.WanderTargetY = targetY; @@ -610,12 +610,12 @@ public static class MobAI // Keep moving toward target (30% speed for casual wandering) mob.UpdateFacingDirection(mob.WanderTargetX, mob.WanderTargetY); mob.CurrentAnimation = mob.GetDirectionalAnimation("walk"); - MoveToward(mob, mob.WanderTargetX, mob.WanderTargetY, mob.Stats.MoveSpeed * 0.3f * deltaTime, sim); + MoveToward(mob, mob.WanderTargetX, mob.WanderTargetY, mob.Stats.MoveSpeed * 0.3f * deltaTime, env); } } } - private static void ReturnToSpawn(MobInstance mob, DungeonSimulation sim, float deltaTime) + private static void ReturnToSpawn(MobInstance mob, ICombatEnvironment env, float deltaTime) { float dist = GetDistance(mob.X, mob.Y, mob.SpawnX, mob.SpawnY); @@ -636,7 +636,7 @@ public static class MobAI mob.TargetId = null; mob.UpdateFacingDirection(mob.SpawnX, mob.SpawnY); mob.CurrentAnimation = mob.GetDirectionalAnimation("walk"); - MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed * deltaTime, sim); + MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed * deltaTime, env); // Heal while returning if (mob.Health < mob.MaxHealth) @@ -650,12 +650,12 @@ public static class MobAI } } - private static void CallForHelp(MobInstance mob, DungeonSimulation sim) + private static void CallForHelp(MobInstance mob, ICombatEnvironment env) { mob.HasCalledForHelp = true; float helpRadius = mob.Stats.AggroRange * 1.5f; - foreach (var ally in sim.Mobs.Values.Where(m => m.IsAlive && m.Id != mob.Id)) + foreach (var ally in env.Mobs.Values.Where(m => m.IsAlive && m.Id != mob.Id)) { if (GetDistance(mob.X, mob.Y, ally.X, ally.Y) <= helpRadius) { @@ -673,7 +673,7 @@ public static class MobAI #region Movement with Collision - private static void MoveToward(MobInstance mob, float targetX, float targetY, float speed, DungeonSimulation sim) + private static void MoveToward(MobInstance mob, float targetX, float targetY, float speed, ICombatEnvironment env) { if (mob.IsRooted) return; @@ -693,7 +693,7 @@ public static class MobAI float newY = mob.Y + moveY; // Check collision for each axis separately - if (sim.CanActorMoveTo(newX, mob.Y)) + if (env.CanActorMoveTo(newX, mob.Y)) { mob.X = newX; } @@ -703,7 +703,7 @@ public static class MobAI mob.StuckTime += 0.05f; } - if (sim.CanActorMoveTo(mob.X, newY)) + if (env.CanActorMoveTo(mob.X, newY)) { mob.Y = newY; } @@ -715,12 +715,12 @@ public static class MobAI // If stuck for too long, try to unstick if (mob.StuckTime > 1f) { - TryUnstick(mob, sim); + TryUnstick(mob, env); mob.StuckTime = 0; } } - private static void MoveAwayFrom(MobInstance mob, float targetX, float targetY, float speed, DungeonSimulation sim) + private static void MoveAwayFrom(MobInstance mob, float targetX, float targetY, float speed, ICombatEnvironment env) { if (mob.IsRooted) return; @@ -736,25 +736,25 @@ public static class MobAI float newX = mob.X + moveX; float newY = mob.Y + moveY; - if (sim.CanActorMoveTo(newX, mob.Y)) + if (env.CanActorMoveTo(newX, mob.Y)) { mob.X = newX; } - if (sim.CanActorMoveTo(mob.X, newY)) + if (env.CanActorMoveTo(mob.X, newY)) { mob.Y = newY; } } - private static void TryUnstick(MobInstance mob, DungeonSimulation sim) + private static void TryUnstick(MobInstance mob, ICombatEnvironment env) { // Try moving in cardinal directions to get unstuck float[] offsets = { 16, -16 }; foreach (float ox in offsets) { - if (sim.CanActorMoveTo(mob.X + ox, mob.Y)) + if (env.CanActorMoveTo(mob.X + ox, mob.Y)) { mob.X += ox * 0.5f; return; @@ -763,7 +763,7 @@ public static class MobAI foreach (float oy in offsets) { - if (sim.CanActorMoveTo(mob.X, mob.Y + oy)) + if (env.CanActorMoveTo(mob.X, mob.Y + oy)) { mob.Y += oy * 0.5f; return; @@ -775,7 +775,7 @@ public static class MobAI #region Ability System - private static void ExecuteAbility(MobInstance mob, MobAbilityState ability, DungeonSimulation sim) + private static void ExecuteAbility(MobInstance mob, MobAbilityState ability, ICombatEnvironment env) { ability.CooldownRemaining = ability.Definition.Cooldown; mob.Mana -= ability.Definition.ManaCost; @@ -786,7 +786,7 @@ public static class MobAI { case MobAbilityType.SummonSingle: case MobAbilityType.SummonBulk: - ExecuteSummon(mob, ability, sim); + ExecuteSummon(mob, ability, env); break; // TODO: Implement other ability types @@ -796,7 +796,7 @@ public static class MobAI } } - private static void ExecuteSummon(MobInstance mob, MobAbilityState ability, DungeonSimulation sim) + private static void ExecuteSummon(MobInstance mob, MobAbilityState ability, ICombatEnvironment env) { if (!ability.Definition.SummonMobId.HasValue) { @@ -819,7 +819,7 @@ public static class MobAI float spawnY = mob.Y + (float)Math.Sin(angle) * summonDistance; // Make sure spawn position is walkable - if (!sim.CanActorMoveTo(spawnX, spawnY)) + if (!env.CanActorMoveTo(spawnX, spawnY)) { // Try closer spawnX = mob.X + (float)Math.Cos(angle) * (summonDistance * 0.5f); @@ -827,7 +827,7 @@ public static class MobAI } // Request mob spawn (this will be handled by DungeonSimulation) - sim.RequestMobSummon(summonMobId, spawnX, spawnY, sim.Tier); + env.RequestMobSummon(summonMobId, spawnX, spawnY, env.Tier); } } @@ -844,7 +844,7 @@ public static class MobAI } } - private static void UpdateStatusEffects(MobInstance mob, DungeonSimulation sim, float deltaTime) + private static void UpdateStatusEffects(MobInstance mob, ICombatEnvironment env, float deltaTime) { var expired = new List(); @@ -898,10 +898,9 @@ public static class MobAI } } - private static PlayerInstance? FindNearestPlayer(MobInstance mob, DungeonSimulation sim) + private static IPlayerTarget? FindNearestPlayer(MobInstance mob, ICombatEnvironment env) { - return sim.Players.Values - .Where(p => p.IsAlive) + return env.GetAlivePlayers() .Where(p => GetDistance(mob.X, mob.Y, p.X, p.Y) <= mob.Stats.AggroRange) .OrderBy(p => GetDistance(mob.X, mob.Y, p.X, p.Y)) .FirstOrDefault(); diff --git a/Game/Dungeon/PlayerInstance.cs b/Game/Dungeon/PlayerInstance.cs index 0cf6844..8295318 100644 --- a/Game/Dungeon/PlayerInstance.cs +++ b/Game/Dungeon/PlayerInstance.cs @@ -1,9 +1,11 @@ +using GameServer.Shared; + namespace GameServer.Dungeon; /// /// Runtime instance of a player in a dungeon /// -public class PlayerInstance +public class PlayerInstance : IPlayerTarget { public ulong CharacterId { get; set; } public string CharacterName { get; set; } = ""; diff --git a/Game/Shared/ICombatEnvironment.cs b/Game/Shared/ICombatEnvironment.cs new file mode 100644 index 0000000..a6e6346 --- /dev/null +++ b/Game/Shared/ICombatEnvironment.cs @@ -0,0 +1,40 @@ +using System.Collections.Concurrent; +using GameServer.Dungeon; + +namespace GameServer.Shared; + +/// +/// Abstraction over the spatial/entity environment that MobAI and combat systems need. +/// Implemented by both DungeonSimulation (dungeons) and WorldZoneSimulation (overworld). +/// +public interface ICombatEnvironment +{ + // ---- Spatial ---- + + /// Check if an actor-sized entity can move to the given world-pixel position. + bool CanActorMoveTo(float x, float y); + + // ---- Entity lookups ---- + + /// All alive players in this environment. + IEnumerable GetAlivePlayers(); + + /// All alive mobs in this environment. + ConcurrentDictionary Mobs { get; } + + /// Get a specific player by character ID. + IPlayerTarget? GetPlayer(ulong characterId); + + // ---- Mob summoning ---- + + /// Request spawning a new mob (summoner ability). + void RequestMobSummon(int mobDefinitionId, float x, float y, int tier); + + // ---- Context ---- + + /// The tier/difficulty level of this environment (dungeon tier or world zone level). + int Tier { get; } + + /// Current simulation tick. + long CurrentTick { get; } +} diff --git a/Game/Shared/IPlayerTarget.cs b/Game/Shared/IPlayerTarget.cs new file mode 100644 index 0000000..edfbbae --- /dev/null +++ b/Game/Shared/IPlayerTarget.cs @@ -0,0 +1,43 @@ +using GameServer.Dungeon; + +namespace GameServer.Shared; + +/// +/// Interface for player combat state, implemented by both dungeon PlayerInstance +/// and world WorldPlayerCombatState. Provides the combat-relevant surface that +/// MobAI and CombatCalculator need. +/// +public interface IPlayerTarget +{ + ulong CharacterId { get; } + string CharacterName { get; } + + // Position + float X { get; } + float Y { get; } + + // Vitals + float Health { get; set; } + float MaxHealth { get; } + bool IsAlive { get; set; } + bool IsInvulnerable { get; } + + // Combat stats + int Strength { get; } + int Intelligence { get; } + int Endurance { get; } + int Dexterity { get; } + int Armor { get; } + string WeaponDamageTypeKey { get; } + Dictionary Resistances { get; } + + // Status effects + List StatusEffects { get; } + bool IsStunned { get; } + bool IsRooted { get; } + bool IsFeared { get; } + + // Combat tracking + bool IsInCombat { get; set; } + long LastCombatTick { get; set; } +} diff --git a/Game/World/WorldBroadcastService.cs b/Game/World/WorldBroadcastService.cs index 103d0c5..1edf6d3 100644 --- a/Game/World/WorldBroadcastService.cs +++ b/Game/World/WorldBroadcastService.cs @@ -44,12 +44,12 @@ public sealed class WorldBroadcastService var zy = ay / region.ChunksPerZoneY; var cx = ax % region.ChunksPerZoneX; var cy = ay % region.ChunksPerZoneY; - var key = $"{region.Id}:{zx}:{zy}:{cx}:{cy}"; + var key = WorldChunkCache.ChunkKey(region.Id, zx, zy, s.ZoneZ, cx, cy); required.Add(key); if (!s.ChunkVersions.ContainsKey(key)) { - var cached = await _cache.GetChunkAsync(region.Id, zx, zy, cx, cy, ct); + var cached = await _cache.GetChunkAsync(region.Id, zx, zy, s.ZoneZ, cx, cy, ct); s.ChunkVersions[key] = cached?.Version ?? 0; if (cached != null) { @@ -82,15 +82,19 @@ public sealed class WorldBroadcastService { s.ChunkVersions.Remove(stale); var p = stale.Split(':'); - list.Add(("chunk_unload", new + if (p.Length >= 6) { - type = "chunk_unload", - regionId = int.Parse(p[0]), - zoneX = int.Parse(p[1]), - zoneY = int.Parse(p[2]), - chunkX = int.Parse(p[3]), - chunkY = int.Parse(p[4]) - })); + list.Add(("chunk_unload", new + { + type = "chunk_unload", + regionId = int.Parse(p[0]), + zoneX = int.Parse(p[1]), + zoneY = int.Parse(p[2]), + zoneZ = int.Parse(p[3]), + chunkX = int.Parse(p[4]), + chunkY = int.Parse(p[5]) + })); + } } return list; } diff --git a/Game/World/WorldChunkCache.cs b/Game/World/WorldChunkCache.cs index 16b8808..ef445ef 100644 --- a/Game/World/WorldChunkCache.cs +++ b/Game/World/WorldChunkCache.cs @@ -45,6 +45,7 @@ public sealed class WorldChunkCache public int RegionId { get; init; } public int ZoneX { get; init; } public int ZoneY { get; init; } + public int ZoneZ { get; init; } public int ChunkX { get; init; } public int ChunkY { get; init; } public int WidthTiles { get; init; } @@ -136,9 +137,9 @@ public sealed class WorldChunkCache return cached; } - public async ValueTask GetChunkAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, CancellationToken ct = default) + public async ValueTask GetChunkAsync(int regionId, int zoneX, int zoneY, int zoneZ, int chunkX, int chunkY, CancellationToken ct = default) { - var key = ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY); + var key = ChunkKey(regionId, zoneX, zoneY, zoneZ, chunkX, chunkY); if (_chunks.TryGetValue(key, out var cached)) return cached; @@ -150,7 +151,7 @@ public sealed class WorldChunkCache if (_chunks.TryGetValue(key, out cached)) return cached; - cached = await LoadChunkFromDbAsync(regionId, zoneX, zoneY, chunkX, chunkY, ct); + cached = await LoadChunkFromDbAsync(regionId, zoneX, zoneY, zoneZ, chunkX, chunkY, ct); _chunks[key] = cached; return cached; } @@ -160,7 +161,7 @@ public sealed class WorldChunkCache } } - public bool IsTileWalkable(CachedRegion region, float wx, float wy, bool isVip) + public bool IsTileWalkable(CachedRegion region, int zoneZ, float wx, float wy, bool isVip) { var gx = (int)MathF.Floor(wx / TileSize); var gy = (int)MathF.Floor(wy / TileSize); @@ -181,7 +182,7 @@ public sealed class WorldChunkCache var tx = lzx % region.ChunkWidthTiles; var ty = lzy % region.ChunkHeightTiles; - var key = ChunkKey(region.Id, zx, zy, cx, cy); + var key = ChunkKey(region.Id, zx, zy, zoneZ, cx, cy); if (!_chunks.TryGetValue(key, out var chunk) || chunk == null) return true; var idx = (ty * chunk.WidthTiles) + tx; @@ -192,17 +193,17 @@ public sealed class WorldChunkCache return true; } - public bool IsPositionWalkable(CachedRegion region, float wx, float wy, bool isVip) + public bool IsPositionWalkable(CachedRegion region, int zoneZ, float wx, float wy, bool isVip) { - if (!IsTileWalkable(region, wx, wy, isVip)) return false; - if (!IsTileWalkable(region, wx + 8f, wy, isVip)) return false; - if (!IsTileWalkable(region, wx - 8f, wy, isVip)) return false; - if (!IsTileWalkable(region, wx, wy + 8f, isVip)) return false; - if (!IsTileWalkable(region, wx, wy - 8f, isVip)) return false; + if (!IsTileWalkable(region, zoneZ, wx, wy, isVip)) return false; + if (!IsTileWalkable(region, zoneZ, wx + 8f, wy, isVip)) return false; + if (!IsTileWalkable(region, zoneZ, wx - 8f, wy, isVip)) return false; + if (!IsTileWalkable(region, zoneZ, wx, wy + 8f, isVip)) return false; + if (!IsTileWalkable(region, zoneZ, wx, wy - 8f, isVip)) return false; return true; } - public CachedPortalObject? FindPortalAtPosition(CachedRegion region, float wx, float wy) + public CachedPortalObject? FindPortalAtPosition(CachedRegion region, int zoneZ, float wx, float wy) { var gx = (int)MathF.Floor(wx / TileSize); var gy = (int)MathF.Floor(wy / TileSize); @@ -223,7 +224,7 @@ public sealed class WorldChunkCache var tx = lzx % region.ChunkWidthTiles; var ty = lzy % region.ChunkHeightTiles; - var key = ChunkKey(region.Id, zx, zy, cx, cy); + var key = ChunkKey(region.Id, zx, zy, zoneZ, cx, cy); if (!_chunks.TryGetValue(key, out var chunk) || chunk == null) return null; foreach (var portal in chunk.Portals) @@ -235,9 +236,9 @@ public sealed class WorldChunkCache return null; } - public void InvalidateChunk(int regionId, int zoneX, int zoneY, int chunkX, int chunkY) + public void InvalidateChunk(int regionId, int zoneX, int zoneY, int zoneZ, int chunkX, int chunkY) { - var key = ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY); + var key = ChunkKey(regionId, zoneX, zoneY, zoneZ, chunkX, chunkY); _chunks.TryRemove(key, out _); _log.LogInformation("Invalidated chunk cache: {Key}", key); } @@ -259,8 +260,9 @@ public sealed class WorldChunkCache using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); + // Only auto-create Z=0 (ground level) zones var existing = await db.WorldZones - .Where(z => z.RegionId == regionId) + .Where(z => z.RegionId == regionId && z.ZoneZ == 0) .Select(z => new { z.ZoneX, z.ZoneY }) .ToListAsync(ct); @@ -277,6 +279,7 @@ public sealed class WorldChunkCache RegionId = regionId, ZoneX = x, ZoneY = y, + ZoneZ = 0, Name = $"Zone {x},{y}", IsEnabled = true, CreatedAt = now, @@ -289,10 +292,13 @@ public sealed class WorldChunkCache // ---- Internal ---- - private static string ChunkKey(int regionId, int zoneX, int zoneY, int chunkX, int chunkY) - => $"{regionId}:{zoneX}:{zoneY}:{chunkX}:{chunkY}"; + public static string ChunkKey(int regionId, int zoneX, int zoneY, int zoneZ, int chunkX, int chunkY) + => $"{regionId}:{zoneX}:{zoneY}:{zoneZ}:{chunkX}:{chunkY}"; - private async Task LoadChunkFromDbAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, CancellationToken ct) + public static string ZoneKey(int regionId, int zoneX, int zoneY, int zoneZ) + => $"{regionId}:{zoneX}:{zoneY}:{zoneZ}"; + + private async Task LoadChunkFromDbAsync(int regionId, int zoneX, int zoneY, int zoneZ, int chunkX, int chunkY, CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); @@ -301,17 +307,17 @@ public sealed class WorldChunkCache if (region == null) return null; var zone = await db.WorldZones.AsNoTracking() - .FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.IsEnabled, ct); + .FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.ZoneZ == zoneZ && z.IsEnabled, ct); if (zone == null) { - return BuildEmptyChunk(region, zoneX, zoneY, chunkX, chunkY); + return BuildEmptyChunk(region, zoneX, zoneY, zoneZ, chunkX, chunkY); } var chunk = await db.WorldChunks.AsNoTracking() .FirstOrDefaultAsync(c => c.WorldZoneId == zone.Id && c.ChunkX == chunkX && c.ChunkY == chunkY, ct); if (chunk == null) { - return BuildEmptyChunk(region, zoneX, zoneY, chunkX, chunkY); + return BuildEmptyChunk(region, zoneX, zoneY, zoneZ, chunkX, chunkY); } var tiles = await db.WorldChunkTiles.AsNoTracking() @@ -428,6 +434,7 @@ public sealed class WorldChunkCache regionId, zoneX, zoneY, + zoneZ, chunkX, chunkY, version = chunk.Version, @@ -436,7 +443,7 @@ public sealed class WorldChunkCache }; _log.LogDebug("Loaded chunk {Key} from DB: {TileCount} tiles, {ObjectCount} objects, {PortalCount} portals", - ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY), tiles.Count, objects.Count, portals.Length); + ChunkKey(regionId, zoneX, zoneY, zoneZ, chunkX, chunkY), tiles.Count, objects.Count, portals.Length); return new CachedChunk { @@ -445,6 +452,7 @@ public sealed class WorldChunkCache RegionId = regionId, ZoneX = zoneX, ZoneY = zoneY, + ZoneZ = zoneZ, ChunkX = chunkX, ChunkY = chunkY, WidthTiles = w, @@ -460,7 +468,7 @@ public sealed class WorldChunkCache }; } - private static CachedChunk BuildEmptyChunk(CachedRegion region, int zoneX, int zoneY, int chunkX, int chunkY) + private static CachedChunk BuildEmptyChunk(CachedRegion region, int zoneX, int zoneY, int zoneZ, int chunkX, int chunkY) { var w = region.ChunkWidthTiles; var h = region.ChunkHeightTiles; @@ -474,6 +482,7 @@ public sealed class WorldChunkCache RegionId = region.Id, ZoneX = zoneX, ZoneY = zoneY, + ZoneZ = zoneZ, ChunkX = chunkX, ChunkY = chunkY, WidthTiles = w, @@ -485,6 +494,7 @@ public sealed class WorldChunkCache regionId = region.Id, zoneX, zoneY, + zoneZ, chunkX, chunkY, version = 0, diff --git a/Game/World/WorldHandler.Combat.cs b/Game/World/WorldHandler.Combat.cs new file mode 100644 index 0000000..ed7934d --- /dev/null +++ b/Game/World/WorldHandler.Combat.cs @@ -0,0 +1,331 @@ +using DataServer.Data; +using DataServer.Data.Entities; +using GameServer.Dungeon; +using GameServer.Shared; +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 WorldAttackRequest + { + public string TargetType { get; set; } = "mob"; // "mob" or "player" + public int? TargetMobId { get; set; } + public ulong? TargetPlayerId { get; set; } + } + + private sealed class WorldMobLootRequest + { + public int MobId { get; set; } + } + + private async Task HandleWorldAttackAsync(IConnection conn, WorldSessionState s, ReadOnlyMemory payload, CancellationToken ct) + { + var req = WorldInputParser.Parse(payload); + if (req == null) return; + + var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); + if (!_activeZones.TryGetValue(zoneKey, out var zoneSim)) return; + + if (!zoneSim.Players.TryGetValue(s.CharacterId, out var attacker)) + return; + + if (!attacker.IsAlive || attacker.IsStunned) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new + { + events = new[] { new { type = "AttackFailed", error = attacker.IsAlive ? "stunned" : "dead" } } + }, ct); + return; + } + + if (req.TargetType == "mob" && req.TargetMobId.HasValue) + { + await HandleAttackMobAsync(conn, s, zoneSim, attacker, req.TargetMobId.Value, ct); + } + else if (req.TargetType == "player" && req.TargetPlayerId.HasValue) + { + await HandleAttackPlayerAsync(conn, s, zoneSim, attacker, req.TargetPlayerId.Value, ct); + } + } + + private async Task HandleAttackMobAsync( + IConnection conn, WorldSessionState s, + WorldZoneSimulation zoneSim, WorldPlayerCombatState attacker, + int targetMobId, CancellationToken ct) + { + if (!zoneSim.Mobs.TryGetValue(targetMobId, out var mob) || !mob.IsAlive) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new + { + events = new[] { new { type = "AttackFailed", error = "target_not_found" } } + }, ct); + return; + } + + // Check range + float distance = MathF.Sqrt(MathF.Pow(mob.X - attacker.X, 2) + MathF.Pow(mob.Y - attacker.Y, 2)); + if (distance > 80f) // ~2.5 tiles melee range + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new + { + events = new[] { new { type = "AttackFailed", error = "out_of_range" } } + }, ct); + return; + } + + // Calculate damage + int baseDamage = Math.Max(1, attacker.Strength * 2 + 5); // Base melee damage formula + var result = CombatCalculator.CalculatePlayerToMobDamage( + attacker, mob, attacker.WeaponDamageTypeKey, baseDamage); + + mob.Health -= result.FinalDamage; + attacker.IsInCombat = true; + attacker.LastCombatTick = zoneSim.CurrentTick; + + // Alert mob to attacker + if (mob.TargetId == null) + { + mob.TargetId = attacker.CharacterId; + mob.State = MobState.Chasing; + } + + var events = new List + { + new + { + type = "PlayerAttack", + sourcePlayerId = attacker.CharacterId, + targetMobId = mob.Id, + damage = result.FinalDamage, + damageTypeKey = attacker.WeaponDamageTypeKey, + x = mob.X, + y = mob.Y, + wasResisted = result.WasResisted, + wasWeakness = result.WasWeakness + } + }; + + if (mob.Health <= 0) + { + mob.Health = 0; + mob.IsAlive = false; + mob.State = MobState.Dead; + mob.CurrentAnimation = mob.GetDirectionalAnimation("death"); + zoneSim.MobSpawnTracker?.OnMobDied(mob.Id); + + events.Add(new + { + type = "MobDeath", + targetMobId = mob.Id, + sourcePlayerId = attacker.CharacterId, + x = mob.X, + y = mob.Y, + xpReward = mob.Stats.XpReward, + lootAvailable = true + }); + + // Award XP + _ = AwardXpAsync(s.CharacterId, mob.Stats.XpReward); + } + + // Broadcast attack event to all players in zone + foreach (var player in zoneSim.Players.Values) + { + await _broadcast.SendAsync(player.Session.Connection, OpCodes.WORLD_COMBAT_STATE, new { events }, ct); + } + } + + private async Task HandleAttackPlayerAsync( + IConnection conn, WorldSessionState s, + WorldZoneSimulation zoneSim, WorldPlayerCombatState attacker, + ulong targetPlayerId, CancellationToken ct) + { + // Check PvP enabled + if (!zoneSim.IsPvpEnabled) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new + { + events = new[] { new { type = "AttackFailed", error = "pvp_disabled_in_zone" } } + }, ct); + return; + } + + if (!zoneSim.Players.TryGetValue(targetPlayerId, out var defender) || !defender.IsAlive) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new + { + events = new[] { new { type = "AttackFailed", error = "target_not_found" } } + }, ct); + return; + } + + if (defender.IsInvulnerable) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new + { + events = new[] { new { type = "AttackFailed", error = "target_invulnerable" } } + }, ct); + return; + } + + // Check range + float distance = MathF.Sqrt(MathF.Pow(defender.X - attacker.X, 2) + MathF.Pow(defender.Y - attacker.Y, 2)); + if (distance > 80f) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_COMBAT_STATE, new + { + events = new[] { new { type = "AttackFailed", error = "out_of_range" } } + }, ct); + return; + } + + // PvP damage (includes 30% PvP reduction from CombatCalculator) + int baseDamage = Math.Max(1, attacker.Strength * 2 + 5); + var result = CombatCalculator.CalculatePlayerToPlayerDamage( + attacker, defender, attacker.WeaponDamageTypeKey, baseDamage); + + defender.Health -= result.FinalDamage; + attacker.IsInCombat = true; + attacker.LastCombatTick = zoneSim.CurrentTick; + defender.IsInCombat = true; + defender.LastCombatTick = zoneSim.CurrentTick; + + var events = new List + { + new + { + type = "PvpDamage", + sourcePlayerId = attacker.CharacterId, + targetPlayerId = defender.CharacterId, + damage = result.FinalDamage, + damageTypeKey = attacker.WeaponDamageTypeKey, + x = defender.X, + y = defender.Y + } + }; + + if (defender.Health <= 0) + { + defender.Health = 0; + defender.IsAlive = false; + + events.Add(new + { + type = "PlayerDeath", + targetPlayerId = defender.CharacterId, + sourcePlayerId = attacker.CharacterId, + x = defender.X, + y = defender.Y, + isPvpKill = true + }); + } + + // Broadcast to all players in zone + foreach (var player in zoneSim.Players.Values) + { + await _broadcast.SendAsync(player.Session.Connection, OpCodes.WORLD_COMBAT_STATE, new { events }, ct); + } + } + + private async Task HandleWorldMobLootAsync(IConnection conn, WorldSessionState s, ReadOnlyMemory payload, CancellationToken ct) + { + var req = WorldInputParser.Parse(payload); + if (req == null) return; + + var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); + if (!_activeZones.TryGetValue(zoneKey, out var zoneSim)) return; + + if (!zoneSim.Mobs.TryGetValue(req.MobId, out var mob)) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_MOB_LOOT_RESULT, new + { + success = false, + error = "mob_not_found" + }, ct); + return; + } + + if (mob.IsAlive) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_MOB_LOOT_RESULT, new + { + success = false, + error = "mob_still_alive" + }, ct); + return; + } + + // Check distance + float distance = MathF.Sqrt(MathF.Pow(mob.X - s.X, 2) + MathF.Pow(mob.Y - s.Y, 2)); + if (distance > 128f) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_MOB_LOOT_RESULT, new + { + success = false, + error = "too_far" + }, ct); + return; + } + + // Generate loot from mob's definition loot table + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + if (!_mobDefinitions.TryGetValue(mob.DefinitionId, out var mobDef)) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_MOB_LOOT_RESULT, new + { + success = true, + mobId = mob.Id, + items = Array.Empty(), + gold = 0 + }, ct); + return; + } + + // Award gold based on mob tier + int goldDrop = Math.Max(1, mob.Stats.XpReward / 2); + var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId, ct); + if (character != null) + { + character.Gold += goldDrop; + await db.SaveChangesAsync(ct); + } + + // Mark mob as looted (it will be cleaned up eventually) + mob.LootEmptiedAtTick = zoneSim.CurrentTick; + + await _broadcast.SendAsync(conn, OpCodes.WORLD_MOB_LOOT_RESULT, new + { + success = true, + mobId = mob.Id, + gold = goldDrop, + items = Array.Empty() // TODO: Loot table integration in future + }, ct); + } + + private async Task AwardXpAsync(ulong characterId, int xpAmount) + { + if (xpAmount <= 0) return; + + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == characterId); + if (character == null) return; + + character.Experience += xpAmount; + await db.SaveChangesAsync(); + } + catch (Exception ex) + { + _log.LogWarning(ex, "Failed to award XP to character {CharacterId}", characterId); + } + } +} diff --git a/Game/World/WorldHandler.Npcs.cs b/Game/World/WorldHandler.Npcs.cs new file mode 100644 index 0000000..cadf656 --- /dev/null +++ b/Game/World/WorldHandler.Npcs.cs @@ -0,0 +1,562 @@ +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, "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(); + foreach (var option in options) + { + var (ok, _) = await EvaluateWorldDialogConditionAsync(db, s.CharacterId, option, ct); + if (!ok) continue; + + filtered.Add(new + { + id = option.Id, + text = option.PlayerText, + nextNodeId = option.NextNodeId + }); + } + + await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new + { + success = true, + npcId = npc.Id, + dialogNode = new + { + id = node.Id, + text = node.Text, + isTerminal = node.IsTerminal, + rewardGold = node.RewardGold, + rewardXp = node.RewardXp, + rewardItemDefinitionId = node.RewardItemDefinitionId, + rewardItemQuantity = node.RewardItemQuantity + }, + options = filtered + }, ct); + } + + private async Task SendWorldNpcShopStateAsync(IConnection conn, int shopId, CancellationToken ct) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var shop = await db.DungeonNpcShops + .Include(s => s.Items) + .ThenInclude(i => i.ItemDefinition) + .FirstOrDefaultAsync(s => s.Id == shopId && s.IsEnabled, ct); + + if (shop == null) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new + { + success = false, + error = "shop_not_found" + }, ct); + return; + } + + // Handle restocking + var now = DateTime.UtcNow; + foreach (var item in shop.Items.Where(i => i.Restocks && i.RestockIntervalSeconds > 0 && i.LastRestockAt.HasValue)) + { + if ((now - item.LastRestockAt!.Value).TotalSeconds >= item.RestockIntervalSeconds) + { + item.LastRestockAt = now; + } + } + await db.SaveChangesAsync(ct); + + await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_INTERACT_STATE, new + { + success = true, + shop = new + { + id = shop.Id, + name = shop.Name, + items = shop.Items.OrderBy(i => i.SlotIndex).Select(i => new + { + slotIndex = i.SlotIndex, + itemDefinitionId = i.ItemDefinitionId, + itemName = i.ItemDefinition != null ? i.ItemDefinition.Name : $"Item {i.ItemDefinitionId}", + quantity = i.Quantity, + priceGold = i.PriceGold, + restocks = i.Restocks, + restockIntervalSeconds = i.RestockIntervalSeconds + }) + } + }, ct); + } + + private async Task<(bool Ok, string? Error)> EvaluateWorldDialogConditionAsync( + GameDbContext db, ulong characterId, DungeonNpcDialogOption option, CancellationToken ct) + { + switch (option.ConditionType) + { + case NpcDialogConditionType.None: + return (true, null); + + case NpcDialogConditionType.HasItem: + if (!int.TryParse(option.ConditionValue, out var itemDefId)) + return (false, "invalid_condition_value"); + var itemCount = await db.DungeonCharacterItems + .Where(i => i.CharacterId == characterId && i.ItemDefinitionId == itemDefId) + .SumAsync(i => (int?)i.Quantity, ct) ?? 0; + return itemCount >= Math.Max(1, option.ConditionQuantity) + ? (true, null) : (false, "requires_item"); + + case NpcDialogConditionType.CharacterLevelAtLeast: + if (!int.TryParse(option.ConditionValue, out var minLevel)) + return (false, "invalid_condition_value"); + var charLevel = await db.DungeonCharacters + .Where(c => c.Id == characterId) + .Select(c => c.Level) + .FirstOrDefaultAsync(ct); + return charLevel >= minLevel ? (true, null) : (false, "level_too_low"); + + case NpcDialogConditionType.CharacterLevelAtMost: + if (!int.TryParse(option.ConditionValue, out var maxLevel)) + return (false, "invalid_condition_value"); + var charLvl = await db.DungeonCharacters + .Where(c => c.Id == characterId) + .Select(c => c.Level) + .FirstOrDefaultAsync(ct); + return charLvl <= maxLevel ? (true, null) : (false, "level_too_high"); + + case NpcDialogConditionType.GoldAtLeast: + if (!long.TryParse(option.ConditionValue, out var minGold)) + return (false, "invalid_condition_value"); + var gold = await db.DungeonCharacters + .Where(c => c.Id == characterId) + .Select(c => c.Gold) + .FirstOrDefaultAsync(ct); + return gold >= minGold ? (true, null) : (false, "not_enough_gold"); + + case NpcDialogConditionType.QuestCompleted: + case NpcDialogConditionType.QuestActive: + return (false, "quest_system_not_ready"); + + default: + return (false, "unsupported_condition"); + } + } + + private async Task ApplyWorldDialogRewardsAsync(GameDbContext db, ulong characterId, DungeonNpcDialogNode node, CancellationToken ct) + { + var modified = false; + var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == characterId, ct); + if (character == null) return; + + if (node.RewardGold > 0) + { + character.Gold += node.RewardGold; + modified = true; + } + + if (node.RewardXp > 0) + { + character.Experience += node.RewardXp; + modified = true; + } + + if (node.RewardItemDefinitionId.HasValue && node.RewardItemQuantity > 0) + { + var added = await AddWorldItemToInventoryAsync(db, characterId, node.RewardItemDefinitionId.Value, node.RewardItemQuantity, ct); + modified = modified || added; + } + + if (modified) await db.SaveChangesAsync(ct); + } + + private async Task AddWorldItemToInventoryAsync(GameDbContext db, ulong characterId, int itemDefinitionId, int quantity, CancellationToken ct) + { + if (quantity <= 0) return true; + + var itemDef = await db.DungeonItemDefinitions.FirstOrDefaultAsync(i => i.Id == itemDefinitionId, ct); + if (itemDef == null) return false; + + var inventoryItems = await db.DungeonCharacterItems + .Where(i => i.CharacterId == characterId && !i.IsEquipped) + .ToListAsync(ct); + + var remaining = quantity; + if (itemDef.Stackable) + { + foreach (var stack in inventoryItems.Where(i => i.ItemDefinitionId == itemDefinitionId && i.Quantity < itemDef.MaxStack)) + { + var canAdd = Math.Min(remaining, itemDef.MaxStack - stack.Quantity); + if (canAdd <= 0) continue; + stack.Quantity += canAdd; + remaining -= canAdd; + if (remaining <= 0) return true; + } + } + + var usedSlots = inventoryItems.Select(i => i.SlotIndex).ToHashSet(); + for (var slot = 0; slot < 30 && remaining > 0; slot++) + { + if (usedSlots.Contains(slot)) continue; + var addQty = itemDef.Stackable ? Math.Min(remaining, itemDef.MaxStack) : 1; + db.DungeonCharacterItems.Add(new DungeonCharacterItem + { + CharacterId = characterId, + ItemDefinitionId = itemDefinitionId, + Quantity = addQty, + SlotIndex = slot, + IsEquipped = false + }); + usedSlots.Add(slot); + remaining -= addQty; + } + + return remaining <= 0; + } + + private async Task ConsumeWorldCharacterItemAsync(GameDbContext db, ulong characterId, int itemDefinitionId, int quantity, CancellationToken ct) + { + if (quantity <= 0) return; + + var items = await db.DungeonCharacterItems + .Where(i => i.CharacterId == characterId && i.ItemDefinitionId == itemDefinitionId && !i.IsEquipped) + .OrderBy(i => i.SlotIndex) + .ToListAsync(ct); + + var remaining = quantity; + foreach (var item in items) + { + if (remaining <= 0) break; + var take = Math.Min(item.Quantity, remaining); + item.Quantity -= take; + remaining -= take; + if (item.Quantity <= 0) + { + db.DungeonCharacterItems.Remove(item); + } + } + + await db.SaveChangesAsync(ct); + } +} diff --git a/Game/World/WorldHandler.Objects.cs b/Game/World/WorldHandler.Objects.cs new file mode 100644 index 0000000..f781aa6 --- /dev/null +++ b/Game/World/WorldHandler.Objects.cs @@ -0,0 +1,255 @@ +using DataServer.Data; +using DataServer.Data.Entities; +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 WorldObjectInteractRequest + { + public long ObjectId { get; set; } + public string Action { get; set; } = "interact"; // "interact", "break", "loot" + } + + private async Task HandleWorldObjectInteract(IConnection conn, WorldSessionState s, ReadOnlyMemory payload, CancellationToken ct) + { + var req = WorldInputParser.Parse(payload); + if (req == null) return; + + // Look up the object from the chunk cache to get its definition + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var worldObj = await db.WorldChunkObjects + .Include(o => o.ObjectDefinition) + .FirstOrDefaultAsync(o => o.Id == req.ObjectId, ct); + + if (worldObj == null || worldObj.ObjectDefinition == null) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new + { + success = false, + error = "object_not_found" + }, ct); + return; + } + + var objDef = worldObj.ObjectDefinition; + + // Check interaction distance (convert tile position to world pixels) + // We need the chunk's world offset - approximate from the object's chunk + var chunk = await db.WorldChunks + .Include(c => c.Zone) + .FirstOrDefaultAsync(c => c.Id == worldObj.WorldChunkId, ct); + + if (chunk?.Zone == null) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new + { + success = false, + error = "object_chunk_not_found" + }, ct); + return; + } + + var region = await _cache.GetRegionAsync(s.RegionId, ct); + if (region == null) return; + + float objWorldX = (chunk.Zone.ZoneX * region.ChunksPerZoneX + chunk.ChunkX) * region.ChunkWidthTiles * TileSize + + worldObj.TileX * TileSize + TileSize / 2f; + float objWorldY = (chunk.Zone.ZoneY * region.ChunksPerZoneY + chunk.ChunkY) * region.ChunkHeightTiles * TileSize + + worldObj.TileY * TileSize + TileSize / 2f; + + float dist = MathF.Sqrt(MathF.Pow(objWorldX - s.X, 2) + MathF.Pow(objWorldY - s.Y, 2)); + if (dist > 128f) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new + { + success = false, + error = "too_far" + }, ct); + return; + } + + // Handle destructible objects first (checked by IsDestructible flag, not InteractionType) + if (objDef.IsDestructible && req.Action == "break") + { + await HandleBreakableObjectAsync(conn, s, worldObj, objDef, ct); + return; + } + + // Handle interaction based on InteractionType + switch (objDef.InteractionType) + { + case ObjectInteractionType.OpenContainer: + await HandleLootableObjectAsync(conn, s, worldObj, objDef, ct); + break; + + case ObjectInteractionType.Teleport: + // Portals are handled by the movement system + await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new + { + success = true, + objectId = worldObj.Id, + type = "teleport", + message = "Portal triggered by movement." + }, ct); + break; + + case ObjectInteractionType.Trigger: + // Trigger objects return metadata text (signs, plaques, etc.) + await HandleReadableObjectAsync(conn, worldObj, objDef, ct); + break; + + default: + await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new + { + success = true, + objectId = worldObj.Id, + type = objDef.InteractionType.ToString().ToLower(), + name = objDef.Name, + metadataJson = worldObj.MetadataJson + }, ct); + break; + } + } + + private async Task HandleBreakableObjectAsync( + IConnection conn, WorldSessionState s, + WorldChunkObject worldObj, DungeonObjectDefinition objDef, + CancellationToken ct) + { + // For breakable objects, the client sends "break" action + // Server validates and fires a destroy event + potential loot + var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); + + // Generate loot if the object has a loot table (from metadata) + var lootItems = new List(); + int goldDrop = 0; + + // Parse metadata for loot info + if (!string.IsNullOrEmpty(worldObj.MetadataJson)) + { + try + { + using var doc = System.Text.Json.JsonDocument.Parse(worldObj.MetadataJson); + var root = doc.RootElement; + if (root.TryGetProperty("goldDrop", out var gp)) + goldDrop = gp.GetInt32(); + } + catch { /* ignore malformed metadata */ } + } + + if (goldDrop > 0) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId, ct); + if (character != null) + { + character.Gold += goldDrop; + await db.SaveChangesAsync(ct); + } + } + + // Broadcast object break to all players in zone + if (_activeZones.TryGetValue(zoneKey, out var zoneSim)) + { + foreach (var player in zoneSim.Players.Values) + { + await _broadcast.SendAsync(player.Session.Connection, OpCodes.WORLD_OBJECT_STATE, new + { + objectId = worldObj.Id, + state = "broken", + x = worldObj.TileX, + y = worldObj.TileY + }, ct); + } + } + + await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new + { + success = true, + objectId = worldObj.Id, + type = "break", + gold = goldDrop, + items = lootItems + }, ct); + } + + private async Task HandleLootableObjectAsync( + IConnection conn, WorldSessionState s, + WorldChunkObject worldObj, DungeonObjectDefinition objDef, + CancellationToken ct) + { + int goldDrop = 0; + var lootItems = new List(); + + // Parse metadata for loot + if (!string.IsNullOrEmpty(worldObj.MetadataJson)) + { + try + { + using var doc = System.Text.Json.JsonDocument.Parse(worldObj.MetadataJson); + var root = doc.RootElement; + if (root.TryGetProperty("goldDrop", out var gp)) + goldDrop = gp.GetInt32(); + } + catch { /* ignore */ } + } + + if (goldDrop > 0) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId, ct); + if (character != null) + { + character.Gold += goldDrop; + await db.SaveChangesAsync(ct); + } + } + + await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new + { + success = true, + objectId = worldObj.Id, + type = "loot", + gold = goldDrop, + items = lootItems + }, ct); + } + + private async Task HandleReadableObjectAsync( + IConnection conn, + WorldChunkObject worldObj, DungeonObjectDefinition objDef, + CancellationToken ct) + { + // Readable objects just return their text content from metadata + string readableText = ""; + if (!string.IsNullOrEmpty(worldObj.MetadataJson)) + { + try + { + using var doc = System.Text.Json.JsonDocument.Parse(worldObj.MetadataJson); + var root = doc.RootElement; + if (root.TryGetProperty("text", out var tp)) + readableText = tp.GetString() ?? ""; + } + catch { /* ignore */ } + } + + await _broadcast.SendAsync(conn, OpCodes.WORLD_OBJECT_INTERACT_RESULT, new + { + success = true, + objectId = worldObj.Id, + type = "readable", + name = objDef.Name, + text = readableText + }, ct); + } +} diff --git a/Game/World/WorldHandler.cs b/Game/World/WorldHandler.cs index 6d0645f..3cd249a 100644 --- a/Game/World/WorldHandler.cs +++ b/Game/World/WorldHandler.cs @@ -2,6 +2,7 @@ using System.Collections.Concurrent; using System.Text.Json; using DataServer.Data; using DataServer.Data.Entities; +using GameServer.Dungeon; using GameServices; using GameServices.Auth; using Microsoft.EntityFrameworkCore; @@ -13,9 +14,10 @@ using Server.Networking.Messages; namespace GameServer.World; -public sealed class WorldHandler : IClientMessageHandler +public sealed partial class WorldHandler : IClientMessageHandler { private const int TileSize = 32; + private const float TickDeltaSeconds = 0.1f; // 10Hz private static readonly TimeSpan NeutralInputGrace = TimeSpan.FromMilliseconds(180); private static readonly TimeSpan DirectionalPriorityGrace = TimeSpan.FromMilliseconds(450); @@ -31,6 +33,13 @@ public sealed class WorldHandler : IClientMessageHandler private readonly ConcurrentDictionary _portalCooldownByCharacter = new(); private readonly bool _debugInput; + // Zone simulations (keyed by "{regionId}:{zoneX}:{zoneY}:{zoneZ}") + private readonly ConcurrentDictionary _activeZones = new(); + + // Mob/NPC definition caches (loaded once at init) + private Dictionary _mobDefinitions = new(); + private Dictionary _npcDefinitions = new(); + private Task? _tickTask; private CancellationTokenSource? _tickCts; private long _tick; @@ -62,18 +71,50 @@ public sealed class WorldHandler : IClientMessageHandler { OpCodes.WORLD_SPAWN_REQUEST, OpCodes.WORLD_INPUT, - OpCodes.PONG + OpCodes.PONG, + // World combat + OpCodes.WORLD_ATTACK, + OpCodes.WORLD_MOB_LOOT_REQUEST, + // World NPC + OpCodes.WORLD_NPC_INTERACT, + OpCodes.WORLD_NPC_DIALOG_SELECT, + OpCodes.WORLD_NPC_SHOP_ACTION, + // World objects + OpCodes.WORLD_OBJECT_INTERACT }; - public Task InitializeAsync() + public async Task InitializeAsync() { - if (_initialized) return Task.CompletedTask; + if (_initialized) return; + + // Load mob and NPC definitions for zone simulations + await LoadWorldDefinitionsAsync(); + _tickCts = new CancellationTokenSource(); _tickTask = Task.Run(() => TickLoopAsync(_tickCts.Token), _tickCts.Token); _deltaHub.OnDeltaPublished += OnWorldEditDelta; _initialized = true; - _log.LogInformation("WorldHandler initialized (cached movement pipeline + live delta forwarding)"); - return Task.CompletedTask; + _log.LogInformation( + "WorldHandler initialized with {MobCount} mob defs, {NpcCount} NPC defs", + _mobDefinitions.Count, _npcDefinitions.Count); + } + + private async Task LoadWorldDefinitionsAsync() + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var mobs = await db.Set() + .Where(m => m.IsEnabled) + .Include(m => m.AbilityAssignments) + .ThenInclude(a => a.AbilityDefinition) + .ToListAsync(); + _mobDefinitions = mobs.ToDictionary(m => m.Id); + + var npcs = await db.Set() + .Where(n => n.IsEnabled) + .ToListAsync(); + _npcDefinitions = npcs.ToDictionary(n => n.Id); } public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory payload, CancellationToken ct) @@ -97,6 +138,35 @@ public sealed class WorldHandler : IClientMessageHandler if (opCode == OpCodes.WORLD_INPUT) { HandleInput(connection, accountId, payload); + return; + } + + // All remaining opcodes require the player to be spawned + if (!_players.TryGetValue(connection.Id, out var session)) return; + + switch (opCode) + { + // Combat + case OpCodes.WORLD_ATTACK: + await HandleWorldAttackAsync(connection, session, payload, ct); + break; + case OpCodes.WORLD_MOB_LOOT_REQUEST: + await HandleWorldMobLootAsync(connection, session, payload, ct); + break; + // NPC + case OpCodes.WORLD_NPC_INTERACT: + await HandleWorldNpcInteract(connection, session, payload, ct); + break; + case OpCodes.WORLD_NPC_DIALOG_SELECT: + await HandleWorldNpcDialogSelect(connection, session, payload, ct); + break; + case OpCodes.WORLD_NPC_SHOP_ACTION: + await HandleWorldNpcShopAction(connection, session, payload, ct); + break; + // Objects + case OpCodes.WORLD_OBJECT_INTERACT: + await HandleWorldObjectInteract(connection, session, payload, ct); + break; } } @@ -104,6 +174,13 @@ public sealed class WorldHandler : IClientMessageHandler { if (_players.TryRemove(connectionId, out var s)) { + // Remove from zone simulation + var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); + if (_activeZones.TryGetValue(zoneKey, out var zoneSim)) + { + zoneSim.RemovePlayer(s.CharacterId); + } + _ = PersistPlayerLocationAsync(s); _ = _broadcast.BroadcastToRegionAsync( OpCodes.WORLD_DESPAWN, @@ -139,6 +216,7 @@ public sealed class WorldHandler : IClientMessageHandler var requestedExplicitChunk = req.ZoneX.HasValue || req.ZoneY.HasValue || req.ChunkX.HasValue || req.ChunkY.HasValue; var zx = Math.Clamp(req.ZoneX ?? character.WorldZoneX ?? 0, 0, Math.Max(0, region.ZonesPerRegionX - 1)); var zy = Math.Clamp(req.ZoneY ?? character.WorldZoneY ?? 0, 0, Math.Max(0, region.ZonesPerRegionY - 1)); + var zz = character.WorldZoneZ ?? 0; var cx = Math.Clamp(req.ChunkX ?? character.WorldChunkX ?? 0, 0, Math.Max(0, region.ChunksPerZoneX - 1)); var cy = Math.Clamp(req.ChunkY ?? character.WorldChunkY ?? 0, 0, Math.Max(0, region.ChunksPerZoneY - 1)); var tx = Math.Max(0, Math.Min(region.ChunkWidthTiles - 1, region.ChunkWidthTiles / 2)); @@ -165,6 +243,7 @@ public sealed class WorldHandler : IClientMessageHandler RegionId = region.Id, ZoneX = pzX, ZoneY = pzY, + ZoneZ = zz, ChunkX = pcX, ChunkY = pcY, X = x, @@ -175,6 +254,7 @@ public sealed class WorldHandler : IClientMessageHandler character.WorldRegionId = s.RegionId; character.WorldZoneX = s.ZoneX; character.WorldZoneY = s.ZoneY; + character.WorldZoneZ = s.ZoneZ; character.WorldChunkX = s.ChunkX; character.WorldChunkY = s.ChunkY; character.WorldX = s.X; @@ -307,12 +387,24 @@ public sealed class WorldHandler : IClientMessageHandler private async Task SendStatesAsync(CancellationToken ct) { - if (_players.IsEmpty) return; + if (_players.IsEmpty && _activeZones.IsEmpty) return; var tick = Interlocked.Read(ref _tick); - // Process all players in parallel instead of sequentially + // 1. Ensure players are registered in zone simulations + await EnsurePlayersInZoneSimsAsync(tick, ct); + + // 2. Tick all active zone simulations (mob AI, combat, projectiles, etc.) + TickActiveZones(tick); + + // 3. Broadcast combat events from zone simulations + await BroadcastCombatEventsAsync(ct); + + // 4. Process all players (movement, chunk updates, state broadcast) var tasks = _players.Values.Select(s => ProcessPlayerTickAsync(s, tick, ct)); await Task.WhenAll(tasks); + + // 5. Clean up deactivated zones + CleanupInactiveZones(); } private async Task ProcessPlayerTickAsync(WorldSessionState s, long tick, CancellationToken ct) @@ -333,12 +425,31 @@ public sealed class WorldHandler : IClientMessageHandler var errs = s.Errors.Count == 0 ? null : s.Errors.Distinct().ToArray(); s.Errors.Clear(); + // Get mob/NPC data from zone simulation if active + var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); + object[]? nearbyMobs = null; + object[]? nearbyNpcs = null; + if (_activeZones.TryGetValue(zoneKey, out var zoneSim)) + { + float visRange = TileSize * 48; + nearbyMobs = zoneSim.Mobs.Values + .Where(m => Math.Abs(m.X - s.X) <= visRange && Math.Abs(m.Y - s.Y) <= visRange) + .Select(m => zoneSim.SerializeMob(m)) + .ToArray(); + nearbyNpcs = zoneSim.Npcs.Values + .Where(n => Math.Abs(n.X - s.X) <= visRange && Math.Abs(n.Y - s.Y) <= visRange) + .Select(n => zoneSim.SerializeNpc(n)) + .ToArray(); + } + await _broadcast.SendAsync(s.Connection, OpCodes.WORLD_STATE, new { tick, ackSeq = s.Seq, self = new { x = s.X, y = s.Y, velocityX = s.VelX, velocityY = s.VelY, regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, chunkX = s.ChunkX, chunkY = s.ChunkY }, players = VisiblePlayers(s).Select(p => new { id = p.CharacterId, name = p.Name, x = p.X, y = p.Y, facing = p.Facing, speed = p.Speed, isMoving = p.IsMoving, regionId = p.RegionId, zoneX = p.ZoneX, zoneY = p.ZoneY, chunkX = p.ChunkX, chunkY = p.ChunkY }), + mobs = nearbyMobs, + npcs = nearbyNpcs, chunkUpdates = updates.Select(u => u.payload), portalEvent = s.PendingPortalEvent, errors = errs @@ -355,6 +466,7 @@ public sealed class WorldHandler : IClientMessageHandler => _players.Values.Where(p => p.ConnectionId != self.ConnectionId && p.RegionId == self.RegionId && + p.ZoneZ == self.ZoneZ && Math.Abs(p.ZoneX - self.ZoneX) <= 1 && Math.Abs(p.ZoneY - self.ZoneY) <= 1 && Math.Abs(p.X - self.X) <= (TileSize * 48) && @@ -380,15 +492,16 @@ public sealed class WorldHandler : IClientMessageHandler // Parse chunk coordinates from the key for cache invalidation var parts = chunkKey.Split(':'); - if (parts.Length == 5 && + if (parts.Length == 6 && int.TryParse(parts[0], out var regionId) && int.TryParse(parts[1], out var zoneX) && int.TryParse(parts[2], out var zoneY) && - int.TryParse(parts[3], out var chunkX) && - int.TryParse(parts[4], out var chunkY)) + int.TryParse(parts[3], out var zoneZ) && + int.TryParse(parts[4], out var chunkX) && + int.TryParse(parts[5], out var chunkY)) { // Invalidate cache so next access reloads fresh data from DB - _cache.InvalidateChunk(regionId, zoneX, zoneY, chunkX, chunkY); + _cache.InvalidateChunk(regionId, zoneX, zoneY, zoneZ, chunkX, chunkY); // Deserialize the delta to a dynamic object for forwarding to clients. // The raw JSON from the hub already has all the fields the client needs. @@ -405,6 +518,233 @@ public sealed class WorldHandler : IClientMessageHandler } } + // ---- Zone Simulation Lifecycle ---- + + /// + /// Ensure all players are registered in their zone's simulation. + /// Activates new zone simulations as needed. + /// + private async Task EnsurePlayersInZoneSimsAsync(long tick, CancellationToken ct) + { + foreach (var s in _players.Values) + { + var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); + + if (!_activeZones.TryGetValue(zoneKey, out var zoneSim)) + { + // Activate zone simulation + zoneSim = await ActivateZoneSimulationAsync(zoneKey, s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ, ct); + if (zoneSim == null) continue; + } + + // Ensure player is in the simulation + if (!zoneSim.Players.ContainsKey(s.CharacterId)) + { + var combatState = new WorldPlayerCombatState(s); + // Initialize with basic stats (character stats would come from DB/gear) + // For now use defaults — Phase 4 will flesh out stat loading from gear + combatState.InitializeFromCharacter( + strength: 10, intelligence: 10, endurance: 10, dexterity: 10, + armor: 0, maxHealth: 100, weaponDamageTypeKey: "physical", + resistances: new Dictionary()); + zoneSim.AddPlayer(combatState); + } + } + } + + /// + /// Activate a new zone simulation by loading mob/NPC spawn data from cached chunks. + /// + private async Task ActivateZoneSimulationAsync( + string zoneKey, int regionId, int zoneX, int zoneY, int zoneZ, CancellationToken ct) + { + try + { + var region = await _cache.GetRegionAsync(regionId, ct); + if (region == null) return null; + + var zoneSim = new WorldZoneSimulation(zoneKey, regionId, zoneX, zoneY, zoneZ, _cache); + zoneSim.SetRegion(region); + + // Collect mob and NPC spawns from all chunks in this zone + var mobSpawns = new List<(WorldChunkMobSpawnData, int, int)>(); + var npcSpawns = new List<(NpcInstance, int, int)>(); + int nextNpcId = 1; + + for (int cx = 0; cx < region.ChunksPerZoneX; cx++) + for (int cy = 0; cy < region.ChunksPerZoneY; cy++) + { + var chunk = await _cache.GetChunkAsync(regionId, zoneX, zoneY, zoneZ, cx, cy, ct); + if (chunk == null) continue; + + // Calculate world pixel offset for this chunk + int chunkWorldOffsetX = (zoneX * region.ChunksPerZoneX + cx) * region.ChunkWidthTiles * TileSize; + int chunkWorldOffsetY = (zoneY * region.ChunksPerZoneY + cy) * region.ChunkHeightTiles * TileSize; + + // Extract mob spawns from MobDtos (anonymous objects) + ExtractMobSpawnsFromChunk(chunk, chunkWorldOffsetX, chunkWorldOffsetY, mobSpawns); + + // Extract NPC spawns from NpcDtos + ExtractNpcSpawnsFromChunk(chunk, chunkWorldOffsetX, chunkWorldOffsetY, npcSpawns, ref nextNpcId); + } + + zoneSim.Initialize(_mobDefinitions, mobSpawns, npcSpawns); + + if (_activeZones.TryAdd(zoneKey, zoneSim)) + { + _log.LogInformation( + "Activated zone simulation {ZoneKey}: {MobCount} mobs, {NpcCount} NPCs", + zoneKey, zoneSim.Mobs.Count, zoneSim.Npcs.Count); + return zoneSim; + } + + // Another thread beat us, use their version + return _activeZones.TryGetValue(zoneKey, out var existing) ? existing : null; + } + catch (Exception ex) + { + _log.LogWarning(ex, "Failed to activate zone simulation {ZoneKey}", zoneKey); + return null; + } + } + + /// + /// Extract mob spawn data from a cached chunk's MobDtos. + /// The MobDtos are anonymous objects serialized from WorldChunkMobSpawn entities. + /// + private static void ExtractMobSpawnsFromChunk( + WorldChunkCache.CachedChunk chunk, + int chunkWorldOffsetX, int chunkWorldOffsetY, + List<(WorldChunkMobSpawnData, int, int)> mobSpawns) + { + foreach (var mobDto in chunk.MobDtos) + { + // MobDtos are anonymous objects with: id, x, y, mobDefinitionId, mobName, rotation, spawnCount, respawnSeconds, metadataJson + // Use JSON round-trip to extract values + var json = JsonSerializer.Serialize(mobDto); + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + + var spawnData = new WorldChunkMobSpawnData + { + Id = root.TryGetProperty("id", out var idProp) ? idProp.GetInt64() : 0, + MobDefinitionId = root.TryGetProperty("mobDefinitionId", out var mobDefProp) ? mobDefProp.GetInt32() : 0, + TileX = root.TryGetProperty("x", out var xProp) ? xProp.GetInt32() : 0, + TileY = root.TryGetProperty("y", out var yProp) ? yProp.GetInt32() : 0, + SpawnCount = root.TryGetProperty("spawnCount", out var scProp) ? scProp.GetInt32() : 1, + RespawnSeconds = root.TryGetProperty("respawnSeconds", out var rsProp) ? rsProp.GetSingle() : 30f + }; + + if (spawnData.MobDefinitionId > 0) + { + mobSpawns.Add((spawnData, chunkWorldOffsetX, chunkWorldOffsetY)); + } + } + } + + /// + /// Extract NPC instances from a cached chunk's NpcDtos. + /// + private void ExtractNpcSpawnsFromChunk( + WorldChunkCache.CachedChunk chunk, + int chunkWorldOffsetX, int chunkWorldOffsetY, + List<(NpcInstance, int, int)> npcSpawns, + ref int nextNpcId) + { + foreach (var npcDto in chunk.NpcDtos) + { + var json = JsonSerializer.Serialize(npcDto); + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + + int npcDefId = root.TryGetProperty("npcDefinitionId", out var defProp) ? defProp.GetInt32() : 0; + if (npcDefId <= 0 || !_npcDefinitions.TryGetValue(npcDefId, out var npcDef)) continue; + + int tileX = root.TryGetProperty("x", out var xProp) ? xProp.GetInt32() : 0; + int tileY = root.TryGetProperty("y", out var yProp) ? yProp.GetInt32() : 0; + float worldX = chunkWorldOffsetX + (tileX * TileSize) + (TileSize / 2f); + float worldY = chunkWorldOffsetY + (tileY * TileSize) + (TileSize / 2f); + + var npc = NpcInstance.FromDefinition(npcDef, nextNpcId++, worldX, worldY); + npcSpawns.Add((npc, chunkWorldOffsetX, chunkWorldOffsetY)); + } + } + + /// + /// Tick all active zone simulations. + /// + private void TickActiveZones(long tick) + { + foreach (var (zoneKey, zoneSim) in _activeZones) + { + try + { + zoneSim.Tick(tick, TickDeltaSeconds); + } + catch (Exception ex) + { + _log.LogWarning(ex, "Error ticking zone simulation {ZoneKey}", zoneKey); + } + } + } + + /// + /// Broadcast pending combat events from all zone simulations. + /// + private async Task BroadcastCombatEventsAsync(CancellationToken ct) + { + foreach (var (_, zoneSim) in _activeZones) + { + var events = new List(); + while (zoneSim.PendingEvents.TryDequeue(out var evt)) + { + events.Add(new + { + type = evt.Type.ToString(), + sourceMobId = evt.SourceMobId, + sourcePlayerId = evt.SourcePlayerId, + targetMobId = evt.TargetMobId, + targetPlayerId = evt.TargetPlayerId, + damage = evt.Damage, + damageTypeKey = evt.DamageTypeKey, + x = evt.X, + y = evt.Y, + mobData = evt.MobData + }); + } + + if (events.Count == 0) continue; + + // Send combat state to all players in this zone + foreach (var player in zoneSim.Players.Values) + { + await _broadcast.SendAsync( + player.Session.Connection, + OpCodes.WORLD_COMBAT_STATE, + new { events }, + ct); + } + } + } + + /// + /// Remove deactivated zone simulations. + /// + private void CleanupInactiveZones() + { + foreach (var (zoneKey, zoneSim) in _activeZones) + { + if (!zoneSim.IsActive) + { + if (_activeZones.TryRemove(zoneKey, out var removed)) + { + removed.Deactivate(); + _log.LogInformation("Deactivated zone simulation {ZoneKey}", zoneKey); + } + } + } + } + // ---- Persistence (only on disconnect) ---- private async Task PersistPlayerLocationAsync(WorldSessionState s) @@ -419,6 +759,7 @@ public sealed class WorldHandler : IClientMessageHandler character.WorldRegionId = s.RegionId; character.WorldZoneX = s.ZoneX; character.WorldZoneY = s.ZoneY; + character.WorldZoneZ = s.ZoneZ; character.WorldChunkX = s.ChunkX; character.WorldChunkY = s.ChunkY; character.WorldX = s.X; diff --git a/Game/World/WorldMobSpawnTracker.cs b/Game/World/WorldMobSpawnTracker.cs new file mode 100644 index 0000000..ac89615 --- /dev/null +++ b/Game/World/WorldMobSpawnTracker.cs @@ -0,0 +1,229 @@ +using DataServer.Data.Entities; +using DataServer.Data.Enums; +using GameServer.Dungeon; + +namespace GameServer.World; + +/// +/// Tracks mob spawn points in a zone, handles respawn timers, and creates MobInstance objects. +/// Each spawn point can have multiple mobs (SpawnCount) that respawn independently. +/// +public sealed class WorldMobSpawnTracker +{ + private readonly Dictionary _mobDefinitions; + private readonly List _spawnPoints = new(); + private int _nextMobId = 1; + private readonly Random _rng = new(); + + public WorldMobSpawnTracker(Dictionary mobDefinitions) + { + _mobDefinitions = mobDefinitions; + } + + /// + /// Register a mob spawn point from chunk data. + /// Returns any initially spawned mobs. + /// + public List RegisterSpawnPoint(WorldChunkMobSpawnData data, int chunkWorldOffsetX, int chunkWorldOffsetY) + { + if (!_mobDefinitions.TryGetValue(data.MobDefinitionId, out var mobDef)) + return new List(); + + var spawnPoint = new SpawnPoint + { + SpawnDataId = data.Id, + MobDefinitionId = data.MobDefinitionId, + WorldX = chunkWorldOffsetX + (data.TileX * 32) + 16, + WorldY = chunkWorldOffsetY + (data.TileY * 32) + 16, + SpawnCount = Math.Max(1, data.SpawnCount), + RespawnSeconds = Math.Max(5f, data.RespawnSeconds), + ActiveMobIds = new List(), + RespawnTimers = new List() + }; + + _spawnPoints.Add(spawnPoint); + + // Spawn initial mobs + var mobs = new List(); + for (int i = 0; i < spawnPoint.SpawnCount; i++) + { + var mob = CreateMob(mobDef, spawnPoint); + if (mob != null) + { + spawnPoint.ActiveMobIds.Add(mob.Id); + mobs.Add(mob); + } + } + + return mobs; + } + + /// + /// Notify that a mob has died. Start respawn timer for its spawn point. + /// + public void OnMobDied(int mobId) + { + foreach (var sp in _spawnPoints) + { + int idx = sp.ActiveMobIds.IndexOf(mobId); + if (idx >= 0) + { + sp.ActiveMobIds.RemoveAt(idx); + sp.RespawnTimers.Add(sp.RespawnSeconds); + break; + } + } + } + + /// + /// Update respawn timers and return any newly spawned mobs. + /// + public List Update(float deltaTime) + { + var newMobs = new List(); + + foreach (var sp in _spawnPoints) + { + for (int i = sp.RespawnTimers.Count - 1; i >= 0; i--) + { + sp.RespawnTimers[i] -= deltaTime; + if (sp.RespawnTimers[i] <= 0) + { + sp.RespawnTimers.RemoveAt(i); + + if (!_mobDefinitions.TryGetValue(sp.MobDefinitionId, out var mobDef)) + continue; + + var mob = CreateMob(mobDef, sp); + if (mob != null) + { + sp.ActiveMobIds.Add(mob.Id); + newMobs.Add(mob); + } + } + } + } + + return newMobs; + } + + private MobInstance? CreateMob(DungeonMobDefinition mobDef, SpawnPoint sp) + { + var stats = mobDef.GetStatsForBracket(1); // World mobs use bracket 1 (base stats) + int id = _nextMobId++; + + // Randomize spawn position slightly around the spawn point + float offsetX = ((float)_rng.NextDouble() - 0.5f) * 64f; + float offsetY = ((float)_rng.NextDouble() - 0.5f) * 64f; + float spawnX = sp.WorldX + offsetX; + float spawnY = sp.WorldY + offsetY; + + var mob = new MobInstance + { + Id = id, + DefinitionId = mobDef.Id, + Name = mobDef.Name, + X = spawnX, + Y = spawnY, + SpawnX = sp.WorldX, + SpawnY = sp.WorldY, + Health = stats.MaxHealth, + MaxHealth = stats.MaxHealth, + Mana = mobDef.BaseMana, + MaxMana = mobDef.BaseMana, + Stats = stats, + State = MobState.Idle, + StateTime = (float)(_rng.NextDouble() * 3f), + SpriteConfigJson = mobDef.SpriteConfigJson, + TintColor = mobDef.TintColor, + Scale = mobDef.Scale, + Type = mobDef.Type, + Behavior = mobDef.Behavior, + PreferredRange = mobDef.PreferredRange, + FleeThreshold = mobDef.FleeThreshold, + Phases = mobDef.Phases, + CurrentAnimation = "idle_down", + FacingDirection = "down" + }; + + // Initialize abilities + InitializeMobAbilities(mob, mobDef, stats); + + return mob; + } + + private void InitializeMobAbilities(MobInstance mob, DungeonMobDefinition mobDef, DungeonMobCombatStats stats) + { + mob.Abilities.Clear(); + + // Load abilities from assignments (same pattern as DungeonSimulation) + if (mobDef.AbilityAssignments != null) + { + foreach (var assignment in mobDef.AbilityAssignments.Where(a => a.IsEnabled)) + { + var abilityDef = assignment.AbilityDefinition; + if (abilityDef == null) continue; + + mob.Abilities.Add(new MobAbilityState + { + AbilityId = abilityDef.Id, + Definition = abilityDef, + ResolvedAnimationKey = abilityDef.AnimationKey, + CooldownRemaining = 0f, + Priority = assignment.PriorityOverride ?? abilityDef.Priority, + Phase = assignment.Phase, + MinHpPercent = assignment.MinHpPercent, + MaxHpPercent = assignment.MaxHpPercent + }); + } + } + + // Ensure at least a basic melee attack + bool hasBasicMelee = mob.Abilities.Any(a => a.Definition.AbilityType == MobAbilityType.MeleeAttack); + if (!hasBasicMelee) + { + mob.Abilities.Add(new MobAbilityState + { + Definition = new MobAbilityDefinition + { + Name = "Melee Attack", + AbilityType = MobAbilityType.MeleeAttack, + BaseDamage = stats.PhysicalDamage > 0 ? stats.PhysicalDamage : 10, + Range = stats.AttackRange > 0 ? stats.AttackRange : 40f, + Cooldown = stats.AttackSpeed > 0 ? 1f / stats.AttackSpeed : 1.5f, + ManaCost = 0, + AnimationKey = "attack" + }, + CooldownRemaining = 0f + }); + } + } + + public int SpawnPointCount => _spawnPoints.Count; + public int TotalActiveMobs => _spawnPoints.Sum(sp => sp.ActiveMobIds.Count); + + private class SpawnPoint + { + public long SpawnDataId { get; set; } + public int MobDefinitionId { get; set; } + public float WorldX { get; set; } + public float WorldY { get; set; } + public int SpawnCount { get; set; } + public float RespawnSeconds { get; set; } + public List ActiveMobIds { get; set; } = new(); + public List RespawnTimers { get; set; } = new(); + } +} + +/// +/// Serializable mob spawn data extracted from CachedChunk's MobDtos. +/// +public sealed class WorldChunkMobSpawnData +{ + public long Id { get; set; } + public int MobDefinitionId { get; set; } + public int TileX { get; set; } + public int TileY { get; set; } + public int SpawnCount { get; set; } = 1; + public float RespawnSeconds { get; set; } = 30f; +} diff --git a/Game/World/WorldMovementService.cs b/Game/World/WorldMovementService.cs index b79da13..d0c1c69 100644 --- a/Game/World/WorldMovementService.cs +++ b/Game/World/WorldMovementService.cs @@ -86,12 +86,12 @@ public sealed class WorldMovementService if (moving) { // Slide collision: try each axis independently (same behavior as original) - if (_cache.IsPositionWalkable(region, nextX, s.Y, s.IsVip)) + if (_cache.IsPositionWalkable(region, s.ZoneZ, nextX, s.Y, s.IsVip)) s.X = nextX; else s.Errors.Add("blocked_non_walkable"); - if (_cache.IsPositionWalkable(region, s.X, nextY, s.IsVip)) + if (_cache.IsPositionWalkable(region, s.ZoneZ, s.X, nextY, s.IsVip)) s.Y = nextY; else s.Errors.Add("blocked_non_walkable"); @@ -150,6 +150,7 @@ public sealed class WorldMovementService s.RegionId = targetRegion.Id; s.X = nx; s.Y = ny; + s.ZoneZ = req.TargetZoneZ; var (zx, zy, cx, cy) = ToChunkPos(targetRegion, s.X, s.Y); s.ZoneX = zx; s.ZoneY = zy; @@ -164,6 +165,7 @@ public sealed class WorldMovementService regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, + zoneZ = s.ZoneZ, chunkX = s.ChunkX, chunkY = s.ChunkY, x = s.X, @@ -187,7 +189,7 @@ public sealed class WorldMovementService if (portalCooldowns.TryGetValue(s.CharacterId, out var untilTick) && untilTick > currentTick) return; - var portal = _cache.FindPortalAtPosition(region, s.X, s.Y); + var portal = _cache.FindPortalAtPosition(region, s.ZoneZ, s.X, s.Y); if (portal == null || string.IsNullOrWhiteSpace(portal.MetadataJson)) return; @@ -196,10 +198,45 @@ public sealed class WorldMovementService portalCooldowns[s.CharacterId] = currentTick + PortalCooldownTicks; + // Building portals (Z-level change within same zone) + if (meta.IsBuildingPortal) + { + var targetZ = meta.TargetZoneZ ?? 0; + var tileX = meta.TargetTileX ?? (int)MathF.Floor(s.X / TileSize) % (region.ChunkWidthTiles > 0 ? region.ChunkWidthTiles : 1); + var tileY = meta.TargetTileY ?? (int)MathF.Floor(s.Y / TileSize) % (region.ChunkHeightTiles > 0 ? region.ChunkHeightTiles : 1); + var cX = meta.TargetChunkX ?? s.ChunkX; + var cY = meta.TargetChunkY ?? s.ChunkY; + var nx = WorldPxX(region, s.ZoneX, cX, tileX); + var ny = WorldPxY(region, s.ZoneY, cY, tileY); + s.X = nx; + s.Y = ny; + s.ZoneZ = targetZ; + var (zx, zy, cx, cy) = ToChunkPos(region, s.X, s.Y); + s.ZoneX = zx; + s.ZoneY = zy; + s.ChunkX = cx; + s.ChunkY = cy; + s.ChunkVersions.Clear(); + s.PendingPortalEvent = new + { + type = "building_teleport", + sourceObjectId = portal.Id, + regionId = s.RegionId, + zoneX = s.ZoneX, + zoneY = s.ZoneY, + zoneZ = s.ZoneZ, + chunkX = s.ChunkX, + chunkY = s.ChunkY, + x = s.X, + y = s.Y + }; + return; + } + if (meta.PortalType.Equals("world", StringComparison.OrdinalIgnoreCase)) { if (WorldPortalMetadata.TryResolveWorldTarget(meta, - out var targetRegionId, out var targetZoneX, out var targetZoneY, + out var targetRegionId, out var targetZoneX, out var targetZoneY, out var targetZoneZ, out var targetChunkX, out var targetChunkY, out var targetTileX, out var targetTileY)) { // If same region, resolve immediately @@ -209,6 +246,7 @@ public sealed class WorldMovementService var ny = WorldPxY(region, targetZoneY, targetChunkY, targetTileY); s.X = nx; s.Y = ny; + s.ZoneZ = targetZoneZ; var (zx, zy, cx, cy) = ToChunkPos(region, s.X, s.Y); s.ZoneX = zx; s.ZoneY = zy; @@ -222,6 +260,7 @@ public sealed class WorldMovementService regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, + zoneZ = s.ZoneZ, chunkX = s.ChunkX, chunkY = s.ChunkY, x = s.X, @@ -237,6 +276,7 @@ public sealed class WorldMovementService TargetRegionId = targetRegionId, TargetZoneX = targetZoneX, TargetZoneY = targetZoneY, + TargetZoneZ = targetZoneZ, TargetChunkX = targetChunkX, TargetChunkY = targetChunkY, TargetTileX = targetTileX, @@ -305,6 +345,7 @@ public sealed class WorldMovementService public int TargetRegionId { get; init; } public int TargetZoneX { get; init; } public int TargetZoneY { get; init; } + public int TargetZoneZ { get; init; } public int TargetChunkX { get; init; } public int TargetChunkY { get; init; } public int TargetTileX { get; init; } diff --git a/Game/World/WorldPlayerCombatState.cs b/Game/World/WorldPlayerCombatState.cs new file mode 100644 index 0000000..1b87e60 --- /dev/null +++ b/Game/World/WorldPlayerCombatState.cs @@ -0,0 +1,120 @@ +using GameServer.Dungeon; +using GameServer.Shared; + +namespace GameServer.World; + +/// +/// Implements IPlayerTarget for a world player, built from character stats on spawn. +/// Position delegates to the WorldSessionState so movement updates are reflected in combat. +/// +public sealed class WorldPlayerCombatState : IPlayerTarget +{ + private readonly WorldSessionState _session; + + public ulong CharacterId => _session.CharacterId; + public string CharacterName => _session.Name; + + // Position delegates to session + public float X => _session.X; + public float Y => _session.Y; + + // Vitals + public float Health { get; set; } + public float MaxHealth { get; private set; } + public bool IsAlive { get; set; } = true; + public bool IsInvulnerable { get; set; } + + // Combat stats (computed from character + gear at spawn) + public int Strength { get; set; } + public int Intelligence { get; set; } + public int Endurance { get; set; } + public int Dexterity { get; set; } + public int Armor { get; set; } + public string WeaponDamageTypeKey { get; set; } = "physical"; + public Dictionary Resistances { get; set; } = new(); + + // Status effects + public List StatusEffects { get; set; } = new(); + public bool IsStunned => StatusEffects.Any(e => e.EffectType == "stun" && e.Duration > 0); + public bool IsRooted => StatusEffects.Any(e => e.EffectType == "root" && e.Duration > 0); + public bool IsFeared => StatusEffects.Any(e => e.EffectType == "fear" && e.Duration > 0); + + // Combat tracking + public bool IsInCombat { get; set; } + public long LastCombatTick { get; set; } + + // Invulnerability timer (for respawn protection) + public float InvulnerabilityTimer { get; set; } + + // Reference to the session for direct access + public WorldSessionState Session => _session; + + public WorldPlayerCombatState(WorldSessionState session) + { + _session = session; + } + + /// + /// Initialize combat state from character stats. + /// Called when player enters a zone with active simulation. + /// + public void InitializeFromCharacter( + int strength, int intelligence, int endurance, int dexterity, + int armor, float maxHealth, string weaponDamageTypeKey, + Dictionary resistances) + { + Strength = strength; + Intelligence = intelligence; + Endurance = endurance; + Dexterity = dexterity; + Armor = armor; + MaxHealth = maxHealth; + Health = maxHealth; + WeaponDamageTypeKey = weaponDamageTypeKey; + Resistances = resistances; + IsAlive = true; + IsInvulnerable = false; + InvulnerabilityTimer = 0; + StatusEffects.Clear(); + } + + /// + /// Update per tick (status effect durations, invulnerability timer, combat timeout) + /// + public void Update(float deltaTime, long currentTick) + { + // Update invulnerability timer + if (InvulnerabilityTimer > 0) + { + InvulnerabilityTimer -= deltaTime; + if (InvulnerabilityTimer <= 0) + { + InvulnerabilityTimer = 0; + IsInvulnerable = false; + } + } + + // Update status effects + var expired = new List(); + foreach (var effect in StatusEffects) + { + effect.Duration -= deltaTime; + if (effect.Duration <= 0) + expired.Add(effect); + } + foreach (var e in expired) + StatusEffects.Remove(e); + + // Combat timeout (5 seconds out of combat) + if (IsInCombat && currentTick - LastCombatTick > 50) + { + IsInCombat = false; + } + + // Passive health regen when not in combat + if (!IsInCombat && IsAlive && Health < MaxHealth) + { + Health = Math.Min(MaxHealth, Health + MaxHealth * 0.02f * deltaTime); + } + } +} diff --git a/Game/World/WorldPortalMetadata.cs b/Game/World/WorldPortalMetadata.cs index cade1fe..304c61f 100644 --- a/Game/World/WorldPortalMetadata.cs +++ b/Game/World/WorldPortalMetadata.cs @@ -8,6 +8,7 @@ public sealed class WorldPortalMetadata public int? TargetRegionId { get; set; } public int? TargetZoneX { get; set; } public int? TargetZoneY { get; set; } + public int? TargetZoneZ { get; set; } public int? TargetChunkX { get; set; } public int? TargetChunkY { get; set; } public int? TargetTileX { get; set; } @@ -41,6 +42,7 @@ public sealed class WorldPortalMetadata out int targetRegionId, out int targetZoneX, out int targetZoneY, + out int targetZoneZ, out int targetChunkX, out int targetChunkY, out int targetTileX, @@ -49,10 +51,19 @@ public sealed class WorldPortalMetadata targetRegionId = m.TargetRegionId ?? 0; targetZoneX = m.TargetZoneX ?? 0; targetZoneY = m.TargetZoneY ?? 0; + targetZoneZ = m.TargetZoneZ ?? 0; targetChunkX = m.TargetChunkX ?? 0; targetChunkY = m.TargetChunkY ?? 0; targetTileX = m.TargetTileX ?? 0; targetTileY = m.TargetTileY ?? 0; return targetRegionId > 0; } + + /// + /// Returns true if this is a building portal (Z-level change within same zone). + /// Building portals may omit TargetRegionId/ZoneX/ZoneY and only specify TargetZoneZ. + /// + public bool IsBuildingPortal => + PortalType.Equals("building", StringComparison.OrdinalIgnoreCase) || + PortalType.Equals("building_exit", StringComparison.OrdinalIgnoreCase); } diff --git a/Game/World/WorldSessionState.cs b/Game/World/WorldSessionState.cs index 7aad5d9..de47e5b 100644 --- a/Game/World/WorldSessionState.cs +++ b/Game/World/WorldSessionState.cs @@ -13,6 +13,7 @@ public sealed class WorldSessionState public int RegionId { get; set; } public int ZoneX { get; set; } public int ZoneY { get; set; } + public int ZoneZ { get; set; } public int ChunkX { get; set; } public int ChunkY { get; set; } public float X { get; set; } diff --git a/Game/World/WorldZoneSimulation.cs b/Game/World/WorldZoneSimulation.cs new file mode 100644 index 0000000..8d7c32c --- /dev/null +++ b/Game/World/WorldZoneSimulation.cs @@ -0,0 +1,771 @@ +using System.Collections.Concurrent; +using DataServer.Data.Entities; +using DataServer.Data.Enums; +using GameServer.Dungeon; +using GameServer.Shared; + +namespace GameServer.World; + +/// +/// Per-zone runtime simulation implementing ICombatEnvironment. +/// Manages mobs, NPCs, projectiles, hazard zones, and interactive objects for a single world zone. +/// Activated when a player enters, deactivated after all players leave (with grace period). +/// +public sealed class WorldZoneSimulation : ICombatEnvironment +{ + private const float DeactivateGraceSeconds = 60f; + + public string ZoneKey { get; } + public int RegionId { get; } + public int ZoneX { get; } + public int ZoneY { get; } + public int ZoneZ { get; } + public bool IsPvpEnabled { get; set; } + + // ICombatEnvironment + public ConcurrentDictionary Mobs { get; } = new(); + public ConcurrentDictionary Projectiles { get; } = new(); + public ConcurrentDictionary HazardZones { get; } = new(); + public ConcurrentDictionary Npcs { get; } = new(); + + // Player tracking (keyed by CharacterId) + public ConcurrentDictionary Players { get; } = new(); + + // Events queue for broadcasting to clients + public ConcurrentQueue PendingEvents { get; } = new(); + + // Spawn management + public WorldMobSpawnTracker? MobSpawnTracker { get; private set; } + + // Tick state + public long CurrentTick { get; private set; } + public int Tier => 1; // World mobs use base tier + private float _tickDelta = 0.1f; // 10Hz = 100ms + + // Lifecycle + public bool IsActive { get; private set; } + public int PlayerCount => Players.Count; + private float _emptyTimer; + private bool _initialized; + + // ID allocators + private int _nextProjectileId = 1; + private int _nextHazardId = 1; + private readonly List<(int MobDefinitionId, float X, float Y, int Tier)> _pendingSummons = new(); + + // Reference to walkability checker + private readonly WorldChunkCache _cache; + private WorldChunkCache.CachedRegion? _cachedRegion; + + public WorldZoneSimulation(string zoneKey, int regionId, int zoneX, int zoneY, int zoneZ, WorldChunkCache cache) + { + ZoneKey = zoneKey; + RegionId = regionId; + ZoneX = zoneX; + ZoneY = zoneY; + ZoneZ = zoneZ; + _cache = cache; + } + + /// + /// Set the cached region reference for walkability checks. + /// Must be called before ticking. + /// + public void SetRegion(WorldChunkCache.CachedRegion region) + { + _cachedRegion = region; + } + + /// + /// Initialize the zone simulation with mob/NPC spawn data. + /// Called once when the zone first activates. + /// + public void Initialize( + Dictionary mobDefinitions, + List<(WorldChunkMobSpawnData spawnData, int chunkWorldOffsetX, int chunkWorldOffsetY)> mobSpawns, + List<(NpcInstance npc, int chunkWorldOffsetX, int chunkWorldOffsetY)> npcSpawns) + { + if (_initialized) return; + + // Initialize mob spawns + MobSpawnTracker = new WorldMobSpawnTracker(mobDefinitions); + foreach (var (spawnData, offsetX, offsetY) in mobSpawns) + { + var mobs = MobSpawnTracker.RegisterSpawnPoint(spawnData, offsetX, offsetY); + foreach (var mob in mobs) + { + Mobs[mob.Id] = mob; + } + } + + // Initialize NPCs + foreach (var (npc, _, _) in npcSpawns) + { + Npcs[npc.Id] = npc; + } + + _initialized = true; + IsActive = true; + _emptyTimer = 0; + } + + /// + /// Add a player to this zone simulation. + /// + public void AddPlayer(WorldPlayerCombatState player) + { + Players[player.CharacterId] = player; + _emptyTimer = 0; // Reset deactivation timer + } + + /// + /// Remove a player from this zone simulation. + /// + public void RemovePlayer(ulong characterId) + { + Players.TryRemove(characterId, out _); + } + + /// + /// Main tick - called each frame by WorldHandler (10Hz). + /// Returns true if zone should remain active, false if ready to deactivate. + /// + public bool Tick(long tick, float deltaTime) + { + if (!IsActive || !_initialized) return false; + + CurrentTick = tick; + _tickDelta = deltaTime; + + // Check if zone should deactivate + if (Players.IsEmpty) + { + _emptyTimer += deltaTime; + if (_emptyTimer >= DeactivateGraceSeconds) + { + IsActive = false; + return false; + } + } + else + { + _emptyTimer = 0; + } + + // Update player combat states + foreach (var player in Players.Values) + { + player.Update(deltaTime, tick); + } + + // Update mob AI + foreach (var mob in Mobs.Values) + { + if (!mob.IsAlive) continue; + MobAI.UpdateMob(mob, this, deltaTime); + } + + // Process mob attacks (mobs in Attacking state) + ProcessMobAttacks(deltaTime); + + // Update projectiles + UpdateProjectiles(deltaTime); + + // Update hazard zones + UpdateHazardZones(deltaTime); + + // Update NPC wander + UpdateNpcs(deltaTime); + + // Process respawns + if (MobSpawnTracker != null) + { + var newMobs = MobSpawnTracker.Update(deltaTime); + foreach (var mob in newMobs) + { + Mobs[mob.Id] = mob; + PendingEvents.Enqueue(new WorldCombatEvent + { + Type = WorldCombatEventType.MobSpawn, + TargetMobId = mob.Id, + X = mob.X, + Y = mob.Y, + MobData = SerializeMob(mob) + }); + } + } + + // Process pending summons + ProcessPendingSummons(); + + return true; + } + + #region Mob Attacks + + private void ProcessMobAttacks(float deltaTime) + { + foreach (var mob in Mobs.Values) + { + if (!mob.IsAlive || mob.State != MobState.Attacking) continue; + if (!mob.TargetId.HasValue) continue; + + // Find available ability + float hpPercent = mob.HpPercent; + var ability = mob.Abilities + .Where(a => a.IsAvailable(hpPercent) && mob.Mana >= a.Definition.ManaCost) + .FirstOrDefault(); + + if (ability == null) continue; + + // Check range + var target = GetPlayer(mob.TargetId.Value); + if (target == null) { mob.TargetId = null; continue; } + + float distance = GetDistance(mob.X, mob.Y, target.X, target.Y); + float abilityRange = ability.Definition.Range > 0 ? ability.Definition.Range : mob.Stats.AttackRange; + if (distance > abilityRange) continue; + + // Execute ability + ability.CooldownRemaining = ability.Definition.Cooldown; + mob.Mana -= ability.Definition.ManaCost; + + switch (ability.Definition.AbilityType) + { + case MobAbilityType.MeleeAttack: + case MobAbilityType.Cleave: + case MobAbilityType.ConeAttack: + ProcessMobDamageAbility(mob, target, ability); + break; + case MobAbilityType.ProjectileSingle: + case MobAbilityType.ProjectileAoe: + SpawnMobProjectile(mob, target, ability); + break; + case MobAbilityType.GroundAoe: + ProcessMobAoeAbility(mob, target, ability); + break; + case MobAbilityType.SummonSingle: + case MobAbilityType.SummonBulk: + // Handled by MobAI casting system + break; + default: + // Fallback to basic damage + ProcessMobDamageAbility(mob, target, ability); + break; + } + } + } + + private void ProcessMobDamageAbility(MobInstance mob, IPlayerTarget target, MobAbilityState ability) + { + if (target.IsInvulnerable || !target.IsAlive) return; + + int baseDamage = ability.Definition.BaseDamage; + string damageType = !string.IsNullOrEmpty(ability.Definition.DamageTypeKey) + ? ability.Definition.DamageTypeKey + : mob.Stats.DamageTypeKey; + + var result = CombatCalculator.CalculateMobToPlayerDamage( + mob, target, damageType, baseDamage, + target.Resistances); + + target.Health -= result.FinalDamage; + target.IsInCombat = true; + target.LastCombatTick = CurrentTick; + + PendingEvents.Enqueue(new WorldCombatEvent + { + Type = WorldCombatEventType.Damage, + SourceMobId = mob.Id, + TargetPlayerId = target.CharacterId, + Damage = result.FinalDamage, + DamageTypeKey = damageType, + X = target.X, + Y = target.Y + }); + + if (target.Health <= 0) + { + target.Health = 0; + target.IsAlive = false; + PendingEvents.Enqueue(new WorldCombatEvent + { + Type = WorldCombatEventType.PlayerDeath, + TargetPlayerId = target.CharacterId, + X = target.X, + Y = target.Y + }); + } + } + + private void SpawnMobProjectile(MobInstance mob, IPlayerTarget target, MobAbilityState ability) + { + float dx = target.X - mob.X; + float dy = target.Y - mob.Y; + float dist = MathF.Sqrt(dx * dx + dy * dy); + if (dist < 1f) return; + + float speed = ability.Definition.ProjectileSpeed > 0 ? ability.Definition.ProjectileSpeed : 300f; + int id = Interlocked.Increment(ref _nextProjectileId); + + var proj = new ProjectileInstance + { + Id = id, + SpawnTick = CurrentTick, + SourceType = ProjectileSource.Mob, + SourceMobId = mob.Id, + X = mob.X, + Y = mob.Y, + VelocityX = (dx / dist) * speed, + VelocityY = (dy / dist) * speed, + Speed = speed, + TargetX = target.X, + TargetY = target.Y, + Damage = ability.Definition.BaseDamage, + DamageTypeKey = !string.IsNullOrEmpty(ability.Definition.DamageTypeKey) + ? ability.Definition.DamageTypeKey : mob.Stats.DamageTypeKey, + AoeRadius = ability.Definition.AoeRadius, + MaxRange = ability.Definition.Range > 0 ? ability.Definition.Range * 1.5f : 500f, + SpriteKey = !string.IsNullOrEmpty(ability.Definition.ProjectileSprite) + ? ability.Definition.ProjectileSprite : "projectile_default", + CanHitPlayers = true, + CanHitMobs = false + }; + + Projectiles[proj.Id] = proj; + } + + private void ProcessMobAoeAbility(MobInstance mob, IPlayerTarget target, MobAbilityState ability) + { + float radius = ability.Definition.AoeRadius > 0 ? ability.Definition.AoeRadius : 64f; + float centerX = target.X; + float centerY = target.Y; + + foreach (var player in Players.Values) + { + if (!player.IsAlive || player.IsInvulnerable) continue; + float dist = GetDistance(centerX, centerY, player.X, player.Y); + if (dist > radius) continue; + + int baseDamage = ability.Definition.BaseDamage; + string damageType = !string.IsNullOrEmpty(ability.Definition.DamageTypeKey) + ? ability.Definition.DamageTypeKey : mob.Stats.DamageTypeKey; + + var result = CombatCalculator.CalculateMobToPlayerDamage( + mob, player, damageType, baseDamage, + player.Resistances); + + player.Health -= result.FinalDamage; + player.IsInCombat = true; + player.LastCombatTick = CurrentTick; + + PendingEvents.Enqueue(new WorldCombatEvent + { + Type = WorldCombatEventType.Damage, + SourceMobId = mob.Id, + TargetPlayerId = player.CharacterId, + Damage = result.FinalDamage, + DamageTypeKey = damageType, + X = player.X, + Y = player.Y + }); + + if (player.Health <= 0) + { + player.Health = 0; + player.IsAlive = false; + PendingEvents.Enqueue(new WorldCombatEvent + { + Type = WorldCombatEventType.PlayerDeath, + TargetPlayerId = player.CharacterId, + X = player.X, + Y = player.Y + }); + } + } + } + + #endregion + + #region Projectiles + + private void UpdateProjectiles(float deltaTime) + { + var expired = new List(); + + foreach (var proj in Projectiles.Values) + { + proj.X += proj.VelocityX * deltaTime; + proj.Y += proj.VelocityY * deltaTime; + proj.DistanceTraveled += proj.Speed * deltaTime; + + // Check max range + if (proj.DistanceTraveled >= proj.MaxRange) + { + expired.Add(proj.Id); + continue; + } + + // Check wall collision + if (!CanActorMoveTo(proj.X, proj.Y)) + { + expired.Add(proj.Id); + continue; + } + + // Check hit on players (mob projectiles) + if (proj.CanHitPlayers && proj.SourceType == ProjectileSource.Mob) + { + foreach (var player in Players.Values) + { + if (!player.IsAlive || player.IsInvulnerable) continue; + float dist = GetDistance(proj.X, proj.Y, player.X, player.Y); + if (dist <= 20f) // Hit radius + { + ApplyProjectileDamageToPlayer(proj, player); + expired.Add(proj.Id); + break; + } + } + } + + // Check hit on mobs (player projectiles) + if (proj.CanHitMobs && proj.SourceType == ProjectileSource.Player) + { + foreach (var mob in Mobs.Values) + { + if (!mob.IsAlive) continue; + float dist = GetDistance(proj.X, proj.Y, mob.X, mob.Y); + if (dist <= 20f) + { + ApplyProjectileDamageToMob(proj, mob); + expired.Add(proj.Id); + break; + } + } + } + } + + foreach (var id in expired) + Projectiles.TryRemove(id, out _); + } + + private void ApplyProjectileDamageToPlayer(ProjectileInstance proj, WorldPlayerCombatState player) + { + var result = CombatCalculator.CalculateMobToPlayerDamage( + Mobs.TryGetValue(proj.SourceMobId, out var srcMob) ? srcMob : null!, + player, proj.DamageTypeKey, proj.Damage, player.Resistances); + + player.Health -= result.FinalDamage; + player.IsInCombat = true; + player.LastCombatTick = CurrentTick; + + PendingEvents.Enqueue(new WorldCombatEvent + { + Type = WorldCombatEventType.Damage, + SourceMobId = proj.SourceMobId, + TargetPlayerId = player.CharacterId, + Damage = result.FinalDamage, + DamageTypeKey = proj.DamageTypeKey, + X = player.X, + Y = player.Y + }); + + if (player.Health <= 0) + { + player.Health = 0; + player.IsAlive = false; + PendingEvents.Enqueue(new WorldCombatEvent + { + Type = WorldCombatEventType.PlayerDeath, + TargetPlayerId = player.CharacterId, + X = player.X, + Y = player.Y + }); + } + } + + private void ApplyProjectileDamageToMob(ProjectileInstance proj, MobInstance mob) + { + var player = GetPlayer(proj.SourcePlayerId); + if (player == null) return; + + var result = CombatCalculator.CalculatePlayerToMobDamage( + player, mob, proj.DamageTypeKey, proj.Damage); + + mob.Health -= result.FinalDamage; + + PendingEvents.Enqueue(new WorldCombatEvent + { + Type = WorldCombatEventType.Damage, + SourcePlayerId = proj.SourcePlayerId, + TargetMobId = mob.Id, + Damage = result.FinalDamage, + DamageTypeKey = proj.DamageTypeKey, + X = mob.X, + Y = mob.Y + }); + + if (mob.Health <= 0) + { + mob.Health = 0; + mob.IsAlive = false; + mob.State = MobState.Dead; + mob.CurrentAnimation = mob.GetDirectionalAnimation("death"); + MobSpawnTracker?.OnMobDied(mob.Id); + + PendingEvents.Enqueue(new WorldCombatEvent + { + Type = WorldCombatEventType.MobDeath, + TargetMobId = mob.Id, + SourcePlayerId = proj.SourcePlayerId, + X = mob.X, + Y = mob.Y + }); + } + } + + #endregion + + #region Hazard Zones + + private void UpdateHazardZones(float deltaTime) + { + var expired = new List(); + + foreach (var hz in HazardZones.Values) + { + hz.Duration -= deltaTime; + if (hz.Duration <= 0) + { + expired.Add(hz.Id); + continue; + } + + hz.NextTickIn -= deltaTime; + if (hz.NextTickIn <= 0) + { + hz.NextTickIn = hz.TickInterval; + + // Damage players in radius + foreach (var player in Players.Values) + { + if (!player.IsAlive || player.IsInvulnerable) continue; + float dist = GetDistance(hz.X, hz.Y, player.X, player.Y); + if (dist > hz.Radius) continue; + + var mob = Mobs.TryGetValue(hz.SourceMobId, out var m) ? m : null; + var result = CombatCalculator.CalculateMobToPlayerDamage( + mob!, player, hz.DamageTypeKey, hz.DamagePerTick, player.Resistances); + + player.Health -= result.FinalDamage; + player.IsInCombat = true; + player.LastCombatTick = CurrentTick; + + PendingEvents.Enqueue(new WorldCombatEvent + { + Type = WorldCombatEventType.Damage, + SourceMobId = hz.SourceMobId, + TargetPlayerId = player.CharacterId, + Damage = result.FinalDamage, + DamageTypeKey = hz.DamageTypeKey, + X = player.X, + Y = player.Y + }); + + if (player.Health <= 0) + { + player.Health = 0; + player.IsAlive = false; + PendingEvents.Enqueue(new WorldCombatEvent + { + Type = WorldCombatEventType.PlayerDeath, + TargetPlayerId = player.CharacterId, + X = player.X, + Y = player.Y + }); + } + } + } + } + + foreach (var id in expired) + HazardZones.TryRemove(id, out _); + } + + #endregion + + #region NPCs + + private void UpdateNpcs(float deltaTime) + { + foreach (var npc in Npcs.Values) + { + if (!npc.IsAlive || !npc.CanWander) continue; + + npc.NextWanderIn -= deltaTime; + if (npc.NextWanderIn <= 0) + { + npc.NextWanderIn = npc.WanderIntervalSeconds; + + // Pick random point within wander radius + var rng = new Random(); + float angle = (float)(rng.NextDouble() * Math.PI * 2); + float dist = (float)(rng.NextDouble() * npc.WanderRadiusPx); + + float targetX = npc.SpawnX + MathF.Cos(angle) * dist; + float targetY = npc.SpawnY + MathF.Sin(angle) * dist; + + if (CanActorMoveTo(targetX, targetY)) + { + // Simple linear move (NPCs don't need full pathfinding) + float moveSpeed = 30f * deltaTime; + float dx = targetX - npc.X; + float dy = targetY - npc.Y; + float moveDist = MathF.Sqrt(dx * dx + dy * dy); + if (moveDist > 1f) + { + npc.X += (dx / moveDist) * Math.Min(moveSpeed, moveDist); + npc.Y += (dy / moveDist) * Math.Min(moveSpeed, moveDist); + } + } + } + } + } + + #endregion + + #region ICombatEnvironment Implementation + + public bool CanActorMoveTo(float x, float y) + { + if (_cachedRegion == null) return true; // Fallback if region not set + return _cache.IsPositionWalkable(_cachedRegion, ZoneZ, x, y, false); + } + + public IEnumerable GetAlivePlayers() + => Players.Values.Where(p => p.IsAlive); + + public IPlayerTarget? GetPlayer(ulong characterId) + => Players.TryGetValue(characterId, out var p) ? p : null; + + public void RequestMobSummon(int mobDefinitionId, float x, float y, int tier) + { + _pendingSummons.Add((mobDefinitionId, x, y, tier)); + } + + #endregion + + #region Helpers + + private void ProcessPendingSummons() + { + // World zone doesn't support dynamic mob summoning yet (would need mob definitions) + // Clear to prevent memory leak + _pendingSummons.Clear(); + } + + public object SerializeMob(MobInstance mob) + { + return new + { + id = mob.Id, + definitionId = mob.DefinitionId, + name = mob.Name, + x = mob.X, + y = mob.Y, + health = mob.Health, + maxHealth = mob.MaxHealth, + isAlive = mob.IsAlive, + state = mob.State.ToString(), + animation = mob.CurrentAnimation, + facing = mob.FacingDirection, + spriteConfig = mob.SpriteConfigJson, + tintColor = mob.TintColor, + scale = mob.Scale + }; + } + + public object SerializeNpc(NpcInstance npc) + { + return new + { + id = npc.Id, + definitionId = npc.DefinitionId, + name = npc.Name, + x = npc.X, + y = npc.Y, + health = npc.Health, + maxHealth = npc.MaxHealth, + isAlive = npc.IsAlive, + canShop = npc.CanShop, + hasDialog = npc.HasDialog, + animation = npc.CurrentAnimation, + spriteConfig = npc.SpriteConfigJson, + tintColor = npc.TintColor, + scale = npc.Scale + }; + } + + private static float GetDistance(float x1, float y1, float x2, float y2) + { + float dx = x2 - x1; + float dy = y2 - y1; + return MathF.Sqrt(dx * dx + dy * dy); + } + + /// + /// Clean up zone state when deactivating + /// + public void Deactivate() + { + IsActive = false; + Mobs.Clear(); + Npcs.Clear(); + Projectiles.Clear(); + HazardZones.Clear(); + Players.Clear(); + while (PendingEvents.TryDequeue(out _)) { } + _initialized = false; + } + + #endregion +} + +#region Combat Events + +public enum WorldCombatEventType +{ + Damage, + MobDeath, + PlayerDeath, + MobSpawn, + ProjectileSpawn, + AbilityUsed, + PlayerAttack, + PvpDamage +} + +public sealed class WorldCombatEvent +{ + public WorldCombatEventType Type { get; set; } + + // Source + public int SourceMobId { get; set; } + public ulong SourcePlayerId { get; set; } + + // Target + public int TargetMobId { get; set; } + public ulong TargetPlayerId { get; set; } + + // Data + public int Damage { get; set; } + public string DamageTypeKey { get; set; } = "physical"; + public float X { get; set; } + public float Y { get; set; } + + // For mob spawn events + public object? MobData { get; set; } +} + +#endregion diff --git a/Networking/Messages/OpCodes.cs b/Networking/Messages/OpCodes.cs index 048769e..15f5fde 100644 --- a/Networking/Messages/OpCodes.cs +++ b/Networking/Messages/OpCodes.cs @@ -121,6 +121,51 @@ public static class OpCodes /// public const int WORLD_CHUNK_DELTA = 712; + // ===== World Combat (720-739) ===== + + /// Server -> Client: Combat state update (mob states, damage events, deaths) + public const int WORLD_COMBAT_STATE = 720; + + /// Client -> Server: Player attacks a mob, player, or object in the world + public const int WORLD_ATTACK = 721; + + /// Client -> Server: Request loot from dead world mob + public const int WORLD_MOB_LOOT_REQUEST = 722; + + /// Server -> Client: Loot contents from world mob + public const int WORLD_MOB_LOOT_RESULT = 723; + + // ===== World NPC (740-749) ===== + + /// Client -> Server: Interact with world NPC + public const int WORLD_NPC_INTERACT = 740; + + /// Server -> Client: NPC interaction state (dialog/shop) + public const int WORLD_NPC_INTERACT_STATE = 741; + + /// Client -> Server: Select dialog option + public const int WORLD_NPC_DIALOG_SELECT = 742; + + /// Server -> Client: Dialog result + public const int WORLD_NPC_DIALOG_RESULT = 743; + + /// Client -> Server: NPC shop buy/sell + public const int WORLD_NPC_SHOP_ACTION = 744; + + /// Server -> Client: Shop action result + public const int WORLD_NPC_SHOP_RESULT = 745; + + // ===== World Object (750-759) ===== + + /// Client -> Server: Interact with world object + public const int WORLD_OBJECT_INTERACT = 750; + + /// Server -> Client: Object interaction result + public const int WORLD_OBJECT_INTERACT_RESULT = 751; + + /// Server -> Client: Object state change broadcast + public const int WORLD_OBJECT_STATE = 752; + // ===== Error Messages (900-999) ===== /// diff --git a/Services/Admin/Pages/WorldEditor/Index.cshtml.cs b/Services/Admin/Pages/WorldEditor/Index.cshtml.cs index d76dfdd..4497548 100644 --- a/Services/Admin/Pages/WorldEditor/Index.cshtml.cs +++ b/Services/Admin/Pages/WorldEditor/Index.cshtml.cs @@ -207,7 +207,7 @@ public class IndexModel : AdminPageModel } await EnsureZonesAsync(region); - var zone = await _db.WorldZones.FirstAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY); + var zone = await _db.WorldZones.FirstAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.ZoneZ == 0); var chunks = await _db.WorldChunks .Where(c => c.WorldZoneId == zone.Id) @@ -901,8 +901,9 @@ public class IndexModel : AdminPageModel private async Task EnsureZonesAsync(WorldRegion region) { + // Only auto-create Z=0 (ground level) zones var existing = await _db.WorldZones - .Where(z => z.RegionId == region.Id) + .Where(z => z.RegionId == region.Id && z.ZoneZ == 0) .Select(z => new { z.ZoneX, z.ZoneY }) .ToListAsync(); @@ -956,7 +957,7 @@ public class IndexModel : AdminPageModel await EnsureZonesAsync(region); var zone = await _db.WorldZones - .FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.IsEnabled); + .FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.ZoneZ == 0 && z.IsEnabled); if (zone == null) return (false, "zone_not_found", region, null, null); @@ -986,16 +987,17 @@ public class IndexModel : AdminPageModel return x >= 0 && y >= 0 && x < width && y < height; } - private void PublishDelta(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, long fromVersion, long toVersion, object op) + private void PublishDelta(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, long fromVersion, long toVersion, object op, int zoneZ = 0) { _deltaHub.Publish( - ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY), + ChunkKey(regionId, zoneX, zoneY, chunkX, chunkY, zoneZ), new { kind = "chunk_delta", regionId, zoneX, zoneY, + zoneZ, chunkX, chunkY, fromVersion, @@ -1004,8 +1006,8 @@ public class IndexModel : AdminPageModel }); } - private static string ChunkKey(int regionId, int zoneX, int zoneY, int chunkX, int chunkY) - => $"{regionId}:{zoneX}:{zoneY}:{chunkX}:{chunkY}"; + private static string ChunkKey(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, int zoneZ = 0) + => $"{regionId}:{zoneX}:{zoneY}:{zoneZ}:{chunkX}:{chunkY}"; private static string NormalizeCdnBaseUrl(string? baseUrl) { diff --git a/data/entities/DungeonCharacter.cs b/data/entities/DungeonCharacter.cs index 14a3475..7ac724f 100644 --- a/data/entities/DungeonCharacter.cs +++ b/data/entities/DungeonCharacter.cs @@ -55,6 +55,7 @@ public class DungeonCharacter public int? WorldRegionId { get; set; } public int? WorldZoneX { get; set; } public int? WorldZoneY { get; set; } + public int? WorldZoneZ { get; set; } public int? WorldChunkX { get; set; } public int? WorldChunkY { get; set; } public float? WorldX { get; set; } diff --git a/data/entities/WorldEntities.cs b/data/entities/WorldEntities.cs index 9c86e6c..9f2c33f 100644 --- a/data/entities/WorldEntities.cs +++ b/data/entities/WorldEntities.cs @@ -39,10 +39,12 @@ public class WorldZone public int ZoneX { get; set; } public int ZoneY { get; set; } + public int ZoneZ { get; set; } = 0; // 0 = ground, positive = upper floors, negative = basements [MaxLength(64)] public string Name { get; set; } = ""; + public bool IsPvpEnabled { get; set; } = false; public bool IsEnabled { get; set; } = true; public DateTime CreatedAt { get; set; } = DateTime.UtcNow; public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; @@ -166,7 +168,7 @@ public sealed class WorldZoneConfig : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder e) { - e.HasIndex(x => new { x.RegionId, x.ZoneX, x.ZoneY }).IsUnique(); + e.HasIndex(x => new { x.RegionId, x.ZoneX, x.ZoneY, x.ZoneZ }).IsUnique(); e.HasOne(x => x.Region) .WithMany() .HasForeignKey(x => x.RegionId)