BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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