BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

service.js 19.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 canCastSpell,
6 defaultPlayerSpells,
7 normalizePlayerSpells,
8 publicSpellsView,
9 storedPlayerSpells,
10 toggleFavorite,
11 learnSpell
12} from "../../../shared/spells/state.js";
13import {
14 CAST_FLASH_MS,
15 COMBAT_RANGE_TILES,
16 LIGHT_DURATION_MS_PER_MIND,
17 SPELL_COOLDOWN_MS,
18 SPELL_PROJECTILE_MS,
19 castFlashRadiusTiles
20} from "../../../shared/spells/constants.js";
21import {
22 mobElementAffinities,
23 ElementMultiplier,
24 resolveMagicAttack,
25 resolveSpellCast,
26 resolveSpellPotency
27} from "../../../shared/combat/magic.js";
28import { mobDefinition } from "../../../shared/definitions/mobs.js";
29import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";
30import {
31 chebyshev,
32 hasCombatLineOfSight,
33 queueStandInRangeApproach,
34 resolveCombatTarget
35} from "../combat/service.js";
36import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
37import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";
38import { publicSpellLight, SpellLightRegistry } from "./lights.js";
39import { SpellbookItemId, spellbookInstance } from "../../../shared/definitions/spellItems.js";
40import { bagView } from "../items/bags.js";
41
42const MAGIC_ATTACK_PROFILE = Object.freeze({
43 hitSkillId: SkillId.magic,
44 damageSkillId: SkillId.mind
45});
46
47export function ensureSpellComponents (ecs, handle, storedSpells = null)
48{
49 if (!ecs.get(handle, Component.spells))
50 {
51 ecs.add(handle, Component.spells, normalizePlayerSpells(storedSpells ?? defaultPlayerSpells()));
52 }
53 if (!ecs.get(handle, Component.spellcasting))
54 {
55 ecs.add(handle, Component.spellcasting, {
56 armedSpellId: null,
57 repeatSpellId: null,
58 repeatTargetEntityId: null,
59 nextCastAt: 0
60 });
61 }
62}
63
64export function handleSpellCommand (world, sessionId, command, now = Date.now())
65{
66 switch (command.type)
67 {
68 case "set-spell-favorite":
69 return setSpellFavorite(world, sessionId, command, now);
70 case "set-spell-autocast":
71 return setSpellAutoCast(world, sessionId, command, now);
72 case "arm-spell":
73 return armSpell(world, sessionId, command, now);
74 case "cancel-arm-spell":
75 return cancelArmSpell(world, sessionId, command, now);
76 case "cast-spell-tile":
77 return castSpellAtTile(world, sessionId, command, now);
78 case "cast-spell-entity":
79 return castSpellAtEntity(world, sessionId, command, now);
80 case "read-spellbook":
81 return readSpellbook(world, sessionId, command, now);
82 default:
83 return null;
84 }
85}
86
87function requirePlayer (world, sessionId, characterId)
88{
89 for (const entity of world.ecs.query(Component.networkIdentity, Component.character))
90 {
91 if (entity.networkIdentity.sessionId !== sessionId)
92 { continue; }
93 if (entity.character.characterId !== characterId)
94 { continue; }
95 return { handle: entity.handle, entityId: entity.entityId, character: entity.character };
96 }
97 const error = new Error("Character not found.");
98 error.userFacing = true;
99 throw error;
100}
101
102function spellsUpdatedEvent (entityId, characterId, spells, skills, levelUps = [])
103{
104 return {
105 type: "spells-updated",
106 entityId,
107 characterId,
108 spells: publicSpellsView(spells, skills),
109 stored: storedPlayerSpells(spells),
110 autoCast: !!spells.autoCast,
111 levelUps
112 };
113}
114
115function setSpellFavorite (world, sessionId, command, now)
116{
117 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
118 ensureSpellComponents(world.ecs, handle);
119 const skills = world.ecs.get(handle, Component.skills);
120 const spells = world.ecs.get(handle, Component.spells);
121 const result = toggleFavorite(spells, command.spellId, skills);
122 if (result.error)
123 {
124 const error = new Error(result.error);
125 error.userFacing = true;
126 throw error;
127 }
128 Object.assign(spells, result.spells);
129 const events = [];
130 if (result.changed)
131 {
132 events.push(spellsUpdatedEvent(entityId, character.characterId, spells, skills));
133 }
134 return { events };
135}
136
137function setSpellAutoCast (world, sessionId, command, now)
138{
139 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
140 ensureSpellComponents(world.ecs, handle);
141 const skills = world.ecs.get(handle, Component.skills);
142 const spells = world.ecs.get(handle, Component.spells);
143 spells.autoCast = !!command.enabled;
144 const casting = world.ecs.get(handle, Component.spellcasting);
145 if (!spells.autoCast)
146 {
147 casting.repeatSpellId = null;
148 casting.repeatTargetEntityId = null;
149 }
150 return {
151 events: [spellsUpdatedEvent(entityId, character.characterId, spells, skills)]
152 };
153}
154
155function armSpell (world, sessionId, command, now)
156{
157 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
158 ensureSpellComponents(world.ecs, handle);
159 const skills = world.ecs.get(handle, Component.skills);
160 const spells = world.ecs.get(handle, Component.spells);
161 const check = canCastSpell(skills, spells, command.spellId);
162 if (!check.ok)
163 {
164 const error = new Error(check.reason);
165 error.userFacing = true;
166 throw error;
167 }
168 const casting = world.ecs.get(handle, Component.spellcasting);
169 casting.armedSpellId = command.spellId;
170 casting.repeatSpellId = null;
171 casting.repeatTargetEntityId = null;
172 casting.pendingCast = null;
173 return {
174 events: [{
175 type: "spell-armed",
176 entityId,
177 characterId: character.characterId,
178 spellId: command.spellId
179 }]
180 };
181}
182
183function cancelArmSpell (world, sessionId, command)
184{
185 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
186 const casting = world.ecs.get(handle, Component.spellcasting);
187 if (!casting)
188 { return { events: [] }; }
189 casting.armedSpellId = null;
190 casting.repeatSpellId = null;
191 casting.repeatTargetEntityId = null;
192 casting.pendingCast = null;
193 return {
194 events: [{
195 type: "spell-disarmed",
196 entityId,
197 characterId: character.characterId
198 }]
199 };
200}
201
202function casterMagicLevels (ecs, handle)
203{
204 const skills = ecs.get(handle, Component.skills);
205 return {
206 magic: skillLevel(skills, SkillId.magic),
207 mind: skillLevel(skills, SkillId.mind)
208 };
209}
210
211function validateCastRange (world, handle, tileX, tileY, now)
212{
213 const pos = world.ecs.get(handle, Component.position);
214 if (!pos)
215 { return { ok: false, reason: "You are not in the world." }; }
216 const dist = chebyshev(pos.tileX, pos.tileY, tileX, tileY);
217 if (dist > COMBAT_RANGE_TILES)
218 { return { ok: false, reason: "That is out of range." }; }
219 if (!hasCombatLineOfSight(world, pos.tileX, pos.tileY, tileX, tileY))
220 { return { ok: false, reason: "You cannot see that spot." }; }
221 return { ok: true };
222}
223
224function resolvePendingCastTarget (world, pending)
225{
226 if (pending.targetEntityId == null)
227 {
228 return {
229 tileX: pending.tileX | 0,
230 tileY: pending.tileY | 0,
231 targetEntityId: null
232 };
233 }
234 const target = resolveCombatTarget(world, pending.targetEntityId);
235 if (!target)
236 { return null; }
237 return {
238 tileX: target.pos.tileX,
239 tileY: target.pos.tileY,
240 targetEntityId: pending.targetEntityId
241 };
242}
243
244function queueSpellApproach (world, handle, entityId, target, minStandDist)
245{
246 const position = world.ecs.get(handle, Component.position);
247 if (!position)
248 { return; }
249 queueStandInRangeApproach(
250 world,
251 entityId,
252 handle,
253 position,
254 target.tileX,
255 target.tileY,
256 COMBAT_RANGE_TILES,
257 minStandDist
258 );
259}
260
261function beginCastOrApproach (world, sessionId, characterId, spellId, target, now, minStandDist = 0)
262{
263 const { handle, entityId } = requirePlayer(world, sessionId, characterId);
264 ensureSpellComponents(world.ecs, handle);
265 const casting = world.ecs.get(handle, Component.spellcasting);
266 const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
267 if (!rangeCheck.ok)
268 {
269 casting.pendingCast = {
270 spellId,
271 tileX: target.tileX,
272 tileY: target.tileY,
273 targetEntityId: target.targetEntityId ?? null
274 };
275 queueSpellApproach(world, handle, entityId, target, minStandDist);
276 return { events: [] };
277 }
278 casting.pendingCast = null;
279 return executeCast(world, sessionId, characterId, spellId, target, now);
280}
281
282function castSpellAtTile (world, sessionId, command, now)
283{
284 const spellId = command.spellId;
285 const def = spellDefinition(spellId);
286 if (!def || def.target !== "tile")
287 {
288 const error = new Error("That spell needs a different target.");
289 error.userFacing = true;
290 throw error;
291 }
292 return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
293 tileX: command.tileX | 0,
294 tileY: command.tileY | 0,
295 targetEntityId: null
296 }, now, 0);
297}
298
299function castSpellAtEntity (world, sessionId, command, now)
300{
301 const spellId = command.spellId;
302 const def = spellDefinition(spellId);
303 if (!def || def.target !== "entity")
304 {
305 const error = new Error("That spell needs a tile target.");
306 error.userFacing = true;
307 throw error;
308 }
309 const target = resolveCombatTarget(world, command.targetEntityId);
310 if (!target)
311 {
312 const error = new Error("Target is not here.");
313 error.userFacing = true;
314 throw error;
315 }
316 return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
317 tileX: target.pos.tileX,
318 tileY: target.pos.tileY,
319 targetEntityId: command.targetEntityId
320 }, now, 1);
321}
322
323function executeCast (world, sessionId, characterId, spellId, target, now)
324{
325 const { handle, entityId, character } = requirePlayer(world, sessionId, characterId);
326 ensureSpellComponents(world.ecs, handle);
327 const skills = world.ecs.get(handle, Component.skills);
328 const spells = world.ecs.get(handle, Component.spells);
329 const casting = world.ecs.get(handle, Component.spellcasting);
330 const def = spellDefinition(spellId);
331 const check = canCastSpell(skills, spells, spellId);
332 if (!check.ok)
333 {
334 const error = new Error(check.reason);
335 error.userFacing = true;
336 throw error;
337 }
338 if (now < (casting.nextCastAt || 0))
339 {
340 const error = new Error("You are not ready to cast yet.");
341 error.userFacing = true;
342 throw error;
343 }
344 const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
345 if (!rangeCheck.ok)
346 {
347 const error = new Error(rangeCheck.reason);
348 error.userFacing = true;
349 throw error;
350 }
351
352 const levels = casterMagicLevels(world.ecs, handle);
353 const difficulty = spellDifficulty(def);
354 const cast = resolveSpellCast({
355 magicSkillLevel: levels.magic,
356 spellDifficulty: difficulty
357 });
358
359 const events = [];
360 const from = world.ecs.get(handle, Component.position);
361 casting.armedSpellId = null;
362 casting.repeatSpellId = null;
363 casting.repeatTargetEntityId = null;
364 casting.nextCastAt = now + SPELL_COOLDOWN_MS;
365 events.push({
366 type: "spell-disarmed",
367 entityId,
368 characterId: character.characterId
369 });
370
371 if (!cast.success)
372 {
373 events.push({
374 type: "spell-fizzle",
375 casterId: entityId,
376 spellId,
377 fromTileX: from.tileX,
378 fromTileY: from.tileY,
379 tileX: target.tileX,
380 tileY: target.tileY
381 });
382 return { events };
383 }
384
385 const xpAward = awardSpellCastXp(world.ecs, handle, difficulty);
386 if (xpAward)
387 {
388 events.push({
389 type: "skills-updated",
390 entityId,
391 characterId: character.characterId,
392 skills: xpAward.view,
393 stored: xpAward.stored,
394 levelUps: xpAward.levelUps ?? []
395 });
396 }
397
398 const flashRadius = castFlashRadiusTiles(def.tier);
399 events.push({
400 type: "spell-cast-flash",
401 casterId: entityId,
402 tileX: from.tileX,
403 tileY: from.tileY,
404 radiusTiles: flashRadius,
405 durationMs: CAST_FLASH_MS,
406 tier: def.tier
407 });
408
409 world.pendingSpellImpacts.push({
410 executeAt: now + SPELL_PROJECTILE_MS,
411 casterEntityId: entityId,
412 casterCharacterId: character.characterId,
413 spellId,
414 targetTileX: target.tileX,
415 targetTileY: target.tileY,
416 targetEntityId: target.targetEntityId,
417 levels
418 });
419
420 events.push({
421 type: "spell-projectile",
422 casterId: entityId,
423 spellId,
424 fromTileX: from.tileX,
425 fromTileY: from.tileY,
426 tileX: target.tileX,
427 tileY: target.tileY,
428 durationMs: SPELL_PROJECTILE_MS,
429 sprite: def.projectileSprite
430 });
431
432 if (def.autoRepeat && spells.autoCast && target.targetEntityId != null)
433 {
434 casting.repeatSpellId = spellId;
435 casting.repeatTargetEntityId = target.targetEntityId;
436 }
437 else
438 {
439 casting.repeatSpellId = null;
440 casting.repeatTargetEntityId = null;
441 }
442
443 return { events };
444}
445
446function targetAffinitiesForEntity (world, entityId)
447{
448 if (entityId == null)
449 { return {}; }
450 const handle = world.ecs.handleOf(entityId);
451 if (handle == null)
452 { return {}; }
453 const creature = world.ecs.get(handle, Component.creature);
454 if (!creature)
455 { return {}; }
456 return mobElementAffinities(mobDefinition(creature.mobTypeId));
457}
458
459export function processSpellImpacts (world, now = Date.now())
460{
461 const queue = world.pendingSpellImpacts ?? [];
462 if (!queue.length)
463 { return []; }
464 const events = [];
465 const keep = [];
466 for (const impact of queue)
467 {
468 if (impact.executeAt > now)
469 {
470 keep.push(impact);
471 continue;
472 }
473 events.push(...applySpellImpact(world, impact, now));
474 }
475 world.pendingSpellImpacts = keep;
476 return events;
477}
478
479function applySpellImpact (world, impact, now)
480{
481 const def = spellDefinition(impact.spellId);
482 if (!def)
483 { return []; }
484 const events = [];
485 events.push({
486 type: "spell-cast-flash",
487 casterId: impact.casterEntityId,
488 tileX: impact.targetTileX,
489 tileY: impact.targetTileY,
490 radiusTiles: castFlashRadiusTiles(def.tier),
491 durationMs: CAST_FLASH_MS,
492 tier: def.tier
493 });
494
495 if (impact.spellId === SpellId.light)
496 {
497 world.spellLights = world.spellLights ?? new SpellLightRegistry();
498 const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
499 const durationMs = mindRoll * LIGHT_DURATION_MS_PER_MIND;
500 const { light, extended } = world.spellLights.placeOrExtend({
501 tileX: impact.targetTileX,
502 tileY: impact.targetTileY,
503 ownerEntityId: impact.casterEntityId,
504 durationMs,
505 now
506 });
507 events.push({
508 type: extended ? "spell-light-update" : "spell-light-appear",
509 ...publicSpellLight(light, now)
510 });
511 return events;
512 }
513
514 if (impact.spellId === SpellId.spark && impact.targetEntityId != null)
515 {
516 const targetHandle = world.ecs.handleOf(impact.targetEntityId);
517 if (targetHandle == null)
518 { return events; }
519 const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
520 const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
521 let multiplier = ElementMultiplier.neutral;
522 const affinity = affinities[def.element ?? "fire"];
523 if (affinity === "weak")
524 { multiplier = ElementMultiplier.weak; }
525 else if (affinity === "resistant")
526 { multiplier = ElementMultiplier.resistant; }
527 const damage = Math.max(1, Math.floor(mindRoll * multiplier));
528 const health = world.ecs.get(targetHandle, Component.health);
529 if (health)
530 {
531 health.current = Math.max(0, (health.current | 0) - damage);
532 }
533 events.push({
534 type: "combat-hit",
535 attackerId: impact.casterEntityId,
536 targetId: impact.targetEntityId,
537 damage,
538 tileX: impact.targetTileX,
539 tileY: impact.targetTileY,
540 health: health?.current ?? 0,
541 maxHealth: health?.max ?? 0
542 });
543 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
544 if (casterHandle != null)
545 {
546 const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);
547 if (xp)
548 {
549 events.push({
550 type: "skills-updated",
551 entityId: impact.casterEntityId,
552 characterId: impact.casterCharacterId,
553 skills: xp.view,
554 stored: xp.stored,
555 levelUps: xp.levelUps ?? []
556 });
557 }
558 }
559 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
560 if (healthXp)
561 {
562 events.push({
563 type: "skills-updated",
564 entityId: impact.targetEntityId,
565 characterId: healthXp.characterId,
566 skills: healthXp.view,
567 stored: healthXp.stored,
568 levelUps: healthXp.levelUps ?? []
569 });
570 }
571 }
572 return events;
573}
574
575export function stepPendingSpellCast (world, now = Date.now())
576{
577 const events = [];
578 for (const entity of world.ecs.query(Component.spellcasting, Component.character, Component.networkIdentity))
579 {
580 const casting = entity.spellcasting;
581 if (!casting?.pendingCast)
582 { continue; }
583 const pending = casting.pendingCast;
584 const target = resolvePendingCastTarget(world, pending);
585 if (!target)
586 {
587 casting.pendingCast = null;
588 continue;
589 }
590 const rangeCheck = validateCastRange(world, entity.handle, target.tileX, target.tileY, now);
591 if (!rangeCheck.ok)
592 {
593 const minStandDist = target.targetEntityId != null ? 1 : 0;
594 queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist);
595 continue;
596 }
597 casting.pendingCast = null;
598 const result = executeCast(
599 world,
600 entity.networkIdentity.sessionId,
601 entity.character.characterId,
602 pending.spellId,
603 target,
604 now
605 );
606 events.push(...(result.events ?? []));
607 }
608 return events;
609}
610
611export function stepSpellAutoCast (world, now = Date.now())
612{
613 const events = [];
614 for (const entity of world.ecs.query(Component.spellcasting, Component.spells, Component.character))
615 {
616 const casting = entity.spellcasting;
617 const spells = entity.spells;
618 if (!spells.autoCast || !casting.repeatSpellId || casting.repeatTargetEntityId == null)
619 { continue; }
620 if (now < (casting.nextCastAt || 0))
621 { continue; }
622 const def = spellDefinition(casting.repeatSpellId);
623 if (!def?.autoRepeat)
624 { continue; }
625 const target = resolveCombatTarget(world, casting.repeatTargetEntityId);
626 if (!target || (target.health && target.health.current <= 0))
627 {
628 casting.repeatSpellId = null;
629 casting.repeatTargetEntityId = null;
630 continue;
631 }
632 const range = validateCastRange(world, entity.handle, target.pos.tileX, target.pos.tileY, now);
633 if (!range.ok)
634 { continue; }
635 const sessionId = entity.networkIdentity?.sessionId;
636 if (!sessionId)
637 { continue; }
638 const result = executeCast(
639 world,
640 sessionId,
641 entity.character.characterId,
642 casting.repeatSpellId,
643 {
644 tileX: target.pos.tileX,
645 tileY: target.pos.tileY,
646 targetEntityId: casting.repeatTargetEntityId
647 },
648 now
649 );
650 events.push(...(result.events ?? []));
651 }
652 return events;
653}
654
655export function tickSpellLights (world, now = Date.now())
656{
657 if (!world.spellLights)
658 { return []; }
659 return world.spellLights.tick(world, now);
660}
661
662function readSpellbook (world, sessionId, command, now)
663{
664 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
665 ensureSpellComponents(world.ecs, handle);
666 const inventory = world.ecs.get(handle, Component.inventory);
667 const slotIndex = command.slotIndex | 0;
668 const slot = inventory?.slots?.[slotIndex];
669 if (!slot?.instance || slot.instance.kind !== "spellbook")
670 {
671 const error = new Error("That is not a spellbook.");
672 error.userFacing = true;
673 throw error;
674 }
675 const spellId = slot.instance.spellId;
676 const spells = world.ecs.get(handle, Component.spells);
677 const skills = world.ecs.get(handle, Component.skills);
678 const learned = learnSpell(spells, spellId);
679 if (!learned.changed)
680 {
681 const error = new Error("You already know that spell.");
682 error.userFacing = true;
683 throw error;
684 }
685 Object.assign(spells, learned.spells);
686 inventory.slots[slotIndex] = null;
687 const events = [
688 spellsUpdatedEvent(entityId, character.characterId, spells, skills)
689 ];
690 return {
691 events,
692 private: bagView(world.ecs, handle)
693 };
694}
695
696export function createSpellbookStack (spellId)
697{
698 const instance = spellbookInstance(spellId);
699 if (!instance)
700 { return null; }
701 const itemId = spellId === SpellId.spark
702 ? SpellbookItemId.sparkSpellbook
703 : null;
704 if (itemId == null)
705 { return null; }
706 return { itemId, quantity: 1, instance };
707}