BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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