BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

service.js 40.9 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 } from "../../../shared/definitions/mobs.js";
5import {
6 mobCanFightType,
7 mobCanFight,
8 mobMeleeAttackProfile,
9 mobSkillLevels,
10 mobIsAggressive,
11 mobAggroRangeTiles
12} from "../../../shared/definitions/mobCombat.js";
13import { spellDefinition } from "../../../shared/definitions/spells.js";
14import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
15import {
16 effectiveHitSkillInDarkness,
17 aggroDistanceMultiplier
18} from "../../../shared/combat/darkness.js";
19import {
20 bakedTileLight01,
21 entityLightAtTile,
22 tileCombatLight01,
23 tileIndexLocal
24} from "../../../shared/lighting/combatLight.js";
25import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
26import {
27 effectiveSkillLevel,
28 equipmentBonusesFromSlots
29} from "../../../shared/equipment/stats.js";
30import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
31import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";
32import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
33import { chunkBoundsAround, findPath } from "../navigation/astar.js";
34import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
35import { rayReaches } from "../../../shared/lighting/raycast.js";
36import { tileToChunk } from "../world/coordinates.js";
37import { stackQuantity } from "../../../shared/items/inventory.js";
38import { addGroundItem, publicGroundItem } from "../items/bags.js";
39import { resolveItemDualTint } from "../../../shared/render/tint.js";
40import { castMobAttackSpell } from "../spells/mobCast.js";
41import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
42
43export function chebyshev (ax, ay, bx, by)
44{
45 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
46}
47
48export function attackProfileOf (ecs, handle)
49{
50 const creature = ecs.get(handle, Component.creature);
51 const level = creatureLevel(ecs, handle);
52 const equipment = ecs.get(handle, Component.equipment);
53 const weapon = equipment?.slots?.weapon;
54 if (weapon?.itemId != null)
55 {
56 const attack = itemDefinition(weapon.itemId)?.equipment?.attack;
57 if (attack)
58 {
59 const profile = { ...attack };
60 if (creature)
61 { profile.mobAttackSkill = level; }
62 return profile;
63 }
64 }
65 if (creature)
66 {
67 const def = mobDefinition(creature.mobTypeId);
68 if (mobCanFightType(creature.mobTypeId))
69 { return mobMeleeAttackProfile(def, level); }
70 }
71 return { ...UNARMED_ATTACK };
72}
73
74function creatureLevel (ecs, handle)
75{
76 const creature = ecs.get(handle, Component.creature);
77 if (!creature)
78 { return 1; }
79 if (creature.level != null)
80 { return Math.max(1, creature.level | 0 || 1); }
81 const origin = ecs.get(handle, Component.spawnOrigin);
82 if (origin?.level != null)
83 { return Math.max(1, origin.level | 0 || 1); }
84 const def = mobDefinition(creature.mobTypeId);
85 return Math.max(1, def?.attackSkill | 0 || 1);
86}
87
88export function weaponEquipmentKind (ecs, handle)
89{
90 const equipment = ecs.get(handle, Component.equipment);
91 const weapon = equipment?.slots?.weapon;
92 if (!weapon?.itemId)
93 { return null; }
94 return itemDefinition(weapon.itemId)?.equipment?.kind ?? null;
95}
96
97export function ensureMobCombat (ecs, entityId)
98{
99 const handle = ecs.handleOf(entityId);
100 if (handle == null)
101 { return false; }
102 const creature = ecs.get(handle, Component.creature);
103 if (!creature || !mobCanFightType(creature.mobTypeId))
104 { return false; }
105 const def = mobDefinition(creature.mobTypeId);
106 const level = creatureLevel(ecs, handle);
107 if (!ecs.get(handle, Component.combat))
108 { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
109 if (!ecs.get(handle, Component.skills))
110 { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); }
111 return true;
112}
113
114function attackerSkillLevel (skills, profile, skillId)
115{
116 if (profile.mobAttackSkill != null)
117 { return profile.mobAttackSkill; }
118 return skillLevel(skills, skillId);
119}
120
121function defenderSkillLevel (skills, skillId, equipment = null, settings = null)
122{
123 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {};
124 return effectiveSkillLevel(skills, skillId, bonuses);
125}
126
127function playerCombatLevels (ecs, handle, profile, settings = null)
128{
129 const skills = ecs.get(handle, Component.skills);
130 const equipment = ecs.get(handle, Component.equipment);
131 const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings);
132 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
133 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
134 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
135
136 return {
137 hitLevel: skillLevel(skills, profile.hitSkillId ?? SkillId.unarmed),
138 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses),
139 agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses),
140 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
141 };
142}
143
144export function isUntargetable (ecs, handle)
145{
146 const creature = ecs.get(handle, Component.creature);
147 if (!creature)
148 { return false; }
149 return !!mobDefinition(creature.mobTypeId)?.untargetable;
150}
151
152export function engageTarget (ecs, attackerId, targetId, now = Date.now())
153{
154 const handle = ecs.handleOf(attackerId);
155 if (handle == null)
156 { return false; }
157 let combat = ecs.get(handle, Component.combat);
158 if (!combat)
159 { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
160 const targetChanged = combat.targetEntityId !== targetId;
161 combat.targetEntityId = targetId;
162 if (targetChanged)
163 {
164 // New engage (or switch): allow an immediate swing; keep cadence if already on this target.
165 combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
166 const path = ecs.get(handle, Component.path);
167 if (path)
168 { path.tiles = []; }
169 }
170 return true;
171}
172
173export function clearEngage (ecs, entityId)
174{
175 const handle = ecs.handleOf(entityId);
176 const combat = handle != null ? ecs.get(handle, Component.combat) : null;
177 if (combat)
178 { combat.targetEntityId = null; }
179}
180
181export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
182{
183 const isClear = world.isClearForRangedAttack
184 ? (x, y) => world.isClearForRangedAttack(x, y)
185 : (x, y) => world.isEnterable(x, y);
186 return rayReaches(fromX, fromY, toX, toY, isClear);
187}
188
189/** Target-tile lighting 0–1 (baked + entity lights + time of day). */
190export function tileLightAt (world, tileX, tileY, now = Date.now())
191{
192 const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY));
193 const index = tileIndexLocal(tileX, tileY);
194 const baked = bakedTileLight01(data?.light, index);
195 const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now);
196 const worldTime = world.worldTime?.(now);
197 return tileCombatLight01({
198 bakedLight01: baked,
199 entityLight01: entity,
200 worldHour: worldTime?.hour ?? 12,
201 nightDarkness: world.settings?.nightDarkness ?? 0.72
202 });
203}
204
205function arrowStackInOffhand (equipment)
206{
207 const stack = equipment?.slots?.offhand;
208 if (!stack)
209 { return null; }
210 const def = itemDefinition(stack.itemId);
211 if (def?.equipment?.kind !== EquipmentKind.arrowAmmo)
212 { return null; }
213 return stack;
214}
215
216function consumeArrow (ecs, handle)
217{
218 const equipment = ecs.get(handle, Component.equipment);
219 const stack = arrowStackInOffhand(equipment);
220 if (!stack || stackQuantity(stack.quantity) <= 0)
221 { return false; }
222 if (stackQuantity(stack.quantity) <= 1)
223 { equipment.slots.offhand = null; }
224 else
225 { stack.quantity = stackQuantity(stack.quantity) - 1; }
226 return true;
227}
228
229/** Fixed `quantity`, or inclusive `quantityMin`/`quantityMax` range (default 1). */
230function rollDropQuantity (drop)
231{
232 if (drop.quantityMin != null || drop.quantityMax != null)
233 {
234 const min = Math.max(0, Math.floor(Number(drop.quantityMin ?? 1)));
235 const max = Math.max(min, Math.floor(Number(drop.quantityMax ?? min)));
236 return min + Math.floor(Math.random() * (max - min + 1));
237 }
238 return Math.max(1, Math.floor(Number(drop.quantity ?? 1)));
239}
240
241function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = null)
242{
243 const creature = world.ecs.get(targetHandle, Component.creature);
244 if (!creature)
245 { return []; }
246 const def = mobDefinition(creature.mobTypeId);
247 const mobName = entityCombatDisplayName(world.ecs, targetHandle)
248 || def?.displayName
249 || "a creature";
250 let killerName = "someone";
251 if (attackerId != null)
252 {
253 const attackerHandle = world.ecs.handleOf(attackerId);
254 if (attackerHandle != null)
255 { killerName = entityCombatDisplayName(world.ecs, attackerHandle) || "someone"; }
256 }
257 const origin = lootOrigin(mobName, killerName);
258 const events = [];
259 for (const drop of def?.drops ?? [])
260 {
261 if (Math.random() > (drop.chance ?? 1))
262 { continue; }
263 const quantity = rollDropQuantity(drop);
264 if (quantity <= 0)
265 { continue; }
266 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
267 const stack = attachOrigins({
268 itemId: drop.itemId,
269 quantity,
270 origins: [{ origin, quantity }]
271 });
272 const item = {
273 groundItemId,
274 tileX,
275 tileY,
276 stack,
277 droppedAt: now,
278 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
279 source: "mob-drop"
280 };
281 addGroundItem(world, item);
282 events.push({
283 type: "ground-item-appear",
284 ...publicGroundItem(item),
285 stack: item.stack,
286 droppedAt: item.droppedAt,
287 source: item.source,
288 expiresAt: item.expiresAt
289 });
290 }
291 return events;
292}
293
294function entityCombatDisplayName (ecs, handle)
295{
296 const appearance = ecs.get(handle, Component.appearance);
297 const fromAppearance = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
298 if (fromAppearance)
299 { return fromAppearance; }
300 const creature = ecs.get(handle, Component.creature);
301 if (creature?.mobTypeId)
302 {
303 const def = mobDefinition(creature.mobTypeId);
304 if (def?.displayName)
305 { return def.displayName; }
306 }
307 return null;
308}
309
310function projectileDualTintFromAttacker (ecs, handle)
311{
312 const equipment = ecs.get(handle, Component.equipment);
313 const stack = arrowStackInOffhand(equipment);
314 if (!stack)
315 { return null; }
316 return resolveItemDualTint(stack, itemDefinition(stack.itemId));
317}
318
319function publicDualTint (dualTint)
320{
321 if (!dualTint)
322 { return null; }
323 return {
324 shaftTint: dualTint.shaft,
325 tipTint: dualTint.tip
326 };
327}
328
329function missProjectileTile (targetTileX, targetTileY, rng = Math.random)
330{
331 const angle = rng() * Math.PI * 2;
332 const dist = rng();
333 return {
334 tileX: Math.round(targetTileX + Math.cos(angle) * dist),
335 tileY: Math.round(targetTileY + Math.sin(angle) * dist)
336 };
337}
338
339/**
340 * Aggressive mobs auto-engage the nearest player character within aggro range
341 * when they have line of sight. Does nothing while already engaged.
342 */
343export function stepAggression (world, now = Date.now())
344{
345 for (const entity of world.ecs.query(Component.creature, Component.position))
346 {
347 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
348 { continue; }
349 const def = mobDefinition(entity.creature.mobTypeId);
350 const origin = world.ecs.get(entity.handle, Component.spawnOrigin);
351 const aggressive = origin
352 ? !!origin.aggressive
353 : mobIsAggressive(def);
354 if (!aggressive || !mobCanFight(def))
355 { continue; }
356 if (world.ecs.has(entity.handle, Component.dead))
357 { continue; }
358 const health = world.ecs.get(entity.handle, Component.health);
359 if (health && health.current <= 0)
360 { continue; }
361 const combat = world.ecs.get(entity.handle, Component.combat);
362 if (combat?.targetEntityId != null)
363 { continue; }
364
365 const range = mobAggroRangeTiles(def);
366 let bestId = null;
367 let bestDist = Infinity;
368 for (const player of world.ecs.query(Component.character, Component.position))
369 {
370 if (world.ecs.has(player.handle, Component.dead))
371 { continue; }
372 const playerHealth = world.ecs.get(player.handle, Component.health);
373 if (playerHealth && playerHealth.current <= 0)
374 { continue; }
375 const dist = chebyshev(
376 entity.position.tileX,
377 entity.position.tileY,
378 player.position.tileX,
379 player.position.tileY
380 );
381 if (dist < 1 || dist > range)
382 { continue; }
383 let effectiveDist = dist;
384 if (dist > 1)
385 {
386 const light = tileLightAt(world, player.position.tileX, player.position.tileY);
387 effectiveDist = dist * aggroDistanceMultiplier(light);
388 }
389 if (effectiveDist > range)
390 { continue; }
391 if (!hasCombatLineOfSight(
392 world,
393 entity.position.tileX,
394 entity.position.tileY,
395 player.position.tileX,
396 player.position.tileY
397 ))
398 { continue; }
399 if (dist < bestDist)
400 {
401 bestDist = dist;
402 bestId = player.entityId;
403 }
404 }
405 if (bestId == null)
406 { continue; }
407 if (!ensureMobCombat(world.ecs, entity.entityId))
408 { continue; }
409 engageTarget(world.ecs, entity.entityId, bestId, now);
410 }
411}
412
413/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
414export function resolveCombatTarget (world, targetId)
415{
416 const handle = world.ecs.handleOf(targetId);
417 if (handle != null)
418 {
419 const pos = world.ecs.get(handle, Component.position);
420 if (!pos)
421 { return null; }
422 if (isUntargetable(world.ecs, handle))
423 { return null; }
424 return {
425 local: true,
426 handle,
427 pos,
428 health: world.ecs.get(handle, Component.health)
429 };
430 }
431 const ghost = world.ghosts?.get?.(targetId);
432 if (!ghost || ghost.untargetable)
433 { return null; }
434 const health = ghost.health != null
435 ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health }
436 : null;
437 return {
438 local: false,
439 handle: null,
440 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
441 health
442 };
443}
444
445function attackerCombatLevels (ecs, attackerHandle, profile, settings = null)
446{
447 const attackerCharacter = ecs.get(attackerHandle, Component.character);
448 if (attackerCharacter)
449 { return playerCombatLevels(ecs, attackerHandle, profile, settings); }
450 const skills = ecs.get(attackerHandle, Component.skills);
451 return {
452 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
453 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
454 agilityLevel: skillLevel(skills, SkillId.agility),
455 defenceLevel: skillLevel(skills, SkillId.defence)
456 };
457}
458
459export function stepCombat (world, now = Date.now())
460{
461 const events = [];
462 for (const entity of world.ecs.query(Component.combat, Component.position))
463 {
464 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
465 { continue; }
466 const combat = entity.combat;
467 const targetId = combat.targetEntityId;
468 if (targetId == null)
469 { continue; }
470 const target = resolveCombatTarget(world, targetId);
471 if (!target)
472 {
473 combat.targetEntityId = null;
474 continue;
475 }
476 if (target.health && target.health.current <= 0)
477 {
478 combat.targetEntityId = null;
479 continue;
480 }
481
482 const profile = attackProfileOf(world.ecs, entity.handle);
483 const targetPos = target.pos;
484 const isCreature = !!world.ecs.get(entity.handle, Component.creature)
485 && !world.ecs.get(entity.handle, Component.character);
486 const weaponKind = weaponEquipmentKind(world.ecs, entity.handle);
487 const isStaff = weaponKind === EquipmentKind.staff;
488
489 if (profile.mode === "ranged")
490 {
491 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
492 const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;
493 const equipment = world.ecs.get(entity.handle, Component.equipment);
494 const hasArrows = isCreature
495 || (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0);
496 const inRange = dist >= 1 && dist <= maxRange
497 && hasCombatLineOfSight(
498 world,
499 entity.position.tileX,
500 entity.position.tileY,
501 targetPos.tileX,
502 targetPos.tileY
503 );
504 if (!inRange || !hasArrows)
505 {
506 if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0)
507 && world.ecs.get(entity.handle, Component.character))
508 {
509 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
510 events.push({
511 type: "combat-no-arrows",
512 attackerId: entity.entityId,
513 sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null
514 });
515 }
516 queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange);
517 continue;
518 }
519 clearCombatApproachPath(world.ecs, entity.handle);
520 if (now < (combat.nextSwingAt || 0))
521 { continue; }
522 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
523 events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos));
524 continue;
525 }
526
527 if (profile.mode !== "melee" && !isStaff)
528 { continue; }
529
530 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
531 const canSwing = !isStaff
532 && dist === 1
533 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
534 const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : [];
535 const shouldCast = isCreature && attackSpells.length > 0 && (isStaff || !canSwing);
536
537 if (shouldCast)
538 {
539 const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES
540 && hasCombatLineOfSight(
541 world,
542 entity.position.tileX,
543 entity.position.tileY,
544 targetPos.tileX,
545 targetPos.tileY
546 );
547 if (!inSpellRange)
548 {
549 queueStandInRangeApproach(
550 world,
551 entity.entityId,
552 entity.handle,
553 entity.position,
554 targetPos.tileX,
555 targetPos.tileY,
556 COMBAT_RANGE_TILES,
557 1
558 );
559 continue;
560 }
561 clearCombatApproachPath(world.ecs, entity.handle);
562 if (now < (combat.nextSwingAt || 0))
563 { continue; }
564 const picked = pickMobAttackSpell(attackSpells);
565 if (!picked)
566 {
567 combat.nextSwingAt = now + SPELL_COOLDOWN_MS;
568 continue;
569 }
570 combat.nextSwingAt = now + SPELL_COOLDOWN_MS;
571 events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now));
572 continue;
573 }
574
575 if (!canSwing)
576 {
577 if (isStaff)
578 {
579 queueStandInRangeApproach(
580 world,
581 entity.entityId,
582 entity.handle,
583 entity.position,
584 targetPos.tileX,
585 targetPos.tileY,
586 COMBAT_RANGE_TILES,
587 1
588 );
589 }
590 else
591 { queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos); }
592 continue;
593 }
594 clearCombatApproachPath(world.ecs, entity.handle);
595 const attackerHealth = world.ecs.get(entity.handle, Component.health);
596 if (attackerHealth && attackerHealth.current <= 0)
597 { continue; }
598 if ((combat.nextSwingAt || 0) > now)
599 { continue; }
600
601 combat.nextSwingAt = now + (profile.cooldownMs || 800);
602 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
603 }
604 return events;
605}
606
607function eligibleMobAttackSpells (ecs, handle)
608{
609 const spells = ecs.get(handle, Component.spells);
610 if (!spells?.known?.length)
611 { return []; }
612 const level = creatureLevel(ecs, handle);
613 const chances = spells.castChances ?? {};
614 const out = [];
615 for (const spellId of spells.known)
616 {
617 const def = spellDefinition(spellId);
618 if (!def || def.target !== "entity")
619 { continue; }
620 const minLevel = Math.max(1, def.minMagicLevel | 0 || 1);
621 if (level < minLevel)
622 { continue; }
623 const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0;
624 if (chance <= 0)
625 { continue; }
626 out.push({ spellId, chance });
627 }
628 return out;
629}
630
631function pickMobAttackSpell (spells)
632{
633 if (!spells.length)
634 { return null; }
635 const pick = spells[Math.floor(Math.random() * spells.length)];
636 if ((Math.random() * 100) >= pick.chance)
637 { return null; }
638 return pick;
639}
640
641function clearCombatApproachPath (ecs, handle)
642{
643 const path = ecs.get(handle, Component.path);
644 if (path?.tiles?.length)
645 { path.tiles = []; }
646}
647
648export function queueMeleeApproach (world, entityId, handle, position, targetPos)
649{
650 if (world.frozen?.has?.(entityId))
651 { return; }
652 let path = world.ecs.get(handle, Component.path);
653 if (!path)
654 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
655
656 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY)
657 ?? true;
658 if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere)
659 {
660 path.tiles = [];
661 return;
662 }
663
664 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
665 if (!goal)
666 {
667 path.tiles = [];
668 return;
669 }
670
671 if (goal.x === position.tileX && goal.y === position.tileY)
672 {
673 path.tiles = [];
674 return;
675 }
676
677 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))
678 { return; }
679
680 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
681 const preferVertical = !!world.ecs.get(handle, Component.character);
682 const tiles = findPath(
683 position.tileX,
684 position.tileY,
685 goal.x,
686 goal.y,
687 (x, y) =>
688 {
689 if (x === goal.x && y === goal.y)
690 {
691 return world.isClearStanding?.(entityId, x, y)
692 ?? world.walkableFor(entityId, x, y);
693 }
694 return world.walkableFor(entityId, x, y);
695 },
696 bounds.minX,
697 bounds.minY,
698 bounds.maxX,
699 bounds.maxY,
700 { preferVertical }
701 );
702 if (!tiles.length)
703 {
704 path.tiles = [];
705 return;
706 }
707 path.tiles = tiles;
708 const movement = world.ecs.get(handle, Component.movement);
709 if (movement)
710 { movement.walkCarry = 0; }
711}
712
713function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist)
714{
715 const dest = path.tiles[path.tiles.length - 1];
716 if (dest.x !== goal.x || dest.y !== goal.y)
717 { return true; }
718 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
719 if (standOff < minStandDist || standOff > maxRange)
720 { return true; }
721 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
722 { return true; }
723 const next = path.tiles[0];
724 if (!next)
725 { return true; }
726 return !world.walkableFor(entityId, next.x, next.y);
727}
728
729/**
730 * Path toward the nearest tile from which `targetTile` is in Chebyshev range with LOS.
731 * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).
732 */
733export function queueStandInRangeApproach (
734 world,
735 entityId,
736 handle,
737 position,
738 targetTileX,
739 targetTileY,
740 maxRange,
741 minStandDist = 1
742)
743{
744 if (world.frozen?.has?.(entityId))
745 { return; }
746 let path = world.ecs.get(handle, Component.path);
747 if (!path)
748 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
749
750 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
751 if (
752 distToTarget <= maxRange
753 && distToTarget >= minStandDist
754 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
755 )
756 {
757 path.tiles = [];
758 return;
759 }
760
761 let bestGoal = null;
762 let bestDist = Infinity;
763 for (let dy = -maxRange; dy <= maxRange; dy++)
764 {
765 for (let dx = -maxRange; dx <= maxRange; dx++)
766 {
767 const x = targetTileX + dx;
768 const y = targetTileY + dy;
769 const standOff = chebyshev(x, y, targetTileX, targetTileY);
770 if (standOff < minStandDist || standOff > maxRange)
771 { continue; }
772 if (!world.walkableFor(entityId, x, y))
773 { continue; }
774 if (!hasCombatLineOfSight(world, x, y, targetTileX, targetTileY))
775 { continue; }
776 const d = chebyshev(position.tileX, position.tileY, x, y);
777 if (d < bestDist)
778 {
779 bestDist = d;
780 bestGoal = { x, y };
781 }
782 }
783 }
784 if (!bestGoal)
785 {
786 path.tiles = [];
787 return;
788 }
789 if (bestGoal.x === position.tileX && bestGoal.y === position.tileY)
790 {
791 path.tiles = [];
792 return;
793 }
794 if (path.tiles?.length && !standInRangePathStale(
795 world,
796 entityId,
797 path,
798 bestGoal,
799 targetTileX,
800 targetTileY,
801 maxRange,
802 minStandDist
803 ))
804 { return; }
805 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
806 const preferVertical = !!world.ecs.get(handle, Component.character);
807 const tiles = findPath(
808 position.tileX,
809 position.tileY,
810 bestGoal.x,
811 bestGoal.y,
812 (x, y) => world.walkableFor(entityId, x, y),
813 bounds.minX,
814 bounds.minY,
815 bounds.maxX,
816 bounds.maxY,
817 { preferVertical }
818 );
819 path.tiles = tiles.length ? tiles : [];
820 const movement = world.ecs.get(handle, Component.movement);
821 if (movement)
822 { movement.walkCarry = 0; }
823}
824
825function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
826{
827 queueStandInRangeApproach(
828 world,
829 entityId,
830 handle,
831 position,
832 targetPos.tileX,
833 targetPos.tileY,
834 maxRange,
835 1
836 );
837}
838
839export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
840{
841 const events = [];
842 const attackerHandle = world.ecs.handleOf(attackerId);
843 if (attackerHandle == null)
844 { return events; }
845 const from = world.ecs.get(attackerHandle, Component.position);
846 if (!from || !targetPos)
847 { return events; }
848 const isCreature = !!world.ecs.get(attackerHandle, Component.creature)
849 && !world.ecs.get(attackerHandle, Component.character);
850 if (!isCreature && !consumeArrow(world.ecs, attackerHandle))
851 { return events; }
852
853 const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY };
854 const target = resolveCombatTarget(world, targetId);
855 if (!target)
856 { return events; }
857
858 if (!target.local)
859 {
860 events.push({
861 type: "remote-ranged-resolve",
862 attackerId,
863 targetId,
864 profile,
865 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings),
866 attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character),
867 now,
868 tileX: snapshot.tileX,
869 tileY: snapshot.tileY,
870 fromTileX: from.tileX,
871 fromTileY: from.tileY,
872 ...(publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {})
873 });
874 return events;
875 }
876
877 const hitEvents = applyLocalMeleeHit(
878 world,
879 attackerId,
880 targetId,
881 attackerHandle,
882 target.handle,
883 profile,
884 now,
885 snapshot
886 );
887 const outcome = hitEvents.find((e) =>
888 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
889 let endX = snapshot.tileX;
890 let endY = snapshot.tileY;
891 if (outcome?.type === "combat-miss")
892 {
893 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
894 endX = miss.tileX;
895 endY = miss.tileY;
896 }
897 else
898 {
899 const currentPos = world.ecs.get(target.handle, Component.position);
900 if (currentPos)
901 {
902 endX = currentPos.tileX;
903 endY = currentPos.tileY;
904 }
905 }
906 events.push({
907 type: "combat-projectile",
908 attackerId,
909 targetId,
910 fromTileX: from.tileX,
911 fromTileY: from.tileY,
912 tileX: endX,
913 tileY: endY,
914 durationMs: RANGED_PROJECTILE_MS,
915 ...publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}
916 });
917 return events.concat(hitEvents);
918}
919
920function meleePathStale (world, entityId, position, targetPos, path, goal)
921{
922 const dest = path.tiles[path.tiles.length - 1];
923 if (dest.x !== goal.x || dest.y !== goal.y)
924 { return true; }
925 if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)
926 { return true; }
927 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
928 { return true; }
929 const next = path.tiles[0];
930 if (!next)
931 { return true; }
932 return !world.walkableFor(entityId, next.x, next.y);
933}
934
935function bestAdjacentGoal (world, entityId, position, targetPos)
936{
937 const dirs = [
938 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
939 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
940 ];
941 let best = null;
942 let bestDist = Infinity;
943 for (const dir of dirs)
944 {
945 const x = targetPos.tileX + dir.x;
946 const y = targetPos.tileY + dir.y;
947 const isHere = x === position.tileX && y === position.tileY;
948 const clear = world.isClearStanding?.(entityId, x, y)
949 ?? world.walkableFor(entityId, x, y);
950 if (!clear && !isHere)
951 { continue; }
952 if (isHere && !(world.isClearStanding?.(entityId, x, y) ?? true))
953 { continue; }
954 const dist = chebyshev(position.tileX, position.tileY, x, y);
955 if (dist < bestDist)
956 {
957 bestDist = dist;
958 best = { x, y };
959 }
960 }
961 return best;
962}
963
964export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
965{
966 const events = [];
967 const attackerHandle = world.ecs.handleOf(attackerId);
968 if (attackerHandle == null)
969 { return events; }
970 const target = resolveCombatTarget(world, targetId);
971 if (!target)
972 { return events; }
973 const from = world.ecs.get(attackerHandle, Component.position);
974 const to = target.pos;
975 if (!from || !to)
976 { return events; }
977 if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)
978 { return events; }
979 if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY))
980 { return events; }
981
982 events.push({
983 type: "combat-swing",
984 attackerId,
985 targetId,
986 tileX: to.tileX,
987 tileY: to.tileY,
988 fromTileX: from.tileX,
989 fromTileY: from.tileY
990 });
991
992 if (!target.local)
993 {
994 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
995 events.push({
996 type: "remote-melee-resolve",
997 attackerId,
998 targetId,
999 profile,
1000 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings),
1001 attackerIsPlayer: !!attackerCharacter,
1002 now,
1003 tileX: to.tileX,
1004 tileY: to.tileY
1005 });
1006 return events;
1007 }
1008
1009 return events.concat(applyLocalMeleeHit(
1010 world,
1011 attackerId,
1012 targetId,
1013 attackerHandle,
1014 target.handle,
1015 profile,
1016 now,
1017 to
1018 ));
1019}
1020
1021/** Authoritative ranged hit when the defender lives on this worker. */
1022export function applyRemoteRangedShot (world, payload)
1023{
1024 const targetHandle = world.ecs.handleOf(payload.targetId);
1025 if (targetHandle == null)
1026 { return { events: [], forwards: [] }; }
1027 const snapshot = {
1028 tileX: payload.tileX,
1029 tileY: payload.tileY
1030 };
1031
1032 const hitEvents = applyLocalMeleeHit(
1033 world,
1034 payload.attackerId,
1035 payload.targetId,
1036 null,
1037 targetHandle,
1038 payload.profile,
1039 payload.now ?? Date.now(),
1040 snapshot,
1041 payload.attackerLevels,
1042 payload.attackerIsPlayer
1043 );
1044
1045 const outcome = hitEvents.find((e) =>
1046 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
1047 let endX = snapshot.tileX;
1048 let endY = snapshot.tileY;
1049 if (outcome?.type === "combat-miss")
1050 {
1051 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
1052 endX = miss.tileX;
1053 endY = miss.tileY;
1054 }
1055 else
1056 {
1057 const currentPos = world.ecs.get(targetHandle, Component.position);
1058 if (currentPos)
1059 {
1060 endX = currentPos.tileX;
1061 endY = currentPos.tileY;
1062 }
1063 }
1064
1065 const events = [{
1066 type: "combat-projectile",
1067 attackerId: payload.attackerId,
1068 targetId: payload.targetId,
1069 fromTileX: payload.fromTileX,
1070 fromTileY: payload.fromTileY,
1071 tileX: endX,
1072 tileY: endY,
1073 durationMs: RANGED_PROJECTILE_MS,
1074 shaftTint: payload.shaftTint ?? null,
1075 tipTint: payload.tipTint ?? null
1076 }, ...hitEvents];
1077
1078 const forwards = [];
1079 const hitEvent = hitEvents.find((event) => event.type === "combat-hit");
1080 if (hitEvent && payload.attackerIsPlayer)
1081 {
1082 forwards.push({
1083 type: "forward-combat-xp",
1084 entityId: payload.attackerId,
1085 profile: payload.profile,
1086 damage: hitEvent.damage
1087 });
1088 }
1089 return { events, forwards };
1090}
1091
1092/** Authoritative hit resolution when the defender lives on this worker. */
1093export function applyRemoteMeleeSwing (world, payload)
1094{
1095 const targetHandle = world.ecs.handleOf(payload.targetId);
1096 if (targetHandle == null)
1097 { return { events: [], forwards: [] }; }
1098 const to = world.ecs.get(targetHandle, Component.position);
1099 if (!to)
1100 { return { events: [], forwards: [] }; }
1101
1102 const events = applyLocalMeleeHit(
1103 world,
1104 payload.attackerId,
1105 payload.targetId,
1106 null,
1107 targetHandle,
1108 payload.profile,
1109 payload.now ?? Date.now(),
1110 to,
1111 payload.attackerLevels,
1112 payload.attackerIsPlayer
1113 );
1114
1115 const forwards = [];
1116 const hitEvent = events.find((event) => event.type === "combat-hit");
1117 if (hitEvent && payload.attackerIsPlayer)
1118 {
1119 forwards.push({
1120 type: "forward-combat-xp",
1121 entityId: payload.attackerId,
1122 profile: payload.profile,
1123 damage: hitEvent.damage
1124 });
1125 }
1126 return { events, forwards };
1127}
1128
1129function applyLocalMeleeHit (
1130 world,
1131 attackerId,
1132 targetId,
1133 attackerHandle,
1134 targetHandle,
1135 profile,
1136 now,
1137 to,
1138 attackerLevelsOverride = null,
1139 attackerIsPlayerOverride = null
1140)
1141{
1142 const events = [];
1143 if (targetHandle == null)
1144 { return events; }
1145
1146 const attackerIsPlayer = attackerIsPlayerOverride != null
1147 ? !!attackerIsPlayerOverride
1148 : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);
1149
1150 // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
1151 if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))
1152 { engageTarget(world.ecs, targetId, attackerId, now); }
1153 if (attackerIsPlayer === false)
1154 {
1155 const targetCharacter = world.ecs.get(targetHandle, Component.character);
1156 if (targetCharacter)
1157 {
1158 engageTarget(world.ecs, targetId, attackerId, now);
1159 const follow = world.ecs.get(targetHandle, Component.follow);
1160 if (follow)
1161 {
1162 follow.targetEntityId = null;
1163 follow.trail = [];
1164 }
1165 if (world.ecs.has(targetHandle, Component.gather))
1166 { world.ecs.remove(targetHandle, Component.gather); }
1167 }
1168 }
1169
1170 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
1171 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
1172 const attackerLevels = attackerLevelsOverride
1173 ?? (attackerHandle != null
1174 ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings)
1175 : null);
1176 if (!attackerLevels)
1177 { return events; }
1178
1179 const agilityLevel = defenderSkillLevel(
1180 defenderSkills,
1181 SkillId.agility,
1182 defenderEquipment,
1183 world.settings
1184 );
1185 const defenceLevel = defenderSkillLevel(
1186 defenderSkills,
1187 SkillId.defence,
1188 defenderEquipment,
1189 world.settings
1190 );
1191
1192 const resolved = resolvePhysicalAttack({
1193 hitSkillLevel: effectiveHitSkillInDarkness(
1194 attackerLevels.hitLevel,
1195 tileLightAt(world, to.tileX, to.tileY)
1196 ),
1197 agilitySkillLevel: agilityLevel,
1198 damageSkillLevel: attackerLevels.damageLevel,
1199 defenceSkillLevel: defenceLevel
1200 });
1201
1202 if (resolved.outcome === "miss")
1203 {
1204 events.push({
1205 type: "combat-miss",
1206 attackerId,
1207 targetId,
1208 tileX: to.tileX,
1209 tileY: to.tileY
1210 });
1211 const dodgeXp = awardCombatAvoidanceXp(
1212 world.ecs,
1213 targetHandle,
1214 SkillId.agility,
1215 resolved.damageRoll
1216 );
1217 if (dodgeXp)
1218 {
1219 events.push({
1220 type: "skills-updated",
1221 entityId: targetId,
1222 characterId: dodgeXp.characterId,
1223 skills: dodgeXp.view,
1224 stored: dodgeXp.stored,
1225 levelUps: dodgeXp.levelUps ?? []
1226 });
1227 }
1228 return events;
1229 }
1230
1231 if (resolved.outcome === "block")
1232 {
1233 events.push({
1234 type: "combat-block",
1235 attackerId,
1236 targetId,
1237 tileX: to.tileX,
1238 tileY: to.tileY
1239 });
1240 const blockXp = awardCombatAvoidanceXp(
1241 world.ecs,
1242 targetHandle,
1243 SkillId.defence,
1244 resolved.damageRoll
1245 );
1246 if (blockXp)
1247 {
1248 events.push({
1249 type: "skills-updated",
1250 entityId: targetId,
1251 characterId: blockXp.characterId,
1252 skills: blockXp.view,
1253 stored: blockXp.stored,
1254 levelUps: blockXp.levelUps ?? []
1255 });
1256 }
1257 return events;
1258 }
1259
1260 const damage = resolved.damage;
1261 const targetCharacter = world.ecs.get(targetHandle, Component.character);
1262 if (targetCharacter)
1263 { syncPlayerHealth(world.ecs, targetHandle); }
1264 const health = world.ecs.get(targetHandle, Component.health);
1265 if (health)
1266 {
1267 health.current = Math.max(0, (health.current | 0) - damage);
1268 }
1269 events.push({
1270 type: "combat-hit",
1271 attackerId,
1272 targetId,
1273 damage,
1274 tileX: to.tileX,
1275 tileY: to.tileY,
1276 health: health?.current ?? 0,
1277 maxHealth: health?.max ?? 0
1278 });
1279
1280 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
1281 if (healthXp)
1282 {
1283 events.push({
1284 type: "skills-updated",
1285 entityId: targetId,
1286 characterId: healthXp.characterId,
1287 skills: healthXp.view,
1288 stored: healthXp.stored,
1289 levelUps: healthXp.levelUps ?? []
1290 });
1291 if (health)
1292 {
1293 const hitEvent = events[events.length - 2];
1294 if (hitEvent?.type === "combat-hit")
1295 {
1296 hitEvent.health = health.current;
1297 hitEvent.maxHealth = health.max;
1298 }
1299 }
1300 }
1301
1302 if (attackerHandle != null)
1303 {
1304 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
1305 if (attackerCharacter)
1306 {
1307 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage);
1308 if (xpAward)
1309 {
1310 events.push({
1311 type: "skills-updated",
1312 entityId: attackerId,
1313 characterId: attackerCharacter.characterId,
1314 skills: xpAward.view,
1315 stored: xpAward.stored,
1316 levelUps: xpAward.levelUps ?? []
1317 });
1318 }
1319 }
1320 }
1321
1322 if (health && health.current <= 0)
1323 {
1324 clearEngage(world.ecs, attackerId);
1325 clearEngage(world.ecs, targetId);
1326 for (const entity of world.ecs.query(Component.combat))
1327 {
1328 if (entity.combat.targetEntityId === targetId)
1329 { entity.combat.targetEntityId = null; }
1330 }
1331 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
1332 {
1333 const path = world.ecs.get(targetHandle, Component.path);
1334 if (path)
1335 { path.tiles = []; }
1336 const follow = world.ecs.get(targetHandle, Component.follow);
1337 if (follow)
1338 {
1339 follow.targetEntityId = null;
1340 follow.trail = [];
1341 }
1342 world.ecs.add(targetHandle, Component.dead, {});
1343 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
1344 events.push({
1345 type: "player-died",
1346 entityId: targetId,
1347 attackerId,
1348 characterId: targetCharacter.characterId,
1349 sessionId: identity?.sessionId ?? null,
1350 tileX: to.tileX,
1351 tileY: to.tileY,
1352 health: 0,
1353 maxHealth: health.max
1354 });
1355 }
1356 const creature = world.ecs.get(targetHandle, Component.creature);
1357 if (creature && !world.ecs.get(targetHandle, Component.character))
1358 {
1359 events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now));
1360 }
1361 }
1362 return events;
1363}
1364
1365/**
1366 * Drops, despawn, and `mob-killed` for bounty / town-guard reaction.
1367 * Shared by melee and spell kill paths.
1368 */
1369export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now)
1370{
1371 const events = [];
1372 const handle = targetHandle ?? world.ecs.handleOf(targetId);
1373 if (handle == null)
1374 { return events; }
1375 const creature = world.ecs.get(handle, Component.creature);
1376 const origin = world.ecs.get(handle, Component.spawnOrigin);
1377 const appearance = world.ecs.get(handle, Component.appearance);
1378 events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId));
1379 events.push({
1380 type: "mob-killed",
1381 entityId: targetId,
1382 attackerId,
1383 mobTypeId: creature?.mobTypeId ?? null,
1384 level: creature?.level ?? origin?.level ?? 1,
1385 bounty: Math.max(0, origin?.bounty | 0 || 0),
1386 spawnerId: origin?.spawnerId ?? null,
1387 originTileX: origin?.originTileX ?? tileX,
1388 originTileY: origin?.originTileY ?? tileY,
1389 wanderRangeTiles: origin?.wanderRangeTiles ?? 0,
1390 townGuard: !!origin?.townGuard,
1391 displayName: appearance?.firstName ?? null,
1392 tileX,
1393 tileY
1394 });
1395 const view = world.destroyEntity?.(targetId) ?? null;
1396 if (view)
1397 {
1398 events.push({
1399 type: "entity-despawn",
1400 entityId: targetId,
1401 tileX: view.tileX,
1402 tileY: view.tileY
1403 });
1404 }
1405 return events;
1406}
1407
1408/** Apply HP loss and shared death/loot side-effects (used by spell impacts). */
1409export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now())
1410{
1411 const events = [];
1412 const targetHandle = world.ecs.handleOf(targetId);
1413 if (targetHandle == null)
1414 { return events; }
1415 const to = world.ecs.get(targetHandle, Component.position);
1416 if (!to)
1417 { return events; }
1418 const health = world.ecs.get(targetHandle, Component.health);
1419 if (health)
1420 { health.current = Math.max(0, (health.current | 0) - damage); }
1421 events.push({
1422 type: "combat-hit",
1423 attackerId,
1424 targetId,
1425 damage,
1426 tileX: to.tileX,
1427 tileY: to.tileY,
1428 health: health?.current ?? 0,
1429 maxHealth: health?.max ?? 0
1430 });
1431
1432 const attackerHandle = world.ecs.handleOf(attackerId);
1433 if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))
1434 {
1435 const targetCombat = world.ecs.get(targetHandle, Component.combat);
1436 if (targetCombat && targetCombat.targetEntityId == null)
1437 { engageTarget(world.ecs, targetId, attackerId, now); }
1438 }
1439 if (attackerHandle != null && world.ecs.get(targetHandle, Component.character))
1440 {
1441 const attackerCreature = world.ecs.get(attackerHandle, Component.creature);
1442 if (attackerCreature)
1443 {
1444 engageTarget(world.ecs, targetId, attackerId, now);
1445 }
1446 }
1447
1448 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
1449 if (healthXp)
1450 {
1451 events.push({
1452 type: "skills-updated",
1453 entityId: targetId,
1454 characterId: healthXp.characterId,
1455 skills: healthXp.view,
1456 stored: healthXp.stored,
1457 levelUps: healthXp.levelUps ?? []
1458 });
1459 }
1460
1461 if (health && health.current <= 0)
1462 {
1463 clearEngage(world.ecs, attackerId);
1464 clearEngage(world.ecs, targetId);
1465 for (const entity of world.ecs.query(Component.combat))
1466 {
1467 if (entity.combat.targetEntityId === targetId)
1468 { entity.combat.targetEntityId = null; }
1469 }
1470 const targetCharacter = world.ecs.get(targetHandle, Component.character);
1471 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
1472 {
1473 const path = world.ecs.get(targetHandle, Component.path);
1474 if (path)
1475 { path.tiles = []; }
1476 world.ecs.add(targetHandle, Component.dead, {});
1477 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
1478 events.push({
1479 type: "player-died",
1480 entityId: targetId,
1481 attackerId,
1482 characterId: targetCharacter.characterId,
1483 sessionId: identity?.sessionId ?? null,
1484 tileX: to.tileX,
1485 tileY: to.tileY,
1486 health: 0,
1487 maxHealth: health.max
1488 });
1489 }
1490 const creature = world.ecs.get(targetHandle, Component.creature);
1491 if (creature && !targetCharacter)
1492 { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); }
1493 }
1494 return events;
1495}