BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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