BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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