import { Component } from "../ecs/components.js"; import { itemDefinition } from "../../../shared/definitions/items.js"; import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js"; import { mobDefinition } from "../../../shared/definitions/mobs.js"; import { mobCanFightType, mobCanFight, mobMeleeAttackProfile, mobSkillLevels, mobIsAggressive, mobAggroRangeTiles } from "../../../shared/definitions/mobCombat.js"; import { spellDefinition } from "../../../shared/definitions/spells.js"; import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js"; import { effectiveHitSkillInDarkness, aggroDistanceMultiplier } from "../../../shared/combat/darkness.js"; import { bakedTileLight01, entityLightAtTile, tileCombatLight01, tileIndexLocal } from "../../../shared/lighting/combatLight.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 { awardCombatHitXp, awardCombatAvoidanceXp, 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"; import { tileToChunk } from "../world/coordinates.js"; import { stackQuantity } from "../../../shared/items/inventory.js"; import { addGroundItem, publicGroundItem } from "../items/bags.js"; import { resolveItemDualTint } from "../../../shared/render/tint.js"; import { castMobAttackSpell } from "../spells/mobCast.js"; import { attachOrigins, lootOrigin } from "../../../shared/items/origin.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 }); } 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: skillLevel(skills, profile.hitSkillId ?? SkillId.unarmed), 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) { 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) { const isClear = world.isClearForRangedAttack ? (x, y) => world.isClearForRangedAttack(x, y) : (x, y) => world.isEnterable(x, y); return rayReaches(fromX, fromY, toX, toY, isClear); } /** Target-tile lighting 0–1 (baked + entity lights + 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 worldTime = world.worldTime?.(now); return tileCombatLight01({ bakedLight01: baked, entityLight01: entity, 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; } 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 []; } 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 = []; for (const drop of def?.drops ?? []) { 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 publicDualTint (dualTint) { if (!dualTint) { return null; } return { shaftTint: dualTint.shaft, tipTint: dualTint.tip }; } 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 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); const origin = world.ecs.get(entity.handle, Component.spawnOrigin); const aggressive = origin ? !!origin.aggressive : mobIsAggressive(def); if (!aggressive || !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); 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; } let effectiveDist = dist; if (dist > 1) { const light = tileLightAt(world, player.position.tileX, player.position.tileY); effectiveDist = dist * aggroDistanceMultiplier(light); } if (effectiveDist > 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, settings = null) { const attackerCharacter = ecs.get(attackerHandle, Component.character); if (attackerCharacter) { return playerCombatLevels(ecs, attackerHandle, profile, settings); } const skills = ecs.get(attackerHandle, Component.skills); return { hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId), damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId), agilityLevel: skillLevel(skills, SkillId.agility), 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); const targetPos = target.pos; const isCreature = !!world.ecs.get(entity.handle, Component.creature) && !world.ecs.get(entity.handle, Component.character); const weaponKind = weaponEquipmentKind(world.ecs, entity.handle); const isStaff = weaponKind === EquipmentKind.staff; 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); events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos)); continue; } if (profile.mode !== "melee" && !isStaff) { continue; } const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY); const canSwing = !isStaff && dist === 1 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY); const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : []; const shouldCast = isCreature && attackSpells.length > 0 && (isStaff || !canSwing); 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) { if (isStaff) { queueStandInRangeApproach( world, entity.entityId, entity.handle, entity.position, targetPos.tileX, targetPos.tileY, COMBAT_RANGE_TILES, 1 ); } else { 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 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 = Math.max(1, def.minMagicLevel | 0 || 1); 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 = []; } } 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 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 standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist) { 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; } const next = path.tiles[0]; if (!next) { return true; } return !world.walkableFor(entityId, next.x, next.y); } /** * Path toward the nearest tile from which `targetTile` is in Chebyshev range with LOS. * @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); if ( distToTarget <= maxRange && distToTarget >= minStandDist && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY) ) { path.tiles = []; return; } let bestGoal = null; let bestDist = Infinity; for (let dy = -maxRange; dy <= maxRange; dy++) { for (let dx = -maxRange; dx <= maxRange; dx++) { const x = targetTileX + dx; const y = targetTileY + dy; const standOff = chebyshev(x, y, targetTileX, targetTileY); if (standOff < minStandDist || standOff > maxRange) { continue; } if (!world.walkableFor(entityId, x, y)) { continue; } if (!hasCombatLineOfSight(world, x, y, targetTileX, targetTileY)) { continue; } const d = chebyshev(position.tileX, position.tileY, x, y); if (d < bestDist) { bestDist = d; bestGoal = { x, y }; } } } if (!bestGoal) { path.tiles = []; return; } if (bestGoal.x === position.tileX && bestGoal.y === position.tileY) { path.tiles = []; return; } if (path.tiles?.length && !standInRangePathStale( world, entityId, path, bestGoal, targetTileX, targetTileY, maxRange, minStandDist )) { 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, bestGoal.x, bestGoal.y, (x, y) => world.walkableFor(entityId, x, y), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, { preferVertical } ); path.tiles = tiles.length ? 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); if (!isCreature && !consumeArrow(world.ecs, attackerHandle)) { return events; } 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, attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings), attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character), now, tileX: snapshot.tileX, tileY: snapshot.tileY, fromTileX: from.tileX, fromTileY: from.tileY, ...(publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}) }); return events; } const hitEvents = applyLocalMeleeHit( world, attackerId, targetId, attackerHandle, target.handle, profile, 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", ...(publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}) }); return events.concat(hitEvents); } 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, 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", shaftTint: payload.shaftTint ?? null, tipTint: payload.tipTint ?? 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 (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, 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 resolved = resolvePhysicalAttack({ hitSkillLevel: effectiveHitSkillInDarkness( attackerLevels.hitLevel, tileLightAt(world, to.tileX, to.tileY) ), agilitySkillLevel: agilityLevel, damageSkillLevel: attackerLevels.damageLevel, defenceSkillLevel: defenceLevel }); 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.view, 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.view, 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); } 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, damage); 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)) { 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 }); 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); } 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 targetCombat = world.ecs.get(targetHandle, Component.combat); if (targetCombat && targetCombat.targetEntityId == null) { engageTarget(world.ecs, targetId, attackerId, now); } } if (attackerHandle != null && world.ecs.get(targetHandle, Component.character)) { const attackerCreature = world.ecs.get(attackerHandle, Component.creature); if (attackerCreature) { engageTarget(world.ecs, targetId, attackerId, now); } } 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 && 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, {}); 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; }