BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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