BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

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