BlueGit

timfa questward

Files

questward / server / src / spells / service.js

service.js

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