BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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