BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

service.js 29.5 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 {
13 effectiveHitSkillInDarkness,
14 aggroDistanceMultiplier
15} from "../../../shared/combat/darkness.js";
16import {
17 bakedTileLight01,
18 entityLightAtTile,
19 tileCombatLight01,
20 tileIndexLocal
21} from "../../../shared/lighting/combatLight.js";
22import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
23import {
24 effectiveSkillLevel,
25 equipmentBonusesFromSlots
26} from "../../../shared/equipment/stats.js";
27import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
28import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
29import { chunkBoundsAround, findPath } from "../navigation/astar.js";
30import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
31import { rayReaches } from "../../../shared/lighting/raycast.js";
32import { tileToChunk } from "../world/coordinates.js";
33import { stackQuantity } from "../../../shared/items/inventory.js";
34import { addGroundItem, publicGroundItem } from "../items/bags.js";
35import { resolveItemDualTint } from "../../../shared/render/tint.js";
36
37export function chebyshev (ax, ay, bx, by)
38{
39 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
40}
41
42export function attackProfileOf (ecs, handle)
43{
44 const equipment = ecs.get(handle, Component.equipment);
45 const weapon = equipment?.slots?.weapon;
46 if (weapon?.itemId != null)
47 {
48 const attack = itemDefinition(weapon.itemId)?.equipment?.attack;
49 if (attack)
50 { return { ...attack }; }
51 }
52 const creature = ecs.get(handle, Component.creature);
53 if (creature)
54 {
55 const def = mobDefinition(creature.mobTypeId);
56 if (mobCanFightType(creature.mobTypeId))
57 { return mobMeleeAttackProfile(def); }
58 }
59 return { ...UNARMED_ATTACK };
60}
61
62export function ensureMobCombat (ecs, entityId)
63{
64 const handle = ecs.handleOf(entityId);
65 if (handle == null)
66 { return false; }
67 const creature = ecs.get(handle, Component.creature);
68 if (!creature || !mobCanFightType(creature.mobTypeId))
69 { return false; }
70 const def = mobDefinition(creature.mobTypeId);
71 if (!ecs.get(handle, Component.combat))
72 { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
73 if (!ecs.get(handle, Component.skills))
74 { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def) }); }
75 return true;
76}
77
78function attackerSkillLevel (skills, profile, skillId)
79{
80 if (profile.mobAttackSkill != null)
81 { return profile.mobAttackSkill; }
82 return skillLevel(skills, skillId);
83}
84
85function defenderSkillLevel (skills, skillId, equipment = null)
86{
87 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots) : {};
88 return effectiveSkillLevel(skills, skillId, bonuses);
89}
90
91function playerCombatLevels (ecs, handle, profile)
92{
93 const skills = ecs.get(handle, Component.skills);
94 const equipment = ecs.get(handle, Component.equipment);
95 const bonuses = equipmentBonusesFromSlots(equipment?.slots);
96 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
97 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
98 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
99
100 return {
101 hitLevel: skillLevel(skills, profile.hitSkillId ?? SkillId.unarmed),
102 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId ?? SkillId.strength, bonuses),
103 agilityLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses),
104 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
105 };
106}
107
108export function isUntargetable (ecs, handle)
109{
110 const creature = ecs.get(handle, Component.creature);
111 if (!creature)
112 { return false; }
113 return !!mobDefinition(creature.mobTypeId)?.untargetable;
114}
115
116export function engageTarget (ecs, attackerId, targetId, now = Date.now())
117{
118 const handle = ecs.handleOf(attackerId);
119 if (handle == null)
120 { return false; }
121 let combat = ecs.get(handle, Component.combat);
122 if (!combat)
123 { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
124 const targetChanged = combat.targetEntityId !== targetId;
125 combat.targetEntityId = targetId;
126 if (targetChanged)
127 {
128 // New engage (or switch): allow an immediate swing; keep cadence if already on this target.
129 combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
130 const path = ecs.get(handle, Component.path);
131 if (path)
132 { path.tiles = []; }
133 }
134 return true;
135}
136
137export function clearEngage (ecs, entityId)
138{
139 const handle = ecs.handleOf(entityId);
140 const combat = handle != null ? ecs.get(handle, Component.combat) : null;
141 if (combat)
142 { combat.targetEntityId = null; }
143}
144
145export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
146{
147 return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y));
148}
149
150/** Target-tile lighting 0–1 (baked + entity lights + time of day). */
151export function tileLightAt (world, tileX, tileY, now = Date.now())
152{
153 const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY));
154 const index = tileIndexLocal(tileX, tileY);
155 const baked = bakedTileLight01(data?.light, index);
156 const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now);
157 const worldTime = world.worldTime?.(now);
158 return tileCombatLight01({
159 bakedLight01: baked,
160 entityLight01: entity,
161 worldHour: worldTime?.hour ?? 12,
162 nightDarkness: world.settings?.nightDarkness ?? 0.72
163 });
164}
165
166function arrowStackInOffhand (equipment)
167{
168 const stack = equipment?.slots?.offhand;
169 if (!stack)
170 { return null; }
171 const def = itemDefinition(stack.itemId);
172 if (def?.equipment?.kind !== EquipmentKind.arrowAmmo)
173 { return null; }
174 return stack;
175}
176
177function consumeArrow (ecs, handle)
178{
179 const equipment = ecs.get(handle, Component.equipment);
180 const stack = arrowStackInOffhand(equipment);
181 if (!stack || stackQuantity(stack.quantity) <= 0)
182 { return false; }
183 if (stackQuantity(stack.quantity) <= 1)
184 { equipment.slots.offhand = null; }
185 else
186 { stack.quantity = stackQuantity(stack.quantity) - 1; }
187 return true;
188}
189
190function spawnMobDrops (world, targetHandle, tileX, tileY, now)
191{
192 const creature = world.ecs.get(targetHandle, Component.creature);
193 if (!creature)
194 { return []; }
195 const def = mobDefinition(creature.mobTypeId);
196 const events = [];
197 for (const drop of def?.drops ?? [])
198 {
199 if (Math.random() > (drop.chance ?? 1))
200 { continue; }
201 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
202 const item = {
203 groundItemId,
204 tileX,
205 tileY,
206 stack: { itemId: drop.itemId, quantity: drop.quantity ?? 1 },
207 droppedAt: now,
208 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
209 source: "mob-drop"
210 };
211 addGroundItem(world, item);
212 events.push({
213 type: "ground-item-appear",
214 ...publicGroundItem(item),
215 stack: item.stack,
216 droppedAt: item.droppedAt,
217 source: item.source,
218 expiresAt: item.expiresAt
219 });
220 }
221 return events;
222}
223
224function projectileDualTintFromAttacker (ecs, handle)
225{
226 const equipment = ecs.get(handle, Component.equipment);
227 const stack = arrowStackInOffhand(equipment);
228 if (!stack)
229 { return null; }
230 return resolveItemDualTint(stack, itemDefinition(stack.itemId));
231}
232
233function publicDualTint (dualTint)
234{
235 if (!dualTint)
236 { return null; }
237 return {
238 shaftTint: dualTint.shaft,
239 tipTint: dualTint.tip
240 };
241}
242
243function missProjectileTile (targetTileX, targetTileY, rng = Math.random)
244{
245 const angle = rng() * Math.PI * 2;
246 const dist = rng();
247 return {
248 tileX: Math.round(targetTileX + Math.cos(angle) * dist),
249 tileY: Math.round(targetTileY + Math.sin(angle) * dist)
250 };
251}
252
253/**
254 * Aggressive mobs auto-engage the nearest player character within aggro range
255 * when they have line of sight. Does nothing while already engaged.
256 */
257export function stepAggression (world, now = Date.now())
258{
259 for (const entity of world.ecs.query(Component.creature, Component.position))
260 {
261 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
262 { continue; }
263 const def = mobDefinition(entity.creature.mobTypeId);
264 if (!mobIsAggressive(def))
265 { continue; }
266 if (world.ecs.has(entity.handle, Component.dead))
267 { continue; }
268 const health = world.ecs.get(entity.handle, Component.health);
269 if (health && health.current <= 0)
270 { continue; }
271 const combat = world.ecs.get(entity.handle, Component.combat);
272 if (combat?.targetEntityId != null)
273 { continue; }
274
275 const range = mobAggroRangeTiles(def);
276 let bestId = null;
277 let bestDist = Infinity;
278 for (const player of world.ecs.query(Component.character, Component.position))
279 {
280 if (world.ecs.has(player.handle, Component.dead))
281 { continue; }
282 const playerHealth = world.ecs.get(player.handle, Component.health);
283 if (playerHealth && playerHealth.current <= 0)
284 { continue; }
285 const dist = chebyshev(
286 entity.position.tileX,
287 entity.position.tileY,
288 player.position.tileX,
289 player.position.tileY
290 );
291 if (dist < 1 || dist > range)
292 { continue; }
293 let effectiveDist = dist;
294 if (dist > 1)
295 {
296 const light = tileLightAt(world, player.position.tileX, player.position.tileY);
297 effectiveDist = dist * aggroDistanceMultiplier(light);
298 }
299 if (effectiveDist > range)
300 { continue; }
301 if (!hasCombatLineOfSight(
302 world,
303 entity.position.tileX,
304 entity.position.tileY,
305 player.position.tileX,
306 player.position.tileY
307 ))
308 { continue; }
309 if (dist < bestDist)
310 {
311 bestDist = dist;
312 bestId = player.entityId;
313 }
314 }
315 if (bestId == null)
316 { continue; }
317 if (!ensureMobCombat(world.ecs, entity.entityId))
318 { continue; }
319 engageTarget(world.ecs, entity.entityId, bestId, now);
320 }
321}
322
323/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
324export function resolveCombatTarget (world, targetId)
325{
326 const handle = world.ecs.handleOf(targetId);
327 if (handle != null)
328 {
329 const pos = world.ecs.get(handle, Component.position);
330 if (!pos)
331 { return null; }
332 if (isUntargetable(world.ecs, handle))
333 { return null; }
334 return {
335 local: true,
336 handle,
337 pos,
338 health: world.ecs.get(handle, Component.health)
339 };
340 }
341 const ghost = world.ghosts?.get?.(targetId);
342 if (!ghost || ghost.untargetable)
343 { return null; }
344 const health = ghost.health != null
345 ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health }
346 : null;
347 return {
348 local: false,
349 handle: null,
350 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
351 health
352 };
353}
354
355function attackerCombatLevels (ecs, attackerHandle, profile)
356{
357 const attackerCharacter = ecs.get(attackerHandle, Component.character);
358 if (attackerCharacter)
359 { return playerCombatLevels(ecs, attackerHandle, profile); }
360 const skills = ecs.get(attackerHandle, Component.skills);
361 return {
362 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
363 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
364 agilityLevel: skillLevel(skills, SkillId.dexterity),
365 defenceLevel: skillLevel(skills, SkillId.defence)
366 };
367}
368
369export function stepCombat (world, now = Date.now())
370{
371 const events = [];
372 for (const entity of world.ecs.query(Component.combat, Component.position))
373 {
374 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
375 { continue; }
376 const combat = entity.combat;
377 const targetId = combat.targetEntityId;
378 if (targetId == null)
379 { continue; }
380 const target = resolveCombatTarget(world, targetId);
381 if (!target)
382 {
383 combat.targetEntityId = null;
384 continue;
385 }
386 if (target.health && target.health.current <= 0)
387 {
388 combat.targetEntityId = null;
389 continue;
390 }
391
392 const profile = attackProfileOf(world.ecs, entity.handle);
393 const targetPos = target.pos;
394
395 if (profile.mode === "ranged")
396 {
397 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
398 const maxRange = profile.rangeTiles | 0 || 8;
399 const equipment = world.ecs.get(entity.handle, Component.equipment);
400 const hasArrows = arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0;
401 const inRange = dist >= 1 && dist <= maxRange
402 && hasCombatLineOfSight(
403 world,
404 entity.position.tileX,
405 entity.position.tileY,
406 targetPos.tileX,
407 targetPos.tileY
408 );
409 if (!inRange || !hasArrows)
410 {
411 if (inRange && !hasArrows && now >= (combat.nextSwingAt || 0)
412 && world.ecs.get(entity.handle, Component.character))
413 {
414 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
415 events.push({
416 type: "combat-no-arrows",
417 attackerId: entity.entityId,
418 sessionId: world.ecs.get(entity.handle, Component.networkIdentity)?.sessionId ?? null
419 });
420 }
421 queueRangedApproach(world, entity.entityId, entity.handle, entity.position, targetPos, maxRange);
422 continue;
423 }
424 clearCombatApproachPath(world.ecs, entity.handle);
425 if (now < (combat.nextSwingAt || 0))
426 { continue; }
427 combat.nextSwingAt = now + (profile.cooldownMs | 0 || 1200);
428 events.push(...resolveRangedShot(world, entity.entityId, targetId, profile, now, targetPos));
429 continue;
430 }
431
432 if (profile.mode !== "melee")
433 { continue; }
434
435 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
436 const canSwing = dist === 1
437 && world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
438 if (!canSwing)
439 {
440 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
441 continue;
442 }
443 clearCombatApproachPath(world.ecs, entity.handle);
444 const attackerHealth = world.ecs.get(entity.handle, Component.health);
445 if (attackerHealth && attackerHealth.current <= 0)
446 { continue; }
447 if ((combat.nextSwingAt || 0) > now)
448 { continue; }
449
450 combat.nextSwingAt = now + (profile.cooldownMs || 800);
451 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
452 }
453 return events;
454}
455
456function clearCombatApproachPath (ecs, handle)
457{
458 const path = ecs.get(handle, Component.path);
459 if (path?.tiles?.length)
460 { path.tiles = []; }
461}
462
463function queueMeleeApproach (world, entityId, handle, position, targetPos)
464{
465 if (world.frozen?.has?.(entityId))
466 { return; }
467 let path = world.ecs.get(handle, Component.path);
468 if (!path)
469 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
470
471 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY)
472 ?? true;
473 if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere)
474 {
475 path.tiles = [];
476 return;
477 }
478
479 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
480 if (!goal)
481 {
482 path.tiles = [];
483 return;
484 }
485
486 if (goal.x === position.tileX && goal.y === position.tileY)
487 {
488 path.tiles = [];
489 return;
490 }
491
492 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))
493 { return; }
494
495 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
496 const preferVertical = !!world.ecs.get(handle, Component.character);
497 const tiles = findPath(
498 position.tileX,
499 position.tileY,
500 goal.x,
501 goal.y,
502 (x, y) =>
503 {
504 if (x === goal.x && y === goal.y)
505 {
506 return world.isClearStanding?.(entityId, x, y)
507 ?? world.walkableFor(entityId, x, y);
508 }
509 return world.walkableFor(entityId, x, y);
510 },
511 bounds.minX,
512 bounds.minY,
513 bounds.maxX,
514 bounds.maxY,
515 { preferVertical }
516 );
517 if (!tiles.length)
518 {
519 path.tiles = [];
520 return;
521 }
522 path.tiles = tiles;
523 const movement = world.ecs.get(handle, Component.movement);
524 if (movement)
525 { movement.walkCarry = 0; }
526}
527
528function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
529{
530 if (world.frozen?.has?.(entityId))
531 { return; }
532 let path = world.ecs.get(handle, Component.path);
533 if (!path)
534 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
535
536 const dist = chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY);
537 if (dist >= 1 && dist <= maxRange && hasCombatLineOfSight(
538 world, position.tileX, position.tileY, targetPos.tileX, targetPos.tileY
539 ))
540 {
541 path.tiles = [];
542 return;
543 }
544
545 let bestGoal = null;
546 let bestDist = Infinity;
547 for (let dy = -maxRange; dy <= maxRange; dy++)
548 {
549 for (let dx = -maxRange; dx <= maxRange; dx++)
550 {
551 const x = targetPos.tileX + dx;
552 const y = targetPos.tileY + dy;
553 const toTarget = chebyshev(x, y, targetPos.tileX, targetPos.tileY);
554 if (toTarget < 1 || toTarget > maxRange)
555 { continue; }
556 if (!world.walkableFor(entityId, x, y))
557 { continue; }
558 if (!hasCombatLineOfSight(world, x, y, targetPos.tileX, targetPos.tileY))
559 { continue; }
560 const d = chebyshev(position.tileX, position.tileY, x, y);
561 if (d < bestDist)
562 {
563 bestDist = d;
564 bestGoal = { x, y };
565 }
566 }
567 }
568 if (!bestGoal)
569 {
570 path.tiles = [];
571 return;
572 }
573 if (bestGoal.x === position.tileX && bestGoal.y === position.tileY)
574 {
575 path.tiles = [];
576 return;
577 }
578 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
579 const preferVertical = !!world.ecs.get(handle, Component.character);
580 const tiles = findPath(
581 position.tileX,
582 position.tileY,
583 bestGoal.x,
584 bestGoal.y,
585 (x, y) => world.walkableFor(entityId, x, y),
586 bounds.minX,
587 bounds.minY,
588 bounds.maxX,
589 bounds.maxY,
590 { preferVertical }
591 );
592 path.tiles = tiles.length ? tiles : [];
593 const movement = world.ecs.get(handle, Component.movement);
594 if (movement)
595 { movement.walkCarry = 0; }
596}
597
598export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
599{
600 const events = [];
601 const attackerHandle = world.ecs.handleOf(attackerId);
602 if (attackerHandle == null)
603 { return events; }
604 const from = world.ecs.get(attackerHandle, Component.position);
605 if (!from || !targetPos)
606 { return events; }
607 if (!consumeArrow(world.ecs, attackerHandle))
608 { return events; }
609
610 const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY };
611 const target = resolveCombatTarget(world, targetId);
612 if (!target)
613 { return events; }
614
615 if (!target.local)
616 {
617 events.push({
618 type: "remote-ranged-resolve",
619 attackerId,
620 targetId,
621 profile,
622 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
623 attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character),
624 now,
625 tileX: snapshot.tileX,
626 tileY: snapshot.tileY,
627 fromTileX: from.tileX,
628 fromTileY: from.tileY,
629 ...(publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {})
630 });
631 return events;
632 }
633
634 const hitEvents = applyLocalMeleeHit(
635 world,
636 attackerId,
637 targetId,
638 attackerHandle,
639 target.handle,
640 profile,
641 now,
642 snapshot
643 );
644 const outcome = hitEvents.find((e) =>
645 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
646 let endX = snapshot.tileX;
647 let endY = snapshot.tileY;
648 if (outcome?.type === "combat-miss")
649 {
650 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
651 endX = miss.tileX;
652 endY = miss.tileY;
653 }
654 else
655 {
656 const currentPos = world.ecs.get(target.handle, Component.position);
657 if (currentPos)
658 {
659 endX = currentPos.tileX;
660 endY = currentPos.tileY;
661 }
662 }
663 events.push({
664 type: "combat-projectile",
665 attackerId,
666 targetId,
667 fromTileX: from.tileX,
668 fromTileY: from.tileY,
669 tileX: endX,
670 tileY: endY,
671 durationMs: 400,
672 ...publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}
673 });
674 return events.concat(hitEvents);
675}
676
677function meleePathStale (world, entityId, position, targetPos, path, goal)
678{
679 const dest = path.tiles[path.tiles.length - 1];
680 if (dest.x !== goal.x || dest.y !== goal.y)
681 { return true; }
682 if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)
683 { return true; }
684 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
685 { return true; }
686 const next = path.tiles[0];
687 if (!next)
688 { return true; }
689 return !world.walkableFor(entityId, next.x, next.y);
690}
691
692function bestAdjacentGoal (world, entityId, position, targetPos)
693{
694 const dirs = [
695 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
696 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
697 ];
698 let best = null;
699 let bestDist = Infinity;
700 for (const dir of dirs)
701 {
702 const x = targetPos.tileX + dir.x;
703 const y = targetPos.tileY + dir.y;
704 const isHere = x === position.tileX && y === position.tileY;
705 const clear = world.isClearStanding?.(entityId, x, y)
706 ?? world.walkableFor(entityId, x, y);
707 if (!clear && !isHere)
708 { continue; }
709 if (isHere && !(world.isClearStanding?.(entityId, x, y) ?? true))
710 { continue; }
711 const dist = chebyshev(position.tileX, position.tileY, x, y);
712 if (dist < bestDist)
713 {
714 bestDist = dist;
715 best = { x, y };
716 }
717 }
718 return best;
719}
720
721export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
722{
723 const events = [];
724 const attackerHandle = world.ecs.handleOf(attackerId);
725 if (attackerHandle == null)
726 { return events; }
727 const target = resolveCombatTarget(world, targetId);
728 if (!target)
729 { return events; }
730 const from = world.ecs.get(attackerHandle, Component.position);
731 const to = target.pos;
732 if (!from || !to)
733 { return events; }
734 if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)
735 { return events; }
736 if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY))
737 { return events; }
738
739 events.push({
740 type: "combat-swing",
741 attackerId,
742 targetId,
743 tileX: to.tileX,
744 tileY: to.tileY,
745 fromTileX: from.tileX,
746 fromTileY: from.tileY
747 });
748
749 if (!target.local)
750 {
751 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
752 events.push({
753 type: "remote-melee-resolve",
754 attackerId,
755 targetId,
756 profile,
757 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
758 attackerIsPlayer: !!attackerCharacter,
759 now,
760 tileX: to.tileX,
761 tileY: to.tileY
762 });
763 return events;
764 }
765
766 return events.concat(applyLocalMeleeHit(
767 world,
768 attackerId,
769 targetId,
770 attackerHandle,
771 target.handle,
772 profile,
773 now,
774 to
775 ));
776}
777
778/** Authoritative ranged hit when the defender lives on this worker. */
779export function applyRemoteRangedShot (world, payload)
780{
781 const targetHandle = world.ecs.handleOf(payload.targetId);
782 if (targetHandle == null)
783 { return { events: [], forwards: [] }; }
784 const snapshot = {
785 tileX: payload.tileX,
786 tileY: payload.tileY
787 };
788
789 const hitEvents = applyLocalMeleeHit(
790 world,
791 payload.attackerId,
792 payload.targetId,
793 null,
794 targetHandle,
795 payload.profile,
796 payload.now ?? Date.now(),
797 snapshot,
798 payload.attackerLevels,
799 payload.attackerIsPlayer
800 );
801
802 const outcome = hitEvents.find((e) =>
803 e.type === "combat-hit" || e.type === "combat-miss" || e.type === "combat-block");
804 let endX = snapshot.tileX;
805 let endY = snapshot.tileY;
806 if (outcome?.type === "combat-miss")
807 {
808 const miss = missProjectileTile(snapshot.tileX, snapshot.tileY);
809 endX = miss.tileX;
810 endY = miss.tileY;
811 }
812 else
813 {
814 const currentPos = world.ecs.get(targetHandle, Component.position);
815 if (currentPos)
816 {
817 endX = currentPos.tileX;
818 endY = currentPos.tileY;
819 }
820 }
821
822 const events = [{
823 type: "combat-projectile",
824 attackerId: payload.attackerId,
825 targetId: payload.targetId,
826 fromTileX: payload.fromTileX,
827 fromTileY: payload.fromTileY,
828 tileX: endX,
829 tileY: endY,
830 durationMs: 400,
831 shaftTint: payload.shaftTint ?? null,
832 tipTint: payload.tipTint ?? null
833 }, ...hitEvents];
834
835 const forwards = [];
836 const hitEvent = hitEvents.find((event) => event.type === "combat-hit");
837 if (hitEvent && payload.attackerIsPlayer)
838 {
839 forwards.push({
840 type: "forward-combat-xp",
841 entityId: payload.attackerId,
842 profile: payload.profile,
843 damage: hitEvent.damage
844 });
845 }
846 return { events, forwards };
847}
848
849/** Authoritative hit resolution when the defender lives on this worker. */
850export function applyRemoteMeleeSwing (world, payload)
851{
852 const targetHandle = world.ecs.handleOf(payload.targetId);
853 if (targetHandle == null)
854 { return { events: [], forwards: [] }; }
855 const to = world.ecs.get(targetHandle, Component.position);
856 if (!to)
857 { return { events: [], forwards: [] }; }
858
859 const events = applyLocalMeleeHit(
860 world,
861 payload.attackerId,
862 payload.targetId,
863 null,
864 targetHandle,
865 payload.profile,
866 payload.now ?? Date.now(),
867 to,
868 payload.attackerLevels,
869 payload.attackerIsPlayer
870 );
871
872 const forwards = [];
873 const hitEvent = events.find((event) => event.type === "combat-hit");
874 if (hitEvent && payload.attackerIsPlayer)
875 {
876 forwards.push({
877 type: "forward-combat-xp",
878 entityId: payload.attackerId,
879 profile: payload.profile,
880 damage: hitEvent.damage
881 });
882 }
883 return { events, forwards };
884}
885
886function applyLocalMeleeHit (
887 world,
888 attackerId,
889 targetId,
890 attackerHandle,
891 targetHandle,
892 profile,
893 now,
894 to,
895 attackerLevelsOverride = null,
896 attackerIsPlayerOverride = null
897)
898{
899 const events = [];
900 if (targetHandle == null)
901 { return events; }
902
903 const attackerIsPlayer = attackerIsPlayerOverride != null
904 ? !!attackerIsPlayerOverride
905 : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);
906
907 // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
908 if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))
909 { engageTarget(world.ecs, targetId, attackerId, now); }
910 if (attackerIsPlayer === false)
911 {
912 const targetCharacter = world.ecs.get(targetHandle, Component.character);
913 if (targetCharacter)
914 {
915 engageTarget(world.ecs, targetId, attackerId, now);
916 const follow = world.ecs.get(targetHandle, Component.follow);
917 if (follow)
918 {
919 follow.targetEntityId = null;
920 follow.trail = [];
921 }
922 if (world.ecs.has(targetHandle, Component.gather))
923 { world.ecs.remove(targetHandle, Component.gather); }
924 }
925 }
926
927 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
928 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
929 const attackerLevels = attackerLevelsOverride
930 ?? (attackerHandle != null ? attackerCombatLevels(world.ecs, attackerHandle, profile) : null);
931 if (!attackerLevels)
932 { return events; }
933
934 const agilityLevel = defenderSkillLevel(
935 defenderSkills,
936 SkillId.dexterity,
937 defenderEquipment
938 );
939 const defenceLevel = defenderSkillLevel(
940 defenderSkills,
941 SkillId.defence,
942 defenderEquipment
943 );
944
945 const resolved = resolvePhysicalAttack({
946 hitSkillLevel: effectiveHitSkillInDarkness(
947 attackerLevels.hitLevel,
948 tileLightAt(world, to.tileX, to.tileY)
949 ),
950 agilitySkillLevel: agilityLevel,
951 damageSkillLevel: attackerLevels.damageLevel,
952 defenceSkillLevel: defenceLevel
953 });
954
955 if (resolved.outcome === "miss")
956 {
957 events.push({
958 type: "combat-miss",
959 attackerId,
960 targetId,
961 tileX: to.tileX,
962 tileY: to.tileY
963 });
964 return events;
965 }
966
967 if (resolved.outcome === "block")
968 {
969 events.push({
970 type: "combat-block",
971 attackerId,
972 targetId,
973 tileX: to.tileX,
974 tileY: to.tileY
975 });
976 return events;
977 }
978
979 const damage = resolved.damage;
980 const targetCharacter = world.ecs.get(targetHandle, Component.character);
981 if (targetCharacter)
982 { syncPlayerHealth(world.ecs, targetHandle); }
983 const health = world.ecs.get(targetHandle, Component.health);
984 if (health)
985 {
986 health.current = Math.max(0, (health.current | 0) - damage);
987 }
988 events.push({
989 type: "combat-hit",
990 attackerId,
991 targetId,
992 damage,
993 tileX: to.tileX,
994 tileY: to.tileY,
995 health: health?.current ?? 0,
996 maxHealth: health?.max ?? 0
997 });
998
999 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
1000 if (healthXp)
1001 {
1002 events.push({
1003 type: "skills-updated",
1004 entityId: targetId,
1005 characterId: healthXp.characterId,
1006 skills: healthXp.view,
1007 stored: healthXp.stored,
1008 levelUps: healthXp.levelUps ?? []
1009 });
1010 if (health)
1011 {
1012 const hitEvent = events[events.length - 2];
1013 if (hitEvent?.type === "combat-hit")
1014 {
1015 hitEvent.health = health.current;
1016 hitEvent.maxHealth = health.max;
1017 }
1018 }
1019 }
1020
1021 if (attackerHandle != null)
1022 {
1023 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
1024 if (attackerCharacter)
1025 {
1026 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile, damage);
1027 if (xpAward)
1028 {
1029 events.push({
1030 type: "skills-updated",
1031 entityId: attackerId,
1032 characterId: attackerCharacter.characterId,
1033 skills: xpAward.view,
1034 stored: xpAward.stored,
1035 levelUps: xpAward.levelUps ?? []
1036 });
1037 }
1038 }
1039 }
1040
1041 if (health && health.current <= 0)
1042 {
1043 clearEngage(world.ecs, attackerId);
1044 clearEngage(world.ecs, targetId);
1045 for (const entity of world.ecs.query(Component.combat))
1046 {
1047 if (entity.combat.targetEntityId === targetId)
1048 { entity.combat.targetEntityId = null; }
1049 }
1050 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
1051 {
1052 const path = world.ecs.get(targetHandle, Component.path);
1053 if (path)
1054 { path.tiles = []; }
1055 const follow = world.ecs.get(targetHandle, Component.follow);
1056 if (follow)
1057 {
1058 follow.targetEntityId = null;
1059 follow.trail = [];
1060 }
1061 world.ecs.add(targetHandle, Component.dead, {});
1062 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
1063 events.push({
1064 type: "player-died",
1065 entityId: targetId,
1066 attackerId,
1067 characterId: targetCharacter.characterId,
1068 sessionId: identity?.sessionId ?? null,
1069 tileX: to.tileX,
1070 tileY: to.tileY,
1071 health: 0,
1072 maxHealth: health.max
1073 });
1074 }
1075 const creature = world.ecs.get(targetHandle, Component.creature);
1076 if (creature && !world.ecs.get(targetHandle, Component.character))
1077 {
1078 events.push(...spawnMobDrops(world, targetHandle, to.tileX, to.tileY, now));
1079 const view = world.destroyEntity?.(targetId) ?? null;
1080 if (view)
1081 {
1082 events.push({
1083 type: "entity-despawn",
1084 entityId: targetId,
1085 tileX: view.tileX,
1086 tileY: view.tileY
1087 });
1088 }
1089 }
1090 }
1091 return events;
1092}