BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

service.js 19.0 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { itemDefinition } from "../../../shared/definitions/items.js";
3import { mobDefinition } from "../../../shared/definitions/mobs.js";
4import {
5 mobCanFightType,
6 mobMeleeAttackProfile,
7 mobSkillLevels,
8 mobIsAggressive,
9 mobAggroRangeTiles
10} from "../../../shared/definitions/mobCombat.js";
11import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
12import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
13import {
14 effectiveSkillLevel,
15 equipmentBonusesFromSlots
16} from "../../../shared/equipment/stats.js";
17import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
18import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
19import { chunkBoundsAround, findPath } from "../navigation/astar.js";
20import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
21import { rayReaches } from "../../../shared/lighting/raycast.js";
22
23export function chebyshev (ax, ay, bx, by)
24{
25 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
26}
27
28export function attackProfileOf (ecs, handle)
29{
30 const equipment = ecs.get(handle, Component.equipment);
31 const weapon = equipment?.slots?.weapon;
32 if (weapon?.itemId != null)
33 {
34 const attack = itemDefinition(weapon.itemId)?.equipment?.attack;
35 if (attack)
36 { return { ...attack }; }
37 }
38 const creature = ecs.get(handle, Component.creature);
39 if (creature)
40 {
41 const def = mobDefinition(creature.mobTypeId);
42 if (mobCanFightType(creature.mobTypeId))
43 { return mobMeleeAttackProfile(def); }
44 }
45 return { ...UNARMED_ATTACK };
46}
47
48export function ensureMobCombat (ecs, entityId)
49{
50 const handle = ecs.handleOf(entityId);
51 if (handle == null)
52 { return false; }
53 const creature = ecs.get(handle, Component.creature);
54 if (!creature || !mobCanFightType(creature.mobTypeId))
55 { return false; }
56 const def = mobDefinition(creature.mobTypeId);
57 if (!ecs.get(handle, Component.combat))
58 { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
59 if (!ecs.get(handle, Component.skills))
60 { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def) }); }
61 return true;
62}
63
64function attackerSkillLevel (skills, profile, skillId)
65{
66 if (profile.mobAttackSkill != null)
67 { return profile.mobAttackSkill; }
68 return skillLevel(skills, skillId);
69}
70
71function defenderSkillLevel (skills, skillId, equipment = null)
72{
73 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots) : {};
74 return effectiveSkillLevel(skills, skillId, bonuses);
75}
76
77function playerCombatLevels (ecs, handle, profile)
78{
79 const skills = ecs.get(handle, Component.skills);
80 const equipment = ecs.get(handle, Component.equipment);
81 const bonuses = equipmentBonusesFromSlots(equipment?.slots);
82 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
83 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
84 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
85 return {
86 hitLevel: skillLevel(skills, profile.hitSkillId),
87 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
88 agilityLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses),
89 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
90 };
91}
92
93export function isUntargetable (ecs, handle)
94{
95 const creature = ecs.get(handle, Component.creature);
96 if (!creature)
97 { return false; }
98 return !!mobDefinition(creature.mobTypeId)?.untargetable;
99}
100
101export function engageTarget (ecs, attackerId, targetId, now = Date.now())
102{
103 const handle = ecs.handleOf(attackerId);
104 if (handle == null)
105 { return false; }
106 let combat = ecs.get(handle, Component.combat);
107 if (!combat)
108 { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
109 const targetChanged = combat.targetEntityId !== targetId;
110 combat.targetEntityId = targetId;
111 if (targetChanged)
112 {
113 // New engage (or switch): allow an immediate swing; keep cadence if already on this target.
114 combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
115 const path = ecs.get(handle, Component.path);
116 if (path)
117 { path.tiles = []; }
118 }
119 return true;
120}
121
122export function clearEngage (ecs, entityId)
123{
124 const handle = ecs.handleOf(entityId);
125 const combat = handle != null ? ecs.get(handle, Component.combat) : null;
126 if (combat)
127 { combat.targetEntityId = null; }
128}
129
130export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
131{
132 return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y));
133}
134
135/**
136 * Aggressive mobs auto-engage the nearest player character within aggro range
137 * when they have line of sight. Does nothing while already engaged.
138 */
139export function stepAggression (world, now = Date.now())
140{
141 for (const entity of world.ecs.query(Component.creature, Component.position))
142 {
143 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
144 { continue; }
145 const def = mobDefinition(entity.creature.mobTypeId);
146 if (!mobIsAggressive(def))
147 { continue; }
148 if (world.ecs.has(entity.handle, Component.dead))
149 { continue; }
150 const health = world.ecs.get(entity.handle, Component.health);
151 if (health && health.current <= 0)
152 { continue; }
153 const combat = world.ecs.get(entity.handle, Component.combat);
154 if (combat?.targetEntityId != null)
155 { continue; }
156
157 const range = mobAggroRangeTiles(def);
158 let bestId = null;
159 let bestDist = Infinity;
160 for (const player of world.ecs.query(Component.character, Component.position))
161 {
162 if (world.ecs.has(player.handle, Component.dead))
163 { continue; }
164 const playerHealth = world.ecs.get(player.handle, Component.health);
165 if (playerHealth && playerHealth.current <= 0)
166 { continue; }
167 const dist = chebyshev(
168 entity.position.tileX,
169 entity.position.tileY,
170 player.position.tileX,
171 player.position.tileY
172 );
173 if (dist < 1 || dist > range)
174 { continue; }
175 if (!hasCombatLineOfSight(
176 world,
177 entity.position.tileX,
178 entity.position.tileY,
179 player.position.tileX,
180 player.position.tileY
181 ))
182 { continue; }
183 if (dist < bestDist)
184 {
185 bestDist = dist;
186 bestId = player.entityId;
187 }
188 }
189 if (bestId == null)
190 { continue; }
191 if (!ensureMobCombat(world.ecs, entity.entityId))
192 { continue; }
193 engageTarget(world.ecs, entity.entityId, bestId, now);
194 }
195}
196
197/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
198export function resolveCombatTarget (world, targetId)
199{
200 const handle = world.ecs.handleOf(targetId);
201 if (handle != null)
202 {
203 const pos = world.ecs.get(handle, Component.position);
204 if (!pos)
205 { return null; }
206 if (isUntargetable(world.ecs, handle))
207 { return null; }
208 return {
209 local: true,
210 handle,
211 pos,
212 health: world.ecs.get(handle, Component.health)
213 };
214 }
215 const ghost = world.ghosts?.get?.(targetId);
216 if (!ghost || ghost.untargetable)
217 { return null; }
218 const health = ghost.health != null
219 ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health }
220 : null;
221 return {
222 local: false,
223 handle: null,
224 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
225 health
226 };
227}
228
229function attackerCombatLevels (ecs, attackerHandle, profile)
230{
231 const attackerCharacter = ecs.get(attackerHandle, Component.character);
232 if (attackerCharacter)
233 { return playerCombatLevels(ecs, attackerHandle, profile); }
234 const skills = ecs.get(attackerHandle, Component.skills);
235 return {
236 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
237 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
238 agilityLevel: skillLevel(skills, SkillId.dexterity),
239 defenceLevel: skillLevel(skills, SkillId.defence)
240 };
241}
242
243export function stepCombat (world, now = Date.now())
244{
245 const events = [];
246 for (const entity of world.ecs.query(Component.combat, Component.position))
247 {
248 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
249 { continue; }
250 const combat = entity.combat;
251 const targetId = combat.targetEntityId;
252 if (targetId == null)
253 { continue; }
254 const target = resolveCombatTarget(world, targetId);
255 if (!target)
256 {
257 combat.targetEntityId = null;
258 continue;
259 }
260 if (target.health && target.health.current <= 0)
261 {
262 combat.targetEntityId = null;
263 continue;
264 }
265
266 const profile = attackProfileOf(world.ecs, entity.handle);
267 if (profile.mode !== "melee")
268 { continue; }
269
270 const targetPos = target.pos;
271 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
272 const canSwing = dist === 1
273 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
274 if (!canSwing)
275 {
276 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
277 continue;
278 }
279 clearCombatApproachPath(world.ecs, entity.handle);
280 const attackerHealth = world.ecs.get(entity.handle, Component.health);
281 if (attackerHealth && attackerHealth.current <= 0)
282 { continue; }
283 if ((combat.nextSwingAt || 0) > now)
284 { continue; }
285
286 combat.nextSwingAt = now + (profile.cooldownMs || 800);
287 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
288 }
289 return events;
290}
291
292function clearCombatApproachPath (ecs, handle)
293{
294 const path = ecs.get(handle, Component.path);
295 if (path?.tiles?.length)
296 { path.tiles = []; }
297}
298
299function queueMeleeApproach (world, entityId, handle, position, targetPos)
300{
301 if (world.frozen?.has?.(entityId))
302 { return; }
303 let path = world.ecs.get(handle, Component.path);
304 if (!path)
305 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
306
307 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY)
308 ?? true;
309 if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere)
310 {
311 path.tiles = [];
312 return;
313 }
314
315 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
316 if (!goal)
317 {
318 path.tiles = [];
319 return;
320 }
321
322 if (goal.x === position.tileX && goal.y === position.tileY)
323 {
324 path.tiles = [];
325 return;
326 }
327
328 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))
329 { return; }
330
331 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
332 const preferVertical = !!world.ecs.get(handle, Component.character);
333 const tiles = findPath(
334 position.tileX,
335 position.tileY,
336 goal.x,
337 goal.y,
338 (x, y) =>
339 {
340 if (x === goal.x && y === goal.y)
341 {
342 return world.isClearStanding?.(entityId, x, y)
343 ?? world.walkableFor(entityId, x, y);
344 }
345 return world.walkableFor(entityId, x, y);
346 },
347 bounds.minX,
348 bounds.minY,
349 bounds.maxX,
350 bounds.maxY,
351 { preferVertical }
352 );
353 if (!tiles.length)
354 {
355 path.tiles = [];
356 return;
357 }
358 path.tiles = tiles;
359 const movement = world.ecs.get(handle, Component.movement);
360 if (movement)
361 { movement.walkCarry = 0; }
362}
363
364function meleePathStale (world, entityId, position, targetPos, path, goal)
365{
366 const dest = path.tiles[path.tiles.length - 1];
367 if (dest.x !== goal.x || dest.y !== goal.y)
368 { return true; }
369 if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)
370 { return true; }
371 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
372 { return true; }
373 const next = path.tiles[0];
374 if (!next)
375 { return true; }
376 return !world.walkableFor(entityId, next.x, next.y);
377}
378
379function bestAdjacentGoal (world, entityId, position, targetPos)
380{
381 const dirs = [
382 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
383 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
384 ];
385 let best = null;
386 let bestDist = Infinity;
387 for (const dir of dirs)
388 {
389 const x = targetPos.tileX + dir.x;
390 const y = targetPos.tileY + dir.y;
391 const isHere = x === position.tileX && y === position.tileY;
392 const clear = world.isClearStanding?.(entityId, x, y)
393 ?? world.walkableFor(entityId, x, y);
394 if (!clear && !isHere)
395 { continue; }
396 if (isHere && !(world.isClearStanding?.(entityId, x, y) ?? true))
397 { continue; }
398 const dist = chebyshev(position.tileX, position.tileY, x, y);
399 if (dist < bestDist)
400 {
401 bestDist = dist;
402 best = { x, y };
403 }
404 }
405 return best;
406}
407
408export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
409{
410 const events = [];
411 const attackerHandle = world.ecs.handleOf(attackerId);
412 if (attackerHandle == null)
413 { return events; }
414 const target = resolveCombatTarget(world, targetId);
415 if (!target)
416 { return events; }
417 const from = world.ecs.get(attackerHandle, Component.position);
418 const to = target.pos;
419 if (!from || !to)
420 { return events; }
421 if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)
422 { return events; }
423 if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY))
424 { return events; }
425
426 events.push({
427 type: "combat-swing",
428 attackerId,
429 targetId,
430 tileX: to.tileX,
431 tileY: to.tileY,
432 fromTileX: from.tileX,
433 fromTileY: from.tileY
434 });
435
436 if (!target.local)
437 {
438 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
439 events.push({
440 type: "remote-melee-resolve",
441 attackerId,
442 targetId,
443 profile,
444 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
445 attackerIsPlayer: !!attackerCharacter,
446 now,
447 tileX: to.tileX,
448 tileY: to.tileY
449 });
450 return events;
451 }
452
453 return events.concat(applyLocalMeleeHit(
454 world,
455 attackerId,
456 targetId,
457 attackerHandle,
458 target.handle,
459 profile,
460 now,
461 to
462 ));
463}
464
465/** Authoritative hit resolution when the defender lives on this worker. */
466export function applyRemoteMeleeSwing (world, payload)
467{
468 const targetHandle = world.ecs.handleOf(payload.targetId);
469 if (targetHandle == null)
470 { return { events: [], forwards: [] }; }
471 const to = world.ecs.get(targetHandle, Component.position);
472 if (!to)
473 { return { events: [], forwards: [] }; }
474
475 const events = applyLocalMeleeHit(
476 world,
477 payload.attackerId,
478 payload.targetId,
479 null,
480 targetHandle,
481 payload.profile,
482 payload.now ?? Date.now(),
483 to,
484 payload.attackerLevels,
485 payload.attackerIsPlayer
486 );
487
488 const forwards = [];
489 const hitEvent = events.find((event) => event.type === "combat-hit");
490 if (hitEvent && payload.attackerIsPlayer)
491 {
492 forwards.push({
493 type: "forward-combat-xp",
494 entityId: payload.attackerId,
495 profile: payload.profile
496 });
497 }
498 return { events, forwards };
499}
500
501function applyLocalMeleeHit (
502 world,
503 attackerId,
504 targetId,
505 attackerHandle,
506 targetHandle,
507 profile,
508 now,
509 to,
510 attackerLevelsOverride = null,
511 attackerIsPlayerOverride = null
512)
513{
514 const events = [];
515 if (targetHandle == null)
516 { return events; }
517
518 const attackerIsPlayer = attackerIsPlayerOverride != null
519 ? !!attackerIsPlayerOverride
520 : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);
521
522 // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
523 if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))
524 { engageTarget(world.ecs, targetId, attackerId, now); }
525 if (attackerIsPlayer === false)
526 {
527 const targetCharacter = world.ecs.get(targetHandle, Component.character);
528 if (targetCharacter)
529 {
530 engageTarget(world.ecs, targetId, attackerId, now);
531 const follow = world.ecs.get(targetHandle, Component.follow);
532 if (follow)
533 {
534 follow.targetEntityId = null;
535 follow.trail = [];
536 }
537 if (world.ecs.has(targetHandle, Component.gather))
538 { world.ecs.remove(targetHandle, Component.gather); }
539 }
540 }
541
542 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
543 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
544 const attackerLevels = attackerLevelsOverride
545 ?? (attackerHandle != null ? attackerCombatLevels(world.ecs, attackerHandle, profile) : null);
546 if (!attackerLevels)
547 { return events; }
548
549 const agilityLevel = defenderSkillLevel(
550 defenderSkills,
551 SkillId.dexterity,
552 defenderEquipment
553 );
554 const defenceLevel = defenderSkillLevel(
555 defenderSkills,
556 SkillId.defence,
557 defenderEquipment
558 );
559
560 const resolved = resolvePhysicalAttack({
561 hitSkillLevel: attackerLevels.hitLevel,
562 agilitySkillLevel: agilityLevel,
563 damageSkillLevel: attackerLevels.damageLevel,
564 defenceSkillLevel: defenceLevel,
565 baseDamage: profile.baseDamage ?? 1
566 });
567
568 if (resolved.outcome === "miss")
569 {
570 events.push({
571 type: "combat-miss",
572 attackerId,
573 targetId,
574 tileX: to.tileX,
575 tileY: to.tileY
576 });
577 return events;
578 }
579
580 if (resolved.outcome === "block")
581 {
582 events.push({
583 type: "combat-block",
584 attackerId,
585 targetId,
586 tileX: to.tileX,
587 tileY: to.tileY
588 });
589 return events;
590 }
591
592 const damage = resolved.damage;
593 const targetCharacter = world.ecs.get(targetHandle, Component.character);
594 if (targetCharacter)
595 { syncPlayerHealth(world.ecs, targetHandle); }
596 const health = world.ecs.get(targetHandle, Component.health);
597 if (health)
598 {
599 health.current = Math.max(0, (health.current | 0) - damage);
600 }
601 events.push({
602 type: "combat-hit",
603 attackerId,
604 targetId,
605 damage,
606 tileX: to.tileX,
607 tileY: to.tileY,
608 health: health?.current ?? 0,
609 maxHealth: health?.max ?? 0
610 });
611
612 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
613 if (healthXp)
614 {
615 events.push({
616 type: "skills-updated",
617 entityId: targetId,
618 characterId: healthXp.characterId,
619 skills: healthXp.view,
620 stored: healthXp.stored,
621 levelUps: healthXp.levelUps ?? []
622 });
623 if (health)
624 {
625 const hitEvent = events[events.length - 2];
626 if (hitEvent?.type === "combat-hit")
627 {
628 hitEvent.health = health.current;
629 hitEvent.maxHealth = health.max;
630 }
631 }
632 }
633
634 if (attackerHandle != null)
635 {
636 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
637 if (attackerCharacter)
638 {
639 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile);
640 if (xpAward)
641 {
642 events.push({
643 type: "skills-updated",
644 entityId: attackerId,
645 characterId: attackerCharacter.characterId,
646 skills: xpAward.view,
647 stored: xpAward.stored,
648 levelUps: xpAward.levelUps ?? []
649 });
650 }
651 }
652 }
653
654 if (health && health.current <= 0)
655 {
656 clearEngage(world.ecs, attackerId);
657 clearEngage(world.ecs, targetId);
658 for (const entity of world.ecs.query(Component.combat))
659 {
660 if (entity.combat.targetEntityId === targetId)
661 { entity.combat.targetEntityId = null; }
662 }
663 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
664 {
665 const path = world.ecs.get(targetHandle, Component.path);
666 if (path)
667 { path.tiles = []; }
668 const follow = world.ecs.get(targetHandle, Component.follow);
669 if (follow)
670 {
671 follow.targetEntityId = null;
672 follow.trail = [];
673 }
674 world.ecs.add(targetHandle, Component.dead, {});
675 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
676 events.push({
677 type: "player-died",
678 entityId: targetId,
679 attackerId,
680 characterId: targetCharacter.characterId,
681 sessionId: identity?.sessionId ?? null,
682 tileX: to.tileX,
683 tileY: to.tileY,
684 health: 0,
685 maxHealth: health.max
686 });
687 }
688 const creature = world.ecs.get(targetHandle, Component.creature);
689 if (creature && !world.ecs.get(targetHandle, Component.character))
690 {
691 const view = world.destroyEntity?.(targetId) ?? null;
692 if (view)
693 {
694 events.push({
695 type: "entity-despawn",
696 entityId: targetId,
697 tileX: view.tileX,
698 tileY: view.tileY
699 });
700 }
701 }
702 }
703 return events;
704}