import { Component } from "../ecs/components.js"; import { SkillId, skillLevel } from "../../../shared/definitions/skills.js"; import { SpellId, spellDefinition, spellDifficulty } from "../../../shared/definitions/spells.js"; import { canCastSpell, defaultPlayerSpells, normalizePlayerSpells, publicSpellsView, storedPlayerSpells, toggleFavorite, learnSpell } from "../../../shared/spells/state.js"; import { CAST_FLASH_MS, COMBAT_RANGE_TILES, LIGHT_DURATION_MS_PER_MIND, SPELL_COOLDOWN_MS, SPELL_LIGHT_RANGE_TILES, SPELL_PROJECTILE_MS, castFlashRadiusTiles } from "../../../shared/spells/constants.js"; import { mobDamageAffinities, mobElementAffinities, ElementMultiplier, resolveMagicAttack, resolveSpellCast, resolveSpellPotency } from "../../../shared/combat/magic.js"; import { rollSpellDamage } from "../../../shared/combat/rolls.js"; import { mobDefinition } from "../../../shared/definitions/mobs.js"; import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js"; import { equipmentBonusesFromSlots, effectiveSkillLevel } from "../../../shared/equipment/stats.js"; import { statusSkillBonuses, applyStatusEffect, emptyStatusEffects, StatusEffectType, publicStatusEffectsView, hasStatusEffect } from "../../../shared/statusEffects/rules.js"; import { chebyshev, clearEngage, hasCombatLineOfSight, queueStandInRangeApproach, resolveCombatTarget, applyDamageAndKill } from "../combat/service.js"; import { storedSkillXp } from "../../../shared/skills/state.js"; import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js"; import { publicSpellLight, SpellLightRegistry } from "./lights.js"; import { spellbookInstance, spellbookItemIdForSpell, spellIdFromSpellbookStack } from "../../../shared/definitions/spellItems.js"; import { itemDefinition } from "../../../shared/definitions/items.js"; import { bagView } from "../items/bags.js"; import { applyTindersAtTile, tindersTileStillNeedsCast } from "./tinders.js"; const MAGIC_ATTACK_PROFILE = Object.freeze({ hitSkillId: SkillId.magic, damageSkillId: SkillId.mind }); export function ensureSpellComponents (ecs, handle, storedSpells = null) { if (!ecs.get(handle, Component.spells)) { ecs.add(handle, Component.spells, normalizePlayerSpells(storedSpells ?? defaultPlayerSpells())); } if (!ecs.get(handle, Component.spellcasting)) { ecs.add(handle, Component.spellcasting, emptySpellcasting()); } else { normalizeSpellcasting(ecs.get(handle, Component.spellcasting)); } } export function emptySpellcasting () { return { armedSpellId: null, repeatSpellId: null, repeatTargetEntityId: null, repeatTileX: null, repeatTileY: null, nextCastAt: 0, pendingCast: null }; } function normalizeSpellcasting (casting) { if (!casting) { return; } if (!("repeatTileX" in casting)) { casting.repeatTileX = null; } if (!("repeatTileY" in casting)) { casting.repeatTileY = null; } } /** Clear auto-repeat / pending cast state (move, melee, cancel, …). */ export function clearSpellAutoRepeat (casting) { if (!casting) { return; } casting.repeatSpellId = null; casting.repeatTargetEntityId = null; casting.repeatTileX = null; casting.repeatTileY = null; casting.pendingCast = null; } function stopCasterMovement (world, handle, entityId) { clearEngage(world.ecs, entityId); const path = world.ecs.get(handle, Component.path); if (path?.tiles?.length) { path.tiles = []; } const movement = world.ecs.get(handle, Component.movement); if (movement) { movement.walkCarry = 0; } } export function handleSpellCommand (world, sessionId, command, now = Date.now()) { switch (command.type) { case "set-spell-favorite": return setSpellFavorite(world, sessionId, command, now); case "set-spell-autocast": return setSpellAutoCast(world, sessionId, command, now); case "arm-spell": return armSpell(world, sessionId, command, now); case "cancel-arm-spell": return cancelArmSpell(world, sessionId, command, now); case "cast-spell-tile": return castSpellAtTile(world, sessionId, command, now); case "cast-spell-entity": return castSpellAtEntity(world, sessionId, command, now); case "read-spellbook": return readSpellbook(world, sessionId, command, now); default: return null; } } function requirePlayer (world, sessionId, characterId) { for (const entity of world.ecs.query(Component.networkIdentity, Component.character)) { if (entity.networkIdentity.sessionId !== sessionId) { continue; } if (entity.character.characterId !== characterId) { continue; } if (world.ecs.has(entity.handle, Component.dead)) { const error = new Error("You are dead."); error.userFacing = true; throw error; } return { handle: entity.handle, entityId: entity.entityId, character: entity.character }; } const error = new Error("Character not found."); error.userFacing = true; throw error; } function spellsUpdatedEvent (entityId, characterId, spells, skills, levelUps = []) { return { type: "spells-updated", entityId, characterId, spells: publicSpellsView(spells, skills), stored: storedPlayerSpells(spells), autoCast: !!spells.autoCast, levelUps }; } function setSpellFavorite (world, sessionId, command, now) { const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId); ensureSpellComponents(world.ecs, handle); const skills = world.ecs.get(handle, Component.skills); const spells = world.ecs.get(handle, Component.spells); const result = toggleFavorite(spells, command.spellId, skills); if (result.error) { const error = new Error(result.error); error.userFacing = true; throw error; } Object.assign(spells, result.spells); const events = []; if (result.changed) { events.push(spellsUpdatedEvent(entityId, character.characterId, spells, skills)); } return { events }; } function setSpellAutoCast (world, sessionId, command, now) { const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId); ensureSpellComponents(world.ecs, handle); const skills = world.ecs.get(handle, Component.skills); const spells = world.ecs.get(handle, Component.spells); spells.autoCast = !!command.enabled; const casting = world.ecs.get(handle, Component.spellcasting); if (!spells.autoCast) { clearSpellAutoRepeat(casting); } return { events: [spellsUpdatedEvent(entityId, character.characterId, spells, skills)] }; } function armSpell (world, sessionId, command, now) { const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId); ensureSpellComponents(world.ecs, handle); const skills = world.ecs.get(handle, Component.skills); const spells = world.ecs.get(handle, Component.spells); const check = canCastSpell(skills, spells, command.spellId); if (!check.ok) { const error = new Error(check.reason); error.userFacing = true; throw error; } const casting = world.ecs.get(handle, Component.spellcasting); casting.armedSpellId = command.spellId; casting.pendingCast = null; /** Re-arming the active auto-repeat spell must not cancel it (favourite bar clicks). */ if (casting.repeatSpellId != null && casting.repeatSpellId !== command.spellId) { casting.repeatSpellId = null; casting.repeatTargetEntityId = null; casting.repeatTileX = null; casting.repeatTileY = null; } return { events: [{ type: "spell-armed", entityId, characterId: character.characterId, spellId: command.spellId }] }; } function cancelArmSpell (world, sessionId, command) { const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId); const casting = world.ecs.get(handle, Component.spellcasting); if (!casting) { return { events: [] }; } casting.armedSpellId = null; casting.pendingCast = null; /** * Do not clear auto-repeat here. Cast already disarms then sets repeat; a late * cancel-arm (right-click while the client still thought it was armed) used to * wipe that repeat and leave the player falling back to melee. */ return { events: [{ type: "spell-disarmed", entityId, characterId: character.characterId }] }; } function casterMagicLevels (ecs, handle, settings = null) { const skills = ecs.get(handle, Component.skills); const equipment = ecs.get(handle, Component.equipment); const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings); const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now()); bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0); return { magic: effectiveSkillLevel(skills, SkillId.magic, bonuses), mind: effectiveSkillLevel(skills, SkillId.mind, bonuses) }; } function validateCastRange (world, handle, tileX, tileY, now) { const pos = world.ecs.get(handle, Component.position); if (!pos) { return { ok: false, reason: "You are not in the world." }; } const dist = chebyshev(pos.tileX, pos.tileY, tileX, tileY); if (dist > COMBAT_RANGE_TILES) { return { ok: false, reason: "That is out of range." }; } if (!hasCombatLineOfSight(world, pos.tileX, pos.tileY, tileX, tileY)) { return { ok: false, reason: "You cannot see that spot." }; } return { ok: true }; } function resolvePendingCastTarget (world, pending) { if (pending.targetEntityId == null) { return { tileX: pending.tileX | 0, tileY: pending.tileY | 0, targetEntityId: null }; } const target = resolveCombatTarget(world, pending.targetEntityId); if (!target) { return null; } return { tileX: target.pos.tileX, tileY: target.pos.tileY, targetEntityId: pending.targetEntityId }; } function queueSpellApproach (world, handle, entityId, target, minStandDist) { const position = world.ecs.get(handle, Component.position); if (!position) { return; } queueStandInRangeApproach( world, entityId, handle, position, target.tileX, target.tileY, COMBAT_RANGE_TILES, minStandDist ); } function beginCastOrApproach (world, sessionId, characterId, spellId, target, now, minStandDist = 0) { const { handle, entityId } = requirePlayer(world, sessionId, characterId); ensureSpellComponents(world.ecs, handle); const casting = world.ecs.get(handle, Component.spellcasting); stopCasterMovement(world, handle, entityId); const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now); if (!rangeCheck.ok) { casting.pendingCast = { spellId, tileX: target.tileX, tileY: target.tileY, targetEntityId: target.targetEntityId ?? null }; queueSpellApproach(world, handle, entityId, target, minStandDist); return { events: [] }; } casting.pendingCast = null; return executeCast(world, sessionId, characterId, spellId, target, now); } function castSpellAtTile (world, sessionId, command, now) { const spellId = command.spellId; const def = spellDefinition(spellId); if (!def || def.target !== "tile") { const error = new Error("That spell needs a different target."); error.userFacing = true; throw error; } return beginCastOrApproach(world, sessionId, command.characterId, spellId, { tileX: command.tileX | 0, tileY: command.tileY | 0, targetEntityId: null }, now, 0); } function castSpellAtEntity (world, sessionId, command, now) { const spellId = command.spellId; const def = spellDefinition(spellId); if (!def || def.target !== "entity") { const error = new Error("That spell needs a tile target."); error.userFacing = true; throw error; } const { entityId: casterEntityId } = requirePlayer(world, sessionId, command.characterId); const target = resolveCombatTarget(world, command.targetEntityId); if (!target) { const error = new Error("Target is not here."); error.userFacing = true; throw error; } const selfTarget = command.targetEntityId === casterEntityId; return beginCastOrApproach(world, sessionId, command.characterId, spellId, { tileX: target.pos.tileX, tileY: target.pos.tileY, targetEntityId: command.targetEntityId }, now, selfTarget ? 0 : 1); } function executeCast (world, sessionId, characterId, spellId, target, now) { const { handle, entityId, character } = requirePlayer(world, sessionId, characterId); ensureSpellComponents(world.ecs, handle); const skills = world.ecs.get(handle, Component.skills); const spells = world.ecs.get(handle, Component.spells); const casting = world.ecs.get(handle, Component.spellcasting); const def = spellDefinition(spellId); const check = canCastSpell(skills, spells, spellId); if (!check.ok) { const error = new Error(check.reason); error.userFacing = true; throw error; } if (now < (casting.nextCastAt || 0)) { const error = new Error("You are not ready to cast yet."); error.userFacing = true; throw error; } const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now); if (!rangeCheck.ok) { const error = new Error(rangeCheck.reason); error.userFacing = true; throw error; } stopCasterMovement(world, handle, entityId); const levels = casterMagicLevels(world.ecs, handle, world.settings); const difficulty = spellDifficulty(def); const cast = resolveSpellCast({ magicSkillLevel: levels.magic, spellDifficulty: difficulty }); const events = []; const from = world.ecs.get(handle, Component.position); casting.armedSpellId = null; casting.nextCastAt = now + SPELL_COOLDOWN_MS; events.push({ type: "spell-disarmed", entityId, characterId: character.characterId }); // Keep / refresh auto-repeat even on fizzle so we keep trying until cancelled. rememberAutoRepeat(casting, spells, def, spellId, target); if (!cast.success) { events.push({ type: "spell-fizzle", casterId: entityId, spellId, fromTileX: from.tileX, fromTileY: from.tileY, tileX: target.tileX, tileY: target.tileY }); return { events }; } const xpAward = awardSpellCastXp(world.ecs, handle, difficulty); if (xpAward) { events.push({ type: "skills-updated", entityId, characterId: character.characterId, skills: xpAward.skills, combatLevel: xpAward.combatLevel, stored: xpAward.stored, levelUps: xpAward.levelUps ?? [] }); } const flashRadius = castFlashRadiusTiles(def.tier); events.push({ type: "spell-cast-flash", casterId: entityId, tileX: from.tileX, tileY: from.tileY, radiusTiles: flashRadius, durationMs: CAST_FLASH_MS, tier: def.tier }); world.pendingSpellImpacts.push({ executeAt: now + SPELL_PROJECTILE_MS, casterEntityId: entityId, casterCharacterId: character.characterId, spellId, targetTileX: target.tileX, targetTileY: target.tileY, targetEntityId: target.targetEntityId, levels }); events.push({ type: "spell-projectile", casterId: entityId, spellId, targetId: target.targetEntityId ?? null, fromTileX: from.tileX, fromTileY: from.tileY, tileX: target.tileX, tileY: target.tileY, durationMs: SPELL_PROJECTILE_MS, sprite: def.projectileSprite }); return { events }; } function rememberAutoRepeat (casting, spells, def, spellId, target) { if (!casting || !def?.autoRepeat) { clearSpellAutoRepeat(casting); return; } const continuingEntityRepeat = !!( casting.repeatSpellId === spellId && casting.repeatTargetEntityId != null && target?.targetEntityId != null && def.target === "entity" ); if (!spells?.autoCast && !continuingEntityRepeat) { clearSpellAutoRepeat(casting); return; } if (def.target === "entity" && target?.targetEntityId != null) { casting.repeatSpellId = spellId; casting.repeatTargetEntityId = target.targetEntityId | 0; casting.repeatTileX = null; casting.repeatTileY = null; casting.pendingCast = null; return; } if (def.target === "tile") { if (!spells?.autoCast) { clearSpellAutoRepeat(casting); return; } casting.repeatSpellId = spellId; casting.repeatTargetEntityId = null; casting.repeatTileX = target.tileX | 0; casting.repeatTileY = target.tileY | 0; casting.pendingCast = null; return; } clearSpellAutoRepeat(casting); } function targetAffinitiesForEntity (world, entityId) { if (entityId == null) { return {}; } const handle = world.ecs.handleOf(entityId); if (handle == null) { return {}; } const creature = world.ecs.get(handle, Component.creature); if (!creature) { return {}; } return mobDamageAffinities(mobDefinition(creature.mobTypeId)); } function applySpellImpact (world, impact, now) { const def = spellDefinition(impact.spellId); if (!def) { return []; } const events = []; events.push({ type: "spell-cast-flash", casterId: impact.casterEntityId, tileX: impact.targetTileX, tileY: impact.targetTileY, radiusTiles: castFlashRadiusTiles(def.tier), durationMs: CAST_FLASH_MS, tier: def.tier }); const effect = def.effect ?? impact.spellId; if (effect === "light" || effect === "dark") { events.push(...applyLightOrDarkImpact(world, impact, def, effect, now)); return events; } if (effect === "damage") { events.push(...applyDamageSpellImpact(world, impact, def, now)); return events; } if (effect === "poison") { events.push(...applyPoisonImpact(world, impact, def, now)); return events; } if (effect === "drain") { events.push(...applyDrainImpact(world, impact, now)); return events; } if (effect === "revitalize") { events.push(...applyRevitalizeImpact(world, impact, now)); return events; } if (effect === "tinders") { events.push(...applyTindersImpact(world, impact, now)); return events; } if (effect === "shade") { events.push(...applyShadeImpact(world, impact, now)); return events; } return events; } function mindRollOf (impact) { return resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll; } function mindDamageRollOf (impact, spellTier = 1) { return rollSpellDamage(impact.levels.mind, spellTier); } function applyLightOrDarkImpact (world, impact, def, effect, now) { const events = []; world.spellLights = world.spellLights ?? new SpellLightRegistry(); const mindRoll = mindRollOf(impact); const durationMs = Math.max(1, mindRoll) * LIGHT_DURATION_MS_PER_MIND; const baseRange = mindRoll === 0 ? SPELL_LIGHT_RANGE_TILES * 0.5 : SPELL_LIGHT_RANGE_TILES; const kind = effect === "dark" ? "dark" : "light"; const { light, extended } = world.spellLights.placeOrExtend({ tileX: impact.targetTileX, tileY: impact.targetTileY, ownerEntityId: impact.casterEntityId, durationMs, baseRange, kind, now }); const appear = kind === "dark" ? (extended ? "spell-dark-update" : "spell-dark-appear") : (extended ? "spell-light-update" : "spell-light-appear"); events.push({ type: appear, ...publicSpellLight(light, now) }); return events; } function elementalDamageMultiplier (def, affinities) { let multiplier = ElementMultiplier.neutral; const affinity = affinities[def.element ?? "none"]; if (affinity === "weak") { multiplier = ElementMultiplier.weak; } else if (affinity === "resistant") { multiplier = ElementMultiplier.resistant; } return multiplier; } function applyDamageSpellImpact (world, impact, def, now) { if (impact.targetEntityId == null) { return []; } const events = []; const affinities = targetAffinitiesForEntity(world, impact.targetEntityId); const mindRoll = mindDamageRollOf(impact, def.tier); const multiplier = elementalDamageMultiplier(def, affinities); const damage = Math.max(1, Math.floor(mindRoll * multiplier)); events.push(...applyDamageAndKill( world, impact.casterEntityId, impact.targetEntityId, damage, now )); events.push(...awardMagicHitXp(world, impact, damage)); return events; } function awardMagicHitXp (world, impact, damage) { const events = []; const casterHandle = world.ecs.handleOf(impact.casterEntityId); if (casterHandle == null || !impact.casterCharacterId) { return events; } const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage); if (xp) { events.push({ type: "skills-updated", entityId: impact.casterEntityId, characterId: impact.casterCharacterId, skills: xp.skills, combatLevel: xp.combatLevel, stored: xp.stored, levelUps: xp.levelUps ?? [] }); } return events; } function ensureEntityStatusEffects (ecs, handle) { let component = ecs.get(handle, Component.statusEffects); if (!component) { component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); } return component; } function applyPoisonImpact (world, impact, def, now) { if (impact.targetEntityId == null) { return []; } const target = resolveCombatTarget(world, impact.targetEntityId); if (!target?.local || target.handle == null) { return []; } const affinities = targetAffinitiesForEntity(world, impact.targetEntityId); const mindRoll = mindRollOf(impact); const multiplier = elementalDamageMultiplier(def, affinities); const total = Math.max(1, Math.floor(mindRoll * multiplier * 2)); const durationMs = total * 1000; const status = ensureEntityStatusEffects(world.ecs, target.handle); applyStatusEffect(status, { type: StatusEffectType.healthDrain, durationMs, amountPerSecond: 1 }, now); return [{ type: "status-effects-entity", entityId: impact.targetEntityId, effects: publicStatusEffectsView(status, now) }]; } function applyDrainImpact (world, impact, now) { if (impact.targetEntityId == null) { return []; } const target = resolveCombatTarget(world, impact.targetEntityId); if (!target?.local || target.handle == null) { return []; } if (!world.ecs.get(target.handle, Component.stamina)) { return []; } const mindRoll = mindRollOf(impact); const durationMs = Math.max(1000, mindRoll * 3 * 1000); const status = ensureEntityStatusEffects(world.ecs, target.handle); applyStatusEffect(status, { type: StatusEffectType.staminaDrain, durationMs, amountPerSecond: 1 }, now); applyStatusEffect(status, { type: StatusEffectType.staminaBlock, durationMs, amountPerSecond: 0 }, now); const character = world.ecs.get(target.handle, Component.character); const events = [{ type: "status-effects-entity", entityId: impact.targetEntityId, effects: publicStatusEffectsView(status, now) }]; if (character?.characterId) { events.push({ type: "status-effects", characterId: character.characterId, effects: publicStatusEffectsView(status, now), blind: hasStatusEffect(status, StatusEffectType.blind, now) }); } return events; } function applyRevitalizeImpact (world, impact, now) { if (impact.targetEntityId == null) { return []; } const target = resolveCombatTarget(world, impact.targetEntityId); if (!target?.local || target.handle == null) { return []; } if (!world.ecs.get(target.handle, Component.health)) { return []; } const mindRoll = mindRollOf(impact); const healTotal = Math.max(1, mindRoll); const durationMs = healTotal * 1000; const status = ensureEntityStatusEffects(world.ecs, target.handle); applyStatusEffect(status, { type: StatusEffectType.healthRegen, durationMs, amountPerSecond: 1 }, now); const character = world.ecs.get(target.handle, Component.character); const events = [{ type: "status-effects-entity", entityId: impact.targetEntityId, effects: publicStatusEffectsView(status, now) }]; if (character?.characterId) { events.push({ type: "status-effects", characterId: character.characterId, effects: publicStatusEffectsView(status, now), blind: hasStatusEffect(status, StatusEffectType.blind, now) }); } return events; } function applyTindersImpact (world, impact, now) { const events = applyTindersAtTile(world, impact, now); const casterHandle = world.ecs.handleOf(impact.casterEntityId); const sessionId = casterHandle != null ? world.ecs.get(casterHandle, Component.networkIdentity)?.sessionId : null; for (const event of events) { if (event.type === "command-error" && sessionId != null) { event.sessionId = sessionId; } } return events; } function applyShadeImpact (world, impact, now) { const mindRoll = mindRollOf(impact); const durationMs = Math.max(1000, mindRoll * 3 * 1000); const casterHandle = world.ecs.handleOf(impact.casterEntityId); const mindLevel = impact.levels?.mind | 0 || 1; const level = Math.max(1, Math.min(99, Math.floor(mindLevel * 0.75))); return [{ type: "summon-entity", ownerEntityId: impact.casterEntityId, ownerCharacterId: impact.casterCharacterId ?? null, tileX: impact.targetTileX, tileY: impact.targetTileY, level, expiresAt: now + durationMs, mobTypeId: "shade" }]; } export function processSpellImpacts (world, now = Date.now()) { const queue = world.pendingSpellImpacts ?? []; if (!queue.length) { return []; } const events = []; const keep = []; for (const impact of queue) { if (impact.executeAt > now) { keep.push(impact); continue; } events.push(...applySpellImpact(world, impact, now)); } world.pendingSpellImpacts = keep; return events; } export function stepPendingSpellCast (world, now = Date.now()) { const events = []; for (const entity of world.ecs.query(Component.spellcasting, Component.character, Component.networkIdentity)) { if (world.ecs.has(entity.handle, Component.dead)) { if (entity.spellcasting) { entity.spellcasting.pendingCast = null; } continue; } const casting = entity.spellcasting; if (!casting?.pendingCast) { continue; } const pending = casting.pendingCast; const target = resolvePendingCastTarget(world, pending); if (!target) { casting.pendingCast = null; continue; } const rangeCheck = validateCastRange(world, entity.handle, target.tileX, target.tileY, now); if (!rangeCheck.ok) { const minStandDist = target.targetEntityId != null ? 1 : 0; queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist); continue; } casting.pendingCast = null; const result = executeCast( world, entity.networkIdentity.sessionId, entity.character.characterId, pending.spellId, target, now ); events.push(...(result.events ?? [])); } return events; } export function stepSpellAutoCast (world, now = Date.now()) { const events = []; for (const entity of world.ecs.query( Component.spellcasting, Component.spells, Component.character, Component.networkIdentity )) { if (world.ecs.has(entity.handle, Component.dead)) { clearSpellAutoRepeat(entity.spellcasting); continue; } const casting = entity.spellcasting; const spells = entity.spells; normalizeSpellcasting(casting); if (!casting.repeatSpellId) { continue; } if (now < (casting.nextCastAt || 0)) { continue; } const def = spellDefinition(casting.repeatSpellId); if (!def?.autoRepeat) { clearSpellAutoRepeat(casting); continue; } /** UI auto-cast toggle gates starting repeats; combat retaliate may set repeat without it. */ if (!spells.autoCast && casting.repeatTargetEntityId == null) { clearSpellAutoRepeat(casting); continue; } const sessionId = entity.networkIdentity.sessionId; if (!sessionId) { continue; } let target = null; let minStandDist = 0; if (casting.repeatTargetEntityId != null) { const resolved = resolveCombatTarget(world, casting.repeatTargetEntityId); if (!resolved || (resolved.health && resolved.health.current <= 0)) { clearSpellAutoRepeat(casting); continue; } target = { tileX: resolved.pos.tileX, tileY: resolved.pos.tileY, targetEntityId: casting.repeatTargetEntityId }; minStandDist = casting.repeatTargetEntityId === entity.entityId ? 0 : 1; } else if (casting.repeatTileX != null && casting.repeatTileY != null) { if (!tileAutoCastStillValid(world, casting.repeatSpellId, casting.repeatTileX, casting.repeatTileY)) { clearSpellAutoRepeat(casting); continue; } target = { tileX: casting.repeatTileX | 0, tileY: casting.repeatTileY | 0, targetEntityId: null }; minStandDist = 0; } else { clearSpellAutoRepeat(casting); continue; } const range = validateCastRange(world, entity.handle, target.tileX, target.tileY, now); if (!range.ok) { queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist); continue; } const result = executeCast( world, sessionId, entity.character.characterId, casting.repeatSpellId, target, now ); events.push(...(result.events ?? [])); } return events; } function tileAutoCastStillValid (world, spellId, tileX, tileY) { const def = spellDefinition(spellId); if (!def) { return false; } if (def.effect === "tinders") { return tindersTileStillNeedsCast(world, tileX, tileY); } return true; } export function tickSpellLights (world, now = Date.now()) { if (!world.spellLights) { return []; } return world.spellLights.tick(world, now); } function readSpellbook (world, sessionId, command, now) { const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId); ensureSpellComponents(world.ecs, handle); const inventory = world.ecs.get(handle, Component.inventory); const slotIndex = command.slotIndex | 0; const slot = inventory?.slots?.[slotIndex]; const itemDef = itemDefinition(slot?.itemId); const spellId = spellIdFromSpellbookStack(slot, itemDef); if (!spellId) { const error = new Error("That is not a spellbook."); error.userFacing = true; throw error; } const spells = world.ecs.get(handle, Component.spells); const skills = world.ecs.get(handle, Component.skills); const learned = learnSpell(spells, spellId); if (!learned.changed) { const error = new Error("You already know that spell."); error.userFacing = true; throw error; } Object.assign(spells, learned.spells); inventory.slots[slotIndex] = null; const events = [ spellsUpdatedEvent(entityId, character.characterId, spells, skills) ]; return { events, private: bagView(world.ecs, handle) }; } export function createSpellbookStack (spellId) { const instance = spellbookInstance(spellId); const itemId = spellbookItemIdForSpell(spellId); if (!instance || itemId == null) { return null; } return { itemId, quantity: 1, instance }; }