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