Remove files that should not be in repo

- Remove .claude/ settings (local Claude Code config)
- Remove CLAUDE.md files (local project instructions)
- Remove PluginCore.backup.cs (pre-refactoring backup, no longer needed)
- Remove FINDINGS.md (scratch analysis file)
- Add .claude/ and CLAUDE.md to .gitignore

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
erik 2026-02-27 08:10:39 +00:00
parent 64e690f625
commit c30704aaa7
7 changed files with 5 additions and 2439 deletions

View file

@ -1,22 +0,0 @@
{
"permissions": {
"allow": [
"Bash(mkdir:*)",
"Bash(grep:*)",
"Bash(rg:*)",
"Bash(sed:*)",
"Bash(find:*)",
"Bash(true)",
"Bash(rm:*)",
"Bash(cp:*)",
"Bash(chmod:*)",
"Bash(./cleanup.sh:*)",
"Bash(bash:*)",
"Bash(ls:*)",
"Bash(python3:*)",
"Bash(msbuild:*)",
"Bash(dotnet build:*)"
]
},
"enableAllProjectMcpServers": false
}

5
.gitignore vendored
View file

@ -366,3 +366,8 @@ FodyWeavers.xsd
/MosswartMassacre/Unused
/MosswartMassacre/Decal.Adapter.csproj
/MosswartMassacre/Decal.Interop.Core.csproj
# Claude Code
.claude/
CLAUDE.md
**/CLAUDE.md

View file

@ -1,81 +0,0 @@
- when we porting flagtracker there mus be no simplification or trunkation of the code
- you can use utility belt for references about how to check views and create them perhaps also for quests. Same with the folder Mag-Tools
- we need to figure out a better way for this. By doing ID might be one thing, but ID changes when a stack run out
# Icon Implementation Discoveries
## DECAL Icon System - CRITICAL DIFFERENCES
### Spell Icons vs Item Icons
**SPELL ICONS**: Use RAW icon values from DECAL FileService SpellTable
- Access via: `fileService.SpellTable.GetById(spellId)` then reflection to find icon property
- **NO OFFSET REQUIRED** - Use raw icon value directly
- Matches original Lua: `game.Character.SpellBook.Get(spellID).Icon` (no offset)
**ITEM ICONS**: Require MagTools-style offset
- Format: `itemIcon + 0x6000000`
- Used for inventory items, weapons, armor, etc.
### Working Implementation
```csharp
// For SPELL icons - NO offset
private int GetRealSpellIcon(int spellId)
{
var fileService = CoreManager.Current.Filter<Decal.Filters.FileService>();
var spell = fileService.SpellTable.GetById(spellId);
// Use reflection to find icon property
return iconValue; // RAW value, no offset
}
// For ITEM icons - WITH offset
int itemIconId = worldObject.Icon + 0x6000000;
```
### VVS Icon Display
- Use `DecalControls.IconColumn` in XML (NOT PictureColumn)
- IconColumn creates HudPictureBox controls automatically
- Set icon via: `((HudPictureBox)control).Image = iconId;`
### Successful Applications
**Flag Tracker Recalls Tab**: Real spell icons working perfectly
**MagTools Reference**: Item icons with 0x6000000 offset
**Original Lua Compatibility**: Exact replication of flagtracker behavior
### Implemented Icon Applications
**Flag Tracker Recalls Tab**: Real spell icons working perfectly
**Flag Tracker Cantrips Tab**: Multi-layered icon system implemented
- **Attributes**: Spell icons (Strength, Endurance, etc.) with background support
- **Protection Auras**: Spell icons (Armor, Flame Ward, etc.)
- **Skills**: Dynamic skill icons from character training data
### Cantrips Tab Icon System (Advanced Implementation)
Based on original Lua flagtracker's sophisticated 3-icon approach:
```csharp
// Attributes: Background + Spell Icon overlay
["Strength"] = new CantripInfo {
SpellIconId = 1354, // StrengthSelf8 spell icon
BackgroundIconId = 0x060013F9 // UI background icon
};
// Protection Auras: Spell icons only
["Armor"] = new CantripInfo {
SpellIconId = 1397 // ArmorSelf8 spell icon
};
// Skills: Dynamic skill icons from character data
IconId = GetSkillIconId(skillId) // Real skill icon + 0x6000000 offset
```
### Icon Priority System
1. **Background + Spell Overlay**: For attributes (complex layering)
2. **Spell Icons Only**: For protection auras
3. **Skill Icons**: From character skill data (item-style offset)
4. **Fallback**: Default portal icon (0x6002D14)
### Future Icon Usage
- **Weapons Tab**: 3-layer system (underlay + icon + overlay) from original Lua
- **Luminance Auras**: Could use custom UI icons
- **Society Items**: Could use item icons with proper offset
- you cant build application. I will build it for you

View file

@ -1,3 +0,0 @@
{
"enableAllProjectMcpServers": false
}

View file

@ -1,375 +0,0 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Build Commands
Build the project:
```
msbuild MosswartMassacre.csproj /p:Configuration=Release /p:Platform=AnyCPU
```
Build debug version:
```
msbuild MosswartMassacre.csproj /p:Configuration=Debug /p:Platform=AnyCPU
```
Restore NuGet packages:
```
nuget restore packages.config
```
Generate installer (post-build, Windows only):
```
powershell -File scripts/post-build.ps1 -NuGetPackageRoot "%USERPROFILE%\.nuget\packages" -ProjectDir "./"
```
Build entire solution from parent directory:
```
msbuild ../mossy.sln
```
## Architecture Overview
This is a DECAL plugin for Asheron's Call that tracks monster kills and rare item discoveries. The plugin architecture consists of several key components:
### Core Plugin Framework
- **PluginCore.cs**: Main plugin entry point inheriting from `PluginBase`. Handles Startup/Shutdown lifecycle, event subscriptions (chat, spawn/despawn, login), and coordinates all subsystems.
- **PluginSettings.cs**: Per-character YAML configuration management using YamlDotNet. Settings are stored as `<CharacterName>.yaml` in the plugin directory.
### UI System (VVS Direct Integration)
- **Views/VVSTabbedMainView.cs**: Main tabbed UI using direct VirindiViewService integration. Displays kill stats, rare counts, elapsed time, settings, statistics, and navigation controls.
- **Views/VVSBaseView.cs**: Base class for VVS-based views providing common functionality like window positioning, control access, and resource management.
- **ViewXML/mainViewTabbed.xml**: XML layout definition for the tabbed UI overlay.
### Communication Systems
- **WebSocket.cs**: Bidirectional WebSocket client connecting to `wss://overlord.snakedesert.se/websocket/` for real-time data streaming (spawns, chat, rares) and remote command reception.
- **HttpCommandServer.cs**: Local HTTP server on port 8085 accepting POST commands for remote control.
- **Telemetry.cs**: Periodic HTTP POST of player stats/position to configured endpoint.
### Game Integration
- **vTank.cs + VtankControl.cs**: Interface with vTank automation bot for meta state control and **NAVIGATION CONTROL**
- **MossyInventory.cs**: Inventory change monitoring and logging.
- **DelayedCommandManager.cs**: Queue system for executing chat commands with delays.
### Utility Components
- **Coordinates.cs + Geometry.cs**: Game coordinate system handling and spatial calculations.
- **Utils.cs**: General utility functions for player position, distance calculations, etc.
- **ManyHook.cs**: Low-level Windows message hooking functionality.
### Event Processing Flow
1. **Chat Events**: `OnChatText()` in PluginCore.cs:217 parses kill messages using regex patterns, rare discovery messages, and remote commands from allegiance chat.
2. **World Events**: `OnSpawn()`/`OnDespawn()` in PluginCore.cs:150,171 track monster spawning for WebSocket streaming.
3. **Command Processing**: `/mm` command handler in `HandleMmCommand()` at PluginCore.cs:448 provides comprehensive plugin control interface.
### Important Implementation Notes
- All regex patterns for kill detection are in `IsKilledByMeMessage()` at PluginCore.cs:337
- Settings auto-save on shutdown and load after character login complete
- WebSocket uses session-based authentication with SharedSecret
- Plugin requires `AllowUnsafeBlocks=true` for P/Invoke operations
### Dependencies
- **DECAL Framework**: Core AC plugin framework (Decal.Adapter, Decal.Interop.Core, Decal.Interop.D3DService)
- **VirindiViewService**: UI system for game overlays - used directly without wrapper abstraction
- **Newtonsoft.Json**: JSON serialization for WebSocket/HTTP communication
- **YamlDotNet**: YAML configuration file handling
- **utank2-i.dll**: vTank integration library
### Key Configuration
- Target Framework: .NET Framework 4.8
- Platform: x86 (required for AC integration)
- Unsafe blocks enabled for low-level operations
- VVS direct integration (no wrapper abstraction layer)
- Post-build script generates NSIS installer
### Shared Code Structure
The project links to shared code in `../Shared/` containing common utilities for multiple AC plugins including constants, world object wrappers, settings management, and VCS chat system integration.
## Navigation Visualization Feature ✅ COMPLETED
### Overview
Successfully implemented complete navigation route comparison feature allowing visualization of VTank .nav files alongside UtilityBelt's active route visualization. Feature is **FULLY FUNCTIONAL** as of May 29, 2025.
### Key Components Added
1. **NavRoute.cs** - VTank nav file parser and D3D line visualizer
2. **NavVisualization.cs** - Route management and file discovery
3. **Enhanced TabbedMainView.cs** - Navigation tab with controls
4. **Navigation Tab UI** - Dropdown selection, enable/disable, status display
### Features Implemented
- ✅ Complete VTank .nav file format parsing (all waypoint types)
- ✅ 3D route visualization with red colored lines
- ✅ Support for all nav types: Circular, Linear, Target, Once
- ✅ Registry-based VTank directory detection
- ✅ Tabbed UI integration with existing interface
- ✅ Enable/disable visualization controls
- ✅ Route loading and clearing functionality
- ✅ Comprehensive debug logging system
### Usage Instructions
1. **Enable**: Check "Enable Navigation Visualization" in Navigation tab
2. **Configure**: Set VTank profiles path in Settings tab (auto-detected)
3. **Select**: Choose route from dropdown and click "Load Route"
4. **View**: Red lines appear in 3D game world showing route path
### Technical Details
- **Dependencies**: Added Decal.Interop.D3DService reference
- **Performance**: Optimized for large routes (max 500 line segments)
- **Integration**: Seamless addition to existing plugin architecture
- **Memory Management**: Proper D3D object disposal and cleanup
### Reference Documentation
See `NAVIGATION_IMPLEMENTATION_SUMMARY.md` for complete technical details, implementation notes, and future enhancement opportunities.
---
## GUI Architecture (Enhanced with Navigation Feature)
### Current Implementation Status
**Tabbed Interface**: Successfully implemented with Navigation, Settings, and Statistics tabs
**BaseView Architecture**: Inherited from UtilityBelt's BaseView pattern
**Advanced Controls**: Dropdown lists, checkboxes, buttons with proper event handling
**Settings Integration**: VTank path configuration in Settings tab
**Resource Management**: Proper disposal and memory management
### Tabs Implemented
1. **Main Tab**: Kill tracking functionality (original)
2. **Settings Tab**: Configuration including VTank profiles path
3. **Statistics Tab**: Enhanced statistics display
4. **Navigation Tab**: ✅ Route visualization controls (NEW)
### Future Enhancement Opportunities
1. **Multiple Route Support**: Visualize several routes simultaneously
2. **Route Analysis**: Distance calculations and efficiency metrics
3. **Advanced Visualization**: Waypoint icons and route optimization
4. **Export Features**: Save custom routes or export comparisons
## VTank Navigation Control Feature ✅ COMPLETED
### Overview
Successfully implemented complete programmatic control of VTank's navigation system, allowing remote waypoint advancement through the `/mm nextwp` command. Feature is **FULLY FUNCTIONAL** as of May 29, 2025.
### Breakthrough Achievement
Cracked VTank's internal architecture through reverse engineering and reflection to enable seamless integration between Mosswart Massacre and VTank's navigation system.
### Key Implementation
- **VtankControl.cs:114-223** - `VtAdvanceWaypoint()` method using precise reflection
- **PluginCore.cs:661-671** - `/mm nextwp` command handler with user feedback
- **Decompiled Analysis** - Complete VTank internal structure mapping
### Technical Solution
Resolved "Ambiguous match found" reflection error by specifying exact method signatures:
```csharp
Type[] parameterTypes = new Type[] { typeof(object), assembly.GetType("MetaViewWrappers.MVControlEventArgs") };
var advanceMethod = pluginCoreType.GetMethod("i",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,
null, parameterTypes, null);
```
### Features Implemented
- ✅ Programmatic waypoint advancement via `/mm nextwp`
- ✅ Navigation state validation (waypoint count, position, nav type)
- ✅ VTank business logic compliance (Target/Once type restrictions)
- ✅ Comprehensive error handling and user feedback
- ✅ Fallback mechanisms for maximum reliability
- ✅ Assembly-based reflection for internal access
### Architecture Discovery
**VTank Internal Structure**:
```
vTank.Instance (cExternalInterfaceTrustedRelay)
└── Assembly: utank2-i.dll
└── Type: uTank2.PluginCore
├── Static Field: PC (PluginCore instance)
│ └── Method: i(object, MVControlEventArgs) ← TARGET
└── Static Field: dz (fallback direct access)
└── Field: o.l (current waypoint index)
```
### Usage
Simply type `/mm nextwp` in-game to advance VTank to the next waypoint. Works with Circular and Linear navigation types.
### Reference Documentation
See `FINDINGS.md` for complete technical breakthrough details, implementation analysis, and reverse engineering discoveries.
## Universal Plugin Message Interception via Harmony ✅ SUCCESSFULLY IMPLEMENTED
### Current Status: FULLY FUNCTIONAL - Harmony 1.2.0.1 Integration Complete
Successfully implemented **universal plugin message interception** using UtilityBelt's Harmony 1.2.0.1 DLL to patch DECAL's core chat methods. All plugin messages are now being captured and streamed!
### ✅ **IMPLEMENTATION SUCCESS**:
- ✅ **UtilityBelt Compatibility Resolved**: Using same Harmony 1.2.0.1 DLL as UB
- ✅ **Plugin Message Capture Working**: Successfully intercepting [UB], [VI], [VGI], [VTank] messages
- ✅ **WebSocket Streaming Active**: All intercepted messages stream to remote server
- ✅ **No Plugin Conflicts**: All plugins functioning normally with our patches
### 🎯 What's Working
- **Harmony Framework**: Complete DECAL method interception using Harmony 1.2.0.1 (old API)
- **Dual-Mode Patching**: Successfully patches `HooksWrapper.AddChatText()` and `AddChatTextRaw()`
- **Universal Capture**: Capturing plugin messages from UtilityBelt, VI, VGI, VTank
- **Debug System**: `/mm decalstatus`, `/mm decaldebug`, `/mm harmonyraw` commands
- **WebSocket Integration**: Real-time streaming of all intercepted messages
- **Duplicate Prevention**: Smart logic prevents double-patching same instance
### 🔧 Technical Solution Implemented
#### **Harmony Version Resolution**
- **Solution Applied**: Using UtilityBelt's 0Harmony.dll (version 1.2.0.1)
- **API Conversion**: Changed from Harmony 2.x API to Harmony 1.x API
- **Key Changes**:
- `HarmonyLib.Harmony``Harmony.HarmonyInstance`
- `new Harmony()``HarmonyInstance.Create()`
- Reference points to `C:\Games\Decal Plugins\UtilityBelt\0Harmony.dll`
#### **Current Patching Architecture**
1. **DecalHarmonyClean.cs** ✅ WORKING
- **Harmony 1.x Integration**: Uses `Harmony.HarmonyInstance` API
- **Smart Patching**: Avoids duplicates by checking if Host.Actions == HooksWrapper
- **Methods Patched**: `AddChatText(string, int)`, `AddChatText(string, int, int)`, `AddChatTextRaw` variants
- **Debug Logging**: Internal queue-based logging with `/mm harmonyraw` command
2. **Message Processing Flow**
- All messages (including [Mosswart Massacre]) are captured and streamed
- Debug output filtered to prevent spam but streaming remains active
- WebSocket streaming requires both `AggressiveChatStreamingEnabled` and `WebSocketEnabled`
### 📊 Performance & Results
- **Messages Intercepted**: Successfully capturing 100+ messages per session
- **Plugin Coverage**: [UB], [VI], [VGI], [VTank] messages all captured
- **Streaming Reliability**: All messages successfully sent to WebSocket endpoint
- **No Performance Impact**: Harmony patches execute efficiently
### ✅ **COMPLETED: Code Cleanup Plan - All Phases Done (May 31, 2025)**
**Successfully completed comprehensive codebase cleanup to resolve API JSON encoding errors and remove experimental code:**
#### **✅ Phase 1: Remove Unused Harmony Experiments** - COMPLETED
**Files Removed (Previously):**
- All experimental Harmony files removed in earlier cleanup sessions
- Kept: `DecalHarmonyClean.cs` (working implementation)
#### **✅ Phase 2: Remove Failed Direct Hook Attempts** - COMPLETED
**Files Removed (Previously):**
- All failed hook attempt files removed in earlier cleanup sessions
- Direct hooks, COM interceptors, and window monitoring approaches removed
#### **✅ Phase 3: Clean Debug & Test Commands** - COMPLETED
**Status:** All debug commands were already cleaned up, no obsolete commands found
#### **✅ Phase 4: Remove Rich Text Formatting** - COMPLETED
**API Error Resolution:**
- **Root Cause Found:** Emoji characters (🎯, ✅, ❌, 🔧, 🔍, 🔄) in chat messages were causing JSON encoding errors
- **Fixed:** All emoji replaced with plain text markers ([OK], [FAIL], [INFO], [WARN])
- **Files Updated:** `PluginCore.cs`, `VTankChatIntegration.cs`, `VCSIntegration.cs`, `PluginLoadDiagnostic.cs`
- **Result:** API JSON encoding errors resolved
#### **✅ Phase 5: Clean Project References** - COMPLETED
**Status:** Project references and packages.config were already clean, no unnecessary dependencies found
#### **✅ Phase 6: Consolidate Integration Classes** - COMPLETED
**Files Removed:**
- `UtilityBeltControl.cs` - Unused UtilityBelt integration (superseded by Harmony)
- `VTankChatIntegration.cs` - Unused VTank chat integration (superseded by Harmony)
- `VCSIntegration.cs` - Unused VCS integration (superseded by Harmony)
- **Project File Updated:** Removed references to deleted integration classes
#### **✅ Phase 7: Clean Verbose Debug Output** - COMPLETED
**Issue:** Harmony initialization was producing 20+ lines of debug spam in chat
**Resolution:**
- **DecalHarmonyClean.cs:** Removed all verbose `PluginCore.WriteToChat()` debug messages
- **PluginCore.cs:** Simplified Harmony initialization to single success/failure message
- **Result:** Clean startup with just `[OK] Plugin message interception active`
#### **✅ Phase 8: Remove Development Scaffolding** - COMPLETED
**Files Removed:**
- `PluginLoadDiagnostic.cs` - Development testing utility no longer needed
- **Syntax Errors Fixed:** Corrected string interpolation issues in `DecalHarmonyClean.cs`
- **Project File Updated:** Removed reference to diagnostic file
### 📋 **Final Testing Checklist**
1. ✅ `/mm decalstatus` - Verify Harmony patches still active
2. ✅ `/mm decaldebug enable` - Test plugin message capture
3. ✅ WebSocket streaming - Confirm no JSON encoding errors
4. ✅ Plugin compatibility - No conflicts with UtilityBelt/VTank
5. ✅ Build verification - All syntax errors resolved
6. ✅ Clean startup - No verbose debug spam, single initialization message
### 🏗️ Build Configuration
- **Harmony Reference**: `C:\Games\Decal Plugins\UtilityBelt\0Harmony.dll`
- **Copy Local**: False (uses UB's loaded assembly)
- **Target Framework**: .NET 4.8
- **Platform**: x86
## Flag Tracker Feature ✅ IN PROGRESS - VVS Integration
### Overview
Successfully implemented comprehensive Flag Tracker feature porting the complete flagtracker Lua plugin from UBS to C# using VirindiViewService (VVS). This is a major new feature providing character tracking for augmentations, luminance auras, recall spells, society quests, character flags, cantrips, and weapons.
### Implementation Status
**Core Framework Completed**:
- FlagTrackerView.cs - Complete 10-tab VVS window
- FlagTrackerData.cs - All data structures ported from Lua
- QuestManager.cs - Quest tracking system
- flagTracker.xml - Comprehensive UI layout
**Integration Completed**:
- Added Flag Tracker tab to main tabbed view
- Button launches dedicated Flag Tracker window
- VVS inheritance from VVSBaseView
- Proper event handling and resource management
### Current Issue: VVS HudList Column Access
**Problem**: "Column out of range" errors when populating VVS HudList controls
**Root Cause**: VVS HudList column creation from XML may not be working as expected
**Status**: Implementing safe column access patterns with detailed debugging
### Files Implemented
1. **Views/FlagTrackerView.cs** - Main Flag Tracker window
- 10-tab structure: Augs, Lum, Recalls, Society, FacHub, Flags, Cantrips, Weapons, Quests, Settings
- VVS HudList population methods with SafeSetListText() helper
- Complete event handling for all refresh buttons
2. **FlagTrackerData.cs** - Data management
- Complete augmentation data (Death, Skill, Rating, Stat, Resistance, Spec, Misc)
- Luminance aura categories (Nalicana, Seer)
- Recall spell definitions
- Society quest structures
- Character flag categories
- Cantrip and weapon data structures
- Reflection-based DECAL property access
3. **QuestManager.cs** - Quest tracking system
- DECAL CoreManager integration
- Quest refresh and parsing
4. **ViewXML/flagTracker.xml** - UI Layout
- 10-tab notebook control
- HudList controls with column definitions
- Comprehensive button and settings controls
### Technical Approach
- **VVS Direct Integration**: No wrapper abstraction, direct VirindiViewService usage
- **Safe Column Access**: SafeSetListText() method with IndexOutOfRangeException handling
- **Reflection-Based Data Access**: Bypasses DECAL type system issues using raw integer property access
- **Complete Data Preservation**: "No simplification or truncation" as requested by user
### Architecture Integration
- **Main View Integration**: Flag Tracker button added to mainViewTabbed.xml
- **Event Handling**: OnOpenFlagTrackerClick() in VVSTabbedMainView.cs
- **Static Interface**: OpenFlagTracker(), CloseFlagTracker(), IsOpen() methods
- **Resource Management**: Proper disposal in base VVSBaseView pattern
### Debug Features Added
- Control initialization status reporting
- Safe column access with detailed error messages
- Column existence validation before access
### Next Steps
1. Resolve VVS HudList column creation from XML
2. Complete remaining tab data population
3. Implement actual character data retrieval
4. Add settings persistence
---

View file

@ -1,304 +0,0 @@
# VTank Next Waypoint Control - BREAKTHROUGH FINDINGS
## SUCCESS: VTank Waypoint Advancement WORKING ✅
**Date**: May 29, 2025
**Status**: FULLY FUNCTIONAL
**Command**: `/mm nextwp`
## The Challenge
Implementing programmatic control of VTank's "Advance Current Point" button functionality to skip to the next waypoint in a navigation route. This required deep reverse engineering of VTank's internal architecture.
## Key Technical Breakthrough
### The "Ambiguous Match Found" Problem
The critical issue was that VTank's `PluginCore` class contains multiple methods named `i`, causing reflection to fail with "Ambiguous match found" when trying to invoke the waypoint advance method.
### The Solution
Specified exact method signature using parameter types in the `GetMethod()` call:
```csharp
Type[] parameterTypes = new Type[] { typeof(object), assembly.GetType("MetaViewWrappers.MVControlEventArgs") };
var advanceMethod = pluginCoreType.GetMethod("i",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,
null, parameterTypes, null);
```
## Complete VTank Architecture Discovery
### Core Architecture Components
#### 1. External Interface Layer
- **Type**: `cExternalInterfaceTrustedRelay`
- **Access**: `vTank.Instance` (singleton pattern)
- **Purpose**: Safe public API facade with permission checking
- **Assembly**: `utank2-i.dll`
- **Permission Levels**: Uses `eExternalsPermissionLevel` enum for access control
#### 2. Internal Core Logic
- **Type**: `uTank2.PluginCore`
- **Static Instance**: `PC` field (PluginCore singleton)
- **Purpose**: Main plugin implementation containing all core functionality
- **Access Pattern**: External interface delegates to internal PluginCore methods
#### 3. Navigation System Architecture
```
Navigation Data Flow:
ExternalInterface.NavCurrent
└── calls: a(eExternalsPermissionLevel.FullUnderlying)
└── returns: PC.NavCurrent
└── accesses: dz.o.l (actual waypoint index storage)
```
### Deep Navigation Implementation Details
#### Navigation State Management
- **Current Waypoint**: `dz.o.l` (int field chain)
- **Total Waypoints**: `dz.o` contains waypoint collection
- **Navigation Type**: Enum values (0=Circular, 1=Linear, 2=Target, 4=Once)
- **Meta State Integration**: `dz.at.f()` and `dz.at.b(value)` for meta state control
#### Waypoint Advancement Logic (from decompiled source)
```csharp
// VTank's internal advance logic:
if (navType != 2 && navType != 4) // Not Target or Once
{
if (dz.o.l < totalWaypoints - 1) // Not at end
{
dz.o.l++; // Advance waypoint
}
}
```
#### Button Click Handler Chain
1. **UI Button**: "Advance Current Point" in VTank interface
2. **Event Handler**: `i(object A_0, MVControlEventArgs A_1)` method
3. **Permission Check**: Validates navigation state and type
4. **Core Logic**: Calls internal waypoint advancement
5. **State Update**: Updates `dz.o.l` and refreshes UI
### Permission and Security Model
#### Access Levels (eExternalsPermissionLevel)
- **LogicObject**: Basic access to cLogic object
- **FullUnderlying**: Complete access to internal state (required for navigation)
- **Permission Validation**: `a(level)` method checks permissions before access
#### Trust Relationship
- External plugins must be "trusted" to access navigation functions
- VTank validates calling assembly and permission levels
- Reflection bypasses normal permission checks (security consideration)
### Method Signature Discovery
#### Navigation Methods in PluginCore
- **Multiple 'i' Methods**: Caused "Ambiguous match found" error
- **Target Method**: `i(object A_0, MVControlEventArgs A_1)` - button event handler
- **Parameter Types**:
- `object` - sender/source object (can be null)
- `MetaViewWrappers.MVControlEventArgs` - VVS event args (can be null)
#### Reflection Access Pattern
```csharp
// Critical discovery: Must specify exact parameter types
Type[] parameterTypes = new Type[] {
typeof(object),
assembly.GetType("MetaViewWrappers.MVControlEventArgs")
};
var method = type.GetMethod("i", flags, null, parameterTypes, null);
```
### Navigation Type Behaviors
#### Circular Navigation (Type 0)
- ✅ Advance allowed at any waypoint
- Wraps from last waypoint back to first
- Most common navigation pattern
#### Linear Navigation (Type 1)
- ✅ Advance allowed until last waypoint
- Stops at final waypoint (no wrap-around)
- Used for point-to-point routes
#### Target Navigation (Type 2)
- ❌ Advance blocked by design
- Single destination waypoint
- Navigation automatically stops at target
#### Once Navigation (Type 4)
- ❌ Advance blocked by design
- One-time route execution
- Cannot manually advance waypoints
### Meta State Integration
#### Current Meta State Access
- **Getter**: `dz.at.f()` returns current meta state string
- **Setter**: `dz.at.b(value)` sets new meta state
- **Integration**: Navigation events can trigger meta state changes
- **Example**: Rare discoveries trigger "loot_rare" meta state
### Assembly and Type Discovery
#### Key Assembly Information
- **File**: `utank2-i.dll` (interface assembly)
- **Namespace**: `uTank2`
- **Main Type**: `PluginCore`
- **Static Fields**: `PC` (PluginCore instance), `dz` (navigation data)
#### Critical Type Relationships
```
uTank2.PluginCore (main logic)
├── Static PC: PluginCore instance
├── Static dz: Navigation data container
│ └── Field o: Navigation object
│ └── Field l: Current waypoint index (int)
└── Method i(object, MVControlEventArgs): Advance handler
```
### Error Patterns and Solutions
#### Common Reflection Errors
1. **"Ambiguous match found"**: Multiple methods with same name
- **Solution**: Specify exact parameter types in GetMethod()
2. **Permission Denied**: External interface blocks access
- **Solution**: Use assembly-level reflection to bypass interface
3. **Null Reference**: Static fields not initialized
- **Solution**: Validate object hierarchy before access
#### Debugging Techniques Used
1. **Type Inspection**: `GetType().Name` to identify actual types
2. **Assembly Analysis**: Loading and inspecting utank2-i.dll
3. **Field Enumeration**: Discovering static fields via reflection
4. **Method Signature Analysis**: Identifying parameter requirements
### Access Pattern Hierarchy
```
Application Level:
/mm nextwp command
└── VtankControl.VtAdvanceWaypoint()
└── Validation (waypoints, nav type, position)
└── Assembly.GetType("uTank2.PluginCore")
└── GetField("PC").GetValue(null)
└── GetMethod("i", paramTypes).Invoke(instance, params)
└── VTank Internal Navigation Logic
└── dz.o.l++ (waypoint advancement)
```
### Performance Characteristics
- **Reflection Overhead**: Minimal (only on command execution)
- **Memory Impact**: No persistent references to VTank objects
- **UI Responsiveness**: No blocking operations
- **Error Recovery**: Graceful fallback to direct field manipulation
## Implementation Details
### File: VtankControl.cs:114-223
Added `VtAdvanceWaypoint()` method with:
- Navigation validation (waypoint count, current position, nav type)
- Assembly-based reflection to access internal VTank types
- Primary approach: Method invocation via PluginCore.PC.i()
- Fallback approach: Direct field manipulation of dz.o.l
- Comprehensive error handling and user feedback
### File: PluginCore.cs:661-671
Added `/mm nextwp` command handler with success/failure messaging.
## Navigation Type Restrictions
Correctly implemented VTank's business logic:
- **Circular/Linear**: ✅ Advance allowed
- **Target/Once**: ❌ Advance blocked (matches VTank UI behavior)
## Testing Results
- ✅ Successfully advances waypoint in Circular navigation
- ✅ Properly validates navigation state before advancing
- ✅ Provides clear user feedback on success/failure
- ✅ Handles edge cases (no waypoints, at end of route)
- ✅ Respects VTank's navigation type restrictions
## Technical Lessons Learned
1. **Reflection Precision**: When dealing with obfuscated/complex assemblies, always specify exact method signatures using parameter types to avoid ambiguity.
2. **Assembly Navigation**: External interfaces often provide facade access to internal implementations via assembly type lookups.
3. **Static Field Patterns**: Many plugin architectures use static fields (like `PC`) to maintain singleton instances for cross-component access.
4. **Decompiled Code Value**: Reverse engineering provided exact field names (`dz.o.l`) and method signatures crucial for implementation.
5. **Fallback Strategies**: Implementing multiple access approaches (method invocation + direct field access) increases reliability.
## Future Enhancement Opportunities
1. **Previous Waypoint**: Implement `/mm prevwp` command using similar reflection techniques
2. **Jump to Waypoint**: `/mm gotowp <index>` for direct waypoint targeting
3. **Route Management**: Integration with VTank's route loading/saving functionality
4. **Navigation State Monitoring**: Real-time tracking of waypoint advancement
## Security Considerations
- Uses private reflection to access VTank internals
- Requires appropriate permissions and trust levels
- No modification of VTank files or persistent state
- Read-only access to navigation configuration
## Chat Capture System - CRITICAL LOOP PREVENTION ⚠️
### The Recursive Loop Problem
When implementing unified chat capture (native + plugin-generated), there's a serious risk of infinite recursion:
1. Plugin calls `WriteToChat()` → Adds text to chat window
2. Window monitor detects new text → Fires chat event
3. Chat handler encounters error → Calls `WriteToChat()` again
4. **INFINITE LOOP** leading to stack overflow and crash
### Prevention Mechanisms Implemented
#### 1. Message Filtering
```csharp
// Block our own plugin messages from being processed
if (text.Contains("[Mosswart Massacre]")) return false;
if (text.Contains("[UnifiedChat]")) return false;
// ... other plugin prefixes
```
#### 2. Safe Error Handling
```csharp
catch (Exception ex)
{
// NEVER use WriteToChat in error handlers!
System.Diagnostics.Debug.WriteLine($"Error: {ex}"); // Safe alternative
}
```
#### 3. Recursion Detection
```csharp
private static bool DetectPotentialRecursion()
{
// Monitor call frequency - if >10 calls in 100ms, likely a loop
if (_recursionDetectionCount > 10) return true;
}
```
#### 4. Multiple Safety Layers
- **Content filtering**: Block plugin-generated messages
- **Debug logging**: Use `Debug.WriteLine()` instead of `WriteToChat()` in handlers
- **Frequency monitoring**: Detect rapid-fire calls indicating loops
- **Circuit breaker**: Temporarily disable monitor if recursion detected
### Implementation Notes
- **NEVER** call `WriteToChat()` from within chat event handlers
- **ALWAYS** filter out your own plugin's messages
- **USE** `System.Diagnostics.Debug.WriteLine()` for error logging in chat handlers
- **TEST** thoroughly with `/mm chattest` command
This prevention system is **CRITICAL** for stability - without it, the plugin would crash AC client on any WebSocket error.
## Performance Impact
- Minimal: Reflection calls only on command execution
- No continuous polling or background processing
- Lightweight validation checks before expensive reflection operations
---
**CONCLUSION**: Complete programmatic control of VTank navigation achieved through precise reflection engineering. The `/mm nextwp` command now provides seamless integration between Mosswart Massacre and VTank's navigation system.

File diff suppressed because it is too large Load diff