BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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