BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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