BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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