BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

service.js 79.2 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { itemDefinition } from "../../../shared/definitions/items.js";
3import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
4import { mobDefinition, isTownGuardMob } from "../../../shared/definitions/mobs.js";
5import
6 {
7 mobCanFightType,
8 mobCanFight,
9 mobMeleeAttackProfile,
10 mobSkillLevels,
11 mobIsAggressive,
12 mobAggroRangeTiles,
13 mobIsBoss
14 } from "../../../shared/definitions/mobCombat.js";
15import {
16 combatLevelFromSkills,
17 mobAggressionLevel,
18 playerOutlevelsMobAggression
19} from "../../../shared/combat/combatLevel.js";
20import { chunkPeaceAggressionImmunity } from "../../../shared/navigation/chunkPresence.js";
21import { skullAttractsTownGuards } from "../../../shared/combat/skull.js";
22import { OVERWORLD_ID, 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 customDrops = Array.isArray(spawnOrigin?.drops) ? spawnOrigin.drops : [];
711 /** Spawner loot picker replaces the mob's default table when any lines are set. */
712 const dropTable = [
713 ...(customDrops.length > 0 ? customDrops : (def?.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.pathWalkableFor?.(entityId, x, y) ?? world.walkableFor(entityId, x, y, { softDoorRequirements: true });
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.pathWalkableFor?.(entityId, x, y) ?? world.walkableFor(entityId, x, y, { softDoorRequirements: true });
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.pathWalkableFor?.(entityId, x, y) ?? world.walkableFor(entityId, x, y, { softDoorRequirements: true });
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.pathWalkableFor?.(entityId, x, y) ?? world.walkableFor(entityId, x, y, { softDoorRequirements: true });
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.pathWalkableFor?.(entityId, x, y) ?? world.walkableFor(entityId, x, y, { softDoorRequirements: true });
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 const position = world.ecs.get(handle, Component.position);
2521 const dimensionId = normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
2522 if (summon?.kind === "jadeite-fairy")
2523 {
2524 const respawnAt = now + JADEITE_FAIRY_RESPAWN_MS;
2525 const characterId = summon.ownerCharacterId | 0;
2526 if (!world.jadeiteFairyTimers)
2527 { world.jadeiteFairyTimers = new Map(); }
2528 if (characterId)
2529 { world.jadeiteFairyTimers.set(characterId, respawnAt); }
2530 const ownerHandle = summon.ownerEntityId != null
2531 ? world.ecs.handleOf(summon.ownerEntityId)
2532 : null;
2533 const character = ownerHandle != null
2534 ? world.ecs.get(ownerHandle, Component.character)
2535 : null;
2536 if (character)
2537 { character.jadeiteFairyRespawnAt = respawnAt; }
2538 }
2539 events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId));
2540 events.push({
2541 type: "mob-killed",
2542 entityId: targetId,
2543 attackerId,
2544 mobTypeId: creature?.mobTypeId ?? null,
2545 level: creature?.level ?? origin?.level ?? 1,
2546 bounty: Math.max(0, origin?.bounty | 0 || 0),
2547 spawnerId: origin?.spawnerId ?? null,
2548 originTileX: origin?.originTileX ?? tileX,
2549 originTileY: origin?.originTileY ?? tileY,
2550 wanderRangeTiles: origin?.wanderRangeTiles ?? 0,
2551 townGuard: !!origin?.townGuard,
2552 displayName: appearance?.firstName ?? null,
2553 tileX,
2554 tileY,
2555 dimensionId
2556 });
2557 if (origin?.spawnerId)
2558 {
2559 scheduleSpawnerRespawn(
2560 world,
2561 origin.spawnerId,
2562 origin.respawnDelaySeconds ?? 25,
2563 now
2564 );
2565 }
2566 const view = world.destroyEntity?.(targetId) ?? null;
2567 if (view)
2568 {
2569 events.push({
2570 type: "entity-despawn",
2571 entityId: targetId,
2572 tileX: view.tileX,
2573 tileY: view.tileY,
2574 dimensionId: view.dimensionId,
2575 cause: "death"
2576 });
2577 }
2578 return events;
2579}
2580
2581/** Apply HP loss and shared death/loot side-effects (used by spell impacts). */
2582export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now(), options = {})
2583{
2584 const events = [];
2585 const targetHandle = world.ecs.handleOf(targetId);
2586 if (targetHandle == null)
2587 { return events; }
2588 const to = world.ecs.get(targetHandle, Component.position);
2589 if (!to)
2590 { return events; }
2591 const health = world.ecs.get(targetHandle, Component.health);
2592 if (health)
2593 {
2594 health.current = Math.max(0, (health.current | 0) - damage);
2595 markHealthDamaged(health, now);
2596 }
2597 events.push({
2598 type: "combat-hit",
2599 attackerId,
2600 targetId,
2601 damage,
2602 tileX: to.tileX,
2603 tileY: to.tileY,
2604 health: health?.current ?? 0,
2605 maxHealth: health?.max ?? 0,
2606 dimensionId: normalizeDimensionId(to.dimensionId ?? OVERWORLD_ID)
2607 });
2608
2609 const attackerHandle = world.ecs.handleOf(attackerId);
2610 if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))
2611 {
2612 const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character);
2613 const targetCombat = world.ecs.get(targetHandle, Component.combat);
2614 if (targetCombat && targetCombat.targetEntityId == null)
2615 { engageTarget(world.ecs, targetId, attackerId, now); }
2616 if (attackerIsPlayer)
2617 { markSeekCover(world.ecs, targetId); }
2618 }
2619 if (attackerHandle != null)
2620 { markFleeOnHit(world, targetId, attackerId); }
2621 if (attackerHandle != null && world.ecs.get(targetHandle, Component.character))
2622 {
2623 const attackerCreature = world.ecs.get(attackerHandle, Component.creature);
2624 if (attackerCreature)
2625 { maybePlayerRetaliate(world, targetId, attackerId, now); }
2626 }
2627
2628 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
2629 if (healthXp)
2630 {
2631 events.push({
2632 type: "skills-updated",
2633 entityId: targetId,
2634 characterId: healthXp.characterId,
2635 skills: healthXp.skills,
2636 combatLevel: healthXp.combatLevel,
2637 stored: healthXp.stored,
2638 levelUps: healthXp.levelUps ?? []
2639 });
2640 }
2641
2642 events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now, options));
2643
2644 if (health && health.current <= 0)
2645 {
2646 clearEngage(world.ecs, attackerId);
2647 clearEngage(world.ecs, targetId);
2648 clearAttackersTargeting(world.ecs, targetId);
2649 const targetCharacter = world.ecs.get(targetHandle, Component.character);
2650 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
2651 {
2652 const path = world.ecs.get(targetHandle, Component.path);
2653 if (path)
2654 { path.tiles = []; }
2655 world.ecs.add(targetHandle, Component.dead, {});
2656 silenceDeadPlayer(world.ecs, targetHandle);
2657 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
2658 events.push({
2659 type: "player-died",
2660 entityId: targetId,
2661 attackerId,
2662 characterId: targetCharacter.characterId,
2663 sessionId: identity?.sessionId ?? null,
2664 tileX: to.tileX,
2665 tileY: to.tileY,
2666 health: 0,
2667 maxHealth: health.max
2668 });
2669 }
2670 const creature = world.ecs.get(targetHandle, Component.creature);
2671 if (creature && !targetCharacter)
2672 { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); }
2673 }
2674 return events;
2675}
2676
2677function maybeReflectDamage (world, attackerId, targetId, targetHandle, damage, now, options = {})
2678{
2679 if (options.noReflect || !(damage > 0) || attackerId == null || attackerId === targetId)
2680 { return []; }
2681 const equipment = world.ecs.get(targetHandle, Component.equipment);
2682 const fraction = damageReflectFraction(equipment);
2683 if (!(fraction > 0))
2684 { return []; }
2685 const attackerHandle = world.ecs.handleOf(attackerId);
2686 if (attackerHandle == null)
2687 { return []; }
2688 const reflectDamage = Math.max(1, Math.floor(damage * fraction));
2689 return applyDamageAndKill(world, targetId, attackerId, reflectDamage, now, { noReflect: true });
2690}