BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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