BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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