BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

service.js 77.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 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);
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 placed = placeOrMergeGroundStack(world, {
736 tileX,
737 tileY,
738 stack,
739 now,
740 source: "mob-drop"
741 });
742 events.push(...placed.events);
743 }
744 return events;
745}
746
747function tryAutoLootToKiller (world, attackerId, stack, events)
748{
749 if (attackerId == null)
750 { return false; }
751 const attackerHandle = world.ecs.handleOf(attackerId);
752 if (attackerHandle == null)
753 { return false; }
754 const equipment = world.ecs.get(attackerHandle, Component.equipment);
755 if (!autoLootOnKill(equipment))
756 { return false; }
757 const inventory = world.ecs.get(attackerHandle, Component.inventory);
758 const character = world.ecs.get(attackerHandle, Component.character);
759 const def = itemDefinition(stack.itemId);
760 if (!inventory || !character || !def)
761 { return false; }
762 const inserted = insertStack(inventory.slots, stack, def);
763 if (!inserted.ok || (inserted.remainder | 0) > 0)
764 { return false; }
765 inventory.slots = inserted.slots;
766 events.push({
767 type: "inventory",
768 characterId: character.characterId,
769 ...bagView(world.ecs, attackerHandle)
770 });
771 return true;
772}
773
774function entityCombatDisplayName (ecs, handle)
775{
776 const appearance = ecs.get(handle, Component.appearance);
777 const fromAppearance = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
778 if (fromAppearance)
779 { return fromAppearance; }
780 const creature = ecs.get(handle, Component.creature);
781 if (creature?.mobTypeId)
782 {
783 const def = mobDefinition(creature.mobTypeId);
784 if (def?.displayName)
785 { return def.displayName; }
786 }
787 return null;
788}
789
790function projectileDualTintFromAttacker (ecs, handle)
791{
792 const equipment = ecs.get(handle, Component.equipment);
793 const stack = arrowStackInOffhand(equipment);
794 if (!stack)
795 { return null; }
796 return resolveItemDualTint(stack, itemDefinition(stack.itemId));
797}
798
799function projectileSpriteFromAttacker (ecs, handle)
800{
801 const equipment = ecs.get(handle, Component.equipment);
802 const stack = arrowStackInOffhand(equipment);
803 if (stack?.instance?.kind === "tipped-arrow")
804 { return "fx:projectile:arrow-tipped"; }
805 return "fx:projectile:arrow";
806}
807
808function publicDualTint (dualTint)
809{
810 if (!dualTint)
811 { return null; }
812 return {
813 shaftTint: dualTint.shaft,
814 tipTint: dualTint.tip,
815 ...(dualTint.coat ? { coatTint: dualTint.coat } : {})
816 };
817}
818
819function missProjectileTile (targetTileX, targetTileY, rng = Math.random)
820{
821 const angle = rng() * Math.PI * 2;
822 const dist = rng();
823 return {
824 tileX: Math.round(targetTileX + Math.cos(angle) * dist),
825 tileY: Math.round(targetTileY + Math.sin(angle) * dist)
826 };
827}
828
829/**
830 * Aggressive mobs auto-engage the nearest player or town guard within aggro range
831 * when they have line of sight. Town guards auto-engage aggressive creatures and
832 * players whose skull tint has started lerping toward red.
833 * Does nothing while already engaged.
834 */
835export function stepAggression (world, now = Date.now())
836{
837 for (const entity of world.ecs.query(Component.creature, Component.position))
838 {
839 if (!world.chunkIsSimulating?.(
840 entity.position.tileX,
841 entity.position.tileY,
842 entity.position.dimensionId ?? OVERWORLD_ID
843 ))
844 { continue; }
845 const def = mobDefinition(entity.creature.mobTypeId);
846 if (world.ecs.get(entity.handle, Component.summon))
847 { continue; }
848 const origin = world.ecs.get(entity.handle, Component.spawnOrigin);
849 const townGuard = !!origin?.townGuard || isTownGuardMob(entity.creature.mobTypeId);
850 const aggressive = origin
851 ? !!origin.aggressive
852 : mobIsAggressive(def);
853 if ((!aggressive && !townGuard) || !mobCanFight(def))
854 { continue; }
855 if (world.ecs.has(entity.handle, Component.dead))
856 { continue; }
857 const health = world.ecs.get(entity.handle, Component.health);
858 if (health && health.current <= 0)
859 { continue; }
860 const combat = world.ecs.get(entity.handle, Component.combat);
861 clearLeashingIfHome(world, { combat, handle: entity.handle, position: entity.position });
862 if (combat?.leashing)
863 { continue; }
864 if (combat?.targetEntityId != null)
865 { continue; }
866
867 const range = mobAggroRangeTiles(def);
868 const bestId = townGuard
869 ? pickAggressionTargetForTownGuard(world, entity, range)
870 : pickAggressionTargetPlayerOrGuard(world, entity, range, now);
871 if (bestId == null)
872 { continue; }
873 if (!ensureMobCombat(world.ecs, entity.entityId))
874 { continue; }
875 engageTarget(world.ecs, entity.entityId, bestId, now);
876 }
877}
878
879function creatureIsAggressiveHostile (world, handle, creature)
880{
881 if (!creature || world.ecs.get(handle, Component.character))
882 { return false; }
883 if (world.ecs.get(handle, Component.summon))
884 { return false; }
885 const origin = world.ecs.get(handle, Component.spawnOrigin);
886 if (origin?.townGuard || isTownGuardMob(creature.mobTypeId))
887 { return false; }
888 if (origin)
889 { return !!origin.aggressive; }
890 return mobIsAggressive(mobDefinition(creature.mobTypeId));
891}
892
893function entityIsTownGuard (world, handle, creature)
894{
895 if (!creature || world.ecs.get(handle, Component.character))
896 { return false; }
897 const origin = world.ecs.get(handle, Component.spawnOrigin);
898 return !!origin?.townGuard || isTownGuardMob(creature.mobTypeId);
899}
900
901/** Nearest living player or town guard in range with LOS. */
902function pickAggressionTargetPlayerOrGuard (world, entity, range, now = Date.now())
903{
904 let bestId = null;
905 let bestDist = Infinity;
906 for (const player of world.ecs.query(Component.character, Component.position))
907 {
908 if (playerIgnoresAggressiveMob(world, entity, player.handle, now))
909 { continue; }
910 const dist = considerAggressionCandidate(world, entity, player.handle, player.entityId, player.position, range);
911 if (dist != null && dist < bestDist)
912 {
913 bestDist = dist;
914 bestId = player.entityId;
915 }
916 }
917 for (const other of world.ecs.query(Component.creature, Component.position))
918 {
919 if (other.entityId === entity.entityId)
920 { continue; }
921 if (!entityIsTownGuard(world, other.handle, other.creature))
922 { continue; }
923 const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range);
924 if (dist != null && dist < bestDist)
925 {
926 bestDist = dist;
927 bestId = other.entityId;
928 }
929 }
930 return bestId;
931}
932
933/** Non-boss aggressive mobs skip players who outlevel them or have chunk peace. */
934function playerIgnoresAggressiveMob (world, mobEntity, playerHandle, now)
935{
936 const def = mobDefinition(mobEntity.creature.mobTypeId);
937 if (mobIsBoss(def))
938 { return false; }
939 const playerEquipment = world.ecs.get(playerHandle, Component.equipment);
940 if (ignoresNonBossAggro(playerEquipment))
941 { return true; }
942 const skills = world.ecs.get(playerHandle, Component.skills);
943 if (!skills)
944 { return false; }
945 const playerLevel = combatLevelFromSkills(skills);
946 const origin = world.ecs.get(mobEntity.handle, Component.spawnOrigin);
947 const mobLevel = mobAggressionLevel(mobEntity.creature, origin, def);
948 if (playerOutlevelsMobAggression(playerLevel, mobLevel))
949 { return true; }
950 const presence = world.ecs.get(playerHandle, Component.chunkPresence);
951 const pos = world.ecs.get(playerHandle, Component.position);
952 if (!presence || !pos)
953 { return false; }
954 return chunkPeaceAggressionImmunity(
955 presence,
956 pos.tileX,
957 pos.tileY,
958 pos.dimensionId ?? OVERWORLD_ID,
959 now,
960 tileToChunk
961 );
962}
963
964/**
965 * Nearest aggressive hostile creature or red-lerping skulled player in range
966 * with LOS (for town guards).
967 */
968function pickAggressionTargetForTownGuard (world, entity, range)
969{
970 let bestId = null;
971 let bestDist = Infinity;
972 for (const other of world.ecs.query(Component.creature, Component.position))
973 {
974 if (other.entityId === entity.entityId)
975 { continue; }
976 if (!creatureIsAggressiveHostile(world, other.handle, other.creature))
977 { continue; }
978 if (!mobCanFight(mobDefinition(other.creature.mobTypeId)))
979 { continue; }
980 const dist = considerAggressionCandidate(world, entity, other.handle, other.entityId, other.position, range);
981 if (dist != null && dist < bestDist)
982 {
983 bestDist = dist;
984 bestId = other.entityId;
985 }
986 }
987 for (const player of world.ecs.query(Component.character, Component.position))
988 {
989 if (!skullAttractsTownGuards(player.character?.skullValue, world.settings))
990 { continue; }
991 const dist = considerAggressionCandidate(world, entity, player.handle, player.entityId, player.position, range);
992 if (dist != null && dist < bestDist)
993 {
994 bestDist = dist;
995 bestId = player.entityId;
996 }
997 }
998 return bestId;
999}
1000
1001/**
1002 * @returns {number|null} Chebyshev distance if a valid aggro candidate, else null.
1003 */
1004function considerAggressionCandidate (world, attacker, targetHandle, targetEntityId, targetPos, range)
1005{
1006 if (world.ecs.has(targetHandle, Component.dead))
1007 { return null; }
1008 const health = world.ecs.get(targetHandle, Component.health);
1009 if (health && health.current <= 0)
1010 { return null; }
1011 const attackerDim = normalizeDimensionId(attacker.position.dimensionId ?? OVERWORLD_ID);
1012 const targetDim = normalizeDimensionId(targetPos.dimensionId ?? OVERWORLD_ID);
1013 if (attackerDim !== targetDim)
1014 { return null; }
1015 const dist = chebyshev(
1016 attacker.position.tileX,
1017 attacker.position.tileY,
1018 targetPos.tileX,
1019 targetPos.tileY
1020 );
1021 if (dist < 1 || dist > range)
1022 { return null; }
1023 let effectiveDist = dist;
1024 if (dist > 1)
1025 {
1026 const light = tileLightAt(world, targetPos.tileX, targetPos.tileY, Date.now(), attackerDim);
1027 effectiveDist = dist * aggroDistanceMultiplier(light);
1028 }
1029 if (effectiveDist > range)
1030 { return null; }
1031 if (!hasCombatLineOfSight(
1032 world,
1033 attacker.position.tileX,
1034 attacker.position.tileY,
1035 targetPos.tileX,
1036 targetPos.tileY,
1037 attackerDim
1038 ))
1039 { return null; }
1040 return dist;
1041}
1042
1043/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
1044export function resolveCombatTarget (world, targetId)
1045{
1046 const handle = world.ecs.handleOf(targetId);
1047 if (handle != null)
1048 {
1049 const pos = world.ecs.get(handle, Component.position);
1050 if (!pos)
1051 { return null; }
1052 if (isUntargetable(world.ecs, handle))
1053 { return null; }
1054 return {
1055 local: true,
1056 handle,
1057 pos,
1058 health: world.ecs.get(handle, Component.health)
1059 };
1060 }
1061 const ghost = world.ghosts?.get?.(targetId);
1062 if (!ghost || ghost.untargetable)
1063 { return null; }
1064 const health = ghost.health != null
1065 ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health }
1066 : null;
1067 return {
1068 local: false,
1069 handle: null,
1070 pos: {
1071 tileX: ghost.tileX,
1072 tileY: ghost.tileY,
1073 dimensionId: normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID)
1074 },
1075 health
1076 };
1077}
1078
1079function attackerCombatLevels (ecs, attackerHandle, profile, settings = null)
1080{
1081 const attackerCharacter = ecs.get(attackerHandle, Component.character);
1082 if (attackerCharacter)
1083 { return playerCombatLevels(ecs, attackerHandle, profile, settings); }
1084 const skills = ecs.get(attackerHandle, Component.skills);
1085 const equipment = ecs.get(attackerHandle, Component.equipment);
1086 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {};
1087 const hitSkillId = profile.hitSkillId ?? SkillId.unarmed;
1088 const damageSkillId = profile.damageSkillId ?? SkillId.strength;
1089 const baseHit = attackerSkillLevel(skills, profile, hitSkillId);
1090 const baseDamage = attackerSkillLevel(skills, profile, damageSkillId);
1091 return {
1092 hitLevel: Math.max(1, baseHit + (bonuses[hitSkillId] ?? 0)),
1093 damageLevel: Math.max(1, baseDamage + (bonuses[damageSkillId] ?? 0)),
1094 agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses),
1095 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
1096 };
1097}
1098
1099export function stepPassiveHealthRegen (world, now = Date.now(), dt = 1 / 20)
1100{
1101 const events = [];
1102 for (const entity of world.ecs.query(Component.health, Component.position))
1103 {
1104 const { handle, entityId, health, position, character } = entity;
1105 if (world.ecs.has(handle, Component.dead))
1106 { continue; }
1107 if (!world.chunkIsSimulating?.(
1108 position.tileX,
1109 position.tileY,
1110 position.dimensionId ?? OVERWORLD_ID
1111 ))
1112 { continue; }
1113 if ((health.current | 0) >= (health.max | 0))
1114 { continue; }
1115 const lastDamageAt = health.lastDamageAt ?? 0;
1116 if (now - lastDamageAt < PASSIVE_HP_REGEN_DELAY_MS)
1117 { continue; }
1118 const beforeInt = health.current | 0;
1119 const equipment = world.ecs.get(handle, Component.equipment);
1120 const regenMult = passiveHpRegenMultiplier(equipment);
1121 health.current = Math.min(
1122 health.max | 0,
1123 (Number(health.current) || 0) + PASSIVE_HP_REGEN_PER_SECOND * regenMult * dt
1124 );
1125 if ((health.current | 0) === beforeInt)
1126 { continue; }
1127 if (character)
1128 { syncPlayerHealth(world.ecs, handle); }
1129 const view = publicEntityView(world.ecs, entityId);
1130 if (!view)
1131 { continue; }
1132 events.push({
1133 type: "entity-health",
1134 entityId,
1135 ...(character ? { characterId: character.characterId } : {}),
1136 health: view.health,
1137 maxHealth: view.maxHealth,
1138 tileX: view.tileX,
1139 tileY: view.tileY
1140 });
1141 }
1142 return events;
1143}
1144
1145export function stepCombat (world, now = Date.now())
1146{
1147 const events = [];
1148 for (const entity of world.ecs.query(Component.combat, Component.position))
1149 {
1150 if (world.ecs.has(entity.handle, Component.dead))
1151 {
1152 dropCombatTarget(world, entity);
1153 continue;
1154 }
1155 if (!world.chunkIsSimulating?.(
1156 entity.position.tileX,
1157 entity.position.tileY,
1158 entity.position.dimensionId ?? OVERWORLD_ID
1159 ))
1160 { continue; }
1161 const combat = entity.combat;
1162 clearLeashingIfHome(world, entity);
1163 if (combat.leashing)
1164 {
1165 combat.targetEntityId = null;
1166 syncCreatureChaseGait(world, entity.handle, 0, false);
1167 continue;
1168 }
1169 const targetId = combat.targetEntityId;
1170 if (targetId == null)
1171 { continue; }
1172 const target = resolveCombatTarget(world, targetId);
1173 if (!target)
1174 {
1175 dropCombatTarget(world, entity);
1176 continue;
1177 }
1178 if (target.health && target.health.current <= 0)
1179 {
1180 dropCombatTarget(world, entity);
1181 continue;
1182 }
1183
1184 if (creatureShouldBreakCombatLeash(world, entity.handle, entity.position))
1185 {
1186 beginCombatLeashReturn(world, entity);
1187 continue;
1188 }
1189
1190 // One combat form at a time: spell cast / auto-cast wins over melee & archery.
1191 if (isSpellCombatBusy(world.ecs, entity.handle))
1192 { continue; }
1193
1194 if (combat.fleeFrom)
1195 {
1196 const flee = combat.fleeFrom;
1197 const minDist = Math.max(1, flee.minDist | 0 || 2);
1198 const fleeDist = chebyshev(
1199 entity.position.tileX,
1200 entity.position.tileY,
1201 flee.tileX,
1202 flee.tileY
1203 );
1204 if (fleeDist >= minDist)
1205 {
1206 combat.fleeFrom = null;
1207 clearCombatApproachPath(world.ecs, entity.handle);
1208 }
1209 else
1210 {
1211 queueFleeFromHitSource(world, entity.entityId, entity.handle, entity.position, flee, minDist);
1212 continue;
1213 }
1214 }
1215
1216 const profile = attackProfileOf(world.ecs, entity.handle);
1217 const targetPos = target.pos;
1218 const isCreature = isCombatCreature(world, entity.handle);
1219 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
1220
1221 if (profile.mode === "ranged")
1222 {
1223 const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;
1224 const equipment = world.ecs.get(entity.handle, Component.equipment);
1225 const hasArrows = isCreature
1226 || (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0);
1227 const inRange = dist >= 1 && dist <= maxRange
1228 && hasCombatLineOfSight(
1229 world,
1230 entity.position.tileX,
1231 entity.position.tileY,
1232 targetPos.tileX,
1233 targetPos.tileY,
1234 entity.position.dimensionId ?? OVERWORLD_ID
1235 );
1236 if (!inRange || !hasArrows)
1237 {
1238 if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0)
1239 && world.ecs.get(entity.handle, Component.character))
1240 {
1241 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
1242 events.push({
1243 type: "combat-no-arrows",
1244 attackerId: entity.entityId,
1245 sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null
1246 });
1247 }
1248 syncCreatureChaseGait(world, entity.handle, dist, true);
1249 queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange);
1250 continue;
1251 }
1252 syncCreatureChaseGait(world, entity.handle, dist, false);
1253 clearCombatApproachPath(world.ecs, entity.handle);
1254 if (now < (combat.nextSwingAt || 0))
1255 { continue; }
1256 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
1257 clearSpellCombatState(world.ecs, entity.handle);
1258 events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos));
1259 continue;
1260 }
1261
1262 if (profile.mode !== "melee")
1263 { continue; }
1264
1265 const canSwing = dist === 1
1266 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
1267 const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : [];
1268 const preferSpell = isCreature
1269 && !!mobDefinition(world.ecs.get(entity.handle, Component.creature)?.mobTypeId)?.preferSpellAttack;
1270 const shouldCast = isCreature && attackSpells.length > 0 && (!canSwing || preferSpell);
1271
1272 if (shouldCast)
1273 {
1274 const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES
1275 && hasCombatLineOfSight(
1276 world,
1277 entity.position.tileX,
1278 entity.position.tileY,
1279 targetPos.tileX,
1280 targetPos.tileY,
1281 entity.position.dimensionId ?? OVERWORLD_ID
1282 );
1283 if (!inSpellRange)
1284 {
1285 syncCreatureChaseGait(world, entity.handle, dist, true);
1286 queueStandInRangeApproach(
1287 world,
1288 entity.entityId,
1289 entity.handle,
1290 entity.position,
1291 targetPos.tileX,
1292 targetPos.tileY,
1293 COMBAT_RANGE_TILES,
1294 1
1295 );
1296 continue;
1297 }
1298 syncCreatureChaseGait(world, entity.handle, dist, false);
1299 clearCombatApproachPath(world.ecs, entity.handle);
1300 if (now < (combat.nextSwingAt || 0))
1301 { continue; }
1302 const picked = pickMobAttackSpell(attackSpells);
1303 if (!picked)
1304 {
1305 combat.nextSwingAt = now + SPELL_COOLDOWN_MS;
1306 continue;
1307 }
1308 combat.nextSwingAt = now + SPELL_COOLDOWN_MS;
1309 events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now));
1310 continue;
1311 }
1312
1313 if (!canSwing)
1314 {
1315 syncCreatureChaseGait(world, entity.handle, dist, true);
1316 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
1317 continue;
1318 }
1319 syncCreatureChaseGait(world, entity.handle, dist, false);
1320 clearCombatApproachPath(world.ecs, entity.handle);
1321 const attackerHealth = world.ecs.get(entity.handle, Component.health);
1322 if (attackerHealth && attackerHealth.current <= 0)
1323 { continue; }
1324 if ((combat.nextSwingAt || 0) > now)
1325 { continue; }
1326
1327 combat.nextSwingAt = now + (profile.cooldownMs || 800);
1328 clearSpellCombatState(world.ecs, entity.handle);
1329 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
1330 }
1331 return events;
1332}
1333
1334function eligibleMobAttackSpells (ecs, handle)
1335{
1336 const spells = ecs.get(handle, Component.spells);
1337 if (!spells?.known?.length)
1338 { return []; }
1339 const level = creatureLevel(ecs, handle);
1340 const chances = spells.castChances ?? {};
1341 const out = [];
1342 for (const spellId of spells.known)
1343 {
1344 const def = spellDefinition(spellId);
1345 if (!def || def.target !== "entity")
1346 { continue; }
1347 const minLevel = spellMinMagicLevel(def);
1348 if (level < minLevel)
1349 { continue; }
1350 const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0;
1351 if (chance <= 0)
1352 { continue; }
1353 out.push({ spellId, chance });
1354 }
1355 return out;
1356}
1357
1358function pickMobAttackSpell (spells)
1359{
1360 if (!spells.length)
1361 { return null; }
1362 const pick = spells[Math.floor(Math.random() * spells.length)];
1363 if ((Math.random() * 100) >= pick.chance)
1364 { return null; }
1365 return pick;
1366}
1367
1368function clearCombatApproachPath (ecs, handle)
1369{
1370 const path = ecs.get(handle, Component.path);
1371 if (path?.tiles?.length)
1372 { path.tiles = []; }
1373}
1374
1375function combatTileKey (tileX, tileY)
1376{
1377 return `${tileX},${tileY}`;
1378}
1379
1380/** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */
1381function collectCombatAllyReservations (world, entityId, targetEntityId)
1382{
1383 const reserved = new Set();
1384 if (targetEntityId == null)
1385 { return reserved; }
1386 for (const entity of world.ecs.query(Component.combat, Component.position))
1387 {
1388 if (entity.entityId === entityId)
1389 { continue; }
1390 if (entity.combat.targetEntityId !== targetEntityId)
1391 { continue; }
1392 reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY));
1393 const allyPath = world.ecs.get(entity.handle, Component.path);
1394 if (!allyPath?.tiles?.length)
1395 { continue; }
1396 const next = allyPath.tiles[0];
1397 if (next)
1398 { reserved.add(combatTileKey(next.x, next.y)); }
1399 const dest = allyPath.tiles[allyPath.tiles.length - 1];
1400 if (dest)
1401 { reserved.add(combatTileKey(dest.x, dest.y)); }
1402 }
1403 return reserved;
1404}
1405
1406function combatGoalPreference (entityId, tileX, tileY)
1407{
1408 return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0;
1409}
1410
1411/** Cost multiplier for tiles the threat can currently shoot. */
1412const COVER_EXPOSED_STEP_COST = 5;
1413
1414function mobHasRangedRetaliation (world, handle)
1415{
1416 const profile = attackProfileOf(world.ecs, handle);
1417 if (profile?.mode === "ranged")
1418 { return true; }
1419 return eligibleMobAttackSpells(world.ecs, handle).length > 0;
1420}
1421
1422/** Melee-only creatures closing after a player ranged/spell hit. */
1423function shouldSeekCoverApproach (world, handle)
1424{
1425 if (world.ecs.get(handle, Component.character))
1426 { return false; }
1427 if (!world.ecs.get(handle, Component.creature))
1428 { return false; }
1429 const combat = world.ecs.get(handle, Component.combat);
1430 if (!combat?.seekCover)
1431 { return false; }
1432 return !mobHasRangedRetaliation(world, handle);
1433}
1434
1435/** Double cost for stepping back onto the tile just left while chasing. */
1436function combatApproachStepCost (position, baseCost = null)
1437{
1438 const prevX = position?.prevTileX;
1439 const prevY = position?.prevTileY;
1440 return (x, y) => withCombatBackstepCost(
1441 baseCost ? baseCost(x, y) : 1,
1442 x,
1443 y,
1444 prevX,
1445 prevY
1446 );
1447}
1448
1449function coverStepCost (world, threatPos, goalX, goalY, x, y)
1450{
1451 // Final adjacent step is always in LOS — don't punish the last lunge.
1452 if (x === goalX && y === goalY)
1453 { return 1; }
1454 if (hasCombatLineOfSight(
1455 world,
1456 threatPos.tileX,
1457 threatPos.tileY,
1458 x,
1459 y,
1460 threatPos.dimensionId ?? OVERWORLD_ID
1461 ))
1462 { return COVER_EXPOSED_STEP_COST; }
1463 return 1;
1464}
1465
1466function pathCoverScore (world, threatPos, tiles)
1467{
1468 let score = 0;
1469 for (const step of tiles)
1470 {
1471 score += hasCombatLineOfSight(
1472 world,
1473 threatPos.tileX,
1474 threatPos.tileY,
1475 step.x,
1476 step.y,
1477 threatPos.dimensionId ?? OVERWORLD_ID
1478 )
1479 ? COVER_EXPOSED_STEP_COST
1480 : 1;
1481 }
1482 return score;
1483}
1484
1485function listAdjacentMeleeGoals (world, entityId, position, targetPos, reserved)
1486{
1487 const dirs = [
1488 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
1489 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
1490 ];
1491 const goals = [];
1492 for (const dir of dirs)
1493 {
1494 const x = targetPos.tileX + dir.x;
1495 const y = targetPos.tileY + dir.y;
1496 const isHere = x === position.tileX && y === position.tileY;
1497 const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true;
1498 const key = combatTileKey(x, y);
1499 if (reserved?.has(key) && !(isHere && aloneHere))
1500 { continue; }
1501 const clear = world.isClearStanding?.(entityId, x, y)
1502 ?? world.walkableFor(entityId, x, y);
1503 if (!clear && !isHere)
1504 { continue; }
1505 if (isHere && !aloneHere)
1506 { continue; }
1507 goals.push({ x, y });
1508 }
1509 return goals;
1510}
1511
1512function findCoverMeleeApproachPath (world, entityId, handle, position, targetPos, reserved)
1513{
1514 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1515 const preferVertical = !!world.ecs.get(handle, Component.character);
1516 const isWalkable = (x, y, goal) =>
1517 {
1518 if (x === goal.x && y === goal.y)
1519 {
1520 return world.isClearStanding?.(entityId, x, y)
1521 ?? world.walkableFor(entityId, x, y);
1522 }
1523 return world.walkableFor(entityId, x, y);
1524 };
1525 let bestTiles = null;
1526 let bestScore = Infinity;
1527 let bestPref = Infinity;
1528 for (const goal of listAdjacentMeleeGoals(world, entityId, position, targetPos, reserved))
1529 {
1530 if (goal.x === position.tileX && goal.y === position.tileY)
1531 { return []; }
1532 const tiles = findPath(
1533 position.tileX,
1534 position.tileY,
1535 goal.x,
1536 goal.y,
1537 (x, y) => isWalkable(x, y, goal),
1538 bounds.minX,
1539 bounds.minY,
1540 bounds.maxX,
1541 bounds.maxY,
1542 {
1543 preferVertical,
1544 stepCost: combatApproachStepCost(
1545 position,
1546 (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)
1547 )
1548 }
1549 );
1550 if (!tiles.length)
1551 { continue; }
1552 const score = pathCoverScore(world, targetPos, tiles);
1553 const pref = combatGoalPreference(entityId, goal.x, goal.y);
1554 if (score < bestScore || (score === bestScore && pref < bestPref))
1555 {
1556 bestScore = score;
1557 bestPref = pref;
1558 bestTiles = tiles;
1559 }
1560 }
1561 return bestTiles;
1562}
1563
1564/** Duck behind the nearest tile the threat cannot shoot when melee approach is impossible. */
1565function queueFleeToCover (world, entityId, handle, position, threatPos)
1566{
1567 let path = world.ecs.get(handle, Component.path);
1568 if (!path)
1569 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
1570 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1571 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
1572 const isGoal = (x, y) =>
1573 {
1574 if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y)))
1575 { return false; }
1576 if (chebyshev(x, y, threatPos.tileX, threatPos.tileY) < 1)
1577 { return false; }
1578 return !hasCombatLineOfSight(
1579 world,
1580 threatPos.tileX,
1581 threatPos.tileY,
1582 x,
1583 y,
1584 threatPos.dimensionId ?? OVERWORLD_ID
1585 );
1586 };
1587 if (isGoal(position.tileX, position.tileY))
1588 {
1589 path.tiles = [];
1590 return;
1591 }
1592 const tiles = findPathToNearestGoal(
1593 position.tileX,
1594 position.tileY,
1595 isGoal,
1596 isWalkable,
1597 bounds.minX,
1598 bounds.minY,
1599 bounds.maxX,
1600 bounds.maxY
1601 );
1602 if (!tiles.length)
1603 {
1604 path.tiles = [];
1605 return;
1606 }
1607 path.tiles = tiles;
1608 const movement = world.ecs.get(handle, Component.movement);
1609 if (movement)
1610 { movement.walkCarry = 0; }
1611}
1612
1613/** Path to the nearest standable tile at least `minDist` from the hit source. */
1614function queueFleeFromHitSource (world, entityId, handle, position, source, minDist)
1615{
1616 if (world.frozen?.has?.(entityId))
1617 { return; }
1618 let path = world.ecs.get(handle, Component.path);
1619 if (!path)
1620 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
1621 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
1622 if (
1623 aloneHere
1624 && chebyshev(position.tileX, position.tileY, source.tileX, source.tileY) >= minDist
1625 )
1626 {
1627 path.tiles = [];
1628 return;
1629 }
1630 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1631 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
1632 const isGoal = (x, y) =>
1633 {
1634 if (chebyshev(x, y, source.tileX, source.tileY) < minDist)
1635 { return false; }
1636 return world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y);
1637 };
1638 if (isGoal(position.tileX, position.tileY) && aloneHere)
1639 {
1640 path.tiles = [];
1641 return;
1642 }
1643 const dest = path.tiles?.length ? path.tiles[path.tiles.length - 1] : null;
1644 if (
1645 dest
1646 && isGoal(dest.x, dest.y)
1647 && path.tiles.every((step) => isWalkable(step.x, step.y))
1648 )
1649 { return; }
1650 const tiles = findPathToNearestGoal(
1651 position.tileX,
1652 position.tileY,
1653 isGoal,
1654 isWalkable,
1655 bounds.minX,
1656 bounds.minY,
1657 bounds.maxX,
1658 bounds.maxY
1659 );
1660 if (!tiles.length)
1661 {
1662 path.tiles = [];
1663 return;
1664 }
1665 path.tiles = tiles;
1666 const movement = world.ecs.get(handle, Component.movement);
1667 if (movement)
1668 { movement.walkCarry = 0; }
1669}
1670
1671export function queueMeleeApproach (world, entityId, handle, position, targetPos)
1672{
1673 if (world.frozen?.has?.(entityId))
1674 { return; }
1675 let path = world.ecs.get(handle, Component.path);
1676 if (!path)
1677 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
1678
1679 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY)
1680 ?? true;
1681 if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere)
1682 {
1683 path.tiles = [];
1684 return;
1685 }
1686
1687 const combat = world.ecs.get(handle, Component.combat);
1688 const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
1689 const seekCover = shouldSeekCoverApproach(world, handle);
1690
1691 if (seekCover)
1692 {
1693 const coverTiles = findCoverMeleeApproachPath(
1694 world,
1695 entityId,
1696 handle,
1697 position,
1698 targetPos,
1699 reserved
1700 );
1701 if (coverTiles)
1702 {
1703 if (!coverTiles.length)
1704 {
1705 path.tiles = [];
1706 return;
1707 }
1708 const goal = coverTiles[coverTiles.length - 1];
1709 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved))
1710 { return; }
1711 path.tiles = coverTiles;
1712 const movement = world.ecs.get(handle, Component.movement);
1713 if (movement)
1714 { movement.walkCarry = 0; }
1715 return;
1716 }
1717 queueFleeToCover(world, entityId, handle, position, targetPos);
1718 return;
1719 }
1720
1721 const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved);
1722 if (!goal)
1723 {
1724 path.tiles = [];
1725 return;
1726 }
1727
1728 if (goal.x === position.tileX && goal.y === position.tileY)
1729 {
1730 path.tiles = [];
1731 return;
1732 }
1733
1734 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved))
1735 { return; }
1736
1737 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1738 const preferVertical = !!world.ecs.get(handle, Component.character);
1739 const tiles = findPath(
1740 position.tileX,
1741 position.tileY,
1742 goal.x,
1743 goal.y,
1744 (x, y) =>
1745 {
1746 if (x === goal.x && y === goal.y)
1747 {
1748 return world.isClearStanding?.(entityId, x, y)
1749 ?? world.walkableFor(entityId, x, y);
1750 }
1751 return world.walkableFor(entityId, x, y);
1752 },
1753 bounds.minX,
1754 bounds.minY,
1755 bounds.maxX,
1756 bounds.maxY,
1757 { preferVertical, stepCost: combatApproachStepCost(position) }
1758 );
1759 if (!tiles.length)
1760 {
1761 path.tiles = [];
1762 return;
1763 }
1764 path.tiles = tiles;
1765 const movement = world.ecs.get(handle, Component.movement);
1766 if (movement)
1767 { movement.walkCarry = 0; }
1768}
1769
1770/**
1771 * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS.
1772 * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left).
1773 * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).
1774 */
1775export function queueStandInRangeApproach (
1776 world,
1777 entityId,
1778 handle,
1779 position,
1780 targetTileX,
1781 targetTileY,
1782 maxRange,
1783 minStandDist = 1
1784)
1785{
1786 if (world.frozen?.has?.(entityId))
1787 { return; }
1788 let path = world.ecs.get(handle, Component.path);
1789 if (!path)
1790 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
1791
1792 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
1793 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
1794 const dimensionId = position.dimensionId ?? OVERWORLD_ID;
1795 if (
1796 distToTarget <= maxRange
1797 && distToTarget >= minStandDist
1798 && aloneHere
1799 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY, dimensionId)
1800 )
1801 {
1802 path.tiles = [];
1803 return;
1804 }
1805
1806 const combat = world.ecs.get(handle, Component.combat);
1807 const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
1808 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1809 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
1810 const isGoal = (x, y) =>
1811 {
1812 const standOff = chebyshev(x, y, targetTileX, targetTileY);
1813 if (standOff < minStandDist || standOff > maxRange)
1814 { return false; }
1815 if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y)))
1816 { return false; }
1817 const key = combatTileKey(x, y);
1818 if (reserved.has(key) && !(x === position.tileX && y === position.tileY))
1819 { return false; }
1820 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY, dimensionId);
1821 };
1822
1823 const tiles = findPathToNearestGoal(
1824 position.tileX,
1825 position.tileY,
1826 isGoal,
1827 isWalkable,
1828 bounds.minX,
1829 bounds.minY,
1830 bounds.maxX,
1831 bounds.maxY,
1832 { stepCost: combatApproachStepCost(position) }
1833 );
1834 if (!tiles.length)
1835 {
1836 path.tiles = [];
1837 return;
1838 }
1839 const bestGoal = tiles[tiles.length - 1];
1840 if (path.tiles?.length && !standInRangePathStale(
1841 world,
1842 entityId,
1843 path,
1844 bestGoal,
1845 targetTileX,
1846 targetTileY,
1847 maxRange,
1848 minStandDist,
1849 reserved,
1850 position
1851 ))
1852 { return; }
1853 path.tiles = tiles;
1854 const movement = world.ecs.get(handle, Component.movement);
1855 if (movement)
1856 { movement.walkCarry = 0; }
1857}
1858
1859function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
1860{
1861 queueStandInRangeApproach(
1862 world,
1863 entityId,
1864 handle,
1865 position,
1866 targetPos.tileX,
1867 targetPos.tileY,
1868 maxRange,
1869 1
1870 );
1871}
1872
1873export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
1874{
1875 const events = [];
1876 const attackerHandle = world.ecs.handleOf(attackerId);
1877 if (attackerHandle == null)
1878 { return events; }
1879 const from = world.ecs.get(attackerHandle, Component.position);
1880 if (!from || !targetPos)
1881 { return events; }
1882 const isCreature = !!world.ecs.get(attackerHandle, Component.creature)
1883 && !world.ecs.get(attackerHandle, Component.character);
1884 const arrowTint = projectileDualTintFromAttacker(world.ecs, attackerHandle);
1885 const arrowSprite = projectileSpriteFromAttacker(world.ecs, attackerHandle);
1886 const tipElement = (() =>
1887 {
1888 const stack = arrowStackInOffhand(world.ecs.get(attackerHandle, Component.equipment));
1889 return stack?.instance?.kind === "tipped-arrow" ? stack.instance.element : null;
1890 })();
1891 if (!isCreature && !consumeArrow(world.ecs, attackerHandle))
1892 { return events; }
1893 const character = world.ecs.get(attackerHandle, Component.character);
1894 if (character?.characterId != null)
1895 {
1896 events.push({
1897 type: "inventory",
1898 characterId: character.characterId,
1899 ...bagView(world.ecs, attackerHandle)
1900 });
1901 }
1902
1903 const shotProfile = tipElement
1904 ? { ...profile, attackType: tipElement }
1905 : profile;
1906
1907 const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY };
1908 const target = resolveCombatTarget(world, targetId);
1909 if (!target)
1910 { return events; }
1911
1912 if (!target.local)
1913 {
1914 events.push({
1915 type: "remote-ranged-resolve",
1916 attackerId,
1917 targetId,
1918 profile: shotProfile,
1919 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, shotProfile, world.settings),
1920 attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character),
1921 now,
1922 tileX: snapshot.tileX,
1923 tileY: snapshot.tileY,
1924 fromTileX: from.tileX,
1925 fromTileY: from.tileY,
1926 sprite: arrowSprite,
1927 ...(publicDualTint(arrowTint) ?? {})
1928 });
1929 return events;
1930 }
1931
1932 const hitEvents = applyLocalMeleeHit(
1933 world,
1934 attackerId,
1935 targetId,
1936 attackerHandle,
1937 target.handle,
1938 shotProfile,
1939 now,
1940 snapshot
1941 );
1942 const outcome = hitEvents.find((e) =>
1943 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
1944 let endX = snapshot.tileX;
1945 let endY = snapshot.tileY;
1946 if (outcome?.type === "combat-miss")
1947 {
1948 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
1949 endX = miss.tileX;
1950 endY = miss.tileY;
1951 }
1952 else
1953 {
1954 const currentPos = world.ecs.get(target.handle, Component.position);
1955 if (currentPos)
1956 {
1957 endX = currentPos.tileX;
1958 endY = currentPos.tileY;
1959 }
1960 }
1961 events.push({
1962 type: "combat-projectile",
1963 attackerId,
1964 targetId,
1965 fromTileX: from.tileX,
1966 fromTileY: from.tileY,
1967 tileX: endX,
1968 tileY: endY,
1969 durationMs: RANGED_PROJECTILE_MS,
1970 trackTarget: outcome?.type !== "combat-miss",
1971 sprite: arrowSprite,
1972 ...(publicDualTint(arrowTint) ?? {})
1973 });
1974 return events.concat(hitEvents);
1975}
1976
1977function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position)
1978{
1979 const dest = path.tiles[path.tiles.length - 1];
1980 if (dest.x !== goal.x || dest.y !== goal.y)
1981 { return true; }
1982 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
1983 if (standOff < minStandDist || standOff > maxRange)
1984 { return true; }
1985 if (!hasCombatLineOfSight(
1986 world,
1987 dest.x,
1988 dest.y,
1989 targetTileX,
1990 targetTileY,
1991 position.dimensionId ?? OVERWORLD_ID
1992 ))
1993 { return true; }
1994 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
1995 { return true; }
1996 const destKey = combatTileKey(dest.x, dest.y);
1997 if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
1998 { return true; }
1999 const next = path.tiles[0];
2000 if (!next)
2001 { return true; }
2002 if (!world.walkableFor(entityId, next.x, next.y))
2003 { return true; }
2004 return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
2005}
2006
2007function meleePathStale (world, entityId, position, targetPos, path, goal, reserved)
2008{
2009 const dest = path.tiles[path.tiles.length - 1];
2010 if (dest.x !== goal.x || dest.y !== goal.y)
2011 { return true; }
2012 if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)
2013 { return true; }
2014 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
2015 { return true; }
2016 const destKey = combatTileKey(dest.x, dest.y);
2017 if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
2018 { return true; }
2019 const next = path.tiles[0];
2020 if (!next)
2021 { return true; }
2022 if (!world.walkableFor(entityId, next.x, next.y))
2023 { return true; }
2024 return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
2025}
2026
2027function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null)
2028{
2029 const dirs = [
2030 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
2031 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
2032 ];
2033 let best = null;
2034 let bestDist = Infinity;
2035 let bestPref = Infinity;
2036 for (const dir of dirs)
2037 {
2038 const x = targetPos.tileX + dir.x;
2039 const y = targetPos.tileY + dir.y;
2040 const isHere = x === position.tileX && y === position.tileY;
2041 const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true;
2042 const key = combatTileKey(x, y);
2043 if (reserved?.has(key) && !(isHere && aloneHere))
2044 { continue; }
2045 const clear = world.isClearStanding?.(entityId, x, y)
2046 ?? world.walkableFor(entityId, x, y);
2047 if (!clear && !isHere)
2048 { continue; }
2049 if (isHere && !aloneHere)
2050 { continue; }
2051 const dist = chebyshev(position.tileX, position.tileY, x, y);
2052 const pref = combatGoalPreference(entityId, x, y);
2053 if (dist < bestDist || (dist === bestDist && pref < bestPref))
2054 {
2055 bestDist = dist;
2056 bestPref = pref;
2057 best = { x, y };
2058 }
2059 }
2060 return best;
2061}
2062
2063export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
2064{
2065 const events = [];
2066 const attackerHandle = world.ecs.handleOf(attackerId);
2067 if (attackerHandle == null)
2068 { return events; }
2069 const target = resolveCombatTarget(world, targetId);
2070 if (!target)
2071 { return events; }
2072 const from = world.ecs.get(attackerHandle, Component.position);
2073 const to = target.pos;
2074 if (!from || !to)
2075 { return events; }
2076 if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)
2077 { return events; }
2078 if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY))
2079 { return events; }
2080
2081 events.push({
2082 type: "combat-swing",
2083 attackerId,
2084 targetId,
2085 tileX: to.tileX,
2086 tileY: to.tileY,
2087 fromTileX: from.tileX,
2088 fromTileY: from.tileY
2089 });
2090
2091 if (!target.local)
2092 {
2093 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
2094 events.push({
2095 type: "remote-melee-resolve",
2096 attackerId,
2097 targetId,
2098 profile,
2099 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings),
2100 attackerIsPlayer: !!attackerCharacter,
2101 now,
2102 tileX: to.tileX,
2103 tileY: to.tileY
2104 });
2105 return events;
2106 }
2107
2108 return events.concat(applyLocalMeleeHit(
2109 world,
2110 attackerId,
2111 targetId,
2112 attackerHandle,
2113 target.handle,
2114 profile,
2115 now,
2116 to
2117 ));
2118}
2119
2120/** Authoritative ranged hit when the defender lives on this worker. */
2121export function applyRemoteRangedShot (world, payload)
2122{
2123 const targetHandle = world.ecs.handleOf(payload.targetId);
2124 if (targetHandle == null)
2125 { return { events: [], forwards: [] }; }
2126 const snapshot = {
2127 tileX: payload.tileX,
2128 tileY: payload.tileY
2129 };
2130
2131 const hitEvents = applyLocalMeleeHit(
2132 world,
2133 payload.attackerId,
2134 payload.targetId,
2135 null,
2136 targetHandle,
2137 payload.profile,
2138 payload.now ?? Date.now(),
2139 snapshot,
2140 payload.attackerLevels,
2141 payload.attackerIsPlayer
2142 );
2143
2144 const outcome = hitEvents.find((e) =>
2145 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
2146 let endX = snapshot.tileX;
2147 let endY = snapshot.tileY;
2148 if (outcome?.type === "combat-miss")
2149 {
2150 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
2151 endX = miss.tileX;
2152 endY = miss.tileY;
2153 }
2154 else
2155 {
2156 const currentPos = world.ecs.get(targetHandle, Component.position);
2157 if (currentPos)
2158 {
2159 endX = currentPos.tileX;
2160 endY = currentPos.tileY;
2161 }
2162 }
2163
2164 const events = [{
2165 type: "combat-projectile",
2166 attackerId: payload.attackerId,
2167 targetId: payload.targetId,
2168 fromTileX: payload.fromTileX,
2169 fromTileY: payload.fromTileY,
2170 tileX: endX,
2171 tileY: endY,
2172 durationMs: RANGED_PROJECTILE_MS,
2173 trackTarget: outcome?.type !== "combat-miss",
2174 sprite: payload.sprite ?? "fx:projectile:arrow",
2175 shaftTint: payload.shaftTint ?? null,
2176 tipTint: payload.tipTint ?? null,
2177 coatTint: payload.coatTint ?? null
2178 }, ...hitEvents];
2179
2180 const forwards = [];
2181 const hitEvent = hitEvents.find((event) => event.type === "combat-hit");
2182 if (hitEvent && payload.attackerIsPlayer)
2183 {
2184 forwards.push({
2185 type: "forward-combat-xp",
2186 entityId: payload.attackerId,
2187 profile: payload.profile,
2188 damage: hitEvent.damage
2189 });
2190 }
2191 return { events, forwards };
2192}
2193
2194/** Authoritative hit resolution when the defender lives on this worker. */
2195export function applyRemoteMeleeSwing (world, payload)
2196{
2197 const targetHandle = world.ecs.handleOf(payload.targetId);
2198 if (targetHandle == null)
2199 { return { events: [], forwards: [] }; }
2200 const to = world.ecs.get(targetHandle, Component.position);
2201 if (!to)
2202 { return { events: [], forwards: [] }; }
2203
2204 const events = applyLocalMeleeHit(
2205 world,
2206 payload.attackerId,
2207 payload.targetId,
2208 null,
2209 targetHandle,
2210 payload.profile,
2211 payload.now ?? Date.now(),
2212 to,
2213 payload.attackerLevels,
2214 payload.attackerIsPlayer
2215 );
2216
2217 const forwards = [];
2218 const hitEvent = events.find((event) => event.type === "combat-hit");
2219 if (hitEvent && payload.attackerIsPlayer)
2220 {
2221 forwards.push({
2222 type: "forward-combat-xp",
2223 entityId: payload.attackerId,
2224 profile: payload.profile,
2225 damage: hitEvent.damage
2226 });
2227 }
2228 return { events, forwards };
2229}
2230
2231function applyLocalMeleeHit (
2232 world,
2233 attackerId,
2234 targetId,
2235 attackerHandle,
2236 targetHandle,
2237 profile,
2238 now,
2239 to,
2240 attackerLevelsOverride = null,
2241 attackerIsPlayerOverride = null
2242)
2243{
2244 const events = [];
2245 if (targetHandle == null)
2246 { return events; }
2247
2248 const attackerIsPlayer = attackerIsPlayerOverride != null
2249 ? !!attackerIsPlayerOverride
2250 : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);
2251
2252 // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
2253 if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))
2254 {
2255 engageTarget(world.ecs, targetId, attackerId, now);
2256 if (profile?.mode === "ranged")
2257 { markSeekCover(world.ecs, targetId); }
2258 }
2259 if (attackerIsPlayer === false)
2260 {
2261 const targetCharacter = world.ecs.get(targetHandle, Component.character);
2262 if (targetCharacter)
2263 { maybePlayerRetaliate(world, targetId, attackerId, now); }
2264 }
2265
2266 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
2267 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
2268 const attackerLevels = attackerLevelsOverride
2269 ?? (attackerHandle != null
2270 ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings)
2271 : null);
2272 if (!attackerLevels)
2273 { return events; }
2274
2275 const agilityLevel = defenderSkillLevel(
2276 defenderSkills,
2277 SkillId.agility,
2278 defenderEquipment,
2279 world.settings
2280 );
2281 const defenceLevel = defenderSkillLevel(
2282 defenderSkills,
2283 SkillId.defence,
2284 defenderEquipment,
2285 world.settings
2286 );
2287
2288 const attackType = resolveAttackDamageType(world.ecs, attackerHandle, profile);
2289 const targetCreature = world.ecs.get(targetHandle, Component.creature);
2290 const mobAffinities = targetCreature
2291 ? mobDamageAffinities(mobDefinition(targetCreature.mobTypeId))
2292 : {};
2293 const targetAffinities = mergeAffinities(mobAffinities, jewelryDamageAffinities(defenderEquipment));
2294 const attackerEquipment = attackerHandle != null
2295 ? world.ecs.get(attackerHandle, Component.equipment)
2296 : null;
2297 let hitRng = Math.random;
2298 hitRng = attackerToHitRng(attackerEquipment, hitRng);
2299 hitRng = enemyToHitRngAgainst(defenderEquipment, hitRng);
2300 const resolved = resolvePhysicalAttack({
2301 hitSkillLevel: effectiveHitSkillInDarkness(
2302 attackerLevels.hitLevel,
2303 tileLightAt(world, to.tileX, to.tileY)
2304 ),
2305 agilitySkillLevel: agilityLevel,
2306 damageSkillLevel: attackerLevels.damageLevel,
2307 defenceSkillLevel: defenceLevel,
2308 attackType,
2309 targetAffinities,
2310 rng: hitRng
2311 });
2312
2313 if (resolved.outcome === "miss")
2314 {
2315 events.push({
2316 type: "combat-miss",
2317 attackerId,
2318 targetId,
2319 tileX: to.tileX,
2320 tileY: to.tileY
2321 });
2322 const dodgeXp = awardCombatAvoidanceXp(
2323 world.ecs,
2324 targetHandle,
2325 SkillId.agility,
2326 resolved.damageRoll
2327 );
2328 if (dodgeXp)
2329 {
2330 events.push({
2331 type: "skills-updated",
2332 entityId: targetId,
2333 characterId: dodgeXp.characterId,
2334 skills: dodgeXp.skills,
2335 combatLevel: dodgeXp.combatLevel,
2336 stored: dodgeXp.stored,
2337 levelUps: dodgeXp.levelUps ?? []
2338 });
2339 }
2340 return events;
2341 }
2342
2343 if (resolved.outcome === "block")
2344 {
2345 events.push({
2346 type: "combat-block",
2347 attackerId,
2348 targetId,
2349 tileX: to.tileX,
2350 tileY: to.tileY
2351 });
2352 const blockXp = awardCombatAvoidanceXp(
2353 world.ecs,
2354 targetHandle,
2355 SkillId.defence,
2356 resolved.damageRoll
2357 );
2358 if (blockXp)
2359 {
2360 events.push({
2361 type: "skills-updated",
2362 entityId: targetId,
2363 characterId: blockXp.characterId,
2364 skills: blockXp.skills,
2365 combatLevel: blockXp.combatLevel,
2366 stored: blockXp.stored,
2367 levelUps: blockXp.levelUps ?? []
2368 });
2369 }
2370 return events;
2371 }
2372
2373 const damage = resolved.damage;
2374 const targetCharacter = world.ecs.get(targetHandle, Component.character);
2375 if (targetCharacter)
2376 { syncPlayerHealth(world.ecs, targetHandle); }
2377 const health = world.ecs.get(targetHandle, Component.health);
2378 if (health)
2379 {
2380 health.current = Math.max(0, (health.current | 0) - damage);
2381 markHealthDamaged(health, now);
2382 }
2383 events.push({
2384 type: "combat-hit",
2385 attackerId,
2386 targetId,
2387 damage,
2388 tileX: to.tileX,
2389 tileY: to.tileY,
2390 health: health?.current ?? 0,
2391 maxHealth: health?.max ?? 0
2392 });
2393
2394 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
2395 if (healthXp)
2396 {
2397 events.push({
2398 type: "skills-updated",
2399 entityId: targetId,
2400 characterId: healthXp.characterId,
2401 skills: healthXp.skills,
2402 combatLevel: healthXp.combatLevel,
2403 stored: healthXp.stored,
2404 levelUps: healthXp.levelUps ?? []
2405 });
2406 if (health)
2407 {
2408 const hitEvent = events[events.length - 2];
2409 if (hitEvent?.type === "combat-hit")
2410 {
2411 hitEvent.health = health.current;
2412 hitEvent.maxHealth = health.max;
2413 }
2414 }
2415 }
2416
2417 events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now));
2418
2419 if (attackerHandle != null)
2420 { markFleeOnHit(world, targetId, attackerId); }
2421
2422 if (attackerHandle != null)
2423 {
2424 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
2425 if (attackerCharacter)
2426 {
2427 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage);
2428 if (xpAward)
2429 {
2430 events.push({
2431 type: "skills-updated",
2432 entityId: attackerId,
2433 characterId: attackerCharacter.characterId,
2434 skills: xpAward.skills,
2435 combatLevel: xpAward.combatLevel,
2436 stored: xpAward.stored,
2437 levelUps: xpAward.levelUps ?? []
2438 });
2439 }
2440 }
2441 }
2442
2443 if (health && health.current <= 0)
2444 {
2445 clearEngage(world.ecs, attackerId);
2446 clearEngage(world.ecs, targetId);
2447 clearAttackersTargeting(world.ecs, targetId);
2448 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
2449 {
2450 const path = world.ecs.get(targetHandle, Component.path);
2451 if (path)
2452 { path.tiles = []; }
2453 const follow = world.ecs.get(targetHandle, Component.follow);
2454 if (follow)
2455 {
2456 follow.targetEntityId = null;
2457 follow.trail = [];
2458 }
2459 world.ecs.add(targetHandle, Component.dead, {});
2460 silenceDeadPlayer(world.ecs, targetHandle);
2461 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
2462 events.push({
2463 type: "player-died",
2464 entityId: targetId,
2465 attackerId,
2466 characterId: targetCharacter.characterId,
2467 sessionId: identity?.sessionId ?? null,
2468 tileX: to.tileX,
2469 tileY: to.tileY,
2470 health: 0,
2471 maxHealth: health.max
2472 });
2473 }
2474 const creature = world.ecs.get(targetHandle, Component.creature);
2475 if (creature && !world.ecs.get(targetHandle, Component.character))
2476 {
2477 events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now));
2478 }
2479 }
2480 return events;
2481}
2482
2483/**
2484 * Drops, despawn, and `mob-killed` for bounty / town-guard reaction.
2485 * Shared by melee and spell kill paths.
2486 */
2487export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now)
2488{
2489 const events = [];
2490 const handle = targetHandle ?? world.ecs.handleOf(targetId);
2491 if (handle == null)
2492 { return events; }
2493 const creature = world.ecs.get(handle, Component.creature);
2494 const origin = world.ecs.get(handle, Component.spawnOrigin);
2495 const appearance = world.ecs.get(handle, Component.appearance);
2496 const summon = world.ecs.get(handle, Component.summon);
2497 if (summon?.kind === "jadeite-fairy")
2498 {
2499 const respawnAt = now + JADEITE_FAIRY_RESPAWN_MS;
2500 const characterId = summon.ownerCharacterId | 0;
2501 if (!world.jadeiteFairyTimers)
2502 { world.jadeiteFairyTimers = new Map(); }
2503 if (characterId)
2504 { world.jadeiteFairyTimers.set(characterId, respawnAt); }
2505 const ownerHandle = summon.ownerEntityId != null
2506 ? world.ecs.handleOf(summon.ownerEntityId)
2507 : null;
2508 const character = ownerHandle != null
2509 ? world.ecs.get(ownerHandle, Component.character)
2510 : null;
2511 if (character)
2512 { character.jadeiteFairyRespawnAt = respawnAt; }
2513 }
2514 events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId));
2515 events.push({
2516 type: "mob-killed",
2517 entityId: targetId,
2518 attackerId,
2519 mobTypeId: creature?.mobTypeId ?? null,
2520 level: creature?.level ?? origin?.level ?? 1,
2521 bounty: Math.max(0, origin?.bounty | 0 || 0),
2522 spawnerId: origin?.spawnerId ?? null,
2523 originTileX: origin?.originTileX ?? tileX,
2524 originTileY: origin?.originTileY ?? tileY,
2525 wanderRangeTiles: origin?.wanderRangeTiles ?? 0,
2526 townGuard: !!origin?.townGuard,
2527 displayName: appearance?.firstName ?? null,
2528 tileX,
2529 tileY
2530 });
2531 if (origin?.spawnerId)
2532 {
2533 scheduleSpawnerRespawn(
2534 world,
2535 origin.spawnerId,
2536 origin.respawnDelaySeconds ?? 25,
2537 now
2538 );
2539 }
2540 const view = world.destroyEntity?.(targetId) ?? null;
2541 if (view)
2542 {
2543 events.push({
2544 type: "entity-despawn",
2545 entityId: targetId,
2546 tileX: view.tileX,
2547 tileY: view.tileY,
2548 cause: "death"
2549 });
2550 }
2551 return events;
2552}
2553
2554/** Apply HP loss and shared death/loot side-effects (used by spell impacts). */
2555export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now(), options = {})
2556{
2557 const events = [];
2558 const targetHandle = world.ecs.handleOf(targetId);
2559 if (targetHandle == null)
2560 { return events; }
2561 const to = world.ecs.get(targetHandle, Component.position);
2562 if (!to)
2563 { return events; }
2564 const health = world.ecs.get(targetHandle, Component.health);
2565 if (health)
2566 {
2567 health.current = Math.max(0, (health.current | 0) - damage);
2568 markHealthDamaged(health, now);
2569 }
2570 events.push({
2571 type: "combat-hit",
2572 attackerId,
2573 targetId,
2574 damage,
2575 tileX: to.tileX,
2576 tileY: to.tileY,
2577 health: health?.current ?? 0,
2578 maxHealth: health?.max ?? 0
2579 });
2580
2581 const attackerHandle = world.ecs.handleOf(attackerId);
2582 if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))
2583 {
2584 const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character);
2585 const targetCombat = world.ecs.get(targetHandle, Component.combat);
2586 if (targetCombat && targetCombat.targetEntityId == null)
2587 { engageTarget(world.ecs, targetId, attackerId, now); }
2588 if (attackerIsPlayer)
2589 { markSeekCover(world.ecs, targetId); }
2590 }
2591 if (attackerHandle != null)
2592 { markFleeOnHit(world, targetId, attackerId); }
2593 if (attackerHandle != null && world.ecs.get(targetHandle, Component.character))
2594 {
2595 const attackerCreature = world.ecs.get(attackerHandle, Component.creature);
2596 if (attackerCreature)
2597 { maybePlayerRetaliate(world, targetId, attackerId, now); }
2598 }
2599
2600 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
2601 if (healthXp)
2602 {
2603 events.push({
2604 type: "skills-updated",
2605 entityId: targetId,
2606 characterId: healthXp.characterId,
2607 skills: healthXp.skills,
2608 combatLevel: healthXp.combatLevel,
2609 stored: healthXp.stored,
2610 levelUps: healthXp.levelUps ?? []
2611 });
2612 }
2613
2614 events.push(...maybeReflectDamage(world, attackerId, targetId, targetHandle, damage, now, options));
2615
2616 if (health && health.current <= 0)
2617 {
2618 clearEngage(world.ecs, attackerId);
2619 clearEngage(world.ecs, targetId);
2620 clearAttackersTargeting(world.ecs, targetId);
2621 const targetCharacter = world.ecs.get(targetHandle, Component.character);
2622 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
2623 {
2624 const path = world.ecs.get(targetHandle, Component.path);
2625 if (path)
2626 { path.tiles = []; }
2627 world.ecs.add(targetHandle, Component.dead, {});
2628 silenceDeadPlayer(world.ecs, targetHandle);
2629 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
2630 events.push({
2631 type: "player-died",
2632 entityId: targetId,
2633 attackerId,
2634 characterId: targetCharacter.characterId,
2635 sessionId: identity?.sessionId ?? null,
2636 tileX: to.tileX,
2637 tileY: to.tileY,
2638 health: 0,
2639 maxHealth: health.max
2640 });
2641 }
2642 const creature = world.ecs.get(targetHandle, Component.creature);
2643 if (creature && !targetCharacter)
2644 { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); }
2645 }
2646 return events;
2647}
2648
2649function maybeReflectDamage (world, attackerId, targetId, targetHandle, damage, now, options = {})
2650{
2651 if (options.noReflect || !(damage > 0) || attackerId == null || attackerId === targetId)
2652 { return []; }
2653 const equipment = world.ecs.get(targetHandle, Component.equipment);
2654 const fraction = damageReflectFraction(equipment);
2655 if (!(fraction > 0))
2656 { return []; }
2657 const attackerHandle = world.ecs.handleOf(attackerId);
2658 if (attackerHandle == null)
2659 { return []; }
2660 const reflectDamage = Math.max(1, Math.floor(damage * fraction));
2661 return applyDamageAndKill(world, targetId, attackerId, reflectDamage, now, { noReflect: true });
2662}