BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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