BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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