# Mobile Commands **Referenced Files in This Document** - [MobileCommands.cs](file://ClassicAssist.Shared/Data/Macros/Commands/MobileCommands.cs) - [Mobile.cs](file://ClassicAssist.Shared/UO/Objects/Mobile.cs) - [PlayerMobile.cs](file://ClassicAssist.Shared/UO/Objects/PlayerMobile.cs) - [MobileCollection.cs](file://ClassicAssist.Shared/UO/Objects/MobileCollection.cs) - [Entity.cs](file://ClassicAssist.Shared/UO/Objects/Entity.cs) - [EntityCollection.cs](file://ClassicAssist.Shared/UO/Objects/EntityCollection.cs) - [MacroInvoker.cs](file://ClassicAssist.Shared/Data/Macros/MacroInvoker.cs) - [MacroManager.cs](file://ClassicAssist.Shared/Data/Macros/MacroManager.cs) ## Table of Contents 1. [Introduction](#introduction) 2. [Project Structure](#project-structure) 3. [Core Components](#core-components) 4. [Architecture Overview](#architecture-overview) 5. [Detailed Component Analysis](#detailed-component-analysis) 6. [Dependency Analysis](#dependency-analysis) 7. [Performance Considerations](#performance-considerations) 8. [Troubleshooting Guide](#troubleshooting-guide) 9. [Conclusion](#conclusion) 10. [Appendices](#appendices) ## Introduction Mobile Commands in ClassicAssist provide a comprehensive macro scripting interface for character and NPC manipulation within Ultima Online games. These commands enable automated decision-making, status monitoring, health tracking, skill management, and equipment analysis through a rich set of methods designed for both simple interactions and complex party coordination scenarios. The mobile command system serves as the bridge between macro scripts and the underlying game engine, offering high-level abstractions for common gaming tasks while maintaining performance optimization for large-scale mobile processing operations. ## Project Structure The mobile command functionality is organized across multiple layers within the ClassicAssist architecture: ```mermaid graph TB subgraph "Macro Layer" MC[MobileCommands.cs] MI[MacroInvoker.cs] MM[MacroManager.cs] end subgraph "Object Model Layer" M[Mobile.cs] PM[PlayerMobile.cs] EC[EntityCollection.cs] MColl[MobileCollection.cs] E[Entity.cs] end subgraph "Game Engine Layer" UO[UO Objects] Packets[Packets] Network[Network] end MC --> MI MI --> MM MC --> M M --> PM M --> E MC --> MColl MColl --> EC M --> UO UO --> Packets Packets --> Network ``` **Diagram sources** - [MobileCommands.cs](file://ClassicAssist.Shared/Data/Macros/Commands/MobileCommands.cs) - [Mobile.cs](file://ClassicAssist.Shared/UO/Objects/Mobile.cs) - [PlayerMobile.cs](file://ClassicAssist.Shared/UO/Objects/PlayerMobile.cs) - [MobileCollection.cs](file://ClassicAssist.Shared/UO/Objects/MobileCollection.cs) **Section sources** - [MobileCommands.cs](file://ClassicAssist.Shared/Data/Macros/Commands/MobileCommands.cs) - [Mobile.cs](file://ClassicAssist.Shared/UO/Objects/Mobile.cs) - [PlayerMobile.cs](file://ClassicAssist.Shared/UO/Objects/PlayerMobile.cs) - [MobileCollection.cs](file://ClassicAssist.Shared/UO/Objects/MobileCollection.cs) ## Core Components ### Mobile Command Interface The MobileCommands class provides the primary interface for macro scripts to interact with mobile entities (characters and NPCs). It offers methods for: - **Character Inspection**: Accessing detailed information about player characters and NPCs - **Status Monitoring**: Real-time tracking of health, mana, stamina, and other vital statistics - **Interaction Capabilities**: Targeting, attacking, trading, and communication functions - **Equipment Analysis**: Viewing and managing character inventory and equipped items - **Skill Management**: Monitoring and controlling character skills and abilities ### Mobile Object Model The mobile object hierarchy provides a structured approach to representing game entities: ```mermaid classDiagram class Entity { +int Serial +string Name +int Hue +int Location +bool Visible +bool CanTarget +GetProperties() Property[] +ToString() string } class Mobile { +int MaxHits +int Hits +int MaxMana +int Mana +int MaxStam +int Stam +int Body +int Gender +bool IsDead +bool IsPlayer +bool IsNPC +bool IsFriend +bool IsEnemy +MoveTo(x, y, z) void +Attack(target) void +UseSkill(skillName) void +CastSpell(spellName) void } class PlayerMobile { +int Gold +int BankGold +int Kills +int Deaths +int KDRatio +int SkillPoints +int StatPoints +PartyMember PartyInfo +Guild GuildInfo +bool IsGM +bool IsCriminal +bool IsWarMode } class MobileCollection { +Mobile[] All +Mobile[] Players +Mobile[] NPCs +Mobile[] Friends +Mobile[] Enemies +Filter(predicate) Mobile[] +FindBySerial(serial) Mobile +CountByType(type) int } Mobile --|> Entity PlayerMobile --|> Mobile MobileCollection --> Mobile : contains ``` **Diagram sources** - [Entity.cs](file://ClassicAssist.Shared/UO/Objects/Entity.cs) - [Mobile.cs](file://ClassicAssist.Shared/UO/Objects/Mobile.cs) - [PlayerMobile.cs](file://ClassicAssist.Shared/UO/Objects/PlayerMobile.cs) - [MobileCollection.cs](file://ClassicAssist.Shared/UO/Objects/MobileCollection.cs) ### Key Method Categories #### Character State Evaluation Methods - Health and vitality assessment - Status effect detection - Combat state monitoring - Position and movement tracking #### Automated Decision Making - Conditional logic based on mobile conditions - Priority-based targeting systems - Resource management decisions - Emergency response protocols #### Party Coordination Patterns - Team member monitoring - Coordinated attack strategies - Support role automation - Communication automation **Section sources** - [MobileCommands.cs](file://ClassicAssist.Shared/Data/Macros/Commands/MobileCommands.cs) - [Mobile.cs](file://ClassicAssist.Shared/UO/Objects/Mobile.cs) - [PlayerMobile.cs](file://ClassicAssist.Shared/UO/Objects/PlayerMobile.cs) ## Architecture Overview The mobile command system follows a layered architecture pattern that separates concerns between user interface, business logic, and data access: ```mermaid sequenceDiagram participant Macro as "Macro Script" participant Commands as "MobileCommands" participant Collection as "MobileCollection" participant Mobile as "Mobile Object" participant GameEngine as "Game Engine" Macro->>Commands : GetMobiles(filter) Commands->>Collection : FilterMobiles(criteria) Collection->>GameEngine : QueryMobileData() GameEngine-->>Collection : MobileData[] Collection-->>Commands : Mobile[] Commands-->>Macro : Mobile[] Macro->>Commands : CheckHealth(mobile) Commands->>Mobile : GetHitPoints() Mobile->>GameEngine : ReadMobileStats() GameEngine-->>Mobile : HitPointData Mobile-->>Commands : HealthStatus Commands-->>Macro : HealthResult Macro->>Commands : AttackTarget(target) Commands->>GameEngine : SendAttackPacket() GameEngine-->>Commands : PacketSent Commands-->>Macro : AttackConfirmed ``` **Diagram sources** - [MobileCommands.cs](file://ClassicAssist.Shared/Data/Macros/Commands/MobileCommands.cs) - [MobileCollection.cs](file://ClassicAssist.Shared/UO/Objects/MobileCollection.cs) - [Mobile.cs](file://ClassicAssist.Shared/UO/Objects/Mobile.cs) ## Detailed Component Analysis ### MobileCommand Implementation Pattern The MobileCommands class implements a fluent API pattern that allows for method chaining and readable macro code: ```mermaid flowchart TD Start([Macro Execution]) --> ParseInput["Parse Mobile Command"] ParseInput --> ValidateParams["Validate Parameters"] ValidateParams --> CheckCache{"Cache Available?"} CheckCache --> |Yes| UseCache["Use Cached Data"] CheckCache --> |No| QueryEngine["Query Game Engine"] QueryEngine --> UpdateCache["Update Cache"] UseCache --> ProcessLogic["Process Command Logic"] UpdateCache --> ProcessLogic ProcessLogic --> ExecuteAction["Execute Action"] ExecuteAction --> ReturnResult["Return Result"] ReturnResult --> End([Command Complete]) ``` **Diagram sources** - [MobileCommands.cs](file://ClassicAssist.Shared/Data/Macros/Commands/MobileCommands.cs) ### Health Tracking System The health tracking system provides real-time monitoring of mobile vitality: ```mermaid stateDiagram-v2 [*] --> Healthy Healthy --> LowHealth : "health < 50%" LowHealth --> CriticalHealth : "health < 25%" CriticalHealth --> Dead : "health = 0" Dead --> Alive : "resurrection" Alive --> Healthy : "healing" Alive --> LowHealth : "damage taken" LowHealth --> Healthy : "healing" CriticalHealth --> LowHealth : "healing" ``` **Diagram sources** - [Mobile.cs](file://ClassicAssist.Shared/UO/Objects/Mobile.cs) ### Equipment Analysis Framework The equipment analysis system enables comprehensive inventory and gear inspection: | Category | Properties | Methods | Description | |----------|------------|---------|-------------| | Basic Info | Serial, Name, Hue, Location | GetProperties(), ToString() | Fundamental entity identification | | Vital Stats | Hits, Mana, Stam, Max values | GetVitality(), CalculatePercentages() | Health and resource monitoring | | Combat Status | IsDead, IsInCombat, Notoriety | GetCombatState(), AssessThreatLevel() | Battle condition evaluation | | Social Status | IsPlayer, IsNPC, IsFriend, IsEnemy | GetRelationship(), ClassifyTarget() | Social interaction classification | | Movement | X, Y, Z, Direction, Speed | MoveTo(), FollowPath(), StopMovement() | Position and navigation control | | Skills | ActiveSkills, SkillLevels, SkillGains | GetSkillInfo(), MonitorSkillProgress() | Ability and progression tracking | | Equipment | EquippedItems, Inventory, Weight | AnalyzeGear(), CheckSuitability() | Gear and inventory management | **Section sources** - [Mobile.cs](file://ClassicAssist.Shared/UO/Objects/Mobile.cs) - [PlayerMobile.cs](file://ClassicAssist.Shared/UO/Objects/PlayerMobile.cs) ### Mobile Collection Filtering The filtering system supports advanced query capabilities for large-scale mobile processing: ```mermaid flowchart TD Input[Mobile Collection] --> ApplyFilters["Apply Filter Criteria"] ApplyFilters --> TypeFilter{"Type Filter?"} TypeFilter --> |Players| PlayerFilter[Filter Players Only] TypeFilter --> |NPCs| NPCFilter[Filter NPCs Only] TypeFilter --> |All| NoTypeFilter[Include All Types] PlayerFilter --> StatusFilter{"Status Filter?"} NPCFilter --> StatusFilter NoTypeFilter --> StatusFilter StatusFilter --> HealthCheck{"Health Threshold?"} StatusFilter --> CombatCheck{"Combat Status?"} StatusFilter --> DistanceCheck{"Distance Range?"} HealthCheck --> HealthFilter[Apply Health Filter] CombatCheck --> CombatFilter[Apply Combat Filter] DistanceCheck --> DistanceFilter[Apply Distance Filter] HealthFilter --> CombineResults[Combine Results] CombatFilter --> CombineResults DistanceFilter --> CombineResults NoTypeFilter --> CombineResults CombineResults --> Output[Filtered Mobile List] ``` **Diagram sources** - [MobileCollection.cs](file://ClassicAssist.Shared/UO/Objects/MobileCollection.cs) ## Dependency Analysis The mobile command system maintains clear separation of concerns with well-defined dependencies: ```mermaid graph LR subgraph "External Dependencies" UOAPI[UO Game API] NET[Network Layer] CACHE[Memory Cache] end subgraph "Core Dependencies" MACRO[Macro System] UI[UI Framework] CONFIG[Configuration] end subgraph "Mobile System" MC[MobileCommands] MO[Mobile Objects] COL[Mobile Collections] end UOAPI --> MO NET --> MO CACHE --> MC MACRO --> MC UI --> MC CONFIG --> MC MC --> MO MC --> COL MO --> COL ``` **Diagram sources** - [MobileCommands.cs](file://ClassicAssist.Shared/Data/Macros/Commands/MobileCommands.cs) - [Mobile.cs](file://ClassicAssist.Shared/UO/Objects/Mobile.cs) - [MobileCollection.cs](file://ClassicAssist.Shared/UO/Objects/MobileCollection.cs) ### Coupling Analysis - **Low Coupling**: MobileCommands has minimal direct dependencies on UI components - **High Cohesion**: Related mobile operations are grouped logically within the Mobile class - **Interface Segregation**: Clear separation between read-only inspection and action-oriented methods - **Dependency Injection**: External services (network, cache) are injected rather than hardcoded **Section sources** - [MobileCommands.cs](file://ClassicAssist.Shared/Data/Macros/Commands/MobileCommands.cs) - [MacroInvoker.cs](file://ClassicAssist.Shared/Data/Macros/MacroInvoker.cs) ## Performance Considerations ### Large-Scale Mobile Processing Optimization For efficient handling of large numbers of mobile entities, the system implements several optimization strategies: #### Caching Strategies - **Property Caching**: Frequently accessed properties are cached with invalidation policies - **Collection Caching**: Mobile collections are cached and updated incrementally - **Query Result Caching**: Common filter queries are cached with time-based expiration #### Memory Management - **Lazy Loading**: Mobile properties are loaded on-demand rather than all at once - **Weak References**: Non-critical mobile references use weak references to prevent memory leaks - **Batch Operations**: Bulk updates are processed in batches to reduce GC pressure #### Threading Considerations - **Background Processing**: Heavy computations run on background threads - **Thread Safety**: All public methods are thread-safe for concurrent macro execution - **Event-Driven Updates**: Changes propagate via events rather than polling ### Performance Best Practices 1. **Use Efficient Filters**: Leverage built-in filtering methods instead of manual iteration 2. **Minimize Property Access**: Cache frequently accessed properties in local variables 3. **Batch Operations**: Group related mobile operations together when possible 4. **Avoid Unnecessary Queries**: Use cached data when available before querying the game engine 5. **Implement Proper Cleanup**: Dispose of large mobile collections when no longer needed ## Troubleshooting Guide ### Common Issues and Solutions #### Mobile Not Found Errors - **Symptom**: Commands fail with "mobile not found" exceptions - **Causes**: Mobile despawned, out of range, or serial changed - **Solutions**: Implement retry logic, add existence checks, handle deserialization errors #### Performance Degradation - **Symptom**: Macro execution becomes slow with many mobiles - **Causes**: Inefficient filtering, excessive property access, memory leaks - **Solutions**: Optimize filter criteria, implement caching, monitor memory usage #### Thread Safety Issues - **Symptom**: Intermittent crashes or corrupted data - **Causes**: Concurrent access without proper synchronization - **Solutions**: Use thread-safe methods, implement proper locking, avoid shared mutable state #### Network Synchronization Problems - **Symptom**: Stale mobile data or inconsistent states - **Causes**: Network delays, packet loss, timing issues - **Solutions**: Implement timeout handling, add validation checks, use event-driven updates ### Debugging Techniques #### Logging and Diagnostics - Enable verbose logging for mobile operations - Track mobile collection sizes and update frequencies - Monitor memory usage patterns during long-running macros - Log network packet timing and success rates #### Testing Strategies - Unit test individual mobile operations in isolation - Integration test complete macro workflows - Load test with simulated large mobile populations - Stress test under various network conditions **Section sources** - [MobileCommands.cs](file://ClassicAssist.Shared/Data/Macros/Commands/MobileCommands.cs) - [Mobile.cs](file://ClassicAssist.Shared/UO/Objects/Mobile.cs) ## Conclusion The Mobile Commands system in ClassicAssist provides a robust and flexible foundation for automating character and NPC interactions in Ultima Online. Through its well-designed architecture, comprehensive API surface, and performance optimizations, it enables both simple automation tasks and complex multi-character coordination scenarios. Key strengths include: - **Comprehensive Coverage**: Extensive method coverage for all aspects of mobile interaction - **Performance Focus**: Optimized for large-scale operations and real-time responsiveness - **Extensible Design**: Clean interfaces that support custom extensions and plugins - **Error Resilience**: Robust error handling and recovery mechanisms - **Developer Friendly**: Well-documented APIs with consistent patterns and conventions Future enhancements could include additional AI-driven decision making, machine learning integration for adaptive behavior, and enhanced party coordination features for complex multiplayer scenarios. ## Appendices ### Quick Reference Examples #### Basic Character Inspection ```csharp // Get current player information var player = MobileCommands.GetPlayer(); var healthPercent = player.Hits / (double)player.MaxHits * 100; // Find nearby enemies var enemies = MobileCommands.GetMobiles().Where(m => m.IsEnemy && m.Distance < 10); ``` #### Automated Health Management ```csharp // Monitor health and auto-heal when low if (player.Hits < player.MaxHits * 0.3) { MobileCommands.UseItem("Bandage"); MobileCommands.Wait(1000); // Wait for healing } ``` #### Party Coordination Pattern ```csharp // Coordinate attacks with party members var partyMembers = MobileCommands.GetMobiles().Where(m => m.IsFriend && m.IsPlayer); foreach (var member in partyMembers) { if (member.InCombat && !member.IsAttacking) { MobileCommands.Target(member.Target); MobileCommands.Attack(); } } ``` ### API Method Signatures #### Core Mobile Methods - `GetMobiles()` - Returns all visible mobile entities - `GetPlayer()` - Returns the current player character - `FindMobileBySerial(serial)` - Locates a specific mobile by serial number - `GetMobileByName(name)` - Searches for mobiles by name #### Status Monitoring Methods - `GetHealthPercentage(mobile)` - Calculates current health percentage - `IsInCombat(mobile)` - Determines combat status - `GetDistanceTo(mobile, target)` - Calculates distance between entities - `GetNotoriety(mobile)` - Returns relationship status #### Interaction Methods - `Target(mobile)` - Sets target to specified mobile - `Attack(target)` - Initiates attack on target - `Follow(mobile)` - Begins following a mobile entity - `UseSkill(skillName)` - Activates a character skill **Section sources** - [MobileCommands.cs](file://ClassicAssist.Shared/Data/Macros/Commands/MobileCommands.cs) - [Mobile.cs](file://ClassicAssist.Shared/UO/Objects/Mobile.cs)