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 const origin = world.ecs.get(entity.handle, Component.spawnOrigin);
535 const aggressive = origin
536 ? !!origin.aggressive
537 : mobIsAggressive(def);
538 if (!aggressive || !mobCanFight(def))
539 { continue; }
540 if (world.ecs.has(entity.handle, Component.dead))
541 { continue; }
542 const health = world.ecs.get(entity.handle, Component.health);
543 if (health && health.current <= 0)
544 { continue; }
545 const combat = world.ecs.get(entity.handle, Component.combat);
546 if (combat?.targetEntityId != null)
547 { continue; }
548
549 const range = mobAggroRangeTiles(def);
550 let bestId = null;
551 let bestDist = Infinity;
552 for (const player of world.ecs.query(Component.character, Component.position))
553 {
554 if (world.ecs.has(player.handle, Component.dead))
555 { continue; }
556 const playerHealth = world.ecs.get(player.handle, Component.health);
557 if (playerHealth && playerHealth.current <= 0)
558 { continue; }
559 const dist = chebyshev(
560 entity.position.tileX,
561 entity.position.tileY,
562 player.position.tileX,
563 player.position.tileY
564 );
565 if (dist < 1 || dist > range)
566 { continue; }
567 let effectiveDist = dist;
568 if (dist > 1)
569 {
570 const light = tileLightAt(world, player.position.tileX, player.position.tileY);
571 effectiveDist = dist * aggroDistanceMultiplier(light);
572 }
573 if (effectiveDist > range)
574 { continue; }
575 if (!hasCombatLineOfSight(
576 world,
577 entity.position.tileX,
578 entity.position.tileY,
579 player.position.tileX,
580 player.position.tileY
581 ))
582 { continue; }
583 if (dist < bestDist)
584 {
585 bestDist = dist;
586 bestId = player.entityId;
587 }
588 }
589 if (bestId == null)
590 { continue; }
591 if (!ensureMobCombat(world.ecs, entity.entityId))
592 { continue; }
593 engageTarget(world.ecs, entity.entityId, bestId, now);
594 }
595}
596
597/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
598export function resolveCombatTarget (world, targetId)
599{
600 const handle = world.ecs.handleOf(targetId);
601 if (handle != null)
602 {
603 const pos = world.ecs.get(handle, Component.position);
604 if (!pos)
605 { return null; }
606 if (isUntargetable(world.ecs, handle))
607 { return null; }
608 return {
609 local: true,
610 handle,
611 pos,
612 health: world.ecs.get(handle, Component.health)
613 };
614 }
615 const ghost = world.ghosts?.get?.(targetId);
616 if (!ghost || ghost.untargetable)
617 { return null; }
618 const health = ghost.health != null
619 ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health }
620 : null;
621 return {
622 local: false,
623 handle: null,
624 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
625 health
626 };
627}
628
629function attackerCombatLevels (ecs, attackerHandle, profile, settings = null)
630{
631 const attackerCharacter = ecs.get(attackerHandle, Component.character);
632 if (attackerCharacter)
633 { return playerCombatLevels(ecs, attackerHandle, profile, settings); }
634 const skills = ecs.get(attackerHandle, Component.skills);
635 const equipment = ecs.get(attackerHandle, Component.equipment);
636 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {};
637 const hitSkillId = profile.hitSkillId ?? SkillId.unarmed;
638 const damageSkillId = profile.damageSkillId ?? SkillId.strength;
639 const baseHit = attackerSkillLevel(skills, profile, hitSkillId);
640 const baseDamage = attackerSkillLevel(skills, profile, damageSkillId);
641 return {
642 hitLevel: Math.max(1, baseHit + (bonuses[hitSkillId] ?? 0)),
643 damageLevel: Math.max(1, baseDamage + (bonuses[damageSkillId] ?? 0)),
644 agilityLevel: effectiveSkillLevel(skills, SkillId.agility, bonuses),
645 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
646 };
647}
648
649export function stepCombat (world, now = Date.now())
650{
651 const events = [];
652 for (const entity of world.ecs.query(Component.combat, Component.position))
653 {
654 if (world.ecs.has(entity.handle, Component.dead))
655 {
656 entity.combat.targetEntityId = null;
657 continue;
658 }
659 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
660 { continue; }
661 const combat = entity.combat;
662 const targetId = combat.targetEntityId;
663 if (targetId == null)
664 { continue; }
665 const target = resolveCombatTarget(world, targetId);
666 if (!target)
667 {
668 combat.targetEntityId = null;
669 continue;
670 }
671 if (target.health && target.health.current <= 0)
672 {
673 combat.targetEntityId = null;
674 continue;
675 }
676
677 // One combat form at a time: spell cast / auto-cast wins over melee & archery.
678 if (isSpellCombatBusy(world.ecs, entity.handle))
679 { continue; }
680
681 if (combat.fleeFrom)
682 {
683 const flee = combat.fleeFrom;
684 const minDist = Math.max(1, flee.minDist | 0 || 2);
685 const fleeDist = chebyshev(
686 entity.position.tileX,
687 entity.position.tileY,
688 flee.tileX,
689 flee.tileY
690 );
691 if (fleeDist >= minDist)
692 {
693 combat.fleeFrom = null;
694 clearCombatApproachPath(world.ecs, entity.handle);
695 }
696 else
697 {
698 queueFleeFromHitSource(world, entity.entityId, entity.handle, entity.position, flee, minDist);
699 continue;
700 }
701 }
702
703 const profile = attackProfileOf(world.ecs, entity.handle);
704 const targetPos = target.pos;
705 const isCreature = !!world.ecs.get(entity.handle, Component.creature)
706 && !world.ecs.get(entity.handle, Component.character);
707
708 if (profile.mode === "ranged")
709 {
710 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
711 const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;
712 const equipment = world.ecs.get(entity.handle, Component.equipment);
713 const hasArrows = isCreature
714 || (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0);
715 const inRange = dist >= 1 && dist <= maxRange
716 && hasCombatLineOfSight(
717 world,
718 entity.position.tileX,
719 entity.position.tileY,
720 targetPos.tileX,
721 targetPos.tileY
722 );
723 if (!inRange || !hasArrows)
724 {
725 if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0)
726 && world.ecs.get(entity.handle, Component.character))
727 {
728 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
729 events.push({
730 type: "combat-no-arrows",
731 attackerId: entity.entityId,
732 sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null
733 });
734 }
735 queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange);
736 continue;
737 }
738 clearCombatApproachPath(world.ecs, entity.handle);
739 if (now < (combat.nextSwingAt || 0))
740 { continue; }
741 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
742 clearSpellCombatState(world.ecs, entity.handle);
743 events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos));
744 continue;
745 }
746
747 if (profile.mode !== "melee")
748 { continue; }
749
750 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
751 const canSwing = dist === 1
752 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
753 const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : [];
754 const preferSpell = isCreature
755 && !!mobDefinition(world.ecs.get(entity.handle, Component.creature)?.mobTypeId)?.preferSpellAttack;
756 const shouldCast = isCreature && attackSpells.length > 0 && (!canSwing || preferSpell);
757
758 if (shouldCast)
759 {
760 const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES
761 && hasCombatLineOfSight(
762 world,
763 entity.position.tileX,
764 entity.position.tileY,
765 targetPos.tileX,
766 targetPos.tileY
767 );
768 if (!inSpellRange)
769 {
770 queueStandInRangeApproach(
771 world,
772 entity.entityId,
773 entity.handle,
774 entity.position,
775 targetPos.tileX,
776 targetPos.tileY,
777 COMBAT_RANGE_TILES,
778 1
779 );
780 continue;
781 }
782 clearCombatApproachPath(world.ecs, entity.handle);
783 if (now < (combat.nextSwingAt || 0))
784 { continue; }
785 const picked = pickMobAttackSpell(attackSpells);
786 if (!picked)
787 {
788 combat.nextSwingAt = now + SPELL_COOLDOWN_MS;
789 continue;
790 }
791 combat.nextSwingAt = now + SPELL_COOLDOWN_MS;
792 events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now));
793 continue;
794 }
795
796 if (!canSwing)
797 {
798 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
799 continue;
800 }
801 clearCombatApproachPath(world.ecs, entity.handle);
802 const attackerHealth = world.ecs.get(entity.handle, Component.health);
803 if (attackerHealth && attackerHealth.current <= 0)
804 { continue; }
805 if ((combat.nextSwingAt || 0) > now)
806 { continue; }
807
808 combat.nextSwingAt = now + (profile.cooldownMs || 800);
809 clearSpellCombatState(world.ecs, entity.handle);
810 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
811 }
812 return events;
813}
814
815function eligibleMobAttackSpells (ecs, handle)
816{
817 const spells = ecs.get(handle, Component.spells);
818 if (!spells?.known?.length)
819 { return []; }
820 const level = creatureLevel(ecs, handle);
821 const chances = spells.castChances ?? {};
822 const out = [];
823 for (const spellId of spells.known)
824 {
825 const def = spellDefinition(spellId);
826 if (!def || def.target !== "entity")
827 { continue; }
828 const minLevel = spellMinMagicLevel(def);
829 if (level < minLevel)
830 { continue; }
831 const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0;
832 if (chance <= 0)
833 { continue; }
834 out.push({ spellId, chance });
835 }
836 return out;
837}
838
839function pickMobAttackSpell (spells)
840{
841 if (!spells.length)
842 { return null; }
843 const pick = spells[Math.floor(Math.random() * spells.length)];
844 if ((Math.random() * 100) >= pick.chance)
845 { return null; }
846 return pick;
847}
848
849function clearCombatApproachPath (ecs, handle)
850{
851 const path = ecs.get(handle, Component.path);
852 if (path?.tiles?.length)
853 { path.tiles = []; }
854}
855
856function combatTileKey (tileX, tileY)
857{
858 return `${tileX},${tileY}`;
859}
860
861/** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */
862function collectCombatAllyReservations (world, entityId, targetEntityId)
863{
864 const reserved = new Set();
865 if (targetEntityId == null)
866 { return reserved; }
867 for (const entity of world.ecs.query(Component.combat, Component.position))
868 {
869 if (entity.entityId === entityId)
870 { continue; }
871 if (entity.combat.targetEntityId !== targetEntityId)
872 { continue; }
873 reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY));
874 const allyPath = world.ecs.get(entity.handle, Component.path);
875 if (!allyPath?.tiles?.length)
876 { continue; }
877 const next = allyPath.tiles[0];
878 if (next)
879 { reserved.add(combatTileKey(next.x, next.y)); }
880 const dest = allyPath.tiles[allyPath.tiles.length - 1];
881 if (dest)
882 { reserved.add(combatTileKey(dest.x, dest.y)); }
883 }
884 return reserved;
885}
886
887function combatGoalPreference (entityId, tileX, tileY)
888{
889 return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0;
890}
891
892/** Cost multiplier for tiles the threat can currently shoot. */
893const COVER_EXPOSED_STEP_COST = 5;
894
895function mobHasRangedRetaliation (world, handle)
896{
897 const profile = attackProfileOf(world.ecs, handle);
898 if (profile?.mode === "ranged")
899 { return true; }
900 return eligibleMobAttackSpells(world.ecs, handle).length > 0;
901}
902
903/** Melee-only creatures closing after a player ranged/spell hit. */
904function shouldSeekCoverApproach (world, handle)
905{
906 if (world.ecs.get(handle, Component.character))
907 { return false; }
908 if (!world.ecs.get(handle, Component.creature))
909 { return false; }
910 const combat = world.ecs.get(handle, Component.combat);
911 if (!combat?.seekCover)
912 { return false; }
913 return !mobHasRangedRetaliation(world, handle);
914}
915
916function coverStepCost (world, threatPos, goalX, goalY, x, y)
917{
918 // Final adjacent step is always in LOS — don't punish the last lunge.
919 if (x === goalX && y === goalY)
920 { return 1; }
921 if (hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y))
922 { return COVER_EXPOSED_STEP_COST; }
923 return 1;
924}
925
926function pathCoverScore (world, threatPos, tiles)
927{
928 let score = 0;
929 for (const step of tiles)
930 {
931 score += hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, step.x, step.y)
932 ? COVER_EXPOSED_STEP_COST
933 : 1;
934 }
935 return score;
936}
937
938function listAdjacentMeleeGoals (world, entityId, position, targetPos, reserved)
939{
940 const dirs = [
941 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
942 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
943 ];
944 const goals = [];
945 for (const dir of dirs)
946 {
947 const x = targetPos.tileX + dir.x;
948 const y = targetPos.tileY + dir.y;
949 const isHere = x === position.tileX && y === position.tileY;
950 const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true;
951 const key = combatTileKey(x, y);
952 if (reserved?.has(key) && !(isHere && aloneHere))
953 { continue; }
954 const clear = world.isClearStanding?.(entityId, x, y)
955 ?? world.walkableFor(entityId, x, y);
956 if (!clear && !isHere)
957 { continue; }
958 if (isHere && !aloneHere)
959 { continue; }
960 goals.push({ x, y });
961 }
962 return goals;
963}
964
965function findCoverMeleeApproachPath (world, entityId, handle, position, targetPos, reserved)
966{
967 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
968 const preferVertical = !!world.ecs.get(handle, Component.character);
969 const isWalkable = (x, y, goal) =>
970 {
971 if (x === goal.x && y === goal.y)
972 {
973 return world.isClearStanding?.(entityId, x, y)
974 ?? world.walkableFor(entityId, x, y);
975 }
976 return world.walkableFor(entityId, x, y);
977 };
978 let bestTiles = null;
979 let bestScore = Infinity;
980 let bestPref = Infinity;
981 for (const goal of listAdjacentMeleeGoals(world, entityId, position, targetPos, reserved))
982 {
983 if (goal.x === position.tileX && goal.y === position.tileY)
984 { return []; }
985 const tiles = findPath(
986 position.tileX,
987 position.tileY,
988 goal.x,
989 goal.y,
990 (x, y) => isWalkable(x, y, goal),
991 bounds.minX,
992 bounds.minY,
993 bounds.maxX,
994 bounds.maxY,
995 {
996 preferVertical,
997 stepCost: (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)
998 }
999 );
1000 if (!tiles.length)
1001 { continue; }
1002 const score = pathCoverScore(world, targetPos, tiles);
1003 const pref = combatGoalPreference(entityId, goal.x, goal.y);
1004 if (score < bestScore || (score === bestScore && pref < bestPref))
1005 {
1006 bestScore = score;
1007 bestPref = pref;
1008 bestTiles = tiles;
1009 }
1010 }
1011 return bestTiles;
1012}
1013
1014/** Duck behind the nearest tile the threat cannot shoot when melee approach is impossible. */
1015function queueFleeToCover (world, entityId, handle, position, threatPos)
1016{
1017 let path = world.ecs.get(handle, Component.path);
1018 if (!path)
1019 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
1020 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1021 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
1022 const isGoal = (x, y) =>
1023 {
1024 if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y)))
1025 { return false; }
1026 if (chebyshev(x, y, threatPos.tileX, threatPos.tileY) < 1)
1027 { return false; }
1028 return !hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y);
1029 };
1030 if (isGoal(position.tileX, position.tileY))
1031 {
1032 path.tiles = [];
1033 return;
1034 }
1035 const tiles = findPathToNearestGoal(
1036 position.tileX,
1037 position.tileY,
1038 isGoal,
1039 isWalkable,
1040 bounds.minX,
1041 bounds.minY,
1042 bounds.maxX,
1043 bounds.maxY
1044 );
1045 if (!tiles.length)
1046 {
1047 path.tiles = [];
1048 return;
1049 }
1050 path.tiles = tiles;
1051 const movement = world.ecs.get(handle, Component.movement);
1052 if (movement)
1053 { movement.walkCarry = 0; }
1054}
1055
1056/** Path to the nearest standable tile at least `minDist` from the hit source. */
1057function queueFleeFromHitSource (world, entityId, handle, position, source, minDist)
1058{
1059 if (world.frozen?.has?.(entityId))
1060 { return; }
1061 let path = world.ecs.get(handle, Component.path);
1062 if (!path)
1063 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
1064 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
1065 if (
1066 aloneHere
1067 && chebyshev(position.tileX, position.tileY, source.tileX, source.tileY) >= minDist
1068 )
1069 {
1070 path.tiles = [];
1071 return;
1072 }
1073 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1074 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
1075 const isGoal = (x, y) =>
1076 {
1077 if (chebyshev(x, y, source.tileX, source.tileY) < minDist)
1078 { return false; }
1079 return world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y);
1080 };
1081 if (isGoal(position.tileX, position.tileY) && aloneHere)
1082 {
1083 path.tiles = [];
1084 return;
1085 }
1086 const dest = path.tiles?.length ? path.tiles[path.tiles.length - 1] : null;
1087 if (
1088 dest
1089 && isGoal(dest.x, dest.y)
1090 && path.tiles.every((step) => isWalkable(step.x, step.y))
1091 )
1092 { return; }
1093 const tiles = findPathToNearestGoal(
1094 position.tileX,
1095 position.tileY,
1096 isGoal,
1097 isWalkable,
1098 bounds.minX,
1099 bounds.minY,
1100 bounds.maxX,
1101 bounds.maxY
1102 );
1103 if (!tiles.length)
1104 {
1105 path.tiles = [];
1106 return;
1107 }
1108 path.tiles = tiles;
1109 const movement = world.ecs.get(handle, Component.movement);
1110 if (movement)
1111 { movement.walkCarry = 0; }
1112}
1113
1114export function queueMeleeApproach (world, entityId, handle, position, targetPos)
1115{
1116 if (world.frozen?.has?.(entityId))
1117 { return; }
1118 let path = world.ecs.get(handle, Component.path);
1119 if (!path)
1120 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
1121
1122 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY)
1123 ?? true;
1124 if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere)
1125 {
1126 path.tiles = [];
1127 return;
1128 }
1129
1130 const combat = world.ecs.get(handle, Component.combat);
1131 const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
1132 const seekCover = shouldSeekCoverApproach(world, handle);
1133
1134 if (seekCover)
1135 {
1136 const coverTiles = findCoverMeleeApproachPath(
1137 world,
1138 entityId,
1139 handle,
1140 position,
1141 targetPos,
1142 reserved
1143 );
1144 if (coverTiles)
1145 {
1146 if (!coverTiles.length)
1147 {
1148 path.tiles = [];
1149 return;
1150 }
1151 const goal = coverTiles[coverTiles.length - 1];
1152 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved))
1153 { return; }
1154 path.tiles = coverTiles;
1155 const movement = world.ecs.get(handle, Component.movement);
1156 if (movement)
1157 { movement.walkCarry = 0; }
1158 return;
1159 }
1160 queueFleeToCover(world, entityId, handle, position, targetPos);
1161 return;
1162 }
1163
1164 const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved);
1165 if (!goal)
1166 {
1167 path.tiles = [];
1168 return;
1169 }
1170
1171 if (goal.x === position.tileX && goal.y === position.tileY)
1172 {
1173 path.tiles = [];
1174 return;
1175 }
1176
1177 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved))
1178 { return; }
1179
1180 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1181 const preferVertical = !!world.ecs.get(handle, Component.character);
1182 const tiles = findPath(
1183 position.tileX,
1184 position.tileY,
1185 goal.x,
1186 goal.y,
1187 (x, y) =>
1188 {
1189 if (x === goal.x && y === goal.y)
1190 {
1191 return world.isClearStanding?.(entityId, x, y)
1192 ?? world.walkableFor(entityId, x, y);
1193 }
1194 return world.walkableFor(entityId, x, y);
1195 },
1196 bounds.minX,
1197 bounds.minY,
1198 bounds.maxX,
1199 bounds.maxY,
1200 { preferVertical }
1201 );
1202 if (!tiles.length)
1203 {
1204 path.tiles = [];
1205 return;
1206 }
1207 path.tiles = tiles;
1208 const movement = world.ecs.get(handle, Component.movement);
1209 if (movement)
1210 { movement.walkCarry = 0; }
1211}
1212
1213/**
1214 * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS.
1215 * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left).
1216 * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).
1217 */
1218export function queueStandInRangeApproach (
1219 world,
1220 entityId,
1221 handle,
1222 position,
1223 targetTileX,
1224 targetTileY,
1225 maxRange,
1226 minStandDist = 1
1227)
1228{
1229 if (world.frozen?.has?.(entityId))
1230 { return; }
1231 let path = world.ecs.get(handle, Component.path);
1232 if (!path)
1233 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
1234
1235 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
1236 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
1237 if (
1238 distToTarget <= maxRange
1239 && distToTarget >= minStandDist
1240 && aloneHere
1241 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
1242 )
1243 {
1244 path.tiles = [];
1245 return;
1246 }
1247
1248 const combat = world.ecs.get(handle, Component.combat);
1249 const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
1250 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1251 const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
1252 const isGoal = (x, y) =>
1253 {
1254 const standOff = chebyshev(x, y, targetTileX, targetTileY);
1255 if (standOff < minStandDist || standOff > maxRange)
1256 { return false; }
1257 if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y)))
1258 { return false; }
1259 const key = combatTileKey(x, y);
1260 if (reserved.has(key) && !(x === position.tileX && y === position.tileY))
1261 { return false; }
1262 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY);
1263 };
1264
1265 const tiles = findPathToNearestGoal(
1266 position.tileX,
1267 position.tileY,
1268 isGoal,
1269 isWalkable,
1270 bounds.minX,
1271 bounds.minY,
1272 bounds.maxX,
1273 bounds.maxY
1274 );
1275 if (!tiles.length)
1276 {
1277 path.tiles = [];
1278 return;
1279 }
1280 const bestGoal = tiles[tiles.length - 1];
1281 if (path.tiles?.length && !standInRangePathStale(
1282 world,
1283 entityId,
1284 path,
1285 bestGoal,
1286 targetTileX,
1287 targetTileY,
1288 maxRange,
1289 minStandDist,
1290 reserved,
1291 position
1292 ))
1293 { return; }
1294 path.tiles = tiles;
1295 const movement = world.ecs.get(handle, Component.movement);
1296 if (movement)
1297 { movement.walkCarry = 0; }
1298}
1299
1300function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
1301{
1302 queueStandInRangeApproach(
1303 world,
1304 entityId,
1305 handle,
1306 position,
1307 targetPos.tileX,
1308 targetPos.tileY,
1309 maxRange,
1310 1
1311 );
1312}
1313
1314export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
1315{
1316 const events = [];
1317 const attackerHandle = world.ecs.handleOf(attackerId);
1318 if (attackerHandle == null)
1319 { return events; }
1320 const from = world.ecs.get(attackerHandle, Component.position);
1321 if (!from || !targetPos)
1322 { return events; }
1323 const isCreature = !!world.ecs.get(attackerHandle, Component.creature)
1324 && !world.ecs.get(attackerHandle, Component.character);
1325 const arrowTint = projectileDualTintFromAttacker(world.ecs, attackerHandle);
1326 const arrowSprite = projectileSpriteFromAttacker(world.ecs, attackerHandle);
1327 const tipElement = (() =>
1328 {
1329 const stack = arrowStackInOffhand(world.ecs.get(attackerHandle, Component.equipment));
1330 return stack?.instance?.kind === "tipped-arrow" ? stack.instance.element : null;
1331 })();
1332 if (!isCreature && !consumeArrow(world.ecs, attackerHandle))
1333 { return events; }
1334
1335 const shotProfile = tipElement
1336 ? { ...profile, attackType: tipElement }
1337 : profile;
1338
1339 const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY };
1340 const target = resolveCombatTarget(world, targetId);
1341 if (!target)
1342 { return events; }
1343
1344 if (!target.local)
1345 {
1346 events.push({
1347 type: "remote-ranged-resolve",
1348 attackerId,
1349 targetId,
1350 profile: shotProfile,
1351 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, shotProfile, world.settings),
1352 attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character),
1353 now,
1354 tileX: snapshot.tileX,
1355 tileY: snapshot.tileY,
1356 fromTileX: from.tileX,
1357 fromTileY: from.tileY,
1358 sprite: arrowSprite,
1359 ...(publicDualTint(arrowTint) ?? {})
1360 });
1361 return events;
1362 }
1363
1364 const hitEvents = applyLocalMeleeHit(
1365 world,
1366 attackerId,
1367 targetId,
1368 attackerHandle,
1369 target.handle,
1370 shotProfile,
1371 now,
1372 snapshot
1373 );
1374 const outcome = hitEvents.find((e) =>
1375 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
1376 let endX = snapshot.tileX;
1377 let endY = snapshot.tileY;
1378 if (outcome?.type === "combat-miss")
1379 {
1380 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
1381 endX = miss.tileX;
1382 endY = miss.tileY;
1383 }
1384 else
1385 {
1386 const currentPos = world.ecs.get(target.handle, Component.position);
1387 if (currentPos)
1388 {
1389 endX = currentPos.tileX;
1390 endY = currentPos.tileY;
1391 }
1392 }
1393 events.push({
1394 type: "combat-projectile",
1395 attackerId,
1396 targetId,
1397 fromTileX: from.tileX,
1398 fromTileY: from.tileY,
1399 tileX: endX,
1400 tileY: endY,
1401 durationMs: RANGED_PROJECTILE_MS,
1402 trackTarget: outcome?.type !== "combat-miss",
1403 sprite: arrowSprite,
1404 ...(publicDualTint(arrowTint) ?? {})
1405 });
1406 return events.concat(hitEvents);
1407}
1408
1409function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position)
1410{
1411 const dest = path.tiles[path.tiles.length - 1];
1412 if (dest.x !== goal.x || dest.y !== goal.y)
1413 { return true; }
1414 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
1415 if (standOff < minStandDist || standOff > maxRange)
1416 { return true; }
1417 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
1418 { return true; }
1419 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
1420 { return true; }
1421 const destKey = combatTileKey(dest.x, dest.y);
1422 if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
1423 { return true; }
1424 const next = path.tiles[0];
1425 if (!next)
1426 { return true; }
1427 if (!world.walkableFor(entityId, next.x, next.y))
1428 { return true; }
1429 return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
1430}
1431
1432function meleePathStale (world, entityId, position, targetPos, path, goal, reserved)
1433{
1434 const dest = path.tiles[path.tiles.length - 1];
1435 if (dest.x !== goal.x || dest.y !== goal.y)
1436 { return true; }
1437 if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)
1438 { return true; }
1439 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
1440 { return true; }
1441 const destKey = combatTileKey(dest.x, dest.y);
1442 if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
1443 { return true; }
1444 const next = path.tiles[0];
1445 if (!next)
1446 { return true; }
1447 if (!world.walkableFor(entityId, next.x, next.y))
1448 { return true; }
1449 return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
1450}
1451
1452function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null)
1453{
1454 const dirs = [
1455 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
1456 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
1457 ];
1458 let best = null;
1459 let bestDist = Infinity;
1460 let bestPref = Infinity;
1461 for (const dir of dirs)
1462 {
1463 const x = targetPos.tileX + dir.x;
1464 const y = targetPos.tileY + dir.y;
1465 const isHere = x === position.tileX && y === position.tileY;
1466 const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true;
1467 const key = combatTileKey(x, y);
1468 if (reserved?.has(key) && !(isHere && aloneHere))
1469 { continue; }
1470 const clear = world.isClearStanding?.(entityId, x, y)
1471 ?? world.walkableFor(entityId, x, y);
1472 if (!clear && !isHere)
1473 { continue; }
1474 if (isHere && !aloneHere)
1475 { continue; }
1476 const dist = chebyshev(position.tileX, position.tileY, x, y);
1477 const pref = combatGoalPreference(entityId, x, y);
1478 if (dist < bestDist || (dist === bestDist && pref < bestPref))
1479 {
1480 bestDist = dist;
1481 bestPref = pref;
1482 best = { x, y };
1483 }
1484 }
1485 return best;
1486}
1487
1488export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
1489{
1490 const events = [];
1491 const attackerHandle = world.ecs.handleOf(attackerId);
1492 if (attackerHandle == null)
1493 { return events; }
1494 const target = resolveCombatTarget(world, targetId);
1495 if (!target)
1496 { return events; }
1497 const from = world.ecs.get(attackerHandle, Component.position);
1498 const to = target.pos;
1499 if (!from || !to)
1500 { return events; }
1501 if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)
1502 { return events; }
1503 if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY))
1504 { return events; }
1505
1506 events.push({
1507 type: "combat-swing",
1508 attackerId,
1509 targetId,
1510 tileX: to.tileX,
1511 tileY: to.tileY,
1512 fromTileX: from.tileX,
1513 fromTileY: from.tileY
1514 });
1515
1516 if (!target.local)
1517 {
1518 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
1519 events.push({
1520 type: "remote-melee-resolve",
1521 attackerId,
1522 targetId,
1523 profile,
1524 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings),
1525 attackerIsPlayer: !!attackerCharacter,
1526 now,
1527 tileX: to.tileX,
1528 tileY: to.tileY
1529 });
1530 return events;
1531 }
1532
1533 return events.concat(applyLocalMeleeHit(
1534 world,
1535 attackerId,
1536 targetId,
1537 attackerHandle,
1538 target.handle,
1539 profile,
1540 now,
1541 to
1542 ));
1543}
1544
1545/** Authoritative ranged hit when the defender lives on this worker. */
1546export function applyRemoteRangedShot (world, payload)
1547{
1548 const targetHandle = world.ecs.handleOf(payload.targetId);
1549 if (targetHandle == null)
1550 { return { events: [], forwards: [] }; }
1551 const snapshot = {
1552 tileX: payload.tileX,
1553 tileY: payload.tileY
1554 };
1555
1556 const hitEvents = applyLocalMeleeHit(
1557 world,
1558 payload.attackerId,
1559 payload.targetId,
1560 null,
1561 targetHandle,
1562 payload.profile,
1563 payload.now ?? Date.now(),
1564 snapshot,
1565 payload.attackerLevels,
1566 payload.attackerIsPlayer
1567 );
1568
1569 const outcome = hitEvents.find((e) =>
1570 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
1571 let endX = snapshot.tileX;
1572 let endY = snapshot.tileY;
1573 if (outcome?.type === "combat-miss")
1574 {
1575 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
1576 endX = miss.tileX;
1577 endY = miss.tileY;
1578 }
1579 else
1580 {
1581 const currentPos = world.ecs.get(targetHandle, Component.position);
1582 if (currentPos)
1583 {
1584 endX = currentPos.tileX;
1585 endY = currentPos.tileY;
1586 }
1587 }
1588
1589 const events = [{
1590 type: "combat-projectile",
1591 attackerId: payload.attackerId,
1592 targetId: payload.targetId,
1593 fromTileX: payload.fromTileX,
1594 fromTileY: payload.fromTileY,
1595 tileX: endX,
1596 tileY: endY,
1597 durationMs: RANGED_PROJECTILE_MS,
1598 trackTarget: outcome?.type !== "combat-miss",
1599 sprite: payload.sprite ?? "fx:projectile:arrow",
1600 shaftTint: payload.shaftTint ?? null,
1601 tipTint: payload.tipTint ?? null,
1602 coatTint: payload.coatTint ?? null
1603 }, ...hitEvents];
1604
1605 const forwards = [];
1606 const hitEvent = hitEvents.find((event) => event.type === "combat-hit");
1607 if (hitEvent && payload.attackerIsPlayer)
1608 {
1609 forwards.push({
1610 type: "forward-combat-xp",
1611 entityId: payload.attackerId,
1612 profile: payload.profile,
1613 damage: hitEvent.damage
1614 });
1615 }
1616 return { events, forwards };
1617}
1618
1619/** Authoritative hit resolution when the defender lives on this worker. */
1620export function applyRemoteMeleeSwing (world, payload)
1621{
1622 const targetHandle = world.ecs.handleOf(payload.targetId);
1623 if (targetHandle == null)
1624 { return { events: [], forwards: [] }; }
1625 const to = world.ecs.get(targetHandle, Component.position);
1626 if (!to)
1627 { return { events: [], forwards: [] }; }
1628
1629 const events = applyLocalMeleeHit(
1630 world,
1631 payload.attackerId,
1632 payload.targetId,
1633 null,
1634 targetHandle,
1635 payload.profile,
1636 payload.now ?? Date.now(),
1637 to,
1638 payload.attackerLevels,
1639 payload.attackerIsPlayer
1640 );
1641
1642 const forwards = [];
1643 const hitEvent = events.find((event) => event.type === "combat-hit");
1644 if (hitEvent && payload.attackerIsPlayer)
1645 {
1646 forwards.push({
1647 type: "forward-combat-xp",
1648 entityId: payload.attackerId,
1649 profile: payload.profile,
1650 damage: hitEvent.damage
1651 });
1652 }
1653 return { events, forwards };
1654}
1655
1656function applyLocalMeleeHit (
1657 world,
1658 attackerId,
1659 targetId,
1660 attackerHandle,
1661 targetHandle,
1662 profile,
1663 now,
1664 to,
1665 attackerLevelsOverride = null,
1666 attackerIsPlayerOverride = null
1667)
1668{
1669 const events = [];
1670 if (targetHandle == null)
1671 { return events; }
1672
1673 const attackerIsPlayer = attackerIsPlayerOverride != null
1674 ? !!attackerIsPlayerOverride
1675 : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);
1676
1677 // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
1678 if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))
1679 {
1680 engageTarget(world.ecs, targetId, attackerId, now);
1681 if (profile?.mode === "ranged")
1682 { markSeekCover(world.ecs, targetId); }
1683 }
1684 if (attackerIsPlayer === false)
1685 {
1686 const targetCharacter = world.ecs.get(targetHandle, Component.character);
1687 if (targetCharacter)
1688 {
1689 engageTarget(world.ecs, targetId, attackerId, now);
1690 const follow = world.ecs.get(targetHandle, Component.follow);
1691 if (follow)
1692 {
1693 follow.targetEntityId = null;
1694 follow.trail = [];
1695 }
1696 if (world.ecs.has(targetHandle, Component.gather))
1697 { world.ecs.remove(targetHandle, Component.gather); }
1698 }
1699 }
1700
1701 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
1702 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
1703 const attackerLevels = attackerLevelsOverride
1704 ?? (attackerHandle != null
1705 ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings)
1706 : null);
1707 if (!attackerLevels)
1708 { return events; }
1709
1710 const agilityLevel = defenderSkillLevel(
1711 defenderSkills,
1712 SkillId.agility,
1713 defenderEquipment,
1714 world.settings
1715 );
1716 const defenceLevel = defenderSkillLevel(
1717 defenderSkills,
1718 SkillId.defence,
1719 defenderEquipment,
1720 world.settings
1721 );
1722
1723 const attackType = resolveAttackDamageType(world.ecs, attackerHandle, profile);
1724 const targetCreature = world.ecs.get(targetHandle, Component.creature);
1725 const targetAffinities = targetCreature
1726 ? mobDamageAffinities(mobDefinition(targetCreature.mobTypeId))
1727 : {};
1728 const resolved = resolvePhysicalAttack({
1729 hitSkillLevel: effectiveHitSkillInDarkness(
1730 attackerLevels.hitLevel,
1731 tileLightAt(world, to.tileX, to.tileY)
1732 ),
1733 agilitySkillLevel: agilityLevel,
1734 damageSkillLevel: attackerLevels.damageLevel,
1735 defenceSkillLevel: defenceLevel,
1736 attackType,
1737 targetAffinities
1738 });
1739
1740 if (resolved.outcome === "miss")
1741 {
1742 events.push({
1743 type: "combat-miss",
1744 attackerId,
1745 targetId,
1746 tileX: to.tileX,
1747 tileY: to.tileY
1748 });
1749 const dodgeXp = awardCombatAvoidanceXp(
1750 world.ecs,
1751 targetHandle,
1752 SkillId.agility,
1753 resolved.damageRoll
1754 );
1755 if (dodgeXp)
1756 {
1757 events.push({
1758 type: "skills-updated",
1759 entityId: targetId,
1760 characterId: dodgeXp.characterId,
1761 skills: dodgeXp.view,
1762 stored: dodgeXp.stored,
1763 levelUps: dodgeXp.levelUps ?? []
1764 });
1765 }
1766 return events;
1767 }
1768
1769 if (resolved.outcome === "block")
1770 {
1771 events.push({
1772 type: "combat-block",
1773 attackerId,
1774 targetId,
1775 tileX: to.tileX,
1776 tileY: to.tileY
1777 });
1778 const blockXp = awardCombatAvoidanceXp(
1779 world.ecs,
1780 targetHandle,
1781 SkillId.defence,
1782 resolved.damageRoll
1783 );
1784 if (blockXp)
1785 {
1786 events.push({
1787 type: "skills-updated",
1788 entityId: targetId,
1789 characterId: blockXp.characterId,
1790 skills: blockXp.view,
1791 stored: blockXp.stored,
1792 levelUps: blockXp.levelUps ?? []
1793 });
1794 }
1795 return events;
1796 }
1797
1798 const damage = resolved.damage;
1799 const targetCharacter = world.ecs.get(targetHandle, Component.character);
1800 if (targetCharacter)
1801 { syncPlayerHealth(world.ecs, targetHandle); }
1802 const health = world.ecs.get(targetHandle, Component.health);
1803 if (health)
1804 {
1805 health.current = Math.max(0, (health.current | 0) - damage);
1806 }
1807 events.push({
1808 type: "combat-hit",
1809 attackerId,
1810 targetId,
1811 damage,
1812 tileX: to.tileX,
1813 tileY: to.tileY,
1814 health: health?.current ?? 0,
1815 maxHealth: health?.max ?? 0
1816 });
1817
1818 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
1819 if (healthXp)
1820 {
1821 events.push({
1822 type: "skills-updated",
1823 entityId: targetId,
1824 characterId: healthXp.characterId,
1825 skills: healthXp.view,
1826 stored: healthXp.stored,
1827 levelUps: healthXp.levelUps ?? []
1828 });
1829 if (health)
1830 {
1831 const hitEvent = events[events.length - 2];
1832 if (hitEvent?.type === "combat-hit")
1833 {
1834 hitEvent.health = health.current;
1835 hitEvent.maxHealth = health.max;
1836 }
1837 }
1838 }
1839
1840 if (attackerHandle != null)
1841 { markFleeOnHit(world, targetId, attackerId); }
1842
1843 if (attackerHandle != null)
1844 {
1845 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
1846 if (attackerCharacter)
1847 {
1848 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage);
1849 if (xpAward)
1850 {
1851 events.push({
1852 type: "skills-updated",
1853 entityId: attackerId,
1854 characterId: attackerCharacter.characterId,
1855 skills: xpAward.view,
1856 stored: xpAward.stored,
1857 levelUps: xpAward.levelUps ?? []
1858 });
1859 }
1860 }
1861 }
1862
1863 if (health && health.current <= 0)
1864 {
1865 clearEngage(world.ecs, attackerId);
1866 clearEngage(world.ecs, targetId);
1867 for (const entity of world.ecs.query(Component.combat))
1868 {
1869 if (entity.combat.targetEntityId === targetId)
1870 { entity.combat.targetEntityId = null; }
1871 }
1872 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
1873 {
1874 const path = world.ecs.get(targetHandle, Component.path);
1875 if (path)
1876 { path.tiles = []; }
1877 const follow = world.ecs.get(targetHandle, Component.follow);
1878 if (follow)
1879 {
1880 follow.targetEntityId = null;
1881 follow.trail = [];
1882 }
1883 world.ecs.add(targetHandle, Component.dead, {});
1884 silenceDeadPlayer(world.ecs, targetHandle);
1885 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
1886 events.push({
1887 type: "player-died",
1888 entityId: targetId,
1889 attackerId,
1890 characterId: targetCharacter.characterId,
1891 sessionId: identity?.sessionId ?? null,
1892 tileX: to.tileX,
1893 tileY: to.tileY,
1894 health: 0,
1895 maxHealth: health.max
1896 });
1897 }
1898 const creature = world.ecs.get(targetHandle, Component.creature);
1899 if (creature && !world.ecs.get(targetHandle, Component.character))
1900 {
1901 events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now));
1902 }
1903 }
1904 return events;
1905}
1906
1907/**
1908 * Drops, despawn, and `mob-killed` for bounty / town-guard reaction.
1909 * Shared by melee and spell kill paths.
1910 */
1911export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now)
1912{
1913 const events = [];
1914 const handle = targetHandle ?? world.ecs.handleOf(targetId);
1915 if (handle == null)
1916 { return events; }
1917 const creature = world.ecs.get(handle, Component.creature);
1918 const origin = world.ecs.get(handle, Component.spawnOrigin);
1919 const appearance = world.ecs.get(handle, Component.appearance);
1920 events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId));
1921 events.push({
1922 type: "mob-killed",
1923 entityId: targetId,
1924 attackerId,
1925 mobTypeId: creature?.mobTypeId ?? null,
1926 level: creature?.level ?? origin?.level ?? 1,
1927 bounty: Math.max(0, origin?.bounty | 0 || 0),
1928 spawnerId: origin?.spawnerId ?? null,
1929 originTileX: origin?.originTileX ?? tileX,
1930 originTileY: origin?.originTileY ?? tileY,
1931 wanderRangeTiles: origin?.wanderRangeTiles ?? 0,
1932 townGuard: !!origin?.townGuard,
1933 displayName: appearance?.firstName ?? null,
1934 tileX,
1935 tileY
1936 });
1937 if (origin?.spawnerId)
1938 {
1939 scheduleSpawnerRespawn(
1940 world,
1941 origin.spawnerId,
1942 origin.respawnDelaySeconds ?? 25,
1943 now
1944 );
1945 }
1946 const view = world.destroyEntity?.(targetId) ?? null;
1947 if (view)
1948 {
1949 events.push({
1950 type: "entity-despawn",
1951 entityId: targetId,
1952 tileX: view.tileX,
1953 tileY: view.tileY
1954 });
1955 }
1956 return events;
1957}
1958
1959/** Apply HP loss and shared death/loot side-effects (used by spell impacts). */
1960export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now())
1961{
1962 const events = [];
1963 const targetHandle = world.ecs.handleOf(targetId);
1964 if (targetHandle == null)
1965 { return events; }
1966 const to = world.ecs.get(targetHandle, Component.position);
1967 if (!to)
1968 { return events; }
1969 const health = world.ecs.get(targetHandle, Component.health);
1970 if (health)
1971 { health.current = Math.max(0, (health.current | 0) - damage); }
1972 events.push({
1973 type: "combat-hit",
1974 attackerId,
1975 targetId,
1976 damage,
1977 tileX: to.tileX,
1978 tileY: to.tileY,
1979 health: health?.current ?? 0,
1980 maxHealth: health?.max ?? 0
1981 });
1982
1983 const attackerHandle = world.ecs.handleOf(attackerId);
1984 if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))
1985 {
1986 const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character);
1987 const targetCombat = world.ecs.get(targetHandle, Component.combat);
1988 if (targetCombat && targetCombat.targetEntityId == null)
1989 { engageTarget(world.ecs, targetId, attackerId, now); }
1990 if (attackerIsPlayer)
1991 { markSeekCover(world.ecs, targetId); }
1992 }
1993 if (attackerHandle != null)
1994 { markFleeOnHit(world, targetId, attackerId); }
1995 if (attackerHandle != null && world.ecs.get(targetHandle, Component.character))
1996 {
1997 const attackerCreature = world.ecs.get(attackerHandle, Component.creature);
1998 if (attackerCreature)
1999 {
2000 engageTarget(world.ecs, targetId, attackerId, now);
2001 }
2002 }
2003
2004 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
2005 if (healthXp)
2006 {
2007 events.push({
2008 type: "skills-updated",
2009 entityId: targetId,
2010 characterId: healthXp.characterId,
2011 skills: healthXp.view,
2012 stored: healthXp.stored,
2013 levelUps: healthXp.levelUps ?? []
2014 });
2015 }
2016
2017 if (health && health.current <= 0)
2018 {
2019 clearEngage(world.ecs, attackerId);
2020 clearEngage(world.ecs, targetId);
2021 for (const entity of world.ecs.query(Component.combat))
2022 {
2023 if (entity.combat.targetEntityId === targetId)
2024 { entity.combat.targetEntityId = null; }
2025 }
2026 const targetCharacter = world.ecs.get(targetHandle, Component.character);
2027 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
2028 {
2029 const path = world.ecs.get(targetHandle, Component.path);
2030 if (path)
2031 { path.tiles = []; }
2032 world.ecs.add(targetHandle, Component.dead, {});
2033 silenceDeadPlayer(world.ecs, targetHandle);
2034 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
2035 events.push({
2036 type: "player-died",
2037 entityId: targetId,
2038 attackerId,
2039 characterId: targetCharacter.characterId,
2040 sessionId: identity?.sessionId ?? null,
2041 tileX: to.tileX,
2042 tileY: to.tileY,
2043 health: 0,
2044 maxHealth: health.max
2045 });
2046 }
2047 const creature = world.ecs.get(targetHandle, Component.creature);
2048 if (creature && !targetCharacter)
2049 { events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); }
2050 }
2051 return events;
2052}