BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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