BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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