BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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