BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

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