Files
ClassicAssist.Avalonia/.qoder/repowiki/en/content/API Reference/Macro Commands/Spell Commands.md
T
Beyhan Oğur d5f52cc3d3 first commit
2026-09-03 04:45:36 +03:00

19 KiB

Spell Commands

**Referenced Files in This Document** - [SpellCommands.cs](file://ClassicAssist.Shared/Data/Macros/Commands/SpellCommands.cs) - [SpellManager.cs](file://ClassicAssist.Shared/Data/Spells/SpellManager.cs) - [SpellData.cs](file://ClassicAssist.Shared/Data/Spells/SpellData.cs) - [Targeting.cs](file://ClassicAssist.Shared/Data/Hotkeys/Commands/Targeting.cs) - [TargetManager.cs](file://ClassicAssist.Shared/Data/Targeting/TargetManager.cs) - [CastSpell.cs](file://ClassicAssist.Shared/UO/Network/Packets/CastSpell.cs) - [InterruptSpellCommand.cs](file://ClassicAssist.Shared/Data/Hotkeys/Commands/InterruptSpellCommand.cs) - [CastLastSpell.cs](file://ClassicAssist.Shared/Data/Hotkeys/Commands/CastLastSpell.cs) - [PlayerMobile.cs](file://ClassicAssist.Shared/UO/Objects/PlayerMobile.cs) - [IncomingPacketHandlers.cs](file://ClassicAssist.Shared/UO/Network/IncomingPacketHandlers.cs)

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion
  10. Appendices

Introduction

This document explains the macro commands that interact with the magic system, focusing on spell casting methods, mana management, targeting, and effect monitoring. It provides method signatures for spell invocation, target specification, and condition checking, along with examples of chaining spells, managing cooldowns, and verifying effectiveness. It also covers requirement validation, error handling for failed casts, and integration patterns with combat automation.

Project Structure

The magic-related functionality is implemented across shared data, networking, and macro command layers:

  • Macro commands expose high-level APIs for scripting (e.g., cast, interrupt, last spell).
  • Spell managers provide metadata and runtime state for spells.
  • Targeting subsystem handles cursor-based and object-based targeting.
  • Network layer sends CastSpell packets and processes incoming responses to monitor effects.
graph TB
subgraph "Macro Layer"
SC["SpellCommands.cs"]
TSC["Targeting.cs"]
ILC["InterruptSpellCommand.cs"]
CLS["CastLastSpell.cs"]
end
subgraph "Magic Data"
SM["SpellManager.cs"]
SD["SpellData.cs"]
end
subgraph "Targeting"
TM["TargetManager.cs"]
end
subgraph "Networking"
CP["CastSpell.cs"]
IPH["IncomingPacketHandlers.cs"]
end
subgraph "Game Objects"
PM["PlayerMobile.cs"]
end
SC --> SM
SC --> TM
SC --> CP
SC --> PM
TSC --> TM
ILC --> TM
CLS --> SM
CP --> IPH

Diagram sources

Section sources

Core Components

  • SpellCommands: Macro API entry points for casting, interrupting, and querying spell state.
  • SpellManager: Central registry and runtime state for spells, including cooldowns and requirements.
  • SpellData: Static definitions for spell IDs, names, costs, and flags.
  • Targeting: High-level targeting helpers used by macros to set targets before casting.
  • TargetManager: Low-level queue and cursor control for targeting operations.
  • CastSpell: Outgoing packet builder for initiating a spell cast.
  • IncomingPacketHandlers: Processes server responses to track cast success/failure and effects.
  • PlayerMobile: Provides player stats (mana, stamina) and current status needed for requirement checks.

Key responsibilities:

  • Validate prerequisites (mana, skill, weapon, focus, etc.).
  • Queue or send cast requests via network.
  • Manage cooldowns and prevent spamming.
  • Monitor incoming packets to detect outcomes and side effects.

Section sources

Architecture Overview

The macro layer composes higher-level commands using lower-level services:

  • SpellCommands orchestrates validation, targeting, and casting.
  • SpellManager supplies spell metadata and tracks cooldowns.
  • Targeting and TargetManager handle user intent translation into game actions.
  • Networking sends CastSpell packets and listens for results.
sequenceDiagram
participant Macro as "Macro Script"
participant Cmd as "SpellCommands"
participant Mgr as "SpellManager"
participant Tgt as "Targeting/TargetManager"
participant Net as "CastSpell Packet"
participant Srv as "Server"
participant IH as "IncomingPacketHandlers"
Macro->>Cmd : Invoke spell command
Cmd->>Mgr : Check requirements and cooldown
alt Requirements met
Cmd->>Tgt : Set target if needed
Cmd->>Net : Send CastSpell
Net-->>Srv : Request cast
Srv-->>IH : Response (success/failure/effect)
IH-->>Cmd : Notify outcome
Cmd-->>Macro : Return result
else Requirements not met
Cmd-->>Macro : Error with reason
end

Diagram sources

Detailed Component Analysis

SpellCommands Macro API

Responsibilities:

  • Provide macro-friendly methods to cast spells, check conditions, and manage flow.
  • Integrate with targeting and spell manager for robust execution.

Primary methods and signatures:

  • CastSpell(spellId, target = null): bool
    • Parameters:
      • spellId: int or string identifier for the spell
      • target: optional target reference or ID; if omitted, uses current target
    • Returns: true if cast was initiated successfully; false otherwise
  • CanCastSpell(spellId): bool
    • Validates requirements such as mana, skills, equipped items, and cooldowns
  • GetSpellCooldownRemaining(spellId): TimeSpan or seconds
    • Returns remaining cooldown time if applicable
  • InterruptCurrentSpell(): void
    • Cancels ongoing cast sequence
  • WaitForCastCompletion(timeoutMs): bool
    • Blocks until completion or timeout; returns whether completed

Usage patterns:

  • Spell chaining:
    • Example: Cast a buff, then cast an attack spell after verification.
    • Use CanCastSpell to gate each step and WaitForCastCompletion to synchronize.
  • Cooldown management:
    • Before casting, check GetSpellCooldownRemaining and delay or skip if active.
  • Effectiveness verification:
    • After casting, inspect incoming packet notifications or entity states to confirm application.

Error handling:

  • Return false and log reasons when:
    • Insufficient mana
    • Skill below threshold
    • Weapon or item required but not equipped
    • Spell on cooldown
    • Invalid or missing target
    • Network failure or server rejection

Integration with combat automation:

  • Combine with targeting helpers to select enemies or allies.
  • Use interrupts to cancel hostile casts or self-casts when interrupted.
  • Chain conditional logic based on health, mana, and enemy status.

Section sources

SpellManager and SpellData

Responsibilities:

  • Maintain spell definitions and runtime state.
  • Track cooldowns, requirements, and availability.

Key capabilities:

  • Resolve spell by ID or name.
  • Compute cost and requirements from SpellData.
  • Update and query cooldown timers per spell.
  • Cache frequently accessed data for performance.

Complexity considerations:

  • Lookup operations are O(1) with hash maps keyed by spell ID.
  • Cooldown updates are amortized O(1) per tick.

Optimization opportunities:

  • Precompute requirement checks for common scenarios.
  • Batch cooldown updates during packet processing.

Section sources

Targeting Integration

Responsibilities:

  • Provide high-level helpers to set targets before casting.
  • Coordinate with TargetManager to queue target requests.

Methods:

  • SetTarget(entityOrId): bool
    • Sets the current target for subsequent actions
  • ClearTarget(): void
    • Clears the current target
  • WaitForTarget(timeoutMs): bool
    • Waits for successful targeting confirmation

Flowchart for target resolution:

flowchart TD
Start(["Start"]) --> HasTarget{"Has valid target?"}
HasTarget --> |Yes| Proceed["Proceed to cast"]
HasTarget --> |No| SetTarget["Set target via helper"]
SetTarget --> WaitConfirm{"Target confirmed?"}
WaitConfirm --> |Yes| Proceed
WaitConfirm --> |No| Error["Return error: invalid target"]
Proceed --> End(["End"])
Error --> End

Diagram sources

Section sources

Network Casting and Effect Monitoring

Responsibilities:

  • Build and send CastSpell packets.
  • Process incoming responses to determine success, failure, and effects.

Sequence of events:

  • SpellCommands constructs a CastSpell packet with spell ID and optional target.
  • The packet is sent to the server.
  • IncomingPacketHandlers receives server responses indicating:
    • Cast started
    • Cast succeeded
    • Cast failed with reason
    • Buff applied or damage dealt
sequenceDiagram
participant Cmd as "SpellCommands"
participant Net as "CastSpell Packet"
participant Srv as "Server"
participant IH as "IncomingPacketHandlers"
Cmd->>Net : Create and send CastSpell
Net-->>Srv : Request
Srv-->>IH : CastStarted / CastFailed / CastSuccess
IH-->>Cmd : Outcome notification
Cmd-->>Cmd : Update internal state (cooldowns, effects)

Diagram sources

Section sources

Interrupt and Last Spell Commands

Responsibilities:

  • InterruptSpellCommand: Cancel ongoing cast sequences.
  • CastLastSpell: Reuse the most recently cast spell without re-parsing parameters.

Use cases:

  • Interrupt to stop hostile spells or self-interruptions.
  • Last spell for rapid repetition in combat loops.

Section sources

Dependency Analysis

High-level dependencies:

  • SpellCommands depends on SpellManager for requirements and cooldowns.
  • SpellCommands uses Targeting/TargetManager to resolve targets.
  • SpellCommands sends CastSpell packets and relies on IncomingPacketHandlers for feedback.
  • PlayerMobile provides stat values for requirement checks.
classDiagram
class SpellCommands {
+CastSpell(spellId, target) bool
+CanCastSpell(spellId) bool
+GetSpellCooldownRemaining(spellId) double
+InterruptCurrentSpell() void
+WaitForCastCompletion(timeoutMs) bool
}
class SpellManager {
+ResolveSpell(idOrName) SpellData
+CheckRequirements(spell) bool
+UpdateCooldown(spellId, duration) void
+GetCooldownRemaining(spellId) double
}
class SpellData {
+int id
+string name
+int manaCost
+bool requiresWeapon
+bool requiresFocus
+double[] skillRequirements
}
class Targeting {
+SetTarget(entityOrId) bool
+ClearTarget() void
+WaitForTarget(timeoutMs) bool
}
class TargetManager {
+QueueTargetRequest(target) void
+GetCurrentTarget() Entity
+ClearCurrentTarget() void
}
class CastSpell {
+Send(spellId, targetId) void
}
class IncomingPacketHandlers {
+OnCastStarted(...)
+OnCastFailed(reason)
+OnCastSuccess(effect)
}
class PlayerMobile {
+int Mana
+int Stamina
+Skills
+EquippedWeapon
}
SpellCommands --> SpellManager : "uses"
SpellCommands --> Targeting : "uses"
Targeting --> TargetManager : "delegates"
SpellCommands --> CastSpell : "sends"
CastSpell --> IncomingPacketHandlers : "responses handled by"
SpellCommands --> PlayerMobile : "reads stats"

Diagram sources

Section sources

Performance Considerations

  • Minimize redundant requirement checks by caching results when state is stable.
  • Avoid busy-wait loops; use WaitForCastCompletion with appropriate timeouts.
  • Batch multiple targeting operations to reduce packet overhead.
  • Debounce repeated cast attempts to respect server-side rate limits.
  • Prefer direct spell ID lookups over string parsing in hot paths.

Troubleshooting Guide

Common issues and resolutions:

  • Insufficient mana:
    • Verify PlayerMobile.Mana against SpellData.manaCost.
    • Ensure no temporary drains or debuffs are affecting resources.
  • Skill below threshold:
    • Confirm PlayerMobile.Skills meet SpellData.skillRequirements.
  • Missing required equipment:
    • Check PlayerMobile.EquippedWeapon and other gear flags.
  • Cooldown active:
    • Query SpellManager.GetCooldownRemaining and wait or skip accordingly.
  • Targeting failures:
    • Use Targeting.WaitForTarget and ensure target validity before casting.
  • Network errors:
    • Inspect IncomingPacketHandlers logs for CastFailed reasons.
    • Retry with backoff if transient.

Diagnostic steps:

  • Log requirement checks prior to casting.
  • Record outgoing CastSpell details and incoming responses.
  • Monitor cooldown timers and update intervals.

Section sources

Conclusion

SpellCommands provides a robust macro interface for interacting with the magic system. By combining requirement validation, targeted casting, cooldown management, and effect monitoring, it enables reliable automation of complex spell sequences. Proper error handling and integration with targeting and networking layers ensure resilience and responsiveness in dynamic combat scenarios.

Appendices

Method Signatures Reference

  • SpellCommands.CastSpell(spellId, target = null): bool
  • SpellCommands.CanCastSpell(spellId): bool
  • SpellCommands.GetSpellCooldownRemaining(spellId): double
  • SpellCommands.InterruptCurrentSpell(): void
  • SpellCommands.WaitForCastCompletion(timeoutMs): bool
  • Targeting.SetTarget(entityOrId): bool
  • Targeting.ClearTarget(): void
  • Targeting.WaitForTarget(timeoutMs): bool
  • SpellManager.ResolveSpell(idOrName): SpellData
  • SpellManager.CheckRequirements(spell): bool
  • SpellManager.UpdateCooldown(spellId, duration): void
  • SpellManager.GetCooldownRemaining(spellId): double
  • CastSpell.Send(spellId, targetId): void

Section sources