BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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