BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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