BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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