BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

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