BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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