import { Component } from "../ecs/components.js"; import { itemDefinition } from "../../../shared/definitions/items.js"; import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js"; import { mobDefinition, isTownGuardMob } from "../../../shared/definitions/mobs.js"; import { mobCanFightType, mobCanFight, mobMeleeAttackProfile, mobSkillLevels, mobIsAggressive, mobAggroRangeTiles, mobIsBoss } from "../../../shared/definitions/mobCombat.js"; import { combatLevelFromSkills, mobAggressionLevel, playerOutlevelsMobAggression } from "../../../shared/combat/combatLevel.js"; import { chunkPeaceAggressionImmunity } from "../../../shared/navigation/chunkPresence.js"; import { OVERWORLD_ID } from "../../../shared/world/dimensions.js"; import { spellDefinition, spellMinMagicLevel } from "../../../shared/definitions/spells.js"; import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js"; import { mobDamageAffinities } from "../../../shared/combat/magic.js"; import { AttackType } from "../../../shared/definitions/attackTypes.js"; import { isMagicStaffEquipped, firstFavoriteAttackSpellId } from "../../../shared/combat/maxHit.js"; import { canCastSpell } from "../../../shared/spells/state.js"; import { effectiveHitSkillInDarkness, aggroDistanceMultiplier } from "../../../shared/combat/darkness.js"; import { bakedTileLight01, entityLightAtTile, tileCombatLight01, tileIndexLocal } from "../../../shared/lighting/combatLight.js"; import { dynamicDarknessAtTile, dynamicLightAtTile, rayReaches } from "../../../shared/lighting/raycast.js"; import { LightOcclusion } from "../../../shared/definitions/tiles.js"; import { tileLightOcclusionAt } from "../../../shared/lighting/chunkOcclusion.js"; import { spellLightsForDynamicLighting } from "../spells/lights.js"; import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js"; import { effectiveSkillLevel, equipmentBonusesFromSlots } from "../../../shared/equipment/stats.js"; import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js"; import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js"; import { markHealthDamaged, PASSIVE_HP_REGEN_DELAY_MS, PASSIVE_HP_REGEN_PER_SECOND } from "../../../shared/combat/passiveRegen.js"; import { publicEntityView } from "../ecs/serialize.js"; import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js"; import { chunkBoundsAround, findPath } from "../navigation/astar.js"; import { tileToChunk } from "../world/coordinates.js"; import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js"; import { CHUNK_SIZE, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js"; import { stackQuantity } from "../../../shared/items/inventory.js"; import { addGroundItem, publicGroundItem } from "../items/bags.js"; import { resolveItemDualTint } from "../../../shared/render/tint.js"; import { essenceItemIdForElement } from "../../../shared/definitions/essenceItems.js"; import { castMobAttackSpell } from "../spells/mobCast.js"; import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js"; import { scheduleSpawnerRespawn } from "../simulation/spawners.js"; export function chebyshev (ax, ay, bx, by) { return Math.max(Math.abs(ax - bx), Math.abs(ay - by)); } export function attackProfileOf (ecs, handle) { const creature = ecs.get(handle, Component.creature); const level = creatureLevel(ecs, handle); const equipment = ecs.get(handle, Component.equipment); const weapon = equipment?.slots?.weapon; if (weapon?.itemId != null) { const attack = itemDefinition(weapon.itemId)?.equipment?.attack; if (attack) { const profile = { ...attack }; if (creature) { profile.mobAttackSkill = level; } return profile; } } if (creature) { const def = mobDefinition(creature.mobTypeId); if (mobCanFightType(creature.mobTypeId)) { return mobMeleeAttackProfile(def, level); } } return { ...UNARMED_ATTACK }; } function creatureLevel (ecs, handle) { const creature = ecs.get(handle, Component.creature); if (!creature) { return 1; } if (creature.level != null) { return Math.max(1, creature.level | 0 || 1); } const origin = ecs.get(handle, Component.spawnOrigin); if (origin?.level != null) { return Math.max(1, origin.level | 0 || 1); } const def = mobDefinition(creature.mobTypeId); return Math.max(1, def?.attackSkill | 0 || 1); } export function weaponEquipmentKind (ecs, handle) { const equipment = ecs.get(handle, Component.equipment); const weapon = equipment?.slots?.weapon; if (!weapon?.itemId) { return null; } return itemDefinition(weapon.itemId)?.equipment?.kind ?? null; } export function ensureMobCombat (ecs, entityId) { const handle = ecs.handleOf(entityId); if (handle == null) { return false; } const creature = ecs.get(handle, Component.creature); if (!creature || !mobCanFightType(creature.mobTypeId)) { return false; } const def = mobDefinition(creature.mobTypeId); const level = creatureLevel(ecs, handle); if (!ecs.get(handle, Component.combat)) { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false, fleeFrom: null }); } if (!ecs.get(handle, Component.skills)) { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); } return true; } function attackerSkillLevel (skills, profile, skillId) { if (profile.mobAttackSkill != null) { return profile.mobAttackSkill; } return skillLevel(skills, skillId); } function defenderSkillLevel (skills, skillId, equipment = null, settings = null) { const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {}; return effectiveSkillLevel(skills, skillId, bonuses); } function playerCombatLevels (ecs, handle, profile, settings = null) { const skills = ecs.get(handle, Component.skills); const equipment = ecs.get(handle, Component.equipment); const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings); const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now()); bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0); bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0); return { hitLevel: effectiveSkillLevel(skills, profile.hitSkillId ?? SkillId.unarmed, bonuses), damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses), agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses), defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) }; } export function isUntargetable (ecs, handle) { if (ecs.has(handle, Component.dead)) { return true; } const creature = ecs.get(handle, Component.creature); if (!creature) { return false; } return !!mobDefinition(creature.mobTypeId)?.untargetable; } /** Stop active combat / cast / path activity when a player dies. * Auto-cast preference is kept so respawn + re-cast can resume repeating. */ export function silenceDeadPlayer (ecs, handle) { if (handle == null) { return; } const entityId = ecs.entityIdOf(handle); if (entityId != null) { clearEngage(ecs, entityId); } const path = ecs.get(handle, Component.path); if (path) { path.tiles = []; } const follow = ecs.get(handle, Component.follow); if (follow) { follow.targetEntityId = null; follow.trail = []; } const casting = ecs.get(handle, Component.spellcasting); if (casting) { casting.armedSpellId = null; casting.repeatSpellId = null; casting.repeatTargetEntityId = null; casting.repeatTileX = null; casting.repeatTileY = null; casting.pendingCast = null; } } /** * Player is mid click-order (walk / harvest) — do not auto-retaliate or * cancel that order when a mob swings. */ export function playerBusyWithClickOrder (ecs, handle) { if (handle == null) { return false; } if (ecs.has(handle, Component.gather)) { return true; } const path = ecs.get(handle, Component.path); return !!(path?.tiles?.length); } /** * Staff with a favorited attack spell → entity auto-cast at the attacker; * otherwise melee engage. Returns true when a response was started. */ export function maybePlayerRetaliate (world, playerId, attackerId, now = Date.now()) { const ecs = world.ecs; const handle = ecs.handleOf(playerId); if (handle == null || ecs.has(handle, Component.dead)) { return false; } if (playerBusyWithClickOrder(ecs, handle)) { return false; } if (isSpellCombatBusy(ecs, handle)) { return false; } const follow = ecs.get(handle, Component.follow); if (follow) { follow.targetEntityId = null; follow.trail = []; } if (ecs.has(handle, Component.gather)) { ecs.remove(handle, Component.gather); } const equipment = ecs.get(handle, Component.equipment); const spells = ecs.get(handle, Component.spells); const skills = ecs.get(handle, Component.skills); const casting = ecs.get(handle, Component.spellcasting); if (isMagicStaffEquipped(equipment?.slots) && casting && spells && skills) { const spellId = firstFavoriteAttackSpellId(spells); const def = spellId ? spellDefinition(spellId) : null; if ( spellId && def?.target === "entity" && def.autoRepeat && canCastSpell(skills, spells, spellId).ok ) { casting.repeatSpellId = spellId; casting.repeatTargetEntityId = attackerId | 0; casting.repeatTileX = null; casting.repeatTileY = null; casting.pendingCast = null; const combat = ecs.get(handle, Component.combat); if (combat) { combat.targetEntityId = null; } return true; } } return engageTarget(ecs, playerId, attackerId, now); } export function engageTarget (ecs, attackerId, targetId, now = Date.now()) { const handle = ecs.handleOf(attackerId); if (handle == null) { return false; } if (ecs.has(handle, Component.dead)) { return false; } const targetHandle = ecs.handleOf(targetId); if (targetHandle != null && ecs.has(targetHandle, Component.dead)) { return false; } // Spell auto-cast / pending cast is already the active combat form. if (isSpellCombatBusy(ecs, handle)) { return false; } let combat = ecs.get(handle, Component.combat); if (!combat) { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false, fleeFrom: null }); } const targetChanged = combat.targetEntityId !== targetId; combat.targetEntityId = targetId; if (targetChanged) { // New engage (or switch): allow an immediate swing; keep cadence if already on this target. combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now); const path = ecs.get(handle, Component.path); if (path) { path.tiles = []; } } return true; } /** Melee mobs shot by player ranged/spells prefer cover while closing. */ export function markSeekCover (ecs, entityId) { const handle = ecs.handleOf(entityId); const combat = handle != null ? ecs.get(handle, Component.combat) : null; if (combat) { combat.seekCover = true; } } /** * Flee-on-hit mobs (fairies) path away from the hit source until far enough, * then stop fleeing until the next successful hit. */ export function markFleeOnHit (world, targetId, attackerId) { const ecs = world.ecs; const targetHandle = ecs.handleOf(targetId); if (targetHandle == null) { return; } const creature = ecs.get(targetHandle, Component.creature); if (!creature || ecs.get(targetHandle, Component.character)) { return; } const fleeDist = mobDefinition(creature.mobTypeId)?.fleeOnHitTiles | 0; if (fleeDist <= 0) { return; } if (!ensureMobCombat(ecs, targetId)) { return; } const combat = ecs.get(targetHandle, Component.combat); const targetPos = ecs.get(targetHandle, Component.position); const attackerHandle = ecs.handleOf(attackerId); const attackerPos = attackerHandle != null ? ecs.get(attackerHandle, Component.position) : null; if (!combat || !targetPos || !attackerPos) { return; } if (chebyshev(targetPos.tileX, targetPos.tileY, attackerPos.tileX, attackerPos.tileY) >= fleeDist) { combat.fleeFrom = null; return; } combat.fleeFrom = { tileX: attackerPos.tileX, tileY: attackerPos.tileY, minDist: fleeDist }; const path = ecs.get(targetHandle, Component.path); if (path) { path.tiles = []; } } /** Pending cast or entity-spell auto-repeat — physical combat must not run. */ export function isSpellCombatBusy (ecs, handle) { const casting = ecs.get(handle, Component.spellcasting); if (!casting) { return false; } if (casting.pendingCast) { return true; } if (!casting.repeatSpellId) { return false; } const def = spellDefinition(casting.repeatSpellId); return def?.target === "entity"; } function clearSpellCombatState (ecs, handle) { const casting = ecs.get(handle, Component.spellcasting); if (!casting) { return; } casting.repeatSpellId = null; casting.repeatTargetEntityId = null; casting.repeatTileX = null; casting.repeatTileY = null; casting.pendingCast = null; } export function clearEngage (ecs, entityId) { const handle = ecs.handleOf(entityId); const combat = handle != null ? ecs.get(handle, Component.combat) : null; if (combat) { combat.targetEntityId = null; combat.seekCover = false; combat.fleeFrom = null; } } export function hasCombatLineOfSight (world, fromX, fromY, toX, toY) { const isClear = world.isClearForRangedAttack ? (x, y) => world.isClearForRangedAttack(x, y) : (x, y) => world.isEnterable(x, y); return rayReaches(fromX, fromY, toX, toY, isClear); } function lightOcclusionAtWorld (world, x, y) { const data = world.chunkData?.(tileToChunk(x), tileToChunk(y)); if (!data) { return LightOcclusion.clear; } const index = tileIndexLocal(x, y); if (Array.isArray(data.occlusion) && data.occlusion.length > index) { return data.occlusion[index] | 0; } const localX = ((x % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; const localY = ((y % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE; return tileLightOcclusionAt(data.grounds, data.blocks, localX, localY); } /** Target-tile lighting 0–1 (baked + entity/spell lights − spell dark + time of day). */ export function tileLightAt (world, tileX, tileY, now = Date.now()) { const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY)); const index = tileIndexLocal(tileX, tileY); const baked = bakedTileLight01(data?.light, index); const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now); const { lights, darks } = spellLightsForDynamicLighting(world.spellLights, now); const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y); const spellLight = dynamicLightAtTile(tileX, tileY, lights, occlusionAt); const spellDark = dynamicDarknessAtTile(tileX, tileY, darks, occlusionAt); const worldTime = world.worldTime?.(now); return tileCombatLight01({ bakedLight01: baked, entityLight01: entity, spellLight01: spellLight, spellDark01: spellDark, worldHour: worldTime?.hour ?? 12, nightDarkness: world.settings?.nightDarkness ?? 0.72 }); } function arrowStackInOffhand (equipment) { const stack = equipment?.slots?.offhand; if (!stack) { return null; } const def = itemDefinition(stack.itemId); if (def?.equipment?.kind !== EquipmentKind.arrowAmmo) { return null; } return stack; } /** Physical attack type, or tipped-arrow element for ranged shots. */ function resolveAttackDamageType (ecs, attackerHandle, profile) { if (attackerHandle != null && profile?.mode === "ranged") { const stack = arrowStackInOffhand(ecs.get(attackerHandle, Component.equipment)); if (stack?.instance?.kind === "tipped-arrow" && stack.instance.element) { return stack.instance.element; } } return profile?.attackType ?? AttackType.blunt; } function consumeArrow (ecs, handle) { const equipment = ecs.get(handle, Component.equipment); const stack = arrowStackInOffhand(equipment); if (!stack || stackQuantity(stack.quantity) <= 0) { return false; } if (stackQuantity(stack.quantity) <= 1) { equipment.slots.offhand = null; } else { stack.quantity = stackQuantity(stack.quantity) - 1; } return true; } /** Fixed `quantity`, or inclusive `quantityMin`/`quantityMax` range (default 1). */ function rollDropQuantity (drop) { if (drop.quantityMin != null || drop.quantityMax != null) { const min = Math.max(0, Math.floor(Number(drop.quantityMin ?? 1))); const max = Math.max(min, Math.floor(Number(drop.quantityMax ?? min))); return min + Math.floor(Math.random() * (max - min + 1)); } return Math.max(1, Math.floor(Number(drop.quantity ?? 1))); } function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = null) { const creature = world.ecs.get(targetHandle, Component.creature); if (!creature) { return []; } // Summons (e.g. Shade spell) never drop loot — only wild / spawner mobs. if (world.ecs.get(targetHandle, Component.summon)) { return []; } const def = mobDefinition(creature.mobTypeId); const mobName = entityCombatDisplayName(world.ecs, targetHandle) || def?.displayName || "a creature"; let killerName = "someone"; if (attackerId != null) { const attackerHandle = world.ecs.handleOf(attackerId); if (attackerHandle != null) { killerName = entityCombatDisplayName(world.ecs, attackerHandle) || "someone"; } } const origin = lootOrigin(mobName, killerName); const events = []; const spawnOrigin = world.ecs.get(targetHandle, Component.spawnOrigin); const dropTable = [ ...(def?.drops ?? []), ...(Array.isArray(spawnOrigin?.drops) ? spawnOrigin.drops : []) ]; if (creature.element && (def?.essenceDropChance ?? 0) > 0) { const essenceId = essenceItemIdForElement(creature.element); if (essenceId) { dropTable.push({ itemId: essenceId, chance: def.essenceDropChance }); } } for (const drop of dropTable) { if (Math.random() > (drop.chance ?? 1)) { continue; } const quantity = rollDropQuantity(drop); if (quantity <= 0) { continue; } const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1); const stack = attachOrigins({ itemId: drop.itemId, quantity, origins: [{ origin, quantity }] }); const item = { groundItemId, tileX, tileY, stack, droppedAt: now, expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000), source: "mob-drop" }; addGroundItem(world, item); events.push({ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, expiresAt: item.expiresAt }); } return events; } function entityCombatDisplayName (ecs, handle) { const appearance = ecs.get(handle, Component.appearance); const fromAppearance = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim(); if (fromAppearance) { return fromAppearance; } const creature = ecs.get(handle, Component.creature); if (creature?.mobTypeId) { const def = mobDefinition(creature.mobTypeId); if (def?.displayName) { return def.displayName; } } return null; } function projectileDualTintFromAttacker (ecs, handle) { const equipment = ecs.get(handle, Component.equipment); const stack = arrowStackInOffhand(equipment); if (!stack) { return null; } return resolveItemDualTint(stack, itemDefinition(stack.itemId)); } function projectileSpriteFromAttacker (ecs, handle) { const equipment = ecs.get(handle, Component.equipment); const stack = arrowStackInOffhand(equipment); if (stack?.instance?.kind === "tipped-arrow") { return "fx:projectile:arrow-tipped"; } return "fx:projectile:arrow"; } function publicDualTint (dualTint) { if (!dualTint) { return null; } return { shaftTint: dualTint.shaft, tipTint: dualTint.tip, ...(dualTint.coat ? { coatTint: dualTint.coat } : {}) }; } function missProjectileTile (targetTileX, targetTileY, rng = Math.random) { const angle = rng() * Math.PI * 2; const dist = rng(); return { tileX: Math.round(targetTileX + Math.cos(angle) * dist), tileY: Math.round(targetTileY + Math.sin(angle) * dist) }; } /** * Aggressive mobs auto-engage the nearest player or town guard within aggro range * when they have line of sight. Town guards auto-engage aggressive creatures. * Does nothing while already engaged. */ export function stepAggression (world, now = Date.now()) { for (const entity of world.ecs.query(Component.creature, Component.position)) { if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY)) { continue; } const def = mobDefinition(entity.creature.mobTypeId); if (world.ecs.get(entity.handle, Component.summon)) { continue; } const origin = world.ecs.get(entity.handle, Component.spawnOrigin); const townGuard = !!origin?.townGuard || isTownGuardMob(entity.creature.mobTypeId); const aggressive = origin ? !!origin.aggressive : mobIsAggressive(def); if ((!aggressive && !townGuard) || !mobCanFight(def)) { continue; } if (world.ecs.has(entity.handle, Component.dead)) { continue; } const health = world.ecs.get(entity.handle, Component.health); if (health && health.current <= 0) { continue; } const combat = world.ecs.get(entity.handle, Component.combat); if (combat?.targetEntityId != null) { continue; } const range = mobAggroRangeTiles(def); const bestId = townGuard ? pickAggressionTargetAggressiveMob(world, entity, range) : pickAggressionTargetPlayerOrGuard(world, entity, range, now); if (bestId == null) { continue; } if (!ensureMobCombat(world.ecs, entity.entityId)) { continue; } engageTarget(world.ecs, entity.entityId, bestId, now); } } function creatureIsAggressiveHostile (world, handle, creature) { if (!creature || world.ecs.get(handle, Component.character)) { return false; } if (world.ecs.get(handle, Component.summon)) { return false; } const origin = world.ecs.get(handle, Component.spawnOrigin); if (origin?.townGuard || isTownGuardMob(creature.mobTypeId)) { return false; } if (origin) { return !!origin.aggressive; } return mobIsAggressive(mobDefinition(creature.mobTypeId)); } function entityIsTownGuard (world, handle, creature) { if (!creature || world.ecs.get(handle, Component.character)) { return false; } const origin = world.ecs.get(handle, Component.spawnOrigin); return !!origin?.townGuard || isTownGuardMob(creature.mobTypeId); } /** Nearest living player or town guard in range with LOS. */ function pickAggressionTargetPlayerOrGuard (world, entity, range, now = Date.now()) { let bestId = null; let bestDist = Infinity; for (const player of world.ecs.query(Component.character, Component.position)) { if (playerIgnoresAggressiveMob(world, entity, player.handle, now)) { continue; } const dist = considerAggressionCandidate(world, entity, player.handle, player.entityId, player.position, range); if (dist != null && dist < bestDist) { bestDist = dist; bestId = player.entityId; } } for (const other of world.ecs.query(Component.creature, Component.position)) { if (other.entityId === entity.entityId) { continue; } if (!entityIsTownGuard(world, other.handle, other.creature)) { continue; } const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range); if (dist != null && dist < bestDist) { bestDist = dist; bestId = other.entityId; } } return bestId; } /** Non-boss aggressive mobs skip players who outlevel them or have chunk peace. */ function playerIgnoresAggressiveMob (world, mobEntity, playerHandle, now) { const def = mobDefinition(mobEntity.creature.mobTypeId); if (mobIsBoss(def)) { return false; } const skills = world.ecs.get(playerHandle, Component.skills); if (!skills) { return false; } const playerLevel = combatLevelFromSkills(skills); const origin = world.ecs.get(mobEntity.handle, Component.spawnOrigin); const mobLevel = mobAggressionLevel(mobEntity.creature, origin, def); if (playerOutlevelsMobAggression(playerLevel, mobLevel)) { return true; } const presence = world.ecs.get(playerHandle, Component.chunkPresence); const pos = world.ecs.get(playerHandle, Component.position); if (!presence || !pos) { return false; } return chunkPeaceAggressionImmunity( presence, pos.tileX, pos.tileY, pos.dimensionId ?? OVERWORLD_ID, now, tileToChunk ); } /** Nearest aggressive hostile creature in range with LOS (for town guards). */ function pickAggressionTargetAggressiveMob (world, entity, range) { let bestId = null; let bestDist = Infinity; for (const other of world.ecs.query(Component.creature, Component.position)) { if (other.entityId === entity.entityId) { continue; } if (!creatureIsAggressiveHostile(world, other.handle, other.creature)) { continue; } if (!mobCanFight(mobDefinition(other.creature.mobTypeId))) { continue; } const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range); if (dist != null && dist < bestDist) { bestDist = dist; bestId = other.entityId; } } return bestId; } /** * @returns {number|null} Chebyshev distance if a valid aggro candidate, else null. */ function considerAggressionCandidate (world, attacker, targetHandle, targetEntityId, targetPos, range) { if (world.ecs.has(targetHandle, Component.dead)) { return null; } const health = world.ecs.get(targetHandle, Component.health); if (health && health.current <= 0) { return null; } const dist = chebyshev( attacker.position.tileX, attacker.position.tileY, targetPos.tileX, targetPos.tileY ); if (dist < 1 || dist > range) { return null; } let effectiveDist = dist; if (dist > 1) { const light = tileLightAt(world, targetPos.tileX, targetPos.tileY); effectiveDist = dist * aggroDistanceMultiplier(light); } if (effectiveDist > range) { return null; } if (!hasCombatLineOfSight( world, attacker.position.tileX, attacker.position.tileY, targetPos.tileX, targetPos.tileY )) { return null; } return dist; } /** Local entity handle or a nearby ghost snapshot for cross-worker combat. */ export function resolveCombatTarget (world, targetId) { const handle = world.ecs.handleOf(targetId); if (handle != null) { const pos = world.ecs.get(handle, Component.position); if (!pos) { return null; } if (isUntargetable(world.ecs, handle)) { return null; } return { local: true, handle, pos, health: world.ecs.get(handle, Component.health) }; } const ghost = world.ghosts?.get?.(targetId); if (!ghost || ghost.untargetable) { return null; } const health = ghost.health != null ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health } : null; return { local: false, handle: null, pos: { tileX: ghost.tileX, tileY: ghost.tileY }, health }; } function attackerCombatLevels (ecs, attackerHandle, profile, settings = null) { const attackerCharacter = ecs.get(attackerHandle, Component.character); if (attackerCharacter) { return playerCombatLevels(ecs, attackerHandle, profile, settings); } const skills = ecs.get(attackerHandle, Component.skills); const equipment = ecs.get(attackerHandle, Component.equipment); const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {}; const hitSkillId = profile.hitSkillId ?? SkillId.unarmed; const damageSkillId = profile.damageSkillId ?? SkillId.strength; const baseHit = attackerSkillLevel(skills, profile, hitSkillId); const baseDamage = attackerSkillLevel(skills, profile, damageSkillId); return { hitLevel: Math.max(1, baseHit + (bonuses[hitSkillId] ?? 0)), damageLevel: Math.max(1, baseDamage + (bonuses[damageSkillId] ?? 0)), agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses), defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) }; } export function stepPassiveHealthRegen (world, now = Date.now(), dt = 1 / 20) { const events = []; for (const entity of world.ecs.query(Component.health, Component.position)) { const { handle, entityId, health, position, character } = entity; if (world.ecs.has(handle, Component.dead)) { continue; } if (!world.chunkIsSimulating?.(position.tileX, position.tileY)) { continue; } if ((health.current | 0) >= (health.max | 0)) { continue; } const lastDamageAt = health.lastDamageAt ?? 0; if (now - lastDamageAt < PASSIVE_HP_REGEN_DELAY_MS) { continue; } const beforeInt = health.current | 0; health.current = Math.min( health.max | 0, (Number(health.current) || 0) + PASSIVE_HP_REGEN_PER_SECOND * dt ); if ((health.current | 0) === beforeInt) { continue; } if (character) { syncPlayerHealth(world.ecs, handle); } const view = publicEntityView(world.ecs, entityId); if (!view) { continue; } events.push({ type: "entity-health", entityId, ...(character ? { characterId: character.characterId } : {}), health: view.health, maxHealth: view.maxHealth, tileX: view.tileX, tileY: view.tileY }); } return events; } export function stepCombat (world, now = Date.now()) { const events = []; for (const entity of world.ecs.query(Component.combat, Component.position)) { if (world.ecs.has(entity.handle, Component.dead)) { entity.combat.targetEntityId = null; continue; } if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY)) { continue; } const combat = entity.combat; const targetId = combat.targetEntityId; if (targetId == null) { continue; } const target = resolveCombatTarget(world, targetId); if (!target) { combat.targetEntityId = null; continue; } if (target.health && target.health.current <= 0) { combat.targetEntityId = null; continue; } // One combat form at a time: spell cast / auto-cast wins over melee & archery. if (isSpellCombatBusy(world.ecs, entity.handle)) { continue; } if (combat.fleeFrom) { const flee = combat.fleeFrom; const minDist = Math.max(1, flee.minDist | 0 || 2); const fleeDist = chebyshev( entity.position.tileX, entity.position.tileY, flee.tileX, flee.tileY ); if (fleeDist >= minDist) { combat.fleeFrom = null; clearCombatApproachPath(world.ecs, entity.handle); } else { queueFleeFromHitSource(world, entity.entityId, entity.handle, entity.position, flee, minDist); continue; } } const profile = attackProfileOf(world.ecs, entity.handle); const targetPos = target.pos; const isCreature = !!world.ecs.get(entity.handle, Component.creature) && !world.ecs.get(entity.handle, Component.character); if (profile.mode === "ranged") { const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY); const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES; const equipment = world.ecs.get(entity.handle, Component.equipment); const hasArrows = isCreature || (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0); const inRange = dist >= 1 && dist <= maxRange && hasCombatLineOfSight( world, entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY ); if (!inRange || !hasArrows) { if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0) && world.ecs.get(entity.handle, Component.character)) { combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200); events.push({ type: "combat-no-arrows", attackerId: entity.entityId, sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null }); } queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange); continue; } clearCombatApproachPath(world.ecs, entity.handle); if (now < (combat.nextSwingAt || 0)) { continue; } combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200); clearSpellCombatState(world.ecs, entity.handle); events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos)); continue; } if (profile.mode !== "melee") { continue; } const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY); const canSwing = dist === 1 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY); const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : []; const preferSpell = isCreature && !!mobDefinition(world.ecs.get(entity.handle, Component.creature)?.mobTypeId)?.preferSpellAttack; const shouldCast = isCreature && attackSpells.length > 0 && (!canSwing || preferSpell); if (shouldCast) { const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES && hasCombatLineOfSight( world, entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY ); if (!inSpellRange) { queueStandInRangeApproach( world, entity.entityId, entity.handle, entity.position, targetPos.tileX, targetPos.tileY, COMBAT_RANGE_TILES, 1 ); continue; } clearCombatApproachPath(world.ecs, entity.handle); if (now < (combat.nextSwingAt || 0)) { continue; } const picked = pickMobAttackSpell(attackSpells); if (!picked) { combat.nextSwingAt = now + SPELL_COOLDOWN_MS; continue; } combat.nextSwingAt = now + SPELL_COOLDOWN_MS; events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now)); continue; } if (!canSwing) { queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos); continue; } clearCombatApproachPath(world.ecs, entity.handle); const attackerHealth = world.ecs.get(entity.handle, Component.health); if (attackerHealth && attackerHealth.current <= 0) { continue; } if ((combat.nextSwingAt || 0) > now) { continue; } combat.nextSwingAt = now + (profile.cooldownMs || 800); clearSpellCombatState(world.ecs, entity.handle); events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now)); } return events; } function eligibleMobAttackSpells (ecs, handle) { const spells = ecs.get(handle, Component.spells); if (!spells?.known?.length) { return []; } const level = creatureLevel(ecs, handle); const chances = spells.castChances ?? {}; const out = []; for (const spellId of spells.known) { const def = spellDefinition(spellId); if (!def || def.target !== "entity") { continue; } const minLevel = spellMinMagicLevel(def); if (level < minLevel) { continue; } const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0; if (chance <= 0) { continue; } out.push({ spellId, chance }); } return out; } function pickMobAttackSpell (spells) { if (!spells.length) { return null; } const pick = spells[Math.floor(Math.random() * spells.length)]; if ((Math.random() * 100) >= pick.chance) { return null; } return pick; } function clearCombatApproachPath (ecs, handle) { const path = ecs.get(handle, Component.path); if (path?.tiles?.length) { path.tiles = []; } } function combatTileKey (tileX, tileY) { return `${tileX},${tileY}`; } /** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */ function collectCombatAllyReservations (world, entityId, targetEntityId) { const reserved = new Set(); if (targetEntityId == null) { return reserved; } for (const entity of world.ecs.query(Component.combat, Component.position)) { if (entity.entityId === entityId) { continue; } if (entity.combat.targetEntityId !== targetEntityId) { continue; } reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY)); const allyPath = world.ecs.get(entity.handle, Component.path); if (!allyPath?.tiles?.length) { continue; } const next = allyPath.tiles[0]; if (next) { reserved.add(combatTileKey(next.x, next.y)); } const dest = allyPath.tiles[allyPath.tiles.length - 1]; if (dest) { reserved.add(combatTileKey(dest.x, dest.y)); } } return reserved; } function combatGoalPreference (entityId, tileX, tileY) { return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0; } /** Cost multiplier for tiles the threat can currently shoot. */ const COVER_EXPOSED_STEP_COST = 5; function mobHasRangedRetaliation (world, handle) { const profile = attackProfileOf(world.ecs, handle); if (profile?.mode === "ranged") { return true; } return eligibleMobAttackSpells(world.ecs, handle).length > 0; } /** Melee-only creatures closing after a player ranged/spell hit. */ function shouldSeekCoverApproach (world, handle) { if (world.ecs.get(handle, Component.character)) { return false; } if (!world.ecs.get(handle, Component.creature)) { return false; } const combat = world.ecs.get(handle, Component.combat); if (!combat?.seekCover) { return false; } return !mobHasRangedRetaliation(world, handle); } function coverStepCost (world, threatPos, goalX, goalY, x, y) { // Final adjacent step is always in LOS — don't punish the last lunge. if (x === goalX && y === goalY) { return 1; } if (hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y)) { return COVER_EXPOSED_STEP_COST; } return 1; } function pathCoverScore (world, threatPos, tiles) { let score = 0; for (const step of tiles) { score += hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, step.x, step.y) ? COVER_EXPOSED_STEP_COST : 1; } return score; } function listAdjacentMeleeGoals (world, entityId, position, targetPos, reserved) { const dirs = [ { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } ]; const goals = []; for (const dir of dirs) { const x = targetPos.tileX + dir.x; const y = targetPos.tileY + dir.y; const isHere = x === position.tileX && y === position.tileY; const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true; const key = combatTileKey(x, y); if (reserved?.has(key) && !(isHere && aloneHere)) { continue; } const clear = world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); if (!clear && !isHere) { continue; } if (isHere && !aloneHere) { continue; } goals.push({ x, y }); } return goals; } function findCoverMeleeApproachPath (world, entityId, handle, position, targetPos, reserved) { const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const preferVertical = !!world.ecs.get(handle, Component.character); const isWalkable = (x, y, goal) => { if (x === goal.x && y === goal.y) { return world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); } return world.walkableFor(entityId, x, y); }; let bestTiles = null; let bestScore = Infinity; let bestPref = Infinity; for (const goal of listAdjacentMeleeGoals(world, entityId, position, targetPos, reserved)) { if (goal.x === position.tileX && goal.y === position.tileY) { return []; } const tiles = findPath( position.tileX, position.tileY, goal.x, goal.y, (x, y) => isWalkable(x, y, goal), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, { preferVertical, stepCost: (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y) } ); if (!tiles.length) { continue; } const score = pathCoverScore(world, targetPos, tiles); const pref = combatGoalPreference(entityId, goal.x, goal.y); if (score < bestScore || (score === bestScore && pref < bestPref)) { bestScore = score; bestPref = pref; bestTiles = tiles; } } return bestTiles; } /** Duck behind the nearest tile the threat cannot shoot when melee approach is impossible. */ function queueFleeToCover (world, entityId, handle, position, threatPos) { let path = world.ecs.get(handle, Component.path); if (!path) { path = world.ecs.add(handle, Component.path, { tiles: [] }); } const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const isWalkable = (x, y) => world.walkableFor(entityId, x, y); const isGoal = (x, y) => { if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y))) { return false; } if (chebyshev(x, y, threatPos.tileX, threatPos.tileY) < 1) { return false; } return !hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y); }; if (isGoal(position.tileX, position.tileY)) { path.tiles = []; return; } const tiles = findPathToNearestGoal( position.tileX, position.tileY, isGoal, isWalkable, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY ); if (!tiles.length) { path.tiles = []; return; } path.tiles = tiles; const movement = world.ecs.get(handle, Component.movement); if (movement) { movement.walkCarry = 0; } } /** Path to the nearest standable tile at least `minDist` from the hit source. */ function queueFleeFromHitSource (world, entityId, handle, position, source, minDist) { if (world.frozen?.has?.(entityId)) { return; } let path = world.ecs.get(handle, Component.path); if (!path) { path = world.ecs.add(handle, Component.path, { tiles: [] }); } const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; if ( aloneHere && chebyshev(position.tileX, position.tileY, source.tileX, source.tileY) >= minDist ) { path.tiles = []; return; } const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const isWalkable = (x, y) => world.walkableFor(entityId, x, y); const isGoal = (x, y) => { if (chebyshev(x, y, source.tileX, source.tileY) < minDist) { return false; } return world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); }; if (isGoal(position.tileX, position.tileY) && aloneHere) { path.tiles = []; return; } const dest = path.tiles?.length ? path.tiles[path.tiles.length - 1] : null; if ( dest && isGoal(dest.x, dest.y) && path.tiles.every((step) => isWalkable(step.x, step.y)) ) { return; } const tiles = findPathToNearestGoal( position.tileX, position.tileY, isGoal, isWalkable, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY ); if (!tiles.length) { path.tiles = []; return; } path.tiles = tiles; const movement = world.ecs.get(handle, Component.movement); if (movement) { movement.walkCarry = 0; } } export function queueMeleeApproach (world, entityId, handle, position, targetPos) { if (world.frozen?.has?.(entityId)) { return; } let path = world.ecs.get(handle, Component.path); if (!path) { path = world.ecs.add(handle, Component.path, { tiles: [] }); } const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere) { path.tiles = []; return; } const combat = world.ecs.get(handle, Component.combat); const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); const seekCover = shouldSeekCoverApproach(world, handle); if (seekCover) { const coverTiles = findCoverMeleeApproachPath( world, entityId, handle, position, targetPos, reserved ); if (coverTiles) { if (!coverTiles.length) { path.tiles = []; return; } const goal = coverTiles[coverTiles.length - 1]; if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved)) { return; } path.tiles = coverTiles; const movement = world.ecs.get(handle, Component.movement); if (movement) { movement.walkCarry = 0; } return; } queueFleeToCover(world, entityId, handle, position, targetPos); return; } const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved); if (!goal) { path.tiles = []; return; } if (goal.x === position.tileX && goal.y === position.tileY) { path.tiles = []; return; } if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved)) { return; } const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const preferVertical = !!world.ecs.get(handle, Component.character); const tiles = findPath( position.tileX, position.tileY, goal.x, goal.y, (x, y) => { if (x === goal.x && y === goal.y) { return world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); } return world.walkableFor(entityId, x, y); }, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, { preferVertical } ); if (!tiles.length) { path.tiles = []; return; } path.tiles = tiles; const movement = world.ecs.get(handle, Component.movement); if (movement) { movement.walkCarry = 0; } } /** * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS. * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left). * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile). */ export function queueStandInRangeApproach ( world, entityId, handle, position, targetTileX, targetTileY, maxRange, minStandDist = 1 ) { if (world.frozen?.has?.(entityId)) { return; } let path = world.ecs.get(handle, Component.path); if (!path) { path = world.ecs.add(handle, Component.path, { tiles: [] }); } const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY); const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; if ( distToTarget <= maxRange && distToTarget >= minStandDist && aloneHere && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY) ) { path.tiles = []; return; } const combat = world.ecs.get(handle, Component.combat); const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const isWalkable = (x, y) => world.walkableFor(entityId, x, y); const isGoal = (x, y) => { const standOff = chebyshev(x, y, targetTileX, targetTileY); if (standOff < minStandDist || standOff > maxRange) { return false; } if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y))) { return false; } const key = combatTileKey(x, y); if (reserved.has(key) && !(x === position.tileX && y === position.tileY)) { return false; } return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY); }; const tiles = findPathToNearestGoal( position.tileX, position.tileY, isGoal, isWalkable, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY ); if (!tiles.length) { path.tiles = []; return; } const bestGoal = tiles[tiles.length - 1]; if (path.tiles?.length && !standInRangePathStale( world, entityId, path, bestGoal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position )) { return; } path.tiles = tiles; const movement = world.ecs.get(handle, Component.movement); if (movement) { movement.walkCarry = 0; } } function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange) { queueStandInRangeApproach( world, entityId, handle, position, targetPos.tileX, targetPos.tileY, maxRange, 1 ); } export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos) { const events = []; const attackerHandle = world.ecs.handleOf(attackerId); if (attackerHandle == null) { return events; } const from = world.ecs.get(attackerHandle, Component.position); if (!from || !targetPos) { return events; } const isCreature = !!world.ecs.get(attackerHandle, Component.creature) && !world.ecs.get(attackerHandle, Component.character); const arrowTint = projectileDualTintFromAttacker(world.ecs, attackerHandle); const arrowSprite = projectileSpriteFromAttacker(world.ecs, attackerHandle); const tipElement = (() => { const stack = arrowStackInOffhand(world.ecs.get(attackerHandle, Component.equipment)); return stack?.instance?.kind === "tipped-arrow" ? stack.instance.element : null; })(); if (!isCreature && !consumeArrow(world.ecs, attackerHandle)) { return events; } const shotProfile = tipElement ? { ...profile, attackType: tipElement } : profile; const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY }; const target = resolveCombatTarget(world, targetId); if (!target) { return events; } if (!target.local) { events.push({ type: "remote-ranged-resolve", attackerId, targetId, profile: shotProfile, attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, shotProfile, world.settings), attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character), now, tileX: snapshot.tileX, tileY: snapshot.tileY, fromTileX: from.tileX, fromTileY: from.tileY, sprite: arrowSprite, ...(publicDualTint(arrowTint) ?? {}) }); return events; } const hitEvents = applyLocalMeleeHit( world, attackerId, targetId, attackerHandle, target.handle, shotProfile, now, snapshot ); const outcome = hitEvents.find((e) => e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block"); let endX = snapshot.tileX; let endY = snapshot.tileY; if (outcome?.type === "combat-miss") { const miss = missProjectileTile(snapshot.tileX, snapshot.tileY); endX = miss.tileX; endY = miss.tileY; } else { const currentPos = world.ecs.get(target.handle, Component.position); if (currentPos) { endX = currentPos.tileX; endY = currentPos.tileY; } } events.push({ type: "combat-projectile", attackerId, targetId, fromTileX: from.tileX, fromTileY: from.tileY, tileX: endX, tileY: endY, durationMs: RANGED_PROJECTILE_MS, trackTarget: outcome?.type !== "combat-miss", sprite: arrowSprite, ...(publicDualTint(arrowTint) ?? {}) }); return events.concat(hitEvents); } function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position) { const dest = path.tiles[path.tiles.length - 1]; if (dest.x !== goal.x || dest.y !== goal.y) { return true; } const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY); if (standOff < minStandDist || standOff > maxRange) { return true; } if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY)) { return true; } if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) { return true; } const destKey = combatTileKey(dest.x, dest.y); if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) { return true; } const next = path.tiles[0]; if (!next) { return true; } if (!world.walkableFor(entityId, next.x, next.y)) { return true; } return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true); } function meleePathStale (world, entityId, position, targetPos, path, goal, reserved) { const dest = path.tiles[path.tiles.length - 1]; if (dest.x !== goal.x || dest.y !== goal.y) { return true; } if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1) { return true; } if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) { return true; } const destKey = combatTileKey(dest.x, dest.y); if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) { return true; } const next = path.tiles[0]; if (!next) { return true; } if (!world.walkableFor(entityId, next.x, next.y)) { return true; } return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true); } function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null) { const dirs = [ { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 } ]; let best = null; let bestDist = Infinity; let bestPref = Infinity; for (const dir of dirs) { const x = targetPos.tileX + dir.x; const y = targetPos.tileY + dir.y; const isHere = x === position.tileX && y === position.tileY; const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true; const key = combatTileKey(x, y); if (reserved?.has(key) && !(isHere && aloneHere)) { continue; } const clear = world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); if (!clear && !isHere) { continue; } if (isHere && !aloneHere) { continue; } const dist = chebyshev(position.tileX, position.tileY, x, y); const pref = combatGoalPreference(entityId, x, y); if (dist < bestDist || (dist === bestDist && pref < bestPref)) { bestDist = dist; bestPref = pref; best = { x, y }; } } return best; } export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now()) { const events = []; const attackerHandle = world.ecs.handleOf(attackerId); if (attackerHandle == null) { return events; } const target = resolveCombatTarget(world, targetId); if (!target) { return events; } const from = world.ecs.get(attackerHandle, Component.position); const to = target.pos; if (!from || !to) { return events; } if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1) { return events; } if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY)) { return events; } events.push({ type: "combat-swing", attackerId, targetId, tileX: to.tileX, tileY: to.tileY, fromTileX: from.tileX, fromTileY: from.tileY }); if (!target.local) { const attackerCharacter = world.ecs.get(attackerHandle, Component.character); events.push({ type: "remote-melee-resolve", attackerId, targetId, profile, attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings), attackerIsPlayer: !!attackerCharacter, now, tileX: to.tileX, tileY: to.tileY }); return events; } return events.concat(applyLocalMeleeHit( world, attackerId, targetId, attackerHandle, target.handle, profile, now, to )); } /** Authoritative ranged hit when the defender lives on this worker. */ export function applyRemoteRangedShot (world, payload) { const targetHandle = world.ecs.handleOf(payload.targetId); if (targetHandle == null) { return { events: [], forwards: [] }; } const snapshot = { tileX: payload.tileX, tileY: payload.tileY }; const hitEvents = applyLocalMeleeHit( world, payload.attackerId, payload.targetId, null, targetHandle, payload.profile, payload.now ?? Date.now(), snapshot, payload.attackerLevels, payload.attackerIsPlayer ); const outcome = hitEvents.find((e) => e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block"); let endX = snapshot.tileX; let endY = snapshot.tileY; if (outcome?.type === "combat-miss") { const miss = missProjectileTile(snapshot.tileX, snapshot.tileY); endX = miss.tileX; endY = miss.tileY; } else { const currentPos = world.ecs.get(targetHandle, Component.position); if (currentPos) { endX = currentPos.tileX; endY = currentPos.tileY; } } const events = [{ type: "combat-projectile", attackerId: payload.attackerId, targetId: payload.targetId, fromTileX: payload.fromTileX, fromTileY: payload.fromTileY, tileX: endX, tileY: endY, durationMs: RANGED_PROJECTILE_MS, trackTarget: outcome?.type !== "combat-miss", sprite: payload.sprite ?? "fx:projectile:arrow", shaftTint: payload.shaftTint ?? null, tipTint: payload.tipTint ?? null, coatTint: payload.coatTint ?? null }, ...hitEvents]; const forwards = []; const hitEvent = hitEvents.find((event) => event.type === "combat-hit"); if (hitEvent && payload.attackerIsPlayer) { forwards.push({ type: "forward-combat-xp", entityId: payload.attackerId, profile: payload.profile, damage: hitEvent.damage }); } return { events, forwards }; } /** Authoritative hit resolution when the defender lives on this worker. */ export function applyRemoteMeleeSwing (world, payload) { const targetHandle = world.ecs.handleOf(payload.targetId); if (targetHandle == null) { return { events: [], forwards: [] }; } const to = world.ecs.get(targetHandle, Component.position); if (!to) { return { events: [], forwards: [] }; } const events = applyLocalMeleeHit( world, payload.attackerId, payload.targetId, null, targetHandle, payload.profile, payload.now ?? Date.now(), to, payload.attackerLevels, payload.attackerIsPlayer ); const forwards = []; const hitEvent = events.find((event) => event.type === "combat-hit"); if (hitEvent && payload.attackerIsPlayer) { forwards.push({ type: "forward-combat-xp", entityId: payload.attackerId, profile: payload.profile, damage: hitEvent.damage }); } return { events, forwards }; } function applyLocalMeleeHit ( world, attackerId, targetId, attackerHandle, targetHandle, profile, now, to, attackerLevelsOverride = null, attackerIsPlayerOverride = null ) { const events = []; if (targetHandle == null) { return events; } const attackerIsPlayer = attackerIsPlayerOverride != null ? !!attackerIsPlayerOverride : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null); // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage. if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId)) { engageTarget(world.ecs, targetId, attackerId, now); if (profile?.mode === "ranged") { markSeekCover(world.ecs, targetId); } } if (attackerIsPlayer === false) { const targetCharacter = world.ecs.get(targetHandle, Component.character); if (targetCharacter) { maybePlayerRetaliate(world, targetId, attackerId, now); } } const defenderSkills = world.ecs.get(targetHandle, Component.skills); const defenderEquipment = world.ecs.get(targetHandle, Component.equipment); const attackerLevels = attackerLevelsOverride ?? (attackerHandle != null ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings) : null); if (!attackerLevels) { return events; } const agilityLevel = defenderSkillLevel( defenderSkills, SkillId.agility, defenderEquipment, world.settings ); const defenceLevel = defenderSkillLevel( defenderSkills, SkillId.defence, defenderEquipment, world.settings ); const attackType = resolveAttackDamageType(world.ecs, attackerHandle, profile); const targetCreature = world.ecs.get(targetHandle, Component.creature); const targetAffinities = targetCreature ? mobDamageAffinities(mobDefinition(targetCreature.mobTypeId)) : {}; const resolved = resolvePhysicalAttack({ hitSkillLevel: effectiveHitSkillInDarkness( attackerLevels.hitLevel, tileLightAt(world, to.tileX, to.tileY) ), agilitySkillLevel: agilityLevel, damageSkillLevel: attackerLevels.damageLevel, defenceSkillLevel: defenceLevel, attackType, targetAffinities }); if (resolved.outcome === "miss") { events.push({ type: "combat-miss", attackerId, targetId, tileX: to.tileX, tileY: to.tileY }); const dodgeXp = awardCombatAvoidanceXp( world.ecs, targetHandle, SkillId.agility, resolved.damageRoll ); if (dodgeXp) { events.push({ type: "skills-updated", entityId: targetId, characterId: dodgeXp.characterId, skills: dodgeXp.skills, combatLevel: dodgeXp.combatLevel, stored: dodgeXp.stored, levelUps: dodgeXp.levelUps ?? [] }); } return events; } if (resolved.outcome === "block") { events.push({ type: "combat-block", attackerId, targetId, tileX: to.tileX, tileY: to.tileY }); const blockXp = awardCombatAvoidanceXp( world.ecs, targetHandle, SkillId.defence, resolved.damageRoll ); if (blockXp) { events.push({ type: "skills-updated", entityId: targetId, characterId: blockXp.characterId, skills: blockXp.skills, combatLevel: blockXp.combatLevel, stored: blockXp.stored, levelUps: blockXp.levelUps ?? [] }); } return events; } const damage = resolved.damage; const targetCharacter = world.ecs.get(targetHandle, Component.character); if (targetCharacter) { syncPlayerHealth(world.ecs, targetHandle); } const health = world.ecs.get(targetHandle, Component.health); if (health) { health.current = Math.max(0, (health.current | 0) - damage); markHealthDamaged(health, now); } events.push({ type: "combat-hit", attackerId, targetId, damage, tileX: to.tileX, tileY: to.tileY, health: health?.current ?? 0, maxHealth: health?.max ?? 0 }); const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); if (healthXp) { events.push({ type: "skills-updated", entityId: targetId, characterId: healthXp.characterId, skills: healthXp.skills, combatLevel: healthXp.combatLevel, stored: healthXp.stored, levelUps: healthXp.levelUps ?? [] }); if (health) { const hitEvent = events[events.length - 2]; if (hitEvent?.type === "combat-hit") { hitEvent.health = health.current; hitEvent.maxHealth = health.max; } } } if (attackerHandle != null) { markFleeOnHit(world, targetId, attackerId); } if (attackerHandle != null) { const attackerCharacter = world.ecs.get(attackerHandle, Component.character); if (attackerCharacter) { const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage); if (xpAward) { events.push({ type: "skills-updated", entityId: attackerId, characterId: attackerCharacter.characterId, skills: xpAward.skills, combatLevel: xpAward.combatLevel, stored: xpAward.stored, levelUps: xpAward.levelUps ?? [] }); } } } if (health && health.current <= 0) { clearEngage(world.ecs, attackerId); clearEngage(world.ecs, targetId); for (const entity of world.ecs.query(Component.combat)) { if (entity.combat.targetEntityId === targetId) { entity.combat.targetEntityId = null; } } if (targetCharacter && !world.ecs.has(targetHandle, Component.dead)) { const path = world.ecs.get(targetHandle, Component.path); if (path) { path.tiles = []; } const follow = world.ecs.get(targetHandle, Component.follow); if (follow) { follow.targetEntityId = null; follow.trail = []; } world.ecs.add(targetHandle, Component.dead, {}); silenceDeadPlayer(world.ecs, targetHandle); const identity = world.ecs.get(targetHandle, Component.networkIdentity); events.push({ type: "player-died", entityId: targetId, attackerId, characterId: targetCharacter.characterId, sessionId: identity?.sessionId ?? null, tileX: to.tileX, tileY: to.tileY, health: 0, maxHealth: health.max }); } const creature = world.ecs.get(targetHandle, Component.creature); if (creature && !world.ecs.get(targetHandle, Component.character)) { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); } } return events; } /** * Drops, despawn, and `mob-killed` for bounty / town-guard reaction. * Shared by melee and spell kill paths. */ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now) { const events = []; const handle = targetHandle ?? world.ecs.handleOf(targetId); if (handle == null) { return events; } const creature = world.ecs.get(handle, Component.creature); const origin = world.ecs.get(handle, Component.spawnOrigin); const appearance = world.ecs.get(handle, Component.appearance); events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId)); events.push({ type: "mob-killed", entityId: targetId, attackerId, mobTypeId: creature?.mobTypeId ?? null, level: creature?.level ?? origin?.level ?? 1, bounty: Math.max(0, origin?.bounty | 0 || 0), spawnerId: origin?.spawnerId ?? null, originTileX: origin?.originTileX ?? tileX, originTileY: origin?.originTileY ?? tileY, wanderRangeTiles: origin?.wanderRangeTiles ?? 0, townGuard: !!origin?.townGuard, displayName: appearance?.firstName ?? null, tileX, tileY }); if (origin?.spawnerId) { scheduleSpawnerRespawn( world, origin.spawnerId, origin.respawnDelaySeconds ?? 25, now ); } const view = world.destroyEntity?.(targetId) ?? null; if (view) { events.push({ type: "entity-despawn", entityId: targetId, tileX: view.tileX, tileY: view.tileY }); } return events; } /** Apply HP loss and shared death/loot side-effects (used by spell impacts). */ export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now()) { const events = []; const targetHandle = world.ecs.handleOf(targetId); if (targetHandle == null) { return events; } const to = world.ecs.get(targetHandle, Component.position); if (!to) { return events; } const health = world.ecs.get(targetHandle, Component.health); if (health) { health.current = Math.max(0, (health.current | 0) - damage); markHealthDamaged(health, now); } events.push({ type: "combat-hit", attackerId, targetId, damage, tileX: to.tileX, tileY: to.tileY, health: health?.current ?? 0, maxHealth: health?.max ?? 0 }); const attackerHandle = world.ecs.handleOf(attackerId); if (attackerHandle != null && ensureMobCombat(world.ecs, targetId)) { const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character); const targetCombat = world.ecs.get(targetHandle, Component.combat); if (targetCombat && targetCombat.targetEntityId == null) { engageTarget(world.ecs, targetId, attackerId, now); } if (attackerIsPlayer) { markSeekCover(world.ecs, targetId); } } if (attackerHandle != null) { markFleeOnHit(world, targetId, attackerId); } if (attackerHandle != null && world.ecs.get(targetHandle, Component.character)) { const attackerCreature = world.ecs.get(attackerHandle, Component.creature); if (attackerCreature) { maybePlayerRetaliate(world, targetId, attackerId, now); } } const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); if (healthXp) { events.push({ type: "skills-updated", entityId: targetId, characterId: healthXp.characterId, skills: healthXp.skills, combatLevel: healthXp.combatLevel, stored: healthXp.stored, levelUps: healthXp.levelUps ?? [] }); } if (health && health.current <= 0) { clearEngage(world.ecs, attackerId); clearEngage(world.ecs, targetId); for (const entity of world.ecs.query(Component.combat)) { if (entity.combat.targetEntityId === targetId) { entity.combat.targetEntityId = null; } } const targetCharacter = world.ecs.get(targetHandle, Component.character); if (targetCharacter && !world.ecs.has(targetHandle, Component.dead)) { const path = world.ecs.get(targetHandle, Component.path); if (path) { path.tiles = []; } world.ecs.add(targetHandle, Component.dead, {}); silenceDeadPlayer(world.ecs, targetHandle); const identity = world.ecs.get(targetHandle, Component.networkIdentity); events.push({ type: "player-died", entityId: targetId, attackerId, characterId: targetCharacter.characterId, sessionId: identity?.sessionId ?? null, tileX: to.tileX, tileY: to.tileY, health: 0, maxHealth: health.max }); } const creature = world.ecs.get(targetHandle, Component.creature); if (creature && !targetCharacter) { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); } } return events; }