BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

service.js 73.2 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { itemDefinition } from "../../../shared/definitions/items.js";
3import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
4import { mobDefinition, isTownGuardMob } from "../../../shared/definitions/mobs.js";
5import
6 {
7 mobCanFightType,
8 mobCanFight,
9 mobMeleeAttackProfile,
10 mobSkillLevels,
11 mobIsAggressive,
12 mobAggroRangeTiles,
13 mobIsBoss
14 } from "../../../shared/definitions/mobCombat.js";
15import {
16 combatLevelFromSkills,
17 mobAggressionLevel,
18 playerOutlevelsMobAggression
19} from "../../../shared/combat/combatLevel.js";
20import { chunkPeaceAggressionImmunity } from "../../../shared/navigation/chunkPresence.js";
21import { skullAttractsTownGuards } from "../../../shared/combat/skull.js";
22import { OVERWORLD_ID } from "../../../shared/world/dimensions.js";
23import { spellDefinition, spellMinMagicLevel } from "../../../shared/definitions/spells.js";
24import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
25import { mobDamageAffinities } from "../../../shared/combat/magic.js";
26import { AttackType } from "../../../shared/definitions/attackTypes.js";
27import
28 {
29 isMagicStaffEquipped,
30 firstFavoriteAttackSpellId
31 } from "../../../shared/combat/maxHit.js";
32import { canCastSpell } from "../../../shared/spells/state.js";
33import
34 {
35 effectiveHitSkillInDarkness,
36 aggroDistanceMultiplier
37 } from "../../../shared/combat/darkness.js";
38import
39 {
40 entityLightAtTile,
41 tileCombatLight01,
42 tileIndexLocal
43 } from "../../../shared/lighting/combatLight.js";
44import { blockLightSourcesNearTile } from "../../../shared/lighting/blockLights.js";
45import { dynamicDarknessAtTile, dynamicLightAtTile, rayReaches } from "../../../shared/lighting/raycast.js";
46import { LightOcclusion } from "../../../shared/definitions/tiles.js";
47import { tileLightOcclusionAt } from "../../../shared/lighting/chunkOcclusion.js";
48import { spellLightsForDynamicLighting } from "../spells/lights.js";
49import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
50import
51 {
52 effectiveSkillLevel,
53 equipmentBonusesFromSlots
54 } from "../../../shared/equipment/stats.js";
55import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
56import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";
57import
58{
59 markHealthDamaged,
60 PASSIVE_HP_REGEN_DELAY_MS,
61 PASSIVE_HP_REGEN_PER_SECOND
62} from "../../../shared/combat/passiveRegen.js";
63import { publicEntityView } from "../ecs/serialize.js";
64import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
65import { chunkBoundsAround, findPath } from "../navigation/astar.js";
66import { tileToChunk } from "../world/coordinates.js";
67import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";
68import { withCombatBackstepCost } from "../../../shared/navigation/combatPathCost.js";
69import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
70import { stackQuantity, insertStack } from "../../../shared/items/inventory.js";
71import { placeOrMergeGroundStack, bagView } from "../items/bags.js";
72import { resolveItemDualTint } from "../../../shared/render/tint.js";
73import { essenceItemIdForElement } from "../../../shared/definitions/essenceItems.js";
74import { castMobAttackSpell } from "../spells/mobCast.js";
75import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
76import { scheduleSpawnerRespawn } from "../simulation/spawners.js";
77import
78{
79 passiveHpRegenMultiplier,
80 attackerToHitRng,
81 enemyToHitRngAgainst,
82 hitSkillBonus,
83 jewelryDamageAffinities,
84 mergeAffinities,
85 damageReflectFraction,
86 autoLootOnKill,
87 ignoresNonBossAggro,
88 JADEITE_FAIRY_RESPAWN_MS
89} from "../../../shared/equipment/jewelryEffects.js";
90
91export function chebyshev (ax, ay, bx, by)
92{
93 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
94}
95
96/** Creatures run while closing; they walk the last two tiles (and when standing to attack). */
97export const COMBAT_CHASE_RUN_TILES = 2;
98
99function creatureCanRun (world, handle)
100{
101 const stamina = world.ecs.get(handle, Component.stamina);
102 if (!stamina)
103 { return true; }
104 return Number(stamina.current) > 0;
105}
106
107function isCombatCreature (world, handle)
108{
109 return !!world.ecs.get(handle, Component.creature)
110 && !world.ecs.get(handle, Component.character);
111}
112
113function syncCreatureChaseGait (world, handle, dist, chasing)
114{
115 if (!isCombatCreature(world, handle))
116 { return; }
117 const movement = world.ecs.get(handle, Component.movement);
118 if (!movement)
119 { return; }
120 if (chasing && dist > COMBAT_CHASE_RUN_TILES && creatureCanRun(world, handle))
121 { movement.gait = GAIT.run; }
122 else
123 { movement.gait = GAIT.walk; }
124}
125
126function dropCombatTarget (world, entity)
127{
128 entity.combat.targetEntityId = null;
129 syncCreatureChaseGait(world, entity.handle, 0, false);
130}
131
132/**
133 * Stop everyone who was attacking / auto-casting at `targetEntityId`
134 * (melee engage, spell repeat, pending cast, approach path).
135 */
136export function clearAttackersTargeting (ecs, targetEntityId)
137{
138 const targetId = targetEntityId | 0;
139 if (!targetId)
140 { return; }
141 for (const entity of ecs.query(Component.combat))
142 {
143 if (entity.combat.targetEntityId !== targetId)
144 { continue; }
145 entity.combat.targetEntityId = null;
146 entity.combat.seekCover = false;
147 entity.combat.fleeFrom = null;
148 clearCombatApproachPath(ecs, entity.handle);
149 }
150 for (const entity of ecs.query(Component.spellcasting))
151 {
152 const casting = entity.spellcasting;
153 if (!casting)
154 { continue; }
155 const pendingTarget = casting.pendingCast?.targetEntityId;
156 const hitting = casting.repeatTargetEntityId === targetId
157 || (pendingTarget != null && (pendingTarget | 0) === targetId);
158 if (!hitting)
159 { continue; }
160 casting.repeatSpellId = null;
161 casting.repeatTargetEntityId = null;
162 casting.repeatTileX = null;
163 casting.repeatTileY = null;
164 casting.pendingCast = null;
165 clearCombatApproachPath(ecs, entity.handle);
166 }
167}
168
169export function attackProfileOf (ecs, handle)
170{
171 const creature = ecs.get(handle, Component.creature);
172 const level = creatureLevel(ecs, handle);
173 const equipment = ecs.get(handle, Component.equipment);
174 const weapon = equipment?.slots?.weapon;
175 if (weapon?.itemId != null)
176 {
177 const attack = itemDefinition(weapon.itemId)?.equipment?.attack;
178 if (attack)
179 {
180 const profile = { ...attack };
181 if (creature)
182 { profile.mobAttackSkill = level; }
183 return profile;
184 }
185 }
186 if (creature)
187 {
188 const def = mobDefinition(creature.mobTypeId);
189 if (mobCanFightType(creature.mobTypeId))
190 { return mobMeleeAttackProfile(def, level); }
191 }
192 return { ...UNARMED_ATTACK };
193}
194
195function creatureLevel (ecs, handle)
196{
197 const creature = ecs.get(handle, Component.creature);
198 if (!creature)
199 { return 1; }
200 if (creature.level != null)
201 { return Math.max(1, creature.level | 0 || 1); }
202 const origin = ecs.get(handle, Component.spawnOrigin);
203 if (origin?.level != null)
204 { return Math.max(1, origin.level | 0 || 1); }
205 const def = mobDefinition(creature.mobTypeId);
206 return Math.max(1, def?.attackSkill | 0 || 1);
207}
208
209export function weaponEquipmentKind (ecs, handle)
210{
211 const equipment = ecs.get(handle, Component.equipment);
212 const weapon = equipment?.slots?.weapon;
213 if (!weapon?.itemId)
214 { return null; }
215 return itemDefinition(weapon.itemId)?.equipment?.kind ?? null;
216}
217
218export function ensureMobCombat (ecs, entityId)
219{
220 const handle = ecs.handleOf(entityId);
221 if (handle == null)
222 { return false; }
223 const creature = ecs.get(handle, Component.creature);
224 if (!creature || !mobCanFightType(creature.mobTypeId))
225 { return false; }
226 const def = mobDefinition(creature.mobTypeId);
227 const level = creatureLevel(ecs, handle);
228 if (!ecs.get(handle, Component.combat))
229 { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false, fleeFrom: null }); }
230 if (!ecs.get(handle, Component.skills))
231 { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); }
232 return true;
233}
234
235function attackerSkillLevel (skills, profile, skillId)
236{
237 if (profile.mobAttackSkill != null)
238 { return profile.mobAttackSkill; }
239 return skillLevel(skills, skillId);
240}
241
242function defenderSkillLevel (skills, skillId, equipment = null, settings = null)
243{
244 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {};
245 return effectiveSkillLevel(skills, skillId, bonuses);
246}
247
248function playerCombatLevels (ecs, handle, profile, settings = null)
249{
250 const skills = ecs.get(handle, Component.skills);
251 const equipment = ecs.get(handle, Component.equipment);
252 const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings);
253 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
254 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
255 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
256
257 return {
258 hitLevel: effectiveSkillLevel(skills, profile.hitSkillId ?? SkillId.unarmed, bonuses)
259 + hitSkillBonus(equipment),
260 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses),
261 agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses),
262 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
263 };
264}
265
266export function isUntargetable (ecs, handle)
267{
268 if (ecs.has(handle, Component.dead))
269 { return true; }
270 const creature = ecs.get(handle, Component.creature);
271 if (!creature)
272 { return false; }
273 return !!mobDefinition(creature.mobTypeId)?.untargetable;
274}
275
276/** Stop active combat / cast / path activity when a player dies.
277 * Auto-cast preference is kept so respawn + re-cast can resume repeating. */
278export function silenceDeadPlayer (ecs, handle)
279{
280 if (handle == null)
281 { return; }
282 const entityId = ecs.entityIdOf(handle);
283 if (entityId != null)
284 { clearEngage(ecs, entityId); }
285 const path = ecs.get(handle, Component.path);
286 if (path)
287 { path.tiles = []; }
288 const follow = ecs.get(handle, Component.follow);
289 if (follow)
290 {
291 follow.targetEntityId = null;
292 follow.trail = [];
293 }
294 const casting = ecs.get(handle, Component.spellcasting);
295 if (casting)
296 {
297 casting.armedSpellId = null;
298 casting.repeatSpellId = null;
299 casting.repeatTargetEntityId = null;
300 casting.repeatTileX = null;
301 casting.repeatTileY = null;
302 casting.pendingCast = null;
303 }
304}
305
306/**
307 * Player is mid click-order (walk / harvest) — do not auto-retaliate or
308 * cancel that order when a mob swings.
309 */
310export function playerBusyWithClickOrder (ecs, handle)
311{
312 if (handle == null)
313 { return false; }
314 if (ecs.has(handle, Component.gather))
315 { return true; }
316 const path = ecs.get(handle, Component.path);
317 return !!(path?.tiles?.length);
318}
319
320/**
321 * Staff with a favorited attack spell → entity auto-cast at the attacker;
322 * otherwise melee engage. Returns true when a response was started.
323 */
324/**
325 * Staff + favorite entity attack spell: arm auto-cast at the target instead of melee engage.
326 * Used by click-Attack and auto-retaliate so casters hold spell range.
327 */
328export function tryArmStaffSpellAttack (ecs, playerId, targetEntityId)
329{
330 const handle = ecs.handleOf(playerId);
331 if (handle == null)
332 { return false; }
333 const equipment = ecs.get(handle, Component.equipment);
334 const spells = ecs.get(handle, Component.spells);
335 const skills = ecs.get(handle, Component.skills);
336 let casting = ecs.get(handle, Component.spellcasting);
337 if (!casting && spells)
338 {
339 casting = ecs.add(handle, Component.spellcasting, {
340 armedSpellId: null,
341 repeatSpellId: null,
342 repeatTargetEntityId: null,
343 repeatTileX: null,
344 repeatTileY: null,
345 nextCastAt: 0,
346 pendingCast: null
347 });
348 }
349 if (!(isMagicStaffEquipped(equipment?.slots) && casting && spells && skills))
350 { return false; }
351 const spellId = firstFavoriteAttackSpellId(spells);
352 const def = spellId ? spellDefinition(spellId) : null;
353 if (
354 !(
355 spellId
356 && def?.target === "entity"
357 && def.autoRepeat
358 && canCastSpell(skills, spells, spellId).ok
359 )
360 )
361 { return false; }
362 casting.repeatSpellId = spellId;
363 casting.repeatTargetEntityId = targetEntityId | 0;
364 casting.repeatTileX = null;
365 casting.repeatTileY = null;
366 casting.pendingCast = null;
367 const combat = ecs.get(handle, Component.combat);
368 if (combat)
369 { combat.targetEntityId = null; }
370 const path = ecs.get(handle, Component.path);
371 if (path)
372 { path.tiles = []; }
373 return true;
374}
375
376export function maybePlayerRetaliate (world, playerId, attackerId, now = Date.now())
377{
378 const ecs = world.ecs;
379 const handle = ecs.handleOf(playerId);
380 if (handle == null || ecs.has(handle, Component.dead))
381 { return false; }
382 if (playerBusyWithClickOrder(ecs, handle))
383 { return false; }
384 if (isSpellCombatBusy(ecs, handle))
385 { return false; }
386
387 const follow = ecs.get(handle, Component.follow);
388 if (follow)
389 {
390 follow.targetEntityId = null;
391 follow.trail = [];
392 }
393 if (ecs.has(handle, Component.gather))
394 { ecs.remove(handle, Component.gather); }
395
396 if (tryArmStaffSpellAttack(ecs, playerId, attackerId))
397 { return true; }
398 return engageTarget(ecs, playerId, attackerId, now);
399}
400
401export function engageTarget (ecs, attackerId, targetId, now = Date.now())
402{
403 const handle = ecs.handleOf(attackerId);
404 if (handle == null)
405 { return false; }
406 if (ecs.has(handle, Component.dead))
407 { return false; }
408 const targetHandle = ecs.handleOf(targetId);
409 if (targetHandle != null && ecs.has(targetHandle, Component.dead))
410 { return false; }
411 // Spell auto-cast / pending cast is already the active combat form.
412 if (isSpellCombatBusy(ecs, handle))
413 { return false; }
414 let combat = ecs.get(handle, Component.combat);
415 if (!combat)
416 { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false, fleeFrom: null }); }
417 const targetChanged = combat.targetEntityId !== targetId;
418 combat.targetEntityId = targetId;
419 if (targetChanged)
420 {
421 // New engage (or switch): allow an immediate swing; keep cadence if already on this target.
422 combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
423 const path = ecs.get(handle, Component.path);
424 if (path)
425 { path.tiles = []; }
426 }
427 return true;
428}
429
430/** Melee mobs shot by player ranged/spells prefer cover while closing. */
431export function markSeekCover (ecs, entityId)
432{
433 const handle = ecs.handleOf(entityId);
434 const combat = handle != null ? ecs.get(handle, Component.combat) : null;
435 if (combat)
436 { combat.seekCover = true; }
437}
438
439/**
440 * Flee-on-hit mobs (fairies) path away from the hit source until far enough,
441 * then stop fleeing until the next successful hit.
442 */
443export function markFleeOnHit (world, targetId, attackerId)
444{
445 const ecs = world.ecs;
446 const targetHandle = ecs.handleOf(targetId);
447 if (targetHandle == null)
448 { return; }
449 const creature = ecs.get(targetHandle, Component.creature);
450 if (!creature || ecs.get(targetHandle, Component.character))
451 { return; }
452 // Companion summons (jadeite fairy, shade) stay in the fight.
453 if (ecs.get(targetHandle, Component.summon))
454 { return; }
455 const fleeDist = mobDefinition(creature.mobTypeId)?.fleeOnHitTiles | 0;
456 if (fleeDist <= 0)
457 { return; }
458 if (!ensureMobCombat(ecs, targetId))
459 { return; }
460 const combat = ecs.get(targetHandle, Component.combat);
461 const targetPos = ecs.get(targetHandle, Component.position);
462 const attackerHandle = ecs.handleOf(attackerId);
463 const attackerPos = attackerHandle != null ? ecs.get(attackerHandle, Component.position) : null;
464 if (!combat || !targetPos || !attackerPos)
465 { return; }
466 if (chebyshev(targetPos.tileX, targetPos.tileY, attackerPos.tileX, attackerPos.tileY) >= fleeDist)
467 {
468 combat.fleeFrom = null;
469 return;
470 }
471 combat.fleeFrom = {
472 tileX: attackerPos.tileX,
473 tileY: attackerPos.tileY,
474 minDist: fleeDist
475 };
476 const path = ecs.get(targetHandle, Component.path);
477 if (path)
478 { path.tiles = []; }
479}
480
481/** Pending cast or entity-spell auto-repeat — physical combat must not run. */
482export function isSpellCombatBusy (ecs, handle)
483{
484 const casting = ecs.get(handle, Component.spellcasting);
485 if (!casting)
486 { return false; }
487 if (casting.pendingCast)
488 { return true; }
489 if (!casting.repeatSpellId)
490 { return false; }
491 const def = spellDefinition(casting.repeatSpellId);
492 return def?.target === "entity";
493}
494
495function clearSpellCombatState (ecs, handle)
496{
497 const casting = ecs.get(handle, Component.spellcasting);
498 if (!casting)
499 { return; }
500 casting.repeatSpellId = null;
501 casting.repeatTargetEntityId = null;
502 casting.repeatTileX = null;
503 casting.repeatTileY = null;
504 casting.pendingCast = null;
505}
506
507export function clearEngage (ecs, entityId)
508{
509 const handle = ecs.handleOf(entityId);
510 const combat = handle != null ? ecs.get(handle, Component.combat) : null;
511 if (combat)
512 {
513 combat.targetEntityId = null;
514 combat.seekCover = false;
515 combat.fleeFrom = null;
516 }
517}
518
519export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
520{
521 const isClear = world.isClearForRangedAttack
522 ? (x, y) => world.isClearForRangedAttack(x, y)
523 : (x, y) => world.isEnterable(x, y);
524 return rayReaches(fromX, fromY, toX, toY, isClear);
525}
526
527function lightOcclusionAtWorld (world, x, y)
528{
529 const data = world.chunkData?.(tileToChunk(x), tileToChunk(y));
530 if (!data)
531 { return LightOcclusion.clear; }
532 const index = tileIndexLocal(x, y);
533 if (Array.isArray(data.occlusion) && data.occlusion.length > index)
534 { return data.occlusion[index] | 0; }
535 const localX = ((x % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
536 const localY = ((y % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
537 return tileLightOcclusionAt(data.grounds, data.blocks, localX, localY);
538}
539
540/**
541 * Target-tile lighting 0–1 for combat.
542 * Block lights (torches, …) use live occlusion so passage-open doors let light through;
543 * entity/spell lights layer on top (same compositing as client inner 3×3).
544 */
545export function tileLightAt (world, tileX, tileY, now = Date.now())
546{
547 const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y);
548 const blockSources = blockLightSourcesNearTile(
549 (chunkX, chunkY) => world.chunkData?.(chunkX, chunkY),
550 tileX,
551 tileY
552 );
553 const blockLit = dynamicLightAtTile(tileX, tileY, blockSources, occlusionAt);
554 const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now);
555 const { lights, darks } = spellLightsForDynamicLighting(world.spellLights, now);
556 const spellLight = dynamicLightAtTile(tileX, tileY, lights, occlusionAt);
557 const spellDark = dynamicDarknessAtTile(tileX, tileY, darks, occlusionAt);
558 const worldTime = world.worldTime?.(now);
559 return tileCombatLight01({
560 bakedLight01: blockLit,
561 entityLight01: entity,
562 spellLight01: spellLight,
563 spellDark01: spellDark,
564 worldHour: worldTime?.hour ?? 12,
565 nightDarkness: world.settings?.nightDarkness ?? 0.72
566 });
567}
568
569function arrowStackInOffhand (equipment)
570{
571 const stack = equipment?.slots?.offhand;
572 if (!stack)
573 { return null; }
574 const def = itemDefinition(stack.itemId);
575 if (def?.equipment?.kind !== EquipmentKind.arrowAmmo)
576 { return null; }
577 return stack;
578}
579
580/** Physical attack type, or tipped-arrow element for ranged shots. */
581function resolveAttackDamageType (ecs, attackerHandle, profile)
582{
583 if (attackerHandle != null && profile?.mode === "ranged")
584 {
585 const stack = arrowStackInOffhand(ecs.get(attackerHandle, Component.equipment));
586 if (stack?.instance?.kind === "tipped-arrow" && stack.instance.element)
587 { return stack.instance.element; }
588 }
589 return profile?.attackType ?? AttackType.blunt;
590}
591
592function consumeArrow (ecs, handle)
593{
594 const equipment = ecs.get(handle, Component.equipment);
595 const stack = arrowStackInOffhand(equipment);
596 if (!stack || stackQuantity(stack.quantity) <= 0)
597 { return false; }
598 if (stackQuantity(stack.quantity) <= 1)
599 { equipment.slots.offhand = null; }
600 else
601 { stack.quantity = stackQuantity(stack.quantity) - 1; }
602 return true;
603}
604
605/** Fixed `quantity`, or inclusive `quantityMin`/`quantityMax` range (default 1). */
606function rollDropQuantity (drop)
607{
608 if (drop.quantityMin != null || drop.quantityMax != null)
609 {
610 const min = Math.max(0, Math.floor(Number(drop.quantityMin ?? 1)));
611 const max = Math.max(min, Math.floor(Number(drop.quantityMax ?? min)));
612 return min + Math.floor(Math.random() * (max - min + 1));
613 }
614 return Math.max(1, Math.floor(Number(drop.quantity ?? 1)));
615}
616
617function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = null)
618{
619 const creature = world.ecs.get(targetHandle, Component.creature);
620 if (!creature)
621 { return []; }
622 // Summons (e.g. Shade spell) never drop loot — only wild / spawner mobs.
623 if (world.ecs.get(targetHandle, Component.summon))
624 { return []; }
625 const def = mobDefinition(creature.mobTypeId);
626 const mobName = entityCombatDisplayName(world.ecs, targetHandle)
627 || def?.displayName
628 || "a creature";
629 let killerName = "someone";
630 if (attackerId != null)
631 {
632 const attackerHandle = world.ecs.handleOf(attackerId);
633 if (attackerHandle != null)
634 { killerName = entityCombatDisplayName(world.ecs, attackerHandle) || "someone"; }
635 }
636 const origin = lootOrigin(mobName, killerName);
637 const events = [];
638 const spawnOrigin = world.ecs.get(targetHandle, Component.spawnOrigin);
639 const dropTable = [
640 ...(def?.drops ?? []),
641 ...(Array.isArray(spawnOrigin?.drops) ? spawnOrigin.drops : [])
642 ];
643 if (creature.element && (def?.essenceDropChance ?? 0) > 0)
644 {
645 const essenceId = essenceItemIdForElement(creature.element);
646 if (essenceId)
647 { dropTable.push({ itemId: essenceId, chance: def.essenceDropChance }); }
648 }
649 for (const drop of dropTable)
650 {
651 if (Math.random() > (drop.chance ?? 1))
652 { continue; }
653 const quantity = rollDropQuantity(drop);
654 if (quantity <= 0)
655 { continue; }
656 const stack = attachOrigins({
657 itemId: drop.itemId,
658 quantity,
659 origins: [{ origin, quantity }]
660 });
661 if (tryAutoLootToKiller(world, attackerId, stack, events))
662 { continue; }
663 const placed = placeOrMergeGroundStack(world, {
664 tileX,
665 tileY,
666 stack,
667 now,
668 source: "mob-drop"
669 });
670 events.push(...placed.events);
671 }
672 return events;
673}
674
675function tryAutoLootToKiller (world, attackerId, stack, events)
676{
677 if (attackerId == null)
678 { return false; }
679 const attackerHandle = world.ecs.handleOf(attackerId);
680 if (attackerHandle == null)
681 { return false; }
682 const equipment = world.ecs.get(attackerHandle, Component.equipment);
683 if (!autoLootOnKill(equipment))
684 { return false; }
685 const inventory = world.ecs.get(attackerHandle, Component.inventory);
686 const character = world.ecs.get(attackerHandle, Component.character);
687 const def = itemDefinition(stack.itemId);
688 if (!inventory || !character || !def)
689 { return false; }
690 const inserted = insertStack(inventory.slots, stack, def);
691 if (!inserted.ok || (inserted.remainder | 0) > 0)
692 { return false; }
693 inventory.slots = inserted.slots;
694 events.push({
695 type: "inventory",
696 characterId: character.characterId,
697 ...bagView(world.ecs, attackerHandle)
698 });
699 return true;
700}
701
702function entityCombatDisplayName (ecs, handle)
703{
704 const appearance = ecs.get(handle, Component.appearance);
705 const fromAppearance = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
706 if (fromAppearance)
707 { return fromAppearance; }
708 const creature = ecs.get(handle, Component.creature);
709 if (creature?.mobTypeId)
710 {
711 const def = mobDefinition(creature.mobTypeId);
712 if (def?.displayName)
713 { return def.displayName; }
714 }
715 return null;
716}
717
718function projectileDualTintFromAttacker (ecs, handle)
719{
720 const equipment = ecs.get(handle, Component.equipment);
721 const stack = arrowStackInOffhand(equipment);
722 if (!stack)
723 { return null; }
724 return resolveItemDualTint(stack, itemDefinition(stack.itemId));
725}
726
727function projectileSpriteFromAttacker (ecs, handle)
728{
729 const equipment = ecs.get(handle, Component.equipment);
730 const stack = arrowStackInOffhand(equipment);
731 if (stack?.instance?.kind === "tipped-arrow")
732 { return "fx:projectile:arrow-tipped"; }
733 return "fx:projectile:arrow";
734}
735
736function publicDualTint (dualTint)
737{
738 if (!dualTint)
739 { return null; }
740 return {
741 shaftTint: dualTint.shaft,
742 tipTint: dualTint.tip,
743 ...(dualTint.coat ? { coatTint: dualTint.coat } : {})
744 };
745}
746
747function missProjectileTile (targetTileX, targetTileY, rng = Math.random)
748{
749 const angle = rng() * Math.PI * 2;
750 const dist = rng();
751 return {
752 tileX: Math.round(targetTileX + Math.cos(angle) * dist),
753 tileY: Math.round(targetTileY + Math.sin(angle) * dist)
754 };
755}
756
757/**
758 * Aggressive mobs auto-engage the nearest player or town guard within aggro range
759 * when they have line of sight. Town guards auto-engage aggressive creatures and
760 * players whose skull tint has started lerping toward red.
761 * Does nothing while already engaged.
762 */
763export function stepAggression (world, now = Date.now())
764{
765 for (const entity of world.ecs.query(Component.creature, Component.position))
766 {
767 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
768 { continue; }
769 const def = mobDefinition(entity.creature.mobTypeId);
770 if (world.ecs.get(entity.handle, Component.summon))
771 { continue; }
772 const origin = world.ecs.get(entity.handle, Component.spawnOrigin);
773 const townGuard = !!origin?.townGuard || isTownGuardMob(entity.creature.mobTypeId);
774 const aggressive = origin
775 ? !!origin.aggressive
776 : mobIsAggressive(def);
777 if ((!aggressive && !townGuard) || !mobCanFight(def))
778 { continue; }
779 if (world.ecs.has(entity.handle, Component.dead))
780 { continue; }
781 const health = world.ecs.get(entity.handle, Component.health);
782 if (health && health.current <= 0)
783 { continue; }
784 const combat = world.ecs.get(entity.handle, Component.combat);
785 if (combat?.targetEntityId != null)
786 { continue; }
787
788 const range = mobAggroRangeTiles(def);
789 const bestId = townGuard
790 ? pickAggressionTargetForTownGuard(world, entity, range)
791 : pickAggressionTargetPlayerOrGuard(world, entity, range, now);
792 if (bestId == null)
793 { continue; }
794 if (!ensureMobCombat(world.ecs, entity.entityId))
795 { continue; }
796 engageTarget(world.ecs, entity.entityId, bestId, now);
797 }
798}
799
800function creatureIsAggressiveHostile (world, handle, creature)
801{
802 if (!creature || world.ecs.get(handle, Component.character))
803 { return false; }
804 if (world.ecs.get(handle, Component.summon))
805 { return false; }
806 const origin = world.ecs.get(handle, Component.spawnOrigin);
807 if (origin?.townGuard || isTownGuardMob(creature.mobTypeId))
808 { return false; }
809 if (origin)
810 { return !!origin.aggressive; }
811 return mobIsAggressive(mobDefinition(creature.mobTypeId));
812}
813
814function entityIsTownGuard (world, handle, creature)
815{
816 if (!creature || world.ecs.get(handle, Component.character))
817 { return false; }
818 const origin = world.ecs.get(handle, Component.spawnOrigin);
819 return !!origin?.townGuard || isTownGuardMob(creature.mobTypeId);
820}
821
822/** Nearest living player or town guard in range with LOS. */
823function pickAggressionTargetPlayerOrGuard (world, entity, range, now = Date.now())
824{
825 let bestId = null;
826 let bestDist = Infinity;
827 for (const player of world.ecs.query(Component.character, Component.position))
828 {
829 if (playerIgnoresAggressiveMob(world, entity, player.handle, now))
830 { continue; }
831 const dist = considerAggressionCandidate(world, entity, player.handle, player.entityId, player.position, range);
832 if (dist != null && dist < bestDist)
833 {
834 bestDist = dist;
835 bestId = player.entityId;
836 }
837 }
838 for (const other of world.ecs.query(Component.creature, Component.position))
839 {
840 if (other.entityId === entity.entityId)
841 { continue; }
842 if (!entityIsTownGuard(world, other.handle, other.creature))
843 { continue; }
844 const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range);
845 if (dist != null && dist < bestDist)
846 {
847 bestDist = dist;
848 bestId = other.entityId;
849 }
850 }
851 return bestId;
852}
853
854/** Non-boss aggressive mobs skip players who outlevel them or have chunk peace. */
855function playerIgnoresAggressiveMob (world, mobEntity, playerHandle, now)
856{
857 const def = mobDefinition(mobEntity.creature.mobTypeId);
858 if (mobIsBoss(def))
859 { return false; }
860 const playerEquipment = world.ecs.get(playerHandle, Component.equipment);
861 if (ignoresNonBossAggro(playerEquipment))
862 { return true; }
863 const skills = world.ecs.get(playerHandle, Component.skills);
864 if (!skills)
865 { return false; }
866 const playerLevel = combatLevelFromSkills(skills);
867 const origin = world.ecs.get(mobEntity.handle, Component.spawnOrigin);
868 const mobLevel = mobAggressionLevel(mobEntity.creature, origin, def);
869 if (playerOutlevelsMobAggression(playerLevel, mobLevel))
870 { return true; }
871 const presence = world.ecs.get(playerHandle, Component.chunkPresence);
872 const pos = world.ecs.get(playerHandle, Component.position);
873 if (!presence || !pos)
874 { return false; }
875 return chunkPeaceAggressionImmunity(
876 presence,
877 pos.tileX,
878 pos.tileY,
879 pos.dimensionId ?? OVERWORLD_ID,
880 now,
881 tileToChunk
882 );
883}
884
885/**
886 * Nearest aggressive hostile creature or red-lerping skulled player in range
887 * with LOS (for town guards).
888 */
889function pickAggressionTargetForTownGuard (world, entity, range)
890{
891 let bestId = null;
892 let bestDist = Infinity;
893 for (const other of world.ecs.query(Component.creature, Component.position))
894 {
895 if (other.entityId === entity.entityId)
896 { continue; }
897 if (!creatureIsAggressiveHostile(world, other.handle, other.creature))
898 { continue; }
899 if (!mobCanFight(mobDefinition(other.creature.mobTypeId)))
900 { continue; }
901 const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range);
902 if (dist != null && dist < bestDist)
903 {
904 bestDist = dist;
905 bestId = other.entityId;
906 }
907 }
908 for (const player of world.ecs.query(Component.character, Component.position))
909 {
910 if (!skullAttractsTownGuards(player.character?.skullValue, world.settings))
911 { continue; }
912 const dist = considerAggressionCandidate(world, entity, player.handle, player.entityId, player.position, range);
913 if (dist != null && dist < bestDist)
914 {
915 bestDist = dist;
916 bestId = player.entityId;
917 }
918 }
919 return bestId;
920}
921
922/**
923 * @returns {number|null} Chebyshev distance if a valid aggro candidate, else null.
924 */
925function considerAggressionCandidate (world, attacker, targetHandle, targetEntityId, targetPos, range)
926{
927 if (world.ecs.has(targetHandle, Component.dead))
928 { return null; }
929 const health = world.ecs.get(targetHandle, Component.health);
930 if (health && health.current <= 0)
931 { return null; }
932 const dist = chebyshev(
933 attacker.position.tileX,
934 attacker.position.tileY,
935 targetPos.tileX,
936 targetPos.tileY
937 );
938 if (dist < 1 || dist > range)
939 { return null; }
940 let effectiveDist = dist;
941 if (dist > 1)
942 {
943 const light = tileLightAt(world, targetPos.tileX, targetPos.tileY);
944 effectiveDist = dist * aggroDistanceMultiplier(light);
945 }
946 if (effectiveDist > range)
947 { return null; }
948 if (!hasCombatLineOfSight(
949 world,
950 attacker.position.tileX,
951 attacker.position.tileY,
952 targetPos.tileX,
953 targetPos.tileY
954 ))
955 { return null; }
956 return dist;
957}
958
959/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
960export function resolveCombatTarget (world, targetId)
961{
962 const handle = world.ecs.handleOf(targetId);
963 if (handle != null)
964 {
965 const pos = world.ecs.get(handle, Component.position);
966 if (!pos)
967 { return null; }
968 if (isUntargetable(world.ecs, handle))
969 { return null; }
970 return {
971 local: true,
972 handle,
973 pos,
974 health: world.ecs.get(handle, Component.health)
975 };
976 }
977 const ghost = world.ghosts?.get?.(targetId);
978 if (!ghost || ghost.untargetable)
979 { return null; }
980 const health = ghost.health != null
981 ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health }
982 : null;
983 return {
984 local: false,
985 handle: null,
986 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
987 health
988 };
989}
990
991function attackerCombatLevels (ecs, attackerHandle, profile, settings = null)
992{
993 const attackerCharacter = ecs.get(attackerHandle, Component.character);
994 if (attackerCharacter)
995 { return playerCombatLevels(ecs, attackerHandle, profile, settings); }
996 const skills = ecs.get(attackerHandle, Component.skills);
997 const equipment = ecs.get(attackerHandle, Component.equipment);
998 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {};
999 const hitSkillId = profile.hitSkillId ?? SkillId.unarmed;
1000 const damageSkillId = profile.damageSkillId ?? SkillId.strength;
1001 const baseHit = attackerSkillLevel(skills, profile, hitSkillId);
1002 const baseDamage = attackerSkillLevel(skills, profile, damageSkillId);
1003 return {
1004 hitLevel: Math.max(1, baseHit + (bonuses[hitSkillId] ?? 0)),
1005 damageLevel: Math.max(1, baseDamage + (bonuses[damageSkillId] ?? 0)),
1006 agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses),
1007 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
1008 };
1009}
1010
1011export function stepPassiveHealthRegen (world, now = Date.now(), dt = 1 / 20)
1012{
1013 const events = [];
1014 for (const entity of world.ecs.query(Component.health, Component.position))
1015 {
1016 const { handle, entityId, health, position, character } = entity;
1017 if (world.ecs.has(handle, Component.dead))
1018 { continue; }
1019 if (!world.chunkIsSimulating?.(position.tileX, position.tileY))
1020 { continue; }
1021 if ((health.current | 0) >= (health.max | 0))
1022 { continue; }
1023 const lastDamageAt = health.lastDamageAt ?? 0;
1024 if (now - lastDamageAt < PASSIVE_HP_REGEN_DELAY_MS)
1025 { continue; }
1026 const beforeInt = health.current | 0;
1027 const equipment = world.ecs.get(handle, Component.equipment);
1028 const regenMult = passiveHpRegenMultiplier(equipment);
1029 health.current = Math.min(
1030 health.max | 0,
1031 (Number(health.current) || 0) + PASSIVE_HP_REGEN_PER_SECOND * regenMult * dt
1032 );
1033 if ((health.current | 0) === beforeInt)
1034 { continue; }
1035 if (character)
1036 { syncPlayerHealth(world.ecs, handle); }
1037 const view = publicEntityView(world.ecs, entityId);
1038 if (!view)
1039 { continue; }
1040 events.push({
1041 type: "entity-health",
1042 entityId,
1043 ...(character ? { characterId: character.characterId } : {}),
1044 health: view.health,
1045 maxHealth: view.maxHealth,
1046 tileX: view.tileX,
1047 tileY: view.tileY
1048 });
1049 }
1050 return events;
1051}
1052
1053export function stepCombat (world, now = Date.now())
1054{
1055 const events = [];
1056 for (const entity of world.ecs.query(Component.combat, Component.position))
1057 {
1058 if (world.ecs.has(entity.handle, Component.dead))
1059 {
1060 dropCombatTarget(world, entity);
1061 continue;
1062 }
1063 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
1064 { continue; }
1065 const combat = entity.combat;
1066 const targetId = combat.targetEntityId;
1067 if (targetId == null)
1068 { continue; }
1069 const target = resolveCombatTarget(world, targetId);
1070 if (!target)
1071 {
1072 dropCombatTarget(world, entity);
1073 continue;
1074 }
1075 if (target.health && target.health.current <= 0)
1076 {
1077 dropCombatTarget(world, entity);
1078 continue;
1079 }
1080
1081 // One combat form at a time: spell cast / auto-cast wins over melee & archery.
1082 if (isSpellCombatBusy(world.ecs, entity.handle))
1083 { continue; }
1084
1085 if (combat.fleeFrom)
1086 {
1087 const flee = combat.fleeFrom;
1088 const minDist = Math.max(1, flee.minDist | 0 || 2);
1089 const fleeDist = chebyshev(
1090 entity.position.tileX,
1091 entity.position.tileY,
1092 flee.tileX,
1093 flee.tileY
1094 );
1095 if (fleeDist >= minDist)
1096 {
1097 combat.fleeFrom = null;
1098 clearCombatApproachPath(world.ecs, entity.handle);
1099 }
1100 else
1101 {
1102 queueFleeFromHitSource(world, entity.entityId, entity.handle, entity.position, flee, minDist);
1103 continue;
1104 }
1105 }
1106
1107 const profile = attackProfileOf(world.ecs, entity.handle);
1108 const targetPos = target.pos;
1109 const isCreature = isCombatCreature(world, entity.handle);
1110 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
1111
1112 if (profile.mode === "ranged")
1113 {
1114 const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;
1115 const equipment = world.ecs.get(entity.handle, Component.equipment);
1116 const hasArrows = isCreature
1117 || (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0);
1118 const inRange = dist >= 1 && dist <= maxRange
1119 && hasCombatLineOfSight(
1120 world,
1121 entity.position.tileX,
1122 entity.position.tileY,
1123 targetPos.tileX,
1124 targetPos.tileY
1125 );
1126 if (!inRange || !hasArrows)
1127 {
1128 if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0)
1129 && world.ecs.get(entity.handle, Component.character))
1130 {
1131 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
1132 events.push({
1133 type: "combat-no-arrows",
1134 attackerId: entity.entityId,
1135 sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null
1136 });
1137 }
1138 syncCreatureChaseGait(world, entity.handle, dist, true);
1139 queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange);
1140 continue;
1141 }
1142 syncCreatureChaseGait(world, entity.handle, dist, false);
1143 clearCombatApproachPath(world.ecs, entity.handle);
1144 if (now < (combat.nextSwingAt || 0))
1145 { continue; }
1146 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
1147 clearSpellCombatState(world.ecs, entity.handle);
1148 events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos));
1149 continue;
1150 }
1151
1152 if (profile.mode !== "melee")
1153 { continue; }
1154
1155 const canSwing = dist === 1
1156 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
1157 const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : [];
1158 const preferSpell = isCreature
1159 && !!mobDefinition(world.ecs.get(entity.handle, Component.creature)?.mobTypeId)?.preferSpellAttack;
1160 const shouldCast = isCreature && attackSpells.length > 0 && (!canSwing || preferSpell);
1161
1162 if (shouldCast)
1163 {
1164 const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES
1165 && hasCombatLineOfSight(
1166 world,
1167 entity.position.tileX,
1168 entity.position.tileY,
1169 targetPos.tileX,
1170 targetPos.tileY
1171 );
1172 if (!inSpellRange)
1173 {
1174 syncCreatureChaseGait(world, entity.handle, dist, true);
1175 queueStandInRangeApproach(
1176 world,
1177 entity.entityId,
1178 entity.handle,
1179 entity.position,
1180 targetPos.tileX,
1181 targetPos.tileY,
1182 COMBAT_RANGE_TILES,
1183 1
1184 );
1185 continue;
1186 }
1187 syncCreatureChaseGait(world, entity.handle, dist, false);
1188 clearCombatApproachPath(world.ecs, entity.handle);
1189 if (now < (combat.nextSwingAt || 0))
1190 { continue; }
1191 const picked = pickMobAttackSpell(attackSpells);
1192 if (!picked)
1193 {
1194 combat.nextSwingAt = now + SPELL_COOLDOWN_MS;
1195 continue;
1196 }
1197 combat.nextSwingAt = now + SPELL_COOLDOWN_MS;
1198 events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now));
1199 continue;
1200 }
1201
1202 if (!canSwing)
1203 {
1204 syncCreatureChaseGait(world, entity.handle, dist, true);
1205 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
1206 continue;
1207 }
1208 syncCreatureChaseGait(world, entity.handle, dist, false);
1209 clearCombatApproachPath(world.ecs, entity.handle);
1210 const attackerHealth = world.ecs.get(entity.handle, Component.health);
1211 if (attackerHealth && attackerHealth.current <= 0)
1212 { continue; }
1213 if ((combat.nextSwingAt || 0) > now)
1214 { continue; }
1215
1216 combat.nextSwingAt = now + (profile.cooldownMs || 800);
1217 clearSpellCombatState(world.ecs, entity.handle);
1218 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
1219 }
1220 return events;
1221}
1222
1223function eligibleMobAttackSpells (ecs, handle)
1224{
1225 const spells = ecs.get(handle, Component.spells);
1226 if (!spells?.known?.length)
1227 { return []; }
1228 const level = creatureLevel(ecs, handle);
1229 const chances = spells.castChances ?? {};
1230 const out = [];
1231 for (const spellId of spells.known)
1232 {
1233 const def = spellDefinition(spellId);
1234 if (!def || def.target !== "entity")
1235 { continue; }
1236 const minLevel = spellMinMagicLevel(def);
1237 if (level < minLevel)
1238 { continue; }
1239 const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0;
1240 if (chance <= 0)
1241 { continue; }
1242 out.push({ spellId, chance });
1243 }
1244 return out;
1245}
1246
1247function pickMobAttackSpell (spells)
1248{
1249 if (!spells.length)
1250 { return null; }
1251 const pick = spells[Math.floor(Math.random() * spells.length)];
1252 if ((Math.random() * 100) >= pick.chance)
1253 { return null; }
1254 return pick;
1255}
1256
1257function clearCombatApproachPath (ecs, handle)
1258{
1259 const path = ecs.get(handle, Component.path);
1260 if (path?.tiles?.length)
1261 { path.tiles = []; }
1262}
1263
1264function combatTileKey (tileX, tileY)
1265{
1266 return `${tileX},${tileY}`;
1267}
1268
1269/** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */
1270function collectCombatAllyReservations (world, entityId, targetEntityId)
1271{
1272 const reserved = new Set();
1273 if (targetEntityId == null)
1274 { return reserved; }
1275 for (const entity of world.ecs.query(Component.combat, Component.position))
1276 {
1277 if (entity.entityId === entityId)
1278 { continue; }
1279 if (entity.combat.targetEntityId !== targetEntityId)
1280 { continue; }
1281 reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY));
1282 const allyPath = world.ecs.get(entity.handle, Component.path);
1283 if (!allyPath?.tiles?.length)
1284 { continue; }
1285 const next = allyPath.tiles[0];
1286 if (next)
1287 { reserved.add(combatTileKey(next.x, next.y)); }
1288 const dest = allyPath.tiles[allyPath.tiles.length - 1];
1289 if (dest)
1290 { reserved.add(combatTileKey(dest.x, dest.y)); }
1291 }
1292 return reserved;
1293}
1294
1295function combatGoalPreference (entityId, tileX, tileY)
1296{
1297 return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0;
1298}
1299
1300/** Cost multiplier for tiles the threat can currently shoot. */
1301const COVER_EXPOSED_STEP_COST = 5;
1302
1303function mobHasRangedRetaliation (world, handle)
1304{
1305 const profile = attackProfileOf(world.ecs, handle);
1306 if (profile?.mode === "ranged")
1307 { return true; }
1308 return eligibleMobAttackSpells(world.ecs, handle).length > 0;
1309}
1310
1311/** Melee-only creatures closing after a player ranged/spell hit. */
1312function shouldSeekCoverApproach (world, handle)
1313{
1314 if (world.ecs.get(handle, Component.character))
1315 { return false; }
1316 if (!world.ecs.get(handle, Component.creature))
1317 { return false; }
1318 const combat = world.ecs.get(handle, Component.combat);
1319 if (!combat?.seekCover)
1320 { return false; }
1321 return !mobHasRangedRetaliation(world, handle);
1322}
1323
1324/** Double cost for stepping back onto the tile just left while chasing. */
1325function combatApproachStepCost (position, baseCost = null)
1326{
1327 const prevX = position?.prevTileX;
1328 const prevY = position?.prevTileY;
1329 return (x, y) => withCombatBackstepCost(
1330 baseCost ? baseCost(x, y) : 1,
1331 x,
1332 y,
1333 prevX,
1334 prevY
1335 );
1336}
1337
1338function coverStepCost (world, threatPos, goalX, goalY, x, y)
1339{
1340 // Final adjacent step is always in LOS — don't punish the last lunge.
1341 if (x === goalX && y === goalY)
1342 { return 1; }
1343 if (hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y))
1344 { return COVER_EXPOSED_STEP_COST; }
1345 return 1;
1346}
1347
1348function pathCoverScore (world, threatPos, tiles)
1349{
1350 let score = 0;
1351 for (const step of tiles)
1352 {
1353 score += hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, step.x, step.y)
1354 ? COVER_EXPOSED_STEP_COST
1355 : 1;
1356 }
1357 return score;
1358}
1359
1360function listAdjacentMeleeGoals (world, entityId, position, targetPos, reserved)
1361{
1362 const dirs = [
1363 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
1364 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
1365 ];
1366 const goals = [];
1367 for (const dir of dirs)
1368 {
1369 const x = targetPos.tileX + dir.x;
1370 const y = targetPos.tileY + dir.y;
1371 const isHere = x === position.tileX && y === position.tileY;
1372 const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true;
1373 const key = combatTileKey(x, y);
1374 if (reserved?.has(key) && !(isHere && aloneHere))
1375 { continue; }
1376 const clear = world.isClearStanding?.(entityId, x, y)
1377 ?? world.walkableFor(entityId, x, y);
1378 if (!clear && !isHere)
1379 { continue; }
1380 if (isHere && !aloneHere)
1381 { continue; }
1382 goals.push({ x, y });
1383 }
1384 return goals;
1385}
1386
1387function findCoverMeleeApproachPath (world, entityId, handle, position, targetPos, reserved)
1388{
1389 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1390 const preferVertical = !!world.ecs.get(handle, Component.character);
1391 const isWalkable = (x, y, goal) =>
1392 {
1393 if (x === goal.x && y === goal.y)
1394 {
1395 return world.isClearStanding?.(entityId, x, y)
1396 ?? world.walkableFor(entityId, x, y);
1397 }
1398 return world.walkableFor(entityId, x, y);
1399 };
1400 let bestTiles = null;
1401 let bestScore = Infinity;
1402 let bestPref = Infinity;
1403 for (const goal of listAdjacentMeleeGoals(world, entityId, position, targetPos, reserved))
1404 {
1405 if (goal.x === position.tileX && goal.y === position.tileY)
1406 { return []; }
1407 const tiles = findPath(
1408 position.tileX,
1409 position.tileY,
1410 goal.x,
1411 goal.y,
1412 (x, y) => isWalkable(x, y, goal),
1413 bounds.minX,
1414 bounds.minY,
1415 bounds.maxX,
1416 bounds.maxY,
1417 {
1418 preferVertical,
1419 stepCost: combatApproachStepCost(
1420 position,
1421 (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)
1422 )
1423 }
1424 );
1425 if (!tiles.length)
1426 { continue; }
1427 const score = pathCoverScore(world, targetPos, tiles);
1428 const pref = combatGoalPreference(entityId, goal.x, goal.y);
1429 if (score < bestScore || (score === bestScore && pref < bestPref))
1430 {
1431 bestScore = score;
1432 bestPref = pref;
1433 bestTiles = tiles;
1434 }
1435 }
1436 return bestTiles;
1437}
1438
1439/** Duck behind the nearest tile the threat cannot shoot when melee approach is impossible. */
1440function queueFleeToCover (world, entityId, handle, position, threatPos)
1441{
1442 let path = world.ecs.get(handle, Component.path);
1443 if (!path)
1444 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
1445 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1446 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
1447 const isGoal = (x, y) =>
1448 {
1449 if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y)))
1450 { return false; }
1451 if (chebyshev(x, y, threatPos.tileX, threatPos.tileY) < 1)
1452 { return false; }
1453 return !hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y);
1454 };
1455 if (isGoal(position.tileX, position.tileY))
1456 {
1457 path.tiles = [];
1458 return;
1459 }
1460 const tiles = findPathToNearestGoal(
1461 position.tileX,
1462 position.tileY,
1463 isGoal,
1464 isWalkable,
1465 bounds.minX,
1466 bounds.minY,
1467 bounds.maxX,
1468 bounds.maxY
1469 );
1470 if (!tiles.length)
1471 {
1472 path.tiles = [];
1473 return;
1474 }
1475 path.tiles = tiles;
1476 const movement = world.ecs.get(handle, Component.movement);
1477 if (movement)
1478 { movement.walkCarry = 0; }
1479}
1480
1481/** Path to the nearest standable tile at least `minDist` from the hit source. */
1482function queueFleeFromHitSource (world, entityId, handle, position, source, minDist)
1483{
1484 if (world.frozen?.has?.(entityId))
1485 { return; }
1486 let path = world.ecs.get(handle, Component.path);
1487 if (!path)
1488 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
1489 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
1490 if (
1491 aloneHere
1492 && chebyshev(position.tileX, position.tileY, source.tileX, source.tileY) >= minDist
1493 )
1494 {
1495 path.tiles = [];
1496 return;
1497 }
1498 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1499 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
1500 const isGoal = (x, y) =>
1501 {
1502 if (chebyshev(x, y, source.tileX, source.tileY) < minDist)
1503 { return false; }
1504 return world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y);
1505 };
1506 if (isGoal(position.tileX, position.tileY) && aloneHere)
1507 {
1508 path.tiles = [];
1509 return;
1510 }
1511 const dest = path.tiles?.length ? path.tiles[path.tiles.length - 1] : null;
1512 if (
1513 dest
1514 && isGoal(dest.x, dest.y)
1515 && path.tiles.every((step) => isWalkable(step.x, step.y))
1516 )
1517 { return; }
1518 const tiles = findPathToNearestGoal(
1519 position.tileX,
1520 position.tileY,
1521 isGoal,
1522 isWalkable,
1523 bounds.minX,
1524 bounds.minY,
1525 bounds.maxX,
1526 bounds.maxY
1527 );
1528 if (!tiles.length)
1529 {
1530 path.tiles = [];
1531 return;
1532 }
1533 path.tiles = tiles;
1534 const movement = world.ecs.get(handle, Component.movement);
1535 if (movement)
1536 { movement.walkCarry = 0; }
1537}
1538
1539export function queueMeleeApproach (world, entityId, handle, position, targetPos)
1540{
1541 if (world.frozen?.has?.(entityId))
1542 { return; }
1543 let path = world.ecs.get(handle, Component.path);
1544 if (!path)
1545 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
1546
1547 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY)
1548 ?? true;
1549 if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere)
1550 {
1551 path.tiles = [];
1552 return;
1553 }
1554
1555 const combat = world.ecs.get(handle, Component.combat);
1556 const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
1557 const seekCover = shouldSeekCoverApproach(world, handle);
1558
1559 if (seekCover)
1560 {
1561 const coverTiles = findCoverMeleeApproachPath(
1562 world,
1563 entityId,
1564 handle,
1565 position,
1566 targetPos,
1567 reserved
1568 );
1569 if (coverTiles)
1570 {
1571 if (!coverTiles.length)
1572 {
1573 path.tiles = [];
1574 return;
1575 }
1576 const goal = coverTiles[coverTiles.length - 1];
1577 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved))
1578 { return; }
1579 path.tiles = coverTiles;
1580 const movement = world.ecs.get(handle, Component.movement);
1581 if (movement)
1582 { movement.walkCarry = 0; }
1583 return;
1584 }
1585 queueFleeToCover(world, entityId, handle, position, targetPos);
1586 return;
1587 }
1588
1589 const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved);
1590 if (!goal)
1591 {
1592 path.tiles = [];
1593 return;
1594 }
1595
1596 if (goal.x === position.tileX && goal.y === position.tileY)
1597 {
1598 path.tiles = [];
1599 return;
1600 }
1601
1602 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved))
1603 { return; }
1604
1605 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1606 const preferVertical = !!world.ecs.get(handle, Component.character);
1607 const tiles = findPath(
1608 position.tileX,
1609 position.tileY,
1610 goal.x,
1611 goal.y,
1612 (x, y) =>
1613 {
1614 if (x === goal.x && y === goal.y)
1615 {
1616 return world.isClearStanding?.(entityId, x, y)
1617 ?? world.walkableFor(entityId, x, y);
1618 }
1619 return world.walkableFor(entityId, x, y);
1620 },
1621 bounds.minX,
1622 bounds.minY,
1623 bounds.maxX,
1624 bounds.maxY,
1625 { preferVertical, stepCost: combatApproachStepCost(position) }
1626 );
1627 if (!tiles.length)
1628 {
1629 path.tiles = [];
1630 return;
1631 }
1632 path.tiles = tiles;
1633 const movement = world.ecs.get(handle, Component.movement);
1634 if (movement)
1635 { movement.walkCarry = 0; }
1636}
1637
1638/**
1639 * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS.
1640 * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left).
1641 * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).
1642 */
1643export function queueStandInRangeApproach (
1644 world,
1645 entityId,
1646 handle,
1647 position,
1648 targetTileX,
1649 targetTileY,
1650 maxRange,
1651 minStandDist = 1
1652)
1653{
1654 if (world.frozen?.has?.(entityId))
1655 { return; }
1656 let path = world.ecs.get(handle, Component.path);
1657 if (!path)
1658 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
1659
1660 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
1661 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
1662 if (
1663 distToTarget <= maxRange
1664 && distToTarget >= minStandDist
1665 && aloneHere
1666 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
1667 )
1668 {
1669 path.tiles = [];
1670 return;
1671 }
1672
1673 const combat = world.ecs.get(handle, Component.combat);
1674 const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
1675 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1676 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
1677 const isGoal = (x, y) =>
1678 {
1679 const standOff = chebyshev(x, y, targetTileX, targetTileY);
1680 if (standOff < minStandDist || standOff > maxRange)
1681 { return false; }
1682 if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y)))
1683 { return false; }
1684 const key = combatTileKey(x, y);
1685 if (reserved.has(key) && !(x === position.tileX && y === position.tileY))
1686 { return false; }
1687 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY);
1688 };
1689
1690 const tiles = findPathToNearestGoal(
1691 position.tileX,
1692 position.tileY,
1693 isGoal,
1694 isWalkable,
1695 bounds.minX,
1696 bounds.minY,
1697 bounds.maxX,
1698 bounds.maxY,
1699 { stepCost: combatApproachStepCost(position) }
1700 );
1701 if (!tiles.length)
1702 {
1703 path.tiles = [];
1704 return;
1705 }
1706 const bestGoal = tiles[tiles.length - 1];
1707 if (path.tiles?.length && !standInRangePathStale(
1708 world,
1709 entityId,
1710 path,
1711 bestGoal,
1712 targetTileX,
1713 targetTileY,
1714 maxRange,
1715 minStandDist,
1716 reserved,
1717 position
1718 ))
1719 { return; }
1720 path.tiles = tiles;
1721 const movement = world.ecs.get(handle, Component.movement);
1722 if (movement)
1723 { movement.walkCarry = 0; }
1724}
1725
1726function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
1727{
1728 queueStandInRangeApproach(
1729 world,
1730 entityId,
1731 handle,
1732 position,
1733 targetPos.tileX,
1734 targetPos.tileY,
1735 maxRange,
1736 1
1737 );
1738}
1739
1740export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
1741{
1742 const events = [];
1743 const attackerHandle = world.ecs.handleOf(attackerId);
1744 if (attackerHandle == null)
1745 { return events; }
1746 const from = world.ecs.get(attackerHandle, Component.position);
1747 if (!from || !targetPos)
1748 { return events; }
1749 const isCreature = !!world.ecs.get(attackerHandle, Component.creature)
1750 && !world.ecs.get(attackerHandle, Component.character);
1751 const arrowTint = projectileDualTintFromAttacker(world.ecs, attackerHandle);
1752 const arrowSprite = projectileSpriteFromAttacker(world.ecs, attackerHandle);
1753 const tipElement = (() =>
1754 {
1755 const stack = arrowStackInOffhand(world.ecs.get(attackerHandle, Component.equipment));
1756 return stack?.instance?.kind === "tipped-arrow" ? stack.instance.element : null;
1757 })();
1758 if (!isCreature && !consumeArrow(world.ecs, attackerHandle))
1759 { return events; }
1760
1761 const shotProfile = tipElement
1762 ? { ...profile, attackType: tipElement }
1763 : profile;
1764
1765 const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY };
1766 const target = resolveCombatTarget(world, targetId);
1767 if (!target)
1768 { return events; }
1769
1770 if (!target.local)
1771 {
1772 events.push({
1773 type: "remote-ranged-resolve",
1774 attackerId,
1775 targetId,
1776 profile: shotProfile,
1777 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, shotProfile, world.settings),
1778 attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character),
1779 now,
1780 tileX: snapshot.tileX,
1781 tileY: snapshot.tileY,
1782 fromTileX: from.tileX,
1783 fromTileY: from.tileY,
1784 sprite: arrowSprite,
1785 ...(publicDualTint(arrowTint) ?? {})
1786 });
1787 return events;
1788 }
1789
1790 const hitEvents = applyLocalMeleeHit(
1791 world,
1792 attackerId,
1793 targetId,
1794 attackerHandle,
1795 target.handle,
1796 shotProfile,
1797 now,
1798 snapshot
1799 );
1800 const outcome = hitEvents.find((e) =>
1801 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
1802 let endX = snapshot.tileX;
1803 let endY = snapshot.tileY;
1804 if (outcome?.type === "combat-miss")
1805 {
1806 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
1807 endX = miss.tileX;
1808 endY = miss.tileY;
1809 }
1810 else
1811 {
1812 const currentPos = world.ecs.get(target.handle, Component.position);
1813 if (currentPos)
1814 {
1815 endX = currentPos.tileX;
1816 endY = currentPos.tileY;
1817 }
1818 }
1819 events.push({
1820 type: "combat-projectile",
1821 attackerId,
1822 targetId,
1823 fromTileX: from.tileX,
1824 fromTileY: from.tileY,
1825 tileX: endX,
1826 tileY: endY,
1827 durationMs: RANGED_PROJECTILE_MS,
1828 trackTarget: outcome?.type !== "combat-miss",
1829 sprite: arrowSprite,
1830 ...(publicDualTint(arrowTint) ?? {})
1831 });
1832 return events.concat(hitEvents);
1833}
1834
1835function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position)
1836{
1837 const dest = path.tiles[path.tiles.length - 1];
1838 if (dest.x !== goal.x || dest.y !== goal.y)
1839 { return true; }
1840 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
1841 if (standOff < minStandDist || standOff > maxRange)
1842 { return true; }
1843 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
1844 { return true; }
1845 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
1846 { return true; }
1847 const destKey = combatTileKey(dest.x, dest.y);
1848 if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
1849 { return true; }
1850 const next = path.tiles[0];
1851 if (!next)
1852 { return true; }
1853 if (!world.walkableFor(entityId, next.x, next.y))
1854 { return true; }
1855 return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
1856}
1857
1858function meleePathStale (world, entityId, position, targetPos, path, goal, reserved)
1859{
1860 const dest = path.tiles[path.tiles.length - 1];
1861 if (dest.x !== goal.x || dest.y !== goal.y)
1862 { return true; }
1863 if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)
1864 { return true; }
1865 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
1866 { return true; }
1867 const destKey = combatTileKey(dest.x, dest.y);
1868 if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
1869 { return true; }
1870 const next = path.tiles[0];
1871 if (!next)
1872 { return true; }
1873 if (!world.walkableFor(entityId, next.x, next.y))
1874 { return true; }
1875 return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
1876}
1877
1878function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null)
1879{
1880 const dirs = [
1881 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
1882 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
1883 ];
1884 let best = null;
1885 let bestDist = Infinity;
1886 let bestPref = Infinity;
1887 for (const dir of dirs)
1888 {
1889 const x = targetPos.tileX + dir.x;
1890 const y = targetPos.tileY + dir.y;
1891 const isHere = x === position.tileX && y === position.tileY;
1892 const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true;
1893 const key = combatTileKey(x, y);
1894 if (reserved?.has(key) && !(isHere && aloneHere))
1895 { continue; }
1896 const clear = world.isClearStanding?.(entityId, x, y)
1897 ?? world.walkableFor(entityId, x, y);
1898 if (!clear && !isHere)
1899 { continue; }
1900 if (isHere && !aloneHere)
1901 { continue; }
1902 const dist = chebyshev(position.tileX, position.tileY, x, y);
1903 const pref = combatGoalPreference(entityId, x, y);
1904 if (dist < bestDist || (dist === bestDist && pref < bestPref))
1905 {
1906 bestDist = dist;
1907 bestPref = pref;
1908 best = { x, y };
1909 }
1910 }
1911 return best;
1912}
1913
1914export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
1915{
1916 const events = [];
1917 const attackerHandle = world.ecs.handleOf(attackerId);
1918 if (attackerHandle == null)
1919 { return events; }
1920 const target = resolveCombatTarget(world, targetId);
1921 if (!target)
1922 { return events; }
1923 const from = world.ecs.get(attackerHandle, Component.position);
1924 const to = target.pos;
1925 if (!from || !to)
1926 { return events; }
1927 if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)
1928 { return events; }
1929 if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY))
1930 { return events; }
1931
1932 events.push({
1933 type: "combat-swing",
1934 attackerId,
1935 targetId,
1936 tileX: to.tileX,
1937 tileY: to.tileY,
1938 fromTileX: from.tileX,
1939 fromTileY: from.tileY
1940 });
1941
1942 if (!target.local)
1943 {
1944 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
1945 events.push({
1946 type: "remote-melee-resolve",
1947 attackerId,
1948 targetId,
1949 profile,
1950 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings),
1951 attackerIsPlayer: !!attackerCharacter,
1952 now,
1953 tileX: to.tileX,
1954 tileY: to.tileY
1955 });
1956 return events;
1957 }
1958
1959 return events.concat(applyLocalMeleeHit(
1960 world,
1961 attackerId,
1962 targetId,
1963 attackerHandle,
1964 target.handle,
1965 profile,
1966 now,
1967 to
1968 ));
1969}
1970
1971/** Authoritative ranged hit when the defender lives on this worker. */
1972export function applyRemoteRangedShot (world, payload)
1973{
1974 const targetHandle = world.ecs.handleOf(payload.targetId);
1975 if (targetHandle == null)
1976 { return { events: [], forwards: [] }; }
1977 const snapshot = {
1978 tileX: payload.tileX,
1979 tileY: payload.tileY
1980 };
1981
1982 const hitEvents = applyLocalMeleeHit(
1983 world,
1984 payload.attackerId,
1985 payload.targetId,
1986 null,
1987 targetHandle,
1988 payload.profile,
1989 payload.now ?? Date.now(),
1990 snapshot,
1991 payload.attackerLevels,
1992 payload.attackerIsPlayer
1993 );
1994
1995 const outcome = hitEvents.find((e) =>
1996 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
1997 let endX = snapshot.tileX;
1998 let endY = snapshot.tileY;
1999 if (outcome?.type === "combat-miss")
2000 {
2001 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
2002 endX = miss.tileX;
2003 endY = miss.tileY;
2004 }
2005 else
2006 {
2007 const currentPos = world.ecs.get(targetHandle, Component.position);
2008 if (currentPos)
2009 {
2010 endX = currentPos.tileX;
2011 endY = currentPos.tileY;
2012 }
2013 }
2014
2015 const events = [{
2016 type: "combat-projectile",
2017 attackerId: payload.attackerId,
2018 targetId: payload.targetId,
2019 fromTileX: payload.fromTileX,
2020 fromTileY: payload.fromTileY,
2021 tileX: endX,
2022 tileY: endY,
2023 durationMs: RANGED_PROJECTILE_MS,
2024 trackTarget: outcome?.type !== "combat-miss",
2025 sprite: payload.sprite ?? "fx:projectile:arrow",
2026 shaftTint: payload.shaftTint ?? null,
2027 tipTint: payload.tipTint ?? null,
2028 coatTint: payload.coatTint ?? null
2029 }, ...hitEvents];
2030
2031 const forwards = [];
2032 const hitEvent = hitEvents.find((event) => event.type === "combat-hit");
2033 if (hitEvent && payload.attackerIsPlayer)
2034 {
2035 forwards.push({
2036 type: "forward-combat-xp",
2037 entityId: payload.attackerId,
2038 profile: payload.profile,
2039 damage: hitEvent.damage
2040 });
2041 }
2042 return { events, forwards };
2043}
2044
2045/** Authoritative hit resolution when the defender lives on this worker. */
2046export function applyRemoteMeleeSwing (world, payload)
2047{
2048 const targetHandle = world.ecs.handleOf(payload.targetId);
2049 if (targetHandle == null)
2050 { return { events: [], forwards: [] }; }
2051 const to = world.ecs.get(targetHandle, Component.position);
2052 if (!to)
2053 { return { events: [], forwards: [] }; }
2054
2055 const events = applyLocalMeleeHit(
2056 world,
2057 payload.attackerId,
2058 payload.targetId,
2059 null,
2060 targetHandle,
2061 payload.profile,
2062 payload.now ?? Date.now(),
2063 to,
2064 payload.attackerLevels,
2065 payload.attackerIsPlayer
2066 );
2067
2068 const forwards = [];
2069 const hitEvent = events.find((event) => event.type === "combat-hit");
2070 if (hitEvent && payload.attackerIsPlayer)
2071 {
2072 forwards.push({
2073 type: "forward-combat-xp",
2074 entityId: payload.attackerId,
2075 profile: payload.profile,
2076 damage: hitEvent.damage
2077 });
2078 }
2079 return { events, forwards };
2080}
2081
2082function applyLocalMeleeHit (
2083 world,
2084 attackerId,
2085 targetId,
2086 attackerHandle,
2087 targetHandle,
2088 profile,
2089 now,
2090 to,
2091 attackerLevelsOverride = null,
2092 attackerIsPlayerOverride = null
2093)
2094{
2095 const events = [];
2096 if (targetHandle == null)
2097 { return events; }
2098
2099 const attackerIsPlayer = attackerIsPlayerOverride != null
2100 ? !!attackerIsPlayerOverride
2101 : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);
2102
2103 // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
2104 if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))
2105 {
2106 engageTarget(world.ecs, targetId, attackerId, now);
2107 if (profile?.mode === "ranged")
2108 { markSeekCover(world.ecs, targetId); }
2109 }
2110 if (attackerIsPlayer === false)
2111 {
2112 const targetCharacter = world.ecs.get(targetHandle, Component.character);
2113 if (targetCharacter)
2114 { maybePlayerRetaliate(world, targetId, attackerId, now); }
2115 }
2116
2117 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
2118 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
2119 const attackerLevels = attackerLevelsOverride
2120 ?? (attackerHandle != null
2121 ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings)
2122 : null);
2123 if (!attackerLevels)
2124 { return events; }
2125
2126 const agilityLevel = defenderSkillLevel(
2127 defenderSkills,
2128 SkillId.agility,
2129 defenderEquipment,
2130 world.settings
2131 );
2132 const defenceLevel = defenderSkillLevel(
2133 defenderSkills,
2134 SkillId.defence,
2135 defenderEquipment,
2136 world.settings
2137 );
2138
2139 const attackType = resolveAttackDamageType(world.ecs, attackerHandle, profile);
2140 const targetCreature = world.ecs.get(targetHandle, Component.creature);
2141 const mobAffinities = targetCreature
2142 ? mobDamageAffinities(mobDefinition(targetCreature.mobTypeId))
2143 : {};
2144 const targetAffinities = mergeAffinities(mobAffinities, jewelryDamageAffinities(defenderEquipment));
2145 const attackerEquipment = attackerHandle != null
2146 ? world.ecs.get(attackerHandle, Component.equipment)
2147 : null;
2148 let hitRng = Math.random;
2149 hitRng = attackerToHitRng(attackerEquipment, hitRng);
2150 hitRng = enemyToHitRngAgainst(defenderEquipment, hitRng);
2151 const resolved = resolvePhysicalAttack({
2152 hitSkillLevel: effectiveHitSkillInDarkness(
2153 attackerLevels.hitLevel,
2154 tileLightAt(world, to.tileX, to.tileY)
2155 ),
2156 agilitySkillLevel: agilityLevel,
2157 damageSkillLevel: attackerLevels.damageLevel,
2158 defenceSkillLevel: defenceLevel,
2159 attackType,
2160 targetAffinities,
2161 rng: hitRng
2162 });
2163
2164 if (resolved.outcome === "miss")
2165 {
2166 events.push({
2167 type: "combat-miss",
2168 attackerId,
2169 targetId,
2170 tileX: to.tileX,
2171 tileY: to.tileY
2172 });
2173 const dodgeXp = awardCombatAvoidanceXp(
2174 world.ecs,
2175 targetHandle,
2176 SkillId.agility,
2177 resolved.damageRoll
2178 );
2179 if (dodgeXp)
2180 {
2181 events.push({
2182 type: "skills-updated",
2183 entityId: targetId,
2184 characterId: dodgeXp.characterId,
2185 skills: dodgeXp.skills,
2186 combatLevel: dodgeXp.combatLevel,
2187 stored: dodgeXp.stored,
2188 levelUps: dodgeXp.levelUps ?? []
2189 });
2190 }
2191 return events;
2192 }
2193
2194 if (resolved.outcome === "block")
2195 {
2196 events.push({
2197 type: "combat-block",
2198 attackerId,
2199 targetId,
2200 tileX: to.tileX,
2201 tileY: to.tileY
2202 });
2203 const blockXp = awardCombatAvoidanceXp(
2204 world.ecs,
2205 targetHandle,
2206 SkillId.defence,
2207 resolved.damageRoll
2208 );
2209 if (blockXp)
2210 {
2211 events.push({
2212 type: "skills-updated",
2213 entityId: targetId,
2214 characterId: blockXp.characterId,
2215 skills: blockXp.skills,
2216 combatLevel: blockXp.combatLevel,
2217 stored: blockXp.stored,
2218 levelUps: blockXp.levelUps ?? []
2219 });
2220 }
2221 return events;
2222 }
2223
2224 const damage = resolved.damage;
2225 const targetCharacter = world.ecs.get(targetHandle, Component.character);
2226 if (targetCharacter)
2227 { syncPlayerHealth(world.ecs, targetHandle); }
2228 const health = world.ecs.get(targetHandle, Component.health);
2229 if (health)
2230 {
2231 health.current = Math.max(0, (health.current | 0) - damage);
2232 markHealthDamaged(health, now);
2233 }
2234 events.push({
2235 type: "combat-hit",
2236 attackerId,
2237 targetId,
2238 damage,
2239 tileX: to.tileX,
2240 tileY: to.tileY,
2241 health: health?.current ?? 0,
2242 maxHealth: health?.max ?? 0
2243 });
2244
2245 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
2246 if (healthXp)
2247 {
2248 events.push({
2249 type: "skills-updated",
2250 entityId: targetId,
2251 characterId: healthXp.characterId,
2252 skills: healthXp.skills,
2253 combatLevel: healthXp.combatLevel,
2254 stored: healthXp.stored,
2255 levelUps: healthXp.levelUps ?? []
2256 });
2257 if (health)
2258 {
2259 const hitEvent = events[events.length - 2];
2260 if (hitEvent?.type === "combat-hit")
2261 {
2262 hitEvent.health = health.current;
2263 hitEvent.maxHealth = health.max;
2264 }
2265 }
2266 }
2267
2268 events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now));
2269
2270 if (attackerHandle != null)
2271 { markFleeOnHit(world, targetId, attackerId); }
2272
2273 if (attackerHandle != null)
2274 {
2275 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
2276 if (attackerCharacter)
2277 {
2278 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage);
2279 if (xpAward)
2280 {
2281 events.push({
2282 type: "skills-updated",
2283 entityId: attackerId,
2284 characterId: attackerCharacter.characterId,
2285 skills: xpAward.skills,
2286 combatLevel: xpAward.combatLevel,
2287 stored: xpAward.stored,
2288 levelUps: xpAward.levelUps ?? []
2289 });
2290 }
2291 }
2292 }
2293
2294 if (health && health.current <= 0)
2295 {
2296 clearEngage(world.ecs, attackerId);
2297 clearEngage(world.ecs, targetId);
2298 clearAttackersTargeting(world.ecs, targetId);
2299 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
2300 {
2301 const path = world.ecs.get(targetHandle, Component.path);
2302 if (path)
2303 { path.tiles = []; }
2304 const follow = world.ecs.get(targetHandle, Component.follow);
2305 if (follow)
2306 {
2307 follow.targetEntityId = null;
2308 follow.trail = [];
2309 }
2310 world.ecs.add(targetHandle, Component.dead, {});
2311 silenceDeadPlayer(world.ecs, targetHandle);
2312 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
2313 events.push({
2314 type: "player-died",
2315 entityId: targetId,
2316 attackerId,
2317 characterId: targetCharacter.characterId,
2318 sessionId: identity?.sessionId ?? null,
2319 tileX: to.tileX,
2320 tileY: to.tileY,
2321 health: 0,
2322 maxHealth: health.max
2323 });
2324 }
2325 const creature = world.ecs.get(targetHandle, Component.creature);
2326 if (creature && !world.ecs.get(targetHandle, Component.character))
2327 {
2328 events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now));
2329 }
2330 }
2331 return events;
2332}
2333
2334/**
2335 * Drops, despawn, and `mob-killed` for bounty / town-guard reaction.
2336 * Shared by melee and spell kill paths.
2337 */
2338export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now)
2339{
2340 const events = [];
2341 const handle = targetHandle ?? world.ecs.handleOf(targetId);
2342 if (handle == null)
2343 { return events; }
2344 const creature = world.ecs.get(handle, Component.creature);
2345 const origin = world.ecs.get(handle, Component.spawnOrigin);
2346 const appearance = world.ecs.get(handle, Component.appearance);
2347 const summon = world.ecs.get(handle, Component.summon);
2348 if (summon?.kind === "jadeite-fairy")
2349 {
2350 const respawnAt = now + JADEITE_FAIRY_RESPAWN_MS;
2351 const characterId = summon.ownerCharacterId | 0;
2352 if (!world.jadeiteFairyTimers)
2353 { world.jadeiteFairyTimers = new Map(); }
2354 if (characterId)
2355 { world.jadeiteFairyTimers.set(characterId, respawnAt); }
2356 const ownerHandle = summon.ownerEntityId != null
2357 ? world.ecs.handleOf(summon.ownerEntityId)
2358 : null;
2359 const character = ownerHandle != null
2360 ? world.ecs.get(ownerHandle, Component.character)
2361 : null;
2362 if (character)
2363 { character.jadeiteFairyRespawnAt = respawnAt; }
2364 }
2365 events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId));
2366 events.push({
2367 type: "mob-killed",
2368 entityId: targetId,
2369 attackerId,
2370 mobTypeId: creature?.mobTypeId ?? null,
2371 level: creature?.level ?? origin?.level ?? 1,
2372 bounty: Math.max(0, origin?.bounty | 0 || 0),
2373 spawnerId: origin?.spawnerId ?? null,
2374 originTileX: origin?.originTileX ?? tileX,
2375 originTileY: origin?.originTileY ?? tileY,
2376 wanderRangeTiles: origin?.wanderRangeTiles ?? 0,
2377 townGuard: !!origin?.townGuard,
2378 displayName: appearance?.firstName ?? null,
2379 tileX,
2380 tileY
2381 });
2382 if (origin?.spawnerId)
2383 {
2384 scheduleSpawnerRespawn(
2385 world,
2386 origin.spawnerId,
2387 origin.respawnDelaySeconds ?? 25,
2388 now
2389 );
2390 }
2391 const view = world.destroyEntity?.(targetId) ?? null;
2392 if (view)
2393 {
2394 events.push({
2395 type: "entity-despawn",
2396 entityId: targetId,
2397 tileX: view.tileX,
2398 tileY: view.tileY,
2399 cause: "death"
2400 });
2401 }
2402 return events;
2403}
2404
2405/** Apply HP loss and shared death/loot side-effects (used by spell impacts). */
2406export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now(), options = {})
2407{
2408 const events = [];
2409 const targetHandle = world.ecs.handleOf(targetId);
2410 if (targetHandle == null)
2411 { return events; }
2412 const to = world.ecs.get(targetHandle, Component.position);
2413 if (!to)
2414 { return events; }
2415 const health = world.ecs.get(targetHandle, Component.health);
2416 if (health)
2417 {
2418 health.current = Math.max(0, (health.current | 0) - damage);
2419 markHealthDamaged(health, now);
2420 }
2421 events.push({
2422 type: "combat-hit",
2423 attackerId,
2424 targetId,
2425 damage,
2426 tileX: to.tileX,
2427 tileY: to.tileY,
2428 health: health?.current ?? 0,
2429 maxHealth: health?.max ?? 0
2430 });
2431
2432 const attackerHandle = world.ecs.handleOf(attackerId);
2433 if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))
2434 {
2435 const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character);
2436 const targetCombat = world.ecs.get(targetHandle, Component.combat);
2437 if (targetCombat && targetCombat.targetEntityId == null)
2438 { engageTarget(world.ecs, targetId, attackerId, now); }
2439 if (attackerIsPlayer)
2440 { markSeekCover(world.ecs, targetId); }
2441 }
2442 if (attackerHandle != null)
2443 { markFleeOnHit(world, targetId, attackerId); }
2444 if (attackerHandle != null && world.ecs.get(targetHandle, Component.character))
2445 {
2446 const attackerCreature = world.ecs.get(attackerHandle, Component.creature);
2447 if (attackerCreature)
2448 { maybePlayerRetaliate(world, targetId, attackerId, now); }
2449 }
2450
2451 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
2452 if (healthXp)
2453 {
2454 events.push({
2455 type: "skills-updated",
2456 entityId: targetId,
2457 characterId: healthXp.characterId,
2458 skills: healthXp.skills,
2459 combatLevel: healthXp.combatLevel,
2460 stored: healthXp.stored,
2461 levelUps: healthXp.levelUps ?? []
2462 });
2463 }
2464
2465 events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now, options));
2466
2467 if (health && health.current <= 0)
2468 {
2469 clearEngage(world.ecs, attackerId);
2470 clearEngage(world.ecs, targetId);
2471 clearAttackersTargeting(world.ecs, targetId);
2472 const targetCharacter = world.ecs.get(targetHandle, Component.character);
2473 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
2474 {
2475 const path = world.ecs.get(targetHandle, Component.path);
2476 if (path)
2477 { path.tiles = []; }
2478 world.ecs.add(targetHandle, Component.dead, {});
2479 silenceDeadPlayer(world.ecs, targetHandle);
2480 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
2481 events.push({
2482 type: "player-died",
2483 entityId: targetId,
2484 attackerId,
2485 characterId: targetCharacter.characterId,
2486 sessionId: identity?.sessionId ?? null,
2487 tileX: to.tileX,
2488 tileY: to.tileY,
2489 health: 0,
2490 maxHealth: health.max
2491 });
2492 }
2493 const creature = world.ecs.get(targetHandle, Component.creature);
2494 if (creature && !targetCharacter)
2495 { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); }
2496 }
2497 return events;
2498}
2499
2500function maybeReflectDamage (world, attackerId, targetId, targetHandle, damage, now, options = {})
2501{
2502 if (options.noReflect || !(damage > 0) || attackerId == null || attackerId === targetId)
2503 { return []; }
2504 const equipment = world.ecs.get(targetHandle, Component.equipment);
2505 const fraction = damageReflectFraction(equipment);
2506 if (!(fraction > 0))
2507 { return []; }
2508 const attackerHandle = world.ecs.handleOf(attackerId);
2509 if (attackerHandle == null)
2510 { return []; }
2511 const reflectDamage = Math.max(1, Math.floor(damage * fraction));
2512 return applyDamageAndKill(world, targetId, attackerId, reflectDamage, now, { noReflect: true });
2513}