import { Component } from "../ecs/components.js"; import { itemDefinition } from "../../../shared/definitions/items.js"; import { mobDefinition } from "../../../shared/definitions/mobs.js"; import { mobCanFightType, mobMeleeAttackProfile, mobSkillLevels, mobIsAggressive, mobAggroRangeTiles } from "../../../shared/definitions/mobCombat.js"; import { resolvePhysicalAttack } from "../../../shared/combat/rolls.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 { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js"; import { chunkBoundsAround, findPath } from "../navigation/astar.js"; import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js"; import { rayReaches } from "../../../shared/lighting/raycast.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 equipment = ecs.get(handle, Component.equipment); const weapon = equipment?.slots?.weapon; if (weapon?.itemId != null) { const attack = itemDefinition(weapon.itemId)?.equipment?.attack; if (attack) { return { ...attack }; } } const creature = ecs.get(handle, Component.creature); if (creature) { const def = mobDefinition(creature.mobTypeId); if (mobCanFightType(creature.mobTypeId)) { return mobMeleeAttackProfile(def); } } return { ...UNARMED_ATTACK }; } 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); if (!ecs.get(handle, Component.combat)) { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); } if (!ecs.get(handle, Component.skills)) { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def) }); } return true; } function attackerSkillLevel (skills, profile, skillId) { if (profile.mobAttackSkill != null) { return profile.mobAttackSkill; } return skillLevel(skills, skillId); } function defenderSkillLevel (skills, skillId, equipment = null) { const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots) : {}; return effectiveSkillLevel(skills, skillId, bonuses); } function playerCombatLevels (ecs, handle, profile) { const skills = ecs.get(handle, Component.skills); const equipment = ecs.get(handle, Component.equipment); const bonuses = equipmentBonusesFromSlots(equipment?.slots); 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: skillLevel(skills, profile.hitSkillId), damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses), agilityLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses), defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) }; } export function isUntargetable (ecs, handle) { const creature = ecs.get(handle, Component.creature); if (!creature) { return false; } return !!mobDefinition(creature.mobTypeId)?.untargetable; } export function engageTarget (ecs, attackerId, targetId, now = Date.now()) { const handle = ecs.handleOf(attackerId); if (handle == null) { return false; } let combat = ecs.get(handle, Component.combat); if (!combat) { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); } 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; } 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; } } export function hasCombatLineOfSight (world, fromX, fromY, toX, toY) { return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y)); } /** * Aggressive mobs auto-engage the nearest player character within aggro range * when they have line of sight. 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 (!mobIsAggressive(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); let bestId = null; let bestDist = Infinity; for (const player of world.ecs.query(Component.character, Component.position)) { if (world.ecs.has(player.handle, Component.dead)) { continue; } const playerHealth = world.ecs.get(player.handle, Component.health); if (playerHealth && playerHealth.current <= 0) { continue; } const dist = chebyshev( entity.position.tileX, entity.position.tileY, player.position.tileX, player.position.tileY ); if (dist < 1 || dist > range) { continue; } if (!hasCombatLineOfSight( world, entity.position.tileX, entity.position.tileY, player.position.tileX, player.position.tileY )) { continue; } if (dist < bestDist) { bestDist = dist; bestId = player.entityId; } } if (bestId == null) { continue; } if (!ensureMobCombat(world.ecs, entity.entityId)) { continue; } engageTarget(world.ecs, entity.entityId, bestId, now); } } /** 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) { const attackerCharacter = ecs.get(attackerHandle, Component.character); if (attackerCharacter) { return playerCombatLevels(ecs, attackerHandle, profile); } const skills = ecs.get(attackerHandle, Component.skills); return { hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId), damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId), agilityLevel: skillLevel(skills, SkillId.dexterity), defenceLevel: skillLevel(skills, SkillId.defence) }; } export function stepCombat (world, now = Date.now()) { const events = []; for (const entity of world.ecs.query(Component.combat, Component.position)) { 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; } const profile = attackProfileOf(world.ecs, entity.handle); if (profile.mode !== "melee") { continue; } const targetPos = target.pos; 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); 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); events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now)); } return events; } function clearCombatApproachPath (ecs, handle) { const path = ecs.get(handle, Component.path); if (path?.tiles?.length) { path.tiles = []; } } 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 goal = bestAdjacentGoal(world, entityId, position, targetPos); 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)) { 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; } } function meleePathStale (world, entityId, position, targetPos, path, goal) { 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 next = path.tiles[0]; if (!next) { return true; } return !world.walkableFor(entityId, next.x, next.y); } function bestAdjacentGoal (world, entityId, position, targetPos) { 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; 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 clear = world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); if (!clear && !isHere) { continue; } if (isHere && !(world.isClearStanding?.(entityId, x, y) ?? true)) { continue; } const dist = chebyshev(position.tileX, position.tileY, x, y); if (dist < bestDist) { bestDist = dist; 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), 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 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 }); } 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 (attackerIsPlayer === false) { const targetCharacter = world.ecs.get(targetHandle, Component.character); if (targetCharacter) { engageTarget(world.ecs, targetId, attackerId, now); const follow = world.ecs.get(targetHandle, Component.follow); if (follow) { follow.targetEntityId = null; follow.trail = []; } if (world.ecs.has(targetHandle, Component.gather)) { world.ecs.remove(targetHandle, Component.gather); } } } 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) : null); if (!attackerLevels) { return events; } const agilityLevel = defenderSkillLevel( defenderSkills, SkillId.dexterity, defenderEquipment ); const defenceLevel = defenderSkillLevel( defenderSkills, SkillId.defence, defenderEquipment ); const resolved = resolvePhysicalAttack({ hitSkillLevel: attackerLevels.hitLevel, agilitySkillLevel: agilityLevel, damageSkillLevel: attackerLevels.damageLevel, defenceSkillLevel: defenceLevel, baseDamage: profile.baseDamage ?? 1 }); if (resolved.outcome === "miss") { events.push({ type: "combat-miss", attackerId, targetId, tileX: to.tileX, tileY: to.tileY }); return events; } if (resolved.outcome === "block") { events.push({ type: "combat-block", attackerId, targetId, tileX: to.tileX, tileY: to.tileY }); 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); } 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.view, 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) { const attackerCharacter = world.ecs.get(attackerHandle, Component.character); if (attackerCharacter) { const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile); if (xpAward) { events.push({ type: "skills-updated", entityId: attackerId, characterId: attackerCharacter.characterId, skills: xpAward.view, 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, {}); 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)) { const view = world.destroyEntity?.(targetId) ?? null; if (view) { events.push({ type: "entity-despawn", entityId: targetId, tileX: view.tileX, tileY: view.tileY }); } } } return events; }