BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

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