BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

service.js 28.8 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
3import { SpellId, spellDefinition, spellDifficulty } from "../../../shared/definitions/spells.js";
4import
5{
6 canCastSpell,
7 defaultPlayerSpells,
8 normalizePlayerSpells,
9 publicSpellsView,
10 storedPlayerSpells,
11 toggleFavorite,
12 learnSpell
13} from "../../../shared/spells/state.js";
14import
15{
16 CAST_FLASH_MS,
17 COMBAT_RANGE_TILES,
18 LIGHT_DURATION_MS_PER_MIND,
19 SPELL_COOLDOWN_MS,
20 SPELL_LIGHT_RANGE_TILES,
21 SPELL_PROJECTILE_MS,
22 castFlashRadiusTiles
23} from "../../../shared/spells/constants.js";
24import
25{
26 mobDamageAffinities,
27 mobElementAffinities,
28 ElementMultiplier,
29 resolveMagicAttack,
30 resolveSpellCast,
31 resolveSpellPotency
32} from "../../../shared/combat/magic.js";
33import { rollCombatDamage } from "../../../shared/combat/rolls.js";
34import { mobDefinition } from "../../../shared/definitions/mobs.js";
35import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";
36import { equipmentBonusesFromSlots, effectiveSkillLevel } from "../../../shared/equipment/stats.js";
37import { statusSkillBonuses, applyStatusEffect, emptyStatusEffects, StatusEffectType, publicStatusEffectsView, hasStatusEffect } from "../../../shared/statusEffects/rules.js";
38import
39{
40 chebyshev,
41 clearEngage,
42 hasCombatLineOfSight,
43 queueStandInRangeApproach,
44 resolveCombatTarget,
45 applyDamageAndKill
46} from "../combat/service.js";
47import { storedSkillXp } from "../../../shared/skills/state.js";
48import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";
49import { publicSpellLight, SpellLightRegistry } from "./lights.js";
50import { spellbookInstance, spellbookItemIdForSpell, spellIdFromSpellbookStack } from "../../../shared/definitions/spellItems.js";
51import { itemDefinition } from "../../../shared/definitions/items.js";
52import { bagView } from "../items/bags.js";
53import { applyTindersAtTile, tindersTileStillNeedsCast } from "./tinders.js";
54
55const MAGIC_ATTACK_PROFILE = Object.freeze({
56 hitSkillId: SkillId.magic,
57 damageSkillId: SkillId.mind
58});
59
60export function ensureSpellComponents (ecs, handle, storedSpells = null)
61{
62 if (!ecs.get(handle, Component.spells))
63 {
64 ecs.add(handle, Component.spells, normalizePlayerSpells(storedSpells ?? defaultPlayerSpells()));
65 }
66 if (!ecs.get(handle, Component.spellcasting))
67 {
68 ecs.add(handle, Component.spellcasting, emptySpellcasting());
69 }
70 else
71 { normalizeSpellcasting(ecs.get(handle, Component.spellcasting)); }
72}
73
74export function emptySpellcasting ()
75{
76 return {
77 armedSpellId: null,
78 repeatSpellId: null,
79 repeatTargetEntityId: null,
80 repeatTileX: null,
81 repeatTileY: null,
82 nextCastAt: 0,
83 pendingCast: null
84 };
85}
86
87function normalizeSpellcasting (casting)
88{
89 if (!casting)
90 { return; }
91 if (!("repeatTileX" in casting))
92 { casting.repeatTileX = null; }
93 if (!("repeatTileY" in casting))
94 { casting.repeatTileY = null; }
95}
96
97/** Clear auto-repeat / pending cast state (move, melee, cancel, …). */
98export function clearSpellAutoRepeat (casting)
99{
100 if (!casting)
101 { return; }
102 casting.repeatSpellId = null;
103 casting.repeatTargetEntityId = null;
104 casting.repeatTileX = null;
105 casting.repeatTileY = null;
106 casting.pendingCast = null;
107}
108
109function stopCasterMovement (world, handle, entityId)
110{
111 clearEngage(world.ecs, entityId);
112 const path = world.ecs.get(handle, Component.path);
113 if (path?.tiles?.length)
114 { path.tiles = []; }
115 const movement = world.ecs.get(handle, Component.movement);
116 if (movement)
117 { movement.walkCarry = 0; }
118}
119
120export function handleSpellCommand (world, sessionId, command, now = Date.now())
121{
122 switch (command.type)
123 {
124 case "set-spell-favorite":
125 return setSpellFavorite(world, sessionId, command, now);
126 case "set-spell-autocast":
127 return setSpellAutoCast(world, sessionId, command, now);
128 case "arm-spell":
129 return armSpell(world, sessionId, command, now);
130 case "cancel-arm-spell":
131 return cancelArmSpell(world, sessionId, command, now);
132 case "cast-spell-tile":
133 return castSpellAtTile(world, sessionId, command, now);
134 case "cast-spell-entity":
135 return castSpellAtEntity(world, sessionId, command, now);
136 case "read-spellbook":
137 return readSpellbook(world, sessionId, command, now);
138 default:
139 return null;
140 }
141}
142
143function requirePlayer (world, sessionId, characterId)
144{
145 for (const entity of world.ecs.query(Component.networkIdentity, Component.character))
146 {
147 if (entity.networkIdentity.sessionId !== sessionId)
148 { continue; }
149 if (entity.character.characterId !== characterId)
150 { continue; }
151 if (world.ecs.has(entity.handle, Component.dead))
152 {
153 const error = new Error("You are dead.");
154 error.userFacing = true;
155 throw error;
156 }
157 return { handle: entity.handle, entityId: entity.entityId, character: entity.character };
158 }
159 const error = new Error("Character not found.");
160 error.userFacing = true;
161 throw error;
162}
163
164function spellsUpdatedEvent (entityId, characterId, spells, skills, levelUps = [])
165{
166 return {
167 type: "spells-updated",
168 entityId,
169 characterId,
170 spells: publicSpellsView(spells, skills),
171 stored: storedPlayerSpells(spells),
172 autoCast: !!spells.autoCast,
173 levelUps
174 };
175}
176
177function setSpellFavorite (world, sessionId, command, now)
178{
179 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
180 ensureSpellComponents(world.ecs, handle);
181 const skills = world.ecs.get(handle, Component.skills);
182 const spells = world.ecs.get(handle, Component.spells);
183 const result = toggleFavorite(spells, command.spellId, skills);
184 if (result.error)
185 {
186 const error = new Error(result.error);
187 error.userFacing = true;
188 throw error;
189 }
190 Object.assign(spells, result.spells);
191 const events = [];
192 if (result.changed)
193 {
194 events.push(spellsUpdatedEvent(entityId, character.characterId, spells, skills));
195 }
196 return { events };
197}
198
199function setSpellAutoCast (world, sessionId, command, now)
200{
201 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
202 ensureSpellComponents(world.ecs, handle);
203 const skills = world.ecs.get(handle, Component.skills);
204 const spells = world.ecs.get(handle, Component.spells);
205 spells.autoCast = !!command.enabled;
206 const casting = world.ecs.get(handle, Component.spellcasting);
207 if (!spells.autoCast)
208 { clearSpellAutoRepeat(casting); }
209 return {
210 events: [spellsUpdatedEvent(entityId, character.characterId, spells, skills)]
211 };
212}
213
214function armSpell (world, sessionId, command, now)
215{
216 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
217 ensureSpellComponents(world.ecs, handle);
218 const skills = world.ecs.get(handle, Component.skills);
219 const spells = world.ecs.get(handle, Component.spells);
220 const check = canCastSpell(skills, spells, command.spellId);
221 if (!check.ok)
222 {
223 const error = new Error(check.reason);
224 error.userFacing = true;
225 throw error;
226 }
227 const casting = world.ecs.get(handle, Component.spellcasting);
228 casting.armedSpellId = command.spellId;
229 casting.pendingCast = null;
230 /** Re-arming the active auto-repeat spell must not cancel it (favourite bar clicks). */
231 if (casting.repeatSpellId != null && casting.repeatSpellId !== command.spellId)
232 {
233 casting.repeatSpellId = null;
234 casting.repeatTargetEntityId = null;
235 casting.repeatTileX = null;
236 casting.repeatTileY = null;
237 }
238 return {
239 events: [{
240 type: "spell-armed",
241 entityId,
242 characterId: character.characterId,
243 spellId: command.spellId
244 }]
245 };
246}
247
248function cancelArmSpell (world, sessionId, command)
249{
250 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
251 const casting = world.ecs.get(handle, Component.spellcasting);
252 if (!casting)
253 { return { events: [] }; }
254 casting.armedSpellId = null;
255 casting.pendingCast = null;
256 /**
257 * Do not clear auto-repeat here. Cast already disarms then sets repeat; a late
258 * cancel-arm (right-click while the client still thought it was armed) used to
259 * wipe that repeat and leave the player falling back to melee.
260 */
261 return {
262 events: [{
263 type: "spell-disarmed",
264 entityId,
265 characterId: character.characterId
266 }]
267 };
268}
269
270function casterMagicLevels (ecs, handle, settings = null)
271{
272 const skills = ecs.get(handle, Component.skills);
273 const equipment = ecs.get(handle, Component.equipment);
274 const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings);
275 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
276 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
277 return {
278 magic: effectiveSkillLevel(skills, SkillId.magic, bonuses),
279 mind: effectiveSkillLevel(skills, SkillId.mind, bonuses)
280 };
281}
282
283function validateCastRange (world, handle, tileX, tileY, now)
284{
285 const pos = world.ecs.get(handle, Component.position);
286 if (!pos)
287 { return { ok: false, reason: "You are not in the world." }; }
288 const dist = chebyshev(pos.tileX, pos.tileY, tileX, tileY);
289 if (dist > COMBAT_RANGE_TILES)
290 { return { ok: false, reason: "That is out of range." }; }
291 if (!hasCombatLineOfSight(world, pos.tileX, pos.tileY, tileX, tileY))
292 { return { ok: false, reason: "You cannot see that spot." }; }
293 return { ok: true };
294}
295
296function resolvePendingCastTarget (world, pending)
297{
298 if (pending.targetEntityId == null)
299 {
300 return {
301 tileX: pending.tileX | 0,
302 tileY: pending.tileY | 0,
303 targetEntityId: null
304 };
305 }
306 const target = resolveCombatTarget(world, pending.targetEntityId);
307 if (!target)
308 { return null; }
309 return {
310 tileX: target.pos.tileX,
311 tileY: target.pos.tileY,
312 targetEntityId: pending.targetEntityId
313 };
314}
315
316function queueSpellApproach (world, handle, entityId, target, minStandDist)
317{
318 const position = world.ecs.get(handle, Component.position);
319 if (!position)
320 { return; }
321 queueStandInRangeApproach(
322 world,
323 entityId,
324 handle,
325 position,
326 target.tileX,
327 target.tileY,
328 COMBAT_RANGE_TILES,
329 minStandDist
330 );
331}
332
333function beginCastOrApproach (world, sessionId, characterId, spellId, target, now, minStandDist = 0)
334{
335 const { handle, entityId } = requirePlayer(world, sessionId, characterId);
336 ensureSpellComponents(world.ecs, handle);
337 const casting = world.ecs.get(handle, Component.spellcasting);
338 stopCasterMovement(world, handle, entityId);
339 const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
340 if (!rangeCheck.ok)
341 {
342 casting.pendingCast = {
343 spellId,
344 tileX: target.tileX,
345 tileY: target.tileY,
346 targetEntityId: target.targetEntityId ?? null
347 };
348 queueSpellApproach(world, handle, entityId, target, minStandDist);
349 return { events: [] };
350 }
351 casting.pendingCast = null;
352 return executeCast(world, sessionId, characterId, spellId, target, now);
353}
354
355function castSpellAtTile (world, sessionId, command, now)
356{
357 const spellId = command.spellId;
358 const def = spellDefinition(spellId);
359 if (!def || def.target !== "tile")
360 {
361 const error = new Error("That spell needs a different target.");
362 error.userFacing = true;
363 throw error;
364 }
365 return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
366 tileX: command.tileX | 0,
367 tileY: command.tileY | 0,
368 targetEntityId: null
369 }, now, 0);
370}
371
372function castSpellAtEntity (world, sessionId, command, now)
373{
374 const spellId = command.spellId;
375 const def = spellDefinition(spellId);
376 if (!def || def.target !== "entity")
377 {
378 const error = new Error("That spell needs a tile target.");
379 error.userFacing = true;
380 throw error;
381 }
382 const { entityId: casterEntityId } = requirePlayer(world, sessionId, command.characterId);
383 const target = resolveCombatTarget(world, command.targetEntityId);
384 if (!target)
385 {
386 const error = new Error("Target is not here.");
387 error.userFacing = true;
388 throw error;
389 }
390 const selfTarget = command.targetEntityId === casterEntityId;
391 return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
392 tileX: target.pos.tileX,
393 tileY: target.pos.tileY,
394 targetEntityId: command.targetEntityId
395 }, now, selfTarget ? 0 : 1);
396}
397
398function executeCast (world, sessionId, characterId, spellId, target, now)
399{
400 const { handle, entityId, character } = requirePlayer(world, sessionId, characterId);
401 ensureSpellComponents(world.ecs, handle);
402 const skills = world.ecs.get(handle, Component.skills);
403 const spells = world.ecs.get(handle, Component.spells);
404 const casting = world.ecs.get(handle, Component.spellcasting);
405 const def = spellDefinition(spellId);
406 const check = canCastSpell(skills, spells, spellId);
407 if (!check.ok)
408 {
409 const error = new Error(check.reason);
410 error.userFacing = true;
411 throw error;
412 }
413 if (now < (casting.nextCastAt || 0))
414 {
415 const error = new Error("You are not ready to cast yet.");
416 error.userFacing = true;
417 throw error;
418 }
419 const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
420 if (!rangeCheck.ok)
421 {
422 const error = new Error(rangeCheck.reason);
423 error.userFacing = true;
424 throw error;
425 }
426
427 stopCasterMovement(world, handle, entityId);
428
429 const levels = casterMagicLevels(world.ecs, handle, world.settings);
430 const difficulty = spellDifficulty(def);
431 const cast = resolveSpellCast({
432 magicSkillLevel: levels.magic,
433 spellDifficulty: difficulty
434 });
435
436 const events = [];
437 const from = world.ecs.get(handle, Component.position);
438 casting.armedSpellId = null;
439 casting.nextCastAt = now + SPELL_COOLDOWN_MS;
440 events.push({
441 type: "spell-disarmed",
442 entityId,
443 characterId: character.characterId
444 });
445
446 // Keep / refresh auto-repeat even on fizzle so we keep trying until cancelled.
447 rememberAutoRepeat(casting, spells, def, spellId, target);
448
449 if (!cast.success)
450 {
451 events.push({
452 type: "spell-fizzle",
453 casterId: entityId,
454 spellId,
455 fromTileX: from.tileX,
456 fromTileY: from.tileY,
457 tileX: target.tileX,
458 tileY: target.tileY
459 });
460 return { events };
461 }
462
463 const xpAward = awardSpellCastXp(world.ecs, handle, difficulty);
464 if (xpAward)
465 {
466 events.push({
467 type: "skills-updated",
468 entityId,
469 characterId: character.characterId,
470 skills: xpAward.skills,
471 combatLevel: xpAward.combatLevel,
472 stored: xpAward.stored,
473 levelUps: xpAward.levelUps ?? []
474 });
475 }
476
477 const flashRadius = castFlashRadiusTiles(def.tier);
478 events.push({
479 type: "spell-cast-flash",
480 casterId: entityId,
481 tileX: from.tileX,
482 tileY: from.tileY,
483 radiusTiles: flashRadius,
484 durationMs: CAST_FLASH_MS,
485 tier: def.tier
486 });
487
488 world.pendingSpellImpacts.push({
489 executeAt: now + SPELL_PROJECTILE_MS,
490 casterEntityId: entityId,
491 casterCharacterId: character.characterId,
492 spellId,
493 targetTileX: target.tileX,
494 targetTileY: target.tileY,
495 targetEntityId: target.targetEntityId,
496 levels
497 });
498
499 events.push({
500 type: "spell-projectile",
501 casterId: entityId,
502 spellId,
503 targetId: target.targetEntityId ?? null,
504 fromTileX: from.tileX,
505 fromTileY: from.tileY,
506 tileX: target.tileX,
507 tileY: target.tileY,
508 durationMs: SPELL_PROJECTILE_MS,
509 sprite: def.projectileSprite
510 });
511
512 return { events };
513}
514
515function rememberAutoRepeat (casting, spells, def, spellId, target)
516{
517 if (!casting || !spells?.autoCast || !def?.autoRepeat)
518 {
519 clearSpellAutoRepeat(casting);
520 return;
521 }
522 if (def.target === "entity" && target?.targetEntityId != null)
523 {
524 casting.repeatSpellId = spellId;
525 casting.repeatTargetEntityId = target.targetEntityId | 0;
526 casting.repeatTileX = null;
527 casting.repeatTileY = null;
528 casting.pendingCast = null;
529 return;
530 }
531 if (def.target === "tile")
532 {
533 casting.repeatSpellId = spellId;
534 casting.repeatTargetEntityId = null;
535 casting.repeatTileX = target.tileX | 0;
536 casting.repeatTileY = target.tileY | 0;
537 casting.pendingCast = null;
538 return;
539 }
540 clearSpellAutoRepeat(casting);
541}
542
543function targetAffinitiesForEntity (world, entityId)
544{
545 if (entityId == null)
546 { return {}; }
547 const handle = world.ecs.handleOf(entityId);
548 if (handle == null)
549 { return {}; }
550 const creature = world.ecs.get(handle, Component.creature);
551 if (!creature)
552 { return {}; }
553 return mobDamageAffinities(mobDefinition(creature.mobTypeId));
554}
555
556function applySpellImpact (world, impact, now)
557{
558 const def = spellDefinition(impact.spellId);
559 if (!def)
560 { return []; }
561 const events = [];
562 events.push({
563 type: "spell-cast-flash",
564 casterId: impact.casterEntityId,
565 tileX: impact.targetTileX,
566 tileY: impact.targetTileY,
567 radiusTiles: castFlashRadiusTiles(def.tier),
568 durationMs: CAST_FLASH_MS,
569 tier: def.tier
570 });
571
572 const effect = def.effect ?? impact.spellId;
573 if (effect === "light" || effect === "dark")
574 {
575 events.push(...applyLightOrDarkImpact(world, impact, def, effect, now));
576 return events;
577 }
578 if (effect === "damage")
579 {
580 events.push(...applyDamageSpellImpact(world, impact, def, now));
581 return events;
582 }
583 if (effect === "poison")
584 {
585 events.push(...applyPoisonImpact(world, impact, def, now));
586 return events;
587 }
588 if (effect === "drain")
589 {
590 events.push(...applyDrainImpact(world, impact, now));
591 return events;
592 }
593 if (effect === "revitalize")
594 {
595 events.push(...applyRevitalizeImpact(world, impact, now));
596 return events;
597 }
598 if (effect === "tinders")
599 {
600 events.push(...applyTindersImpact(world, impact, now));
601 return events;
602 }
603 if (effect === "shade")
604 {
605 events.push(...applyShadeImpact(world, impact, now));
606 return events;
607 }
608 return events;
609}
610
611function mindRollOf (impact)
612{
613 return resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
614}
615
616function mindDamageRollOf (impact)
617{
618 return rollCombatDamage(impact.levels.mind);
619}
620
621function applyLightOrDarkImpact (world, impact, def, effect, now)
622{
623 const events = [];
624 world.spellLights = world.spellLights ?? new SpellLightRegistry();
625 const mindRoll = mindRollOf(impact);
626 const durationMs = Math.max(1, mindRoll) * LIGHT_DURATION_MS_PER_MIND;
627 const baseRange = mindRoll === 0
628 ? SPELL_LIGHT_RANGE_TILES * 0.5
629 : SPELL_LIGHT_RANGE_TILES;
630 const kind = effect === "dark" ? "dark" : "light";
631 const { light, extended } = world.spellLights.placeOrExtend({
632 tileX: impact.targetTileX,
633 tileY: impact.targetTileY,
634 ownerEntityId: impact.casterEntityId,
635 durationMs,
636 baseRange,
637 kind,
638 now
639 });
640 const appear = kind === "dark"
641 ? (extended ? "spell-dark-update" : "spell-dark-appear")
642 : (extended ? "spell-light-update" : "spell-light-appear");
643 events.push({ type: appear, ...publicSpellLight(light, now) });
644 return events;
645}
646
647function elementalDamageMultiplier (def, affinities)
648{
649 let multiplier = ElementMultiplier.neutral;
650 const affinity = affinities[def.element ?? "none"];
651 if (affinity === "weak")
652 { multiplier = ElementMultiplier.weak; }
653 else if (affinity === "resistant")
654 { multiplier = ElementMultiplier.resistant; }
655 return multiplier;
656}
657
658function applyDamageSpellImpact (world, impact, def, now)
659{
660 if (impact.targetEntityId == null)
661 { return []; }
662 const events = [];
663 const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
664 const mindRoll = mindDamageRollOf(impact);
665 const multiplier = elementalDamageMultiplier(def, affinities);
666 const damage = Math.max(1, Math.floor(mindRoll * multiplier));
667 events.push(...applyDamageAndKill(
668 world,
669 impact.casterEntityId,
670 impact.targetEntityId,
671 damage,
672 now
673 ));
674 events.push(...awardMagicHitXp(world, impact, damage));
675 return events;
676}
677
678function awardMagicHitXp (world, impact, damage)
679{
680 const events = [];
681 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
682 if (casterHandle == null || !impact.casterCharacterId)
683 { return events; }
684 const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);
685 if (xp)
686 {
687 events.push({
688 type: "skills-updated",
689 entityId: impact.casterEntityId,
690 characterId: impact.casterCharacterId,
691 skills: xp.skills,
692 combatLevel: xp.combatLevel,
693 stored: xp.stored,
694 levelUps: xp.levelUps ?? []
695 });
696 }
697 return events;
698}
699
700function ensureEntityStatusEffects (ecs, handle)
701{
702 let component = ecs.get(handle, Component.statusEffects);
703 if (!component)
704 { component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); }
705 return component;
706}
707
708function applyPoisonImpact (world, impact, def, now)
709{
710 if (impact.targetEntityId == null)
711 { return []; }
712 const target = resolveCombatTarget(world, impact.targetEntityId);
713 if (!target?.local || target.handle == null)
714 { return []; }
715 const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
716 const mindRoll = mindRollOf(impact);
717 const multiplier = elementalDamageMultiplier(def, affinities);
718 const total = Math.max(1, Math.floor(mindRoll * multiplier * 2));
719 const durationMs = total * 1000;
720 const status = ensureEntityStatusEffects(world.ecs, target.handle);
721 applyStatusEffect(status, {
722 type: StatusEffectType.healthDrain,
723 durationMs,
724 amountPerSecond: 1
725 }, now);
726 return [{
727 type: "status-effects-entity",
728 entityId: impact.targetEntityId,
729 effects: publicStatusEffectsView(status, now)
730 }];
731}
732
733function applyDrainImpact (world, impact, now)
734{
735 if (impact.targetEntityId == null)
736 { return []; }
737 const target = resolveCombatTarget(world, impact.targetEntityId);
738 if (!target?.local || target.handle == null)
739 { return []; }
740 if (!world.ecs.get(target.handle, Component.stamina))
741 { return []; }
742 const mindRoll = mindRollOf(impact);
743 const durationMs = Math.max(1000, mindRoll * 3 * 1000);
744 const status = ensureEntityStatusEffects(world.ecs, target.handle);
745 applyStatusEffect(status, {
746 type: StatusEffectType.staminaDrain,
747 durationMs,
748 amountPerSecond: 1
749 }, now);
750 applyStatusEffect(status, {
751 type: StatusEffectType.staminaBlock,
752 durationMs,
753 amountPerSecond: 0
754 }, now);
755 const character = world.ecs.get(target.handle, Component.character);
756 const events = [{
757 type: "status-effects-entity",
758 entityId: impact.targetEntityId,
759 effects: publicStatusEffectsView(status, now)
760 }];
761 if (character?.characterId)
762 {
763 events.push({
764 type: "status-effects",
765 characterId: character.characterId,
766 effects: publicStatusEffectsView(status, now),
767 blind: hasStatusEffect(status, StatusEffectType.blind, now)
768 });
769 }
770 return events;
771}
772
773function applyRevitalizeImpact (world, impact, now)
774{
775 if (impact.targetEntityId == null)
776 { return []; }
777 const target = resolveCombatTarget(world, impact.targetEntityId);
778 if (!target?.local || target.handle == null)
779 { return []; }
780 if (!world.ecs.get(target.handle, Component.health))
781 { return []; }
782 const mindRoll = mindRollOf(impact);
783 const healTotal = Math.max(1, mindRoll);
784 const durationMs = healTotal * 1000;
785 const status = ensureEntityStatusEffects(world.ecs, target.handle);
786 applyStatusEffect(status, {
787 type: StatusEffectType.healthRegen,
788 durationMs,
789 amountPerSecond: 1
790 }, now);
791 const character = world.ecs.get(target.handle, Component.character);
792 const events = [{
793 type: "status-effects-entity",
794 entityId: impact.targetEntityId,
795 effects: publicStatusEffectsView(status, now)
796 }];
797 if (character?.characterId)
798 {
799 events.push({
800 type: "status-effects",
801 characterId: character.characterId,
802 effects: publicStatusEffectsView(status, now),
803 blind: hasStatusEffect(status, StatusEffectType.blind, now)
804 });
805 }
806 return events;
807}
808
809function applyTindersImpact (world, impact, now)
810{
811 const events = applyTindersAtTile(world, impact, now);
812 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
813 const sessionId = casterHandle != null
814 ? world.ecs.get(casterHandle, Component.networkIdentity)?.sessionId
815 : null;
816 for (const event of events)
817 {
818 if (event.type === "command-error" && sessionId != null)
819 { event.sessionId = sessionId; }
820 }
821 return events;
822}
823
824function applyShadeImpact (world, impact, now)
825{
826 const mindRoll = mindRollOf(impact);
827 const durationMs = Math.max(1000, mindRoll * 3 * 1000);
828 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
829 const mindLevel = impact.levels?.mind | 0 || 1;
830 const level = Math.max(1, Math.min(99, Math.floor(mindLevel * 0.75)));
831 return [{
832 type: "summon-entity",
833 ownerEntityId: impact.casterEntityId,
834 ownerCharacterId: impact.casterCharacterId ?? null,
835 tileX: impact.targetTileX,
836 tileY: impact.targetTileY,
837 level,
838 expiresAt: now + durationMs,
839 mobTypeId: "shade"
840 }];
841}
842
843export function processSpellImpacts (world, now = Date.now())
844{
845 const queue = world.pendingSpellImpacts ?? [];
846 if (!queue.length)
847 { return []; }
848 const events = [];
849 const keep = [];
850 for (const impact of queue)
851 {
852 if (impact.executeAt > now)
853 {
854 keep.push(impact);
855 continue;
856 }
857 events.push(...applySpellImpact(world, impact, now));
858 }
859 world.pendingSpellImpacts = keep;
860 return events;
861}
862
863export function stepPendingSpellCast (world, now = Date.now())
864{
865 const events = [];
866 for (const entity of world.ecs.query(Component.spellcasting, Component.character, Component.networkIdentity))
867 {
868 if (world.ecs.has(entity.handle, Component.dead))
869 {
870 if (entity.spellcasting)
871 { entity.spellcasting.pendingCast = null; }
872 continue;
873 }
874 const casting = entity.spellcasting;
875 if (!casting?.pendingCast)
876 { continue; }
877 const pending = casting.pendingCast;
878 const target = resolvePendingCastTarget(world, pending);
879 if (!target)
880 {
881 casting.pendingCast = null;
882 continue;
883 }
884 const rangeCheck = validateCastRange(world, entity.handle, target.tileX, target.tileY, now);
885 if (!rangeCheck.ok)
886 {
887 const minStandDist = target.targetEntityId != null ? 1 : 0;
888 queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist);
889 continue;
890 }
891 casting.pendingCast = null;
892 const result = executeCast(
893 world,
894 entity.networkIdentity.sessionId,
895 entity.character.characterId,
896 pending.spellId,
897 target,
898 now
899 );
900 events.push(...(result.events ?? []));
901 }
902 return events;
903}
904
905export function stepSpellAutoCast (world, now = Date.now())
906{
907 const events = [];
908 for (const entity of world.ecs.query(
909 Component.spellcasting,
910 Component.spells,
911 Component.character,
912 Component.networkIdentity
913 ))
914 {
915 if (world.ecs.has(entity.handle, Component.dead))
916 {
917 clearSpellAutoRepeat(entity.spellcasting);
918 continue;
919 }
920 const casting = entity.spellcasting;
921 const spells = entity.spells;
922 normalizeSpellcasting(casting);
923 if (!spells.autoCast || !casting.repeatSpellId)
924 { continue; }
925 if (now < (casting.nextCastAt || 0))
926 { continue; }
927 const def = spellDefinition(casting.repeatSpellId);
928 if (!def?.autoRepeat)
929 {
930 clearSpellAutoRepeat(casting);
931 continue;
932 }
933
934 const sessionId = entity.networkIdentity.sessionId;
935 if (!sessionId)
936 { continue; }
937
938 let target = null;
939 let minStandDist = 0;
940 if (casting.repeatTargetEntityId != null)
941 {
942 const resolved = resolveCombatTarget(world, casting.repeatTargetEntityId);
943 if (!resolved || (resolved.health && resolved.health.current <= 0))
944 {
945 clearSpellAutoRepeat(casting);
946 continue;
947 }
948 target = {
949 tileX: resolved.pos.tileX,
950 tileY: resolved.pos.tileY,
951 targetEntityId: casting.repeatTargetEntityId
952 };
953 minStandDist = casting.repeatTargetEntityId === entity.entityId ? 0 : 1;
954 }
955 else if (casting.repeatTileX != null && casting.repeatTileY != null)
956 {
957 if (!tileAutoCastStillValid(world, casting.repeatSpellId, casting.repeatTileX, casting.repeatTileY))
958 {
959 clearSpellAutoRepeat(casting);
960 continue;
961 }
962 target = {
963 tileX: casting.repeatTileX | 0,
964 tileY: casting.repeatTileY | 0,
965 targetEntityId: null
966 };
967 minStandDist = 0;
968 }
969 else
970 {
971 clearSpellAutoRepeat(casting);
972 continue;
973 }
974
975 const range = validateCastRange(world, entity.handle, target.tileX, target.tileY, now);
976 if (!range.ok)
977 {
978 queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist);
979 continue;
980 }
981
982 const result = executeCast(
983 world,
984 sessionId,
985 entity.character.characterId,
986 casting.repeatSpellId,
987 target,
988 now
989 );
990 events.push(...(result.events ?? []));
991 }
992 return events;
993}
994
995function tileAutoCastStillValid (world, spellId, tileX, tileY)
996{
997 const def = spellDefinition(spellId);
998 if (!def)
999 { return false; }
1000 if (def.effect === "tinders")
1001 { return tindersTileStillNeedsCast(world, tileX, tileY); }
1002 return true;
1003}
1004
1005export function tickSpellLights (world, now = Date.now())
1006{
1007 if (!world.spellLights)
1008 { return []; }
1009 return world.spellLights.tick(world, now);
1010}
1011
1012function readSpellbook (world, sessionId, command, now)
1013{
1014 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
1015 ensureSpellComponents(world.ecs, handle);
1016 const inventory = world.ecs.get(handle, Component.inventory);
1017 const slotIndex = command.slotIndex | 0;
1018 const slot = inventory?.slots?.[slotIndex];
1019 const itemDef = itemDefinition(slot?.itemId);
1020 const spellId = spellIdFromSpellbookStack(slot, itemDef);
1021 if (!spellId)
1022 {
1023 const error = new Error("That is not a spellbook.");
1024 error.userFacing = true;
1025 throw error;
1026 }
1027 const spells = world.ecs.get(handle, Component.spells);
1028 const skills = world.ecs.get(handle, Component.skills);
1029 const learned = learnSpell(spells, spellId);
1030 if (!learned.changed)
1031 {
1032 const error = new Error("You already know that spell.");
1033 error.userFacing = true;
1034 throw error;
1035 }
1036 Object.assign(spells, learned.spells);
1037 inventory.slots[slotIndex] = null;
1038 const events = [
1039 spellsUpdatedEvent(entityId, character.characterId, spells, skills)
1040 ];
1041 return {
1042 events,
1043 private: bagView(world.ecs, handle)
1044 };
1045}
1046
1047export function createSpellbookStack (spellId)
1048{
1049 const instance = spellbookInstance(spellId);
1050 const itemId = spellbookItemIdForSpell(spellId);
1051 if (!instance || itemId == null)
1052 { return null; }
1053 return { itemId, quantity: 1, instance };
1054}