commit 80b71d295d0c4e5dfd37eb3cf5b24d023f2792e1 Author: tombohar Date: Fri Apr 10 18:38:07 2026 -0400 Initial commit A modern .NET 9 NativeAOT framework for Asheron's Call client modding. Self-contained injection system that hooks D3D9 EndScene to render an ImGui overlay inside the AC client process. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f13e079 --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +# Build outputs +**/bin/ +**/obj/ +artifacts/ +TestResults/ + +# IDE and local tooling +.vs/ +.vscode/ +.idea/ +.claude/ +Claude +*.suo +*.user +*.userosscache +*.rsuser + +# Local SDK/package caches +.dotnet-home/ +.dotnet-home-*/ +packages/ + +# Logs and transient files +*.log +*.tmp +*.temp +*.cache +Thumbs.db +Desktop.ini + +# Local secrets and machine-specific config +.env +.env.* +*.secrets.json +secrets.* +appsettings.Local.json +appsettings.*.local.json + +# Scratch space +scratch/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..b1e83fa --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,133 @@ +# RynthCore — Claude Context + +A modern .NET 9 NativeAOT framework for Asheron's Call client modding. Replaces Decal + UBService with a self-contained injection system. Hooks D3D9 EndScene to render an ImGui overlay inside the AC client process. + +--- + +## ⚠ Active Focus: RynthAi ImGui Plugin + +**Do NOT work on `src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs` (the Avalonia version of RynthAi).** +The Avalonia RynthAi panel is disabled (`EntryPoint.cs` registration is commented out) and parked until the ImGui plugin is feature-complete. All RynthAi work goes in `Plugins/RynthCore.Plugin.RynthAi/` which uses ImGui via `RynthCore.PluginCore`. + +--- + +## Project Layout + +``` +C:\Projects\RynthCore\ +└── src\ + ├── RynthCore.Injector\ Console app — injects Engine into acclient.exe + │ └── Program.cs LoadLibrary + CreateRemoteThread injection + └── RynthCore.Engine\ NativeAOT x86 DLL — lives inside acclient.exe + ├── EntryPoint.cs Exported RynthCoreInit, preloads native DLLs, spawns init thread + ├── D3D9\ + │ ├── D3D9VTable.cs Temp device to harvest vtable pointers + │ ├── EndSceneHook.cs MinHook detour on EndScene + │ └── TestRenderer.cs v0.1 proof-of-life, kept for reference + └── ImGui\ + ├── ImGuiController.cs Context creation, frame loop orchestration + ├── DX9Backend.cs Renders ImGui draw data via raw D3D9 vtable calls + └── Win32Backend.cs WndProc subclass for mouse/keyboard input +``` + +Deploy folder: `C:\Games\RynthCore\` + +--- + +## Build + +```bash +# Engine (NativeAOT — slow first build, ~2 min) +cd src\RynthCore.Engine +dotnet publish -c Release + +# Injector +cd src\RynthCore.Injector +dotnet publish -c Release +``` + +Both projects target **x86** only. The Engine is NativeAOT (`PublishAot=true`) — it has no .NET runtime dependency and injects as a plain native DLL. + +Deploy output: +``` +C:\Games\RynthCore\ +├── RynthCore.Engine.dll ← Engine publish output +├── RynthCore.Injector.exe ← Injector publish output +├── minhook.x86.dll ← MinHook (x86), preloaded by EntryPoint +└── cimgui.dll ← ImGui C bindings (x86, docking branch) +``` + +Log file: `%USERPROFILE%\Desktop\RynthCore.log` + +--- + +## Key Technical Facts + +### NativeAOT / x86 +- .NET 9, `net9.0-windows`, `PlatformTarget=x86`, `RuntimeIdentifier=win-x86` +- `AllowUnsafeBlocks=true`, `PublishAot=true`, `TrimMode=link` +- `ImGui.NET` assembly is trim-rooted to preserve P/Invoke bindings +- `SetWindowLongA` not `SetWindowLongPtrA` — the Ptr variant doesn't exist on x86 + +### Injection flow +1. `RynthCore.Injector.exe` calls `CreateRemoteThread(LoadLibrary, "RynthCore.Engine.dll")` +2. `RynthCoreInit` export fires under loader lock — immediately spawns background thread +3. Init thread sleeps 2s (lets AC finish D3D9 init), preloads minhook + cimgui, then installs EndScene hook + +### D3D9 hook +- Vtable discovery: creates a throwaway device via `D3D9VTable.cs`, captures 119 vtable entries +- Hook installed via MinHook on `EndScene` (vtable index 42) +- All D3D9 calls go through cached delegates (stdcall, `this` as first param) — never via COM wrappers +- State save/restore is manual (get/set each render state) — D3D9 state blocks don't work reliably inside EndScene + +### ImGui / cimgui version situation +- ImGui.NET NuGet: **1.91.6.1** +- cimgui.dll must match: use `%USERPROFILE%\.nuget\packages\imgui.net\1.91.6.1\runtimes\win-x86\native\cimgui.dll` +- Post-1.90 struct layout: `ImDrawData.CmdLists` is an **ImVector (12 bytes)**, not a raw pointer (4 bytes) +- `DX9Backend.cs` reads `ImDrawData` fields from native memory at confirmed offsets as a safety fallback: + - `+4` = CmdListsCount + - `+16` = CmdLists array pointer + - `+20/24` = DisplayPos (X, Y) + - `+28/32` = DisplaySize (X, Y) + +### ImGui input API +- Uses the **modern** API: `AddKeyEvent` / `AddMouseButtonEvent` / `AddMousePosEvent` +- `KeyMap` / `KeysDown` / `MouseDown` arrays were removed in ImGui 1.87 — do not use them +- WndProc subclass via `SetWindowLongA` (not Ptr) in `Win32Backend.cs` + +### DX9Backend render notes +- `DrawIndexedPrimitiveUP` takes user-memory pointers directly — **do not** call `SetStreamSource(null)` before it, this crashes the driver +- Vertex format: `D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1` — xyz (3 floats) + BGRA color (uint) + uv (2 floats) +- ImGui gives RGBA pixel data; D3D9 `A8R8G8B8` is BGRA in memory — swizzle R↔B on upload +- Color conversion per vertex: `(c & 0xFF00FF00) | ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16)` +- Font texture: `POOL_MANAGED`, created once in `Init`, `TexID` set via `io.Fonts.SetTexID` + +### Multi-viewport (docking/undocking outside AC window) +- `DockingEnable` is on +- `ViewportsEnable` is commented out — requires cimgui built with `IMGUI_ENABLE_VIEWPORTS` + +--- + +## Common Pitfalls + +| Symptom | Cause | +|---------|-------| +| `DisplaySize = <1, 1>` | cimgui.dll version mismatch (pre/post 1.90 layout) | +| Font cache crash on frame 2 | `io.Fonts.TexID` was zero after init (usually fixed by matching cimgui) | +| Crash in `SetupRenderStateNative` | Do not call `SetStreamSource(null, 0)` — invalid for UP drawing | +| Duplicate `vtxCount` compile error | Was present in early source — remove the second declaration | +| Hook not firing | acclient.exe must be running and past login before injection | +| `ChangePortalMode` event (future) | Crashes Decal — never use (RynthCore note carried from NexTank) | + +--- + +## Current Status (v0.2) + +- [x] D3D9 EndScene hook stable +- [x] ImGui context, font texture, WndProc subclass working +- [x] ImGui demo window + RynthCore info panel rendering +- [x] Mouse/keyboard input forwarded; ImGui captures input when hovered +- [ ] Multi-viewport (needs IMGUI_ENABLE_VIEWPORTS cimgui build) +- [ ] NexTank UI panels ported to RynthCore +- [ ] Network message hooks +- [ ] World state / actions API diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d164a84 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Tom Bohar + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Plugins/RynthAi/Combat/BuffManager.cs b/Plugins/RynthAi/Combat/BuffManager.cs new file mode 100644 index 0000000..a4119c2 --- /dev/null +++ b/Plugins/RynthAi/Combat/BuffManager.cs @@ -0,0 +1,580 @@ +using System; +using System.Collections.Generic; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; + +namespace NexSuite.Plugins.RynthAi +{ + public class BuffManager : IDisposable + { + private CoreManager _core; + private UISettings _settings; + private SpellManager _spellManager; + + private DateTime _lastCastAttempt = DateTime.MinValue; + private bool _isForceRebuffing = false; + private int _pendingSpellId = 0; + + private class RamTimerInfo + { + public DateTime Expiration; + public int SpellLevel; + public string SpellName; // Added to make debug easier + } + private Dictionary _ramBuffTimers = new Dictionary(); + private string _buffTimerPath; + + private bool _isRechargingMana = false; + private bool _isRechargingStamina = false; + private bool _isHealingSelf = false; + + private readonly List BaseCreatureBuffs = new List + { + "Strength Self", "Endurance Self", "Coordination Self", + "Quickness Self", "Focus Self", "Willpower Self", + "Magic Resistance Self", "Invulnerability Self", "Impregnability Self" + }; + + private readonly Dictionary CreatureSkillBuffs = new Dictionary + { + { CharFilterSkillType.MeleeDefense, "Invulnerability Self" }, + { CharFilterSkillType.MissileDefense, "Impregnability Self" }, + { CharFilterSkillType.MagicDefense, "Magic Resistance Self" }, + { CharFilterSkillType.HeavyWeapons, "Heavy Weapon Mastery" }, + { CharFilterSkillType.LightWeapons, "Light Weapon Mastery" }, + { CharFilterSkillType.FinesseWeapons, "Finesse Weapon Mastery" }, + { CharFilterSkillType.TwoHandedCombat, "Two Handed Combat Mastery" }, + { CharFilterSkillType.Shield, "Shield Mastery" }, + { CharFilterSkillType.DualWield, "Dual Wield Mastery" }, + { CharFilterSkillType.Recklessness, "Recklessness Mastery" }, + { CharFilterSkillType.SneakAttack, "Sneak Attack Mastery" }, + { CharFilterSkillType.DirtyFighting, "Dirty Fighting Mastery" }, + { CharFilterSkillType.AssessCreature, "Monster Attunement" }, + { CharFilterSkillType.AssessPerson, "Person Attunement" }, + { CharFilterSkillType.ArcaneLore, "Arcane Enlightenment" }, + { CharFilterSkillType.ArmorTinkering, "Armor Tinkering Expertise" }, + { CharFilterSkillType.ItemTinkering, "Item Tinkering Expertise" }, + { CharFilterSkillType.MagicItemTinkering, "Magic Item Tinkering Expertise" }, + { CharFilterSkillType.WeaponTinkering, "Weapon Tinkering Expertise" }, + { CharFilterSkillType.Salvaging, "Arcanum Salvaging" }, + { CharFilterSkillType.Run, "Sprint" }, + { CharFilterSkillType.Jump, "Jumping Mastery" }, + { CharFilterSkillType.Loyalty, "Fealty" }, + { CharFilterSkillType.Leadership, "Leadership Mastery" }, + { CharFilterSkillType.Deception, "Deception Mastery" }, + { CharFilterSkillType.Healing, "Healing Mastery" }, + { CharFilterSkillType.Lockpick, "Lockpick Mastery" }, + { CharFilterSkillType.Cooking, "Cooking Mastery" }, + { CharFilterSkillType.Fletching, "Fletching Mastery" }, + { CharFilterSkillType.Alchemy, "Alchemy Mastery" }, + { CharFilterSkillType.ManaConversion, "Mana Conversion Mastery" }, + { CharFilterSkillType.CreatureEnchantment, "Creature Enchantment Mastery" }, + { CharFilterSkillType.ItemEnchantment, "Item Enchantment Mastery" }, + { CharFilterSkillType.LifeMagic, "Life Magic Mastery" }, + { CharFilterSkillType.WarMagic, "War Magic Mastery" }, + { CharFilterSkillType.VoidMagic, "Void Magic Mastery" }, + { CharFilterSkillType.Summoning, "Summoning Mastery" } + }; + + public BuffManager(CoreManager core, UISettings settings, SpellManager spellManager) + { + _core = core; + _settings = settings; + _spellManager = spellManager; + _core.ChatBoxMessage += OnChatMsg; + } + + /// + /// Set the path for persisting buff timers. Call after settings path is known. + /// Automatically loads any existing timers from disk. + /// + public void SetTimerPath(string charFolder) + { + _buffTimerPath = System.IO.Path.Combine(charFolder, "bufftimers.txt"); + LoadBuffTimers(); + } + + public void SaveBuffTimers() + { + if (string.IsNullOrEmpty(_buffTimerPath)) return; + try + { + var lines = new System.Collections.Generic.List(); + foreach (var kvp in _ramBuffTimers) + { + var info = kvp.Value; + // Format: Family|Expiration(ticks)|SpellLevel|SpellName + lines.Add($"{kvp.Key}|{info.Expiration.Ticks}|{info.SpellLevel}|{info.SpellName}"); + } + System.IO.File.WriteAllLines(_buffTimerPath, lines); + } + catch { } + } + + public void LoadBuffTimers() + { + if (string.IsNullOrEmpty(_buffTimerPath)) return; + if (!System.IO.File.Exists(_buffTimerPath)) return; + try + { + _ramBuffTimers.Clear(); + foreach (string line in System.IO.File.ReadAllLines(_buffTimerPath)) + { + string[] parts = line.Split('|'); + if (parts.Length < 4) continue; + + int family = int.Parse(parts[0]); + DateTime expiration = new DateTime(long.Parse(parts[1])); + int level = int.Parse(parts[2]); + string name = parts[3]; + + // Only load if not expired + if (expiration > DateTime.Now) + { + _ramBuffTimers[family] = new RamTimerInfo + { + Expiration = expiration, + SpellLevel = level, + SpellName = name + }; + } + } + if (_ramBuffTimers.Count > 0) + _core.Actions.AddChatText($"[RynthAi] Restored {_ramBuffTimers.Count} buff timer(s) from last session.", 1); + } + catch { } + } + + public void Dispose() => _core.ChatBoxMessage -= OnChatMsg; + + public void ForceFullRebuff() + { + _isForceRebuffing = true; + _ramBuffTimers.Clear(); + SaveBuffTimers(); + _core.Actions.AddChatText("[RynthAi] Starting Force Rebuff...", 5); + } + + public void CancelBuffing() + { + _isForceRebuffing = false; + _isRechargingMana = false; + _isRechargingStamina = false; + _isHealingSelf = false; + _pendingSpellId = 0; + _core.Actions.AddChatText("[RynthAi] Sequence cancelled.", 5); + } + + public void OnHeartbeat() + { + if (!_settings.IsMacroRunning) return; + if (_core.CharacterFilter.LoginStatus != 3) return; + + // 1. Are we locked in a cast/equip animation? + if ((DateTime.Now - _lastCastAttempt).TotalMilliseconds < 1500) + { + _settings.CurrentState = "Buffing"; + return; + } + + // 2. Do we need to heal/recharge? + if (CheckVitals()) + { + _settings.CurrentState = "Buffing"; + return; + } + + // 3. Do we need to buff? + if (_settings.EnableBuffing) + { + if (CheckAndCastSelfBuffs()) + { + _settings.CurrentState = "Buffing"; + return; + } + + if (_isForceRebuffing) + { + _isForceRebuffing = false; + _core.Actions.AddChatText("[RynthAi] Force Rebuff Complete.", 1); + } + } + + // === THE FIX === + // 4. Only release the traffic light if WE were the ones holding it! + if (_settings.CurrentState == "Buffing") + { + _settings.CurrentState = "Idle"; + } + } + + private bool CheckVitals() + { + double maxHealth = _core.CharacterFilter.EffectiveVital[CharFilterVitalType.Health]; + double maxMana = _core.CharacterFilter.EffectiveVital[CharFilterVitalType.Mana]; + double maxStam = _core.CharacterFilter.EffectiveVital[CharFilterVitalType.Stamina]; + + int curHealthPct = maxHealth > 0 ? (int)((_core.CharacterFilter.Health / maxHealth) * 100) : 100; + int curManaPct = maxMana > 0 ? (int)((_core.CharacterFilter.Mana / maxMana) * 100) : 100; + int curStamPct = maxStam > 0 ? (int)((_core.CharacterFilter.Stamina / maxStam) * 100) : 100; + + if (curHealthPct <= 30 && curStamPct > 20) return AttemptVitalCast("Stamina to Health Self"); + + if (curHealthPct <= _settings.HealAt) _isHealingSelf = true; + if (curHealthPct >= _settings.TopOffHP) _isHealingSelf = false; + if (curManaPct <= _settings.GetManaAt) _isRechargingMana = true; + if (curManaPct >= _settings.TopOffMana) _isRechargingMana = false; + if (curStamPct <= _settings.RestamAt) _isRechargingStamina = true; + if (curStamPct >= _settings.TopOffStam) _isRechargingStamina = false; + + if (_isHealingSelf) return AttemptVitalCast("Heal Self"); + if (_isRechargingMana && curStamPct > 15) return AttemptVitalCast("Stamina to Mana Self"); + if (_isRechargingStamina) return AttemptVitalCast("Revitalize Self"); + + return false; + } + + private bool AttemptVitalCast(string baseName) + { + int spellId = FindBestSpellId(baseName, CharFilterSkillType.LifeMagic); + if (spellId == 0) return false; + + // Use our new wand-equipping check + if (!EnsureMagicMode()) return true; + + _core.Actions.CastSpell(spellId, _core.CharacterFilter.Id); + _lastCastAttempt = DateTime.Now; + return true; + } + + private bool CheckAndCastSelfBuffs() + { + List desiredBuffs = BuildDynamicBuffList(); + + foreach (string buffBaseName in desiredBuffs) + { + CharFilterSkillType castSkill = SkillForBuff(buffBaseName); + if (!IsSkillUsable(castSkill)) continue; + + int spellId = FindBestSpellId(buffBaseName, castSkill); + if (spellId == 0) continue; + + if (!IsBuffActive(spellId)) + { + // Use our new wand-equipping check + if (!EnsureMagicMode()) return true; + + _pendingSpellId = spellId; + + var fs = _core.Filter(); + var spell = fs.SpellTable.GetById(spellId); + if (spell != null) _core.Actions.AddChatText($"[RynthAi] Casting: {spell.Name}", 5); + + _core.Actions.CastSpell(spellId, _core.CharacterFilter.Id); + _lastCastAttempt = DateTime.Now; + return true; + } + } + return false; + } + + private int FindBestSpellId(string baseName, CharFilterSkillType skill) + { + // GetDynamicSelfBuffId handles the correct priority: + // Incantation → Lore name → VII → VI → ... → I + return _spellManager.GetDynamicSelfBuffId(baseName, skill); + } + + private bool IsArmorEnchantment(string name) + { + string[] armorSpells = { + "Impenetrability", "Brogard's Defiance", "Acid Bane", "Olthoi's Bane", + "Blade Bane", "Swordsman's Bane", "Swordman's Bane", "Bludgeoning Bane", "Tusker's Bane", + "Flame Bane", "Inferno's Bane", "Frost Bane", "Gelidite's Bane", + "Lightning Bane", "Astyrrian's Bane", "Piercing Bane", "Archer's Bane" + }; + + foreach (string s in armorSpells) + { + if (name.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0) return true; + } + return false; + } + + private bool IsBuffActive(int spellId) + { + var fs = _core.Filter(); + var targetSpell = fs.SpellTable.GetById(spellId); + if (targetSpell == null) return false; + + int targetLevel = GetSpellLevel(targetSpell); + + if (_ramBuffTimers.TryGetValue(targetSpell.Family, out RamTimerInfo timer)) + { + if (DateTime.Now < timer.Expiration.AddMinutes(-5)) + { + if (timer.SpellLevel >= targetLevel) return true; + } + } + + if (_isForceRebuffing) return false; + + if (IsArmorEnchantment(targetSpell.Name)) + { + return false; + } + + foreach (var ench in _core.CharacterFilter.Enchantments) + { + var activeSpell = fs.SpellTable.GetById(ench.SpellId); + if (activeSpell != null && activeSpell.Family == targetSpell.Family) + { + if (GetSpellLevel(activeSpell) < targetLevel) continue; + return ench.TimeRemaining > 300; + } + } + return false; + } + + private int GetSpellLevel(Spell spell) + { + if (spell == null) return 0; + string n = spell.Name; + if (n.StartsWith("Incantation")) return 8; + if (n.Contains(" VII")) return 7; + if (n.Contains(" VI")) return 6; + if (n.Contains(" V")) return 5; + if (n.Contains(" IV")) return 4; + if (n.Contains(" III")) return 3; + if (n.Contains(" II")) return 2; + if (n.EndsWith(" I") || n.Contains(" I ")) return 1; + + if (n.Contains("Mastery") || n.Contains("Blessing") || n.Contains("Aura of") || + n.Contains("Intervention") || n.Contains("Trance") || n.Contains("Recovery") || + n.Contains("Robustify") || n.Contains("Persistence") || n.Contains("Robustification") || + n.Contains("Might of the Lugians") || n.Contains("Preservance") || n.Contains("Perseverance") || + n.Contains("Honed Control") || n.Contains("Hastening") || n.Contains("Inner Calm") || + n.Contains("Mind Blossom") || n.Contains("Infected Caress") || n.Contains("Elysa's Sight") || + n.Contains("Infected Spirit") || n.Contains("Atlan's Alacrity") || n.Contains("Cragstone's Will") || + n.Contains("Brogard's Defiance") || n.Contains("Olthoi's Bane") || n.Contains("Swordsman's Bane") || + n.Contains("Swordman's Bane") || n.Contains("Tusker's Bane") || n.Contains("Inferno's Bane") || + n.Contains("Gelidite's Bane") || n.Contains("Astyrrian's Bane") || n.Contains("Archer's Bane")) + return 7; + + return 1; + } + + private int GetArchmageEnduranceCount() + { + try + { + var me = _core.WorldFilter[_core.CharacterFilter.Id]; + if (me != null) + { + int count = me.Values((LongValueKey)238, 0); + return Math.Min(Math.Max(count, 0), 5); + } + } + catch { } + return 0; + } + + private double GetCustomSpellDuration(int spellLevel) + { + double baseSeconds = 1800; + if (spellLevel == 6) baseSeconds = 2700; + else if (spellLevel == 7) baseSeconds = 3600; + else if (spellLevel == 8) baseSeconds = 5400; + + int augs = GetArchmageEnduranceCount(); + return baseSeconds * (1.0 + (augs * 0.20)); + } + + public void PrintBuffDebug() + { + int augs = GetArchmageEnduranceCount(); + _core.Actions.AddChatText($"[RynthAi] Archmage endurance count: {augs}", 1); + + if (_ramBuffTimers.Count == 0) + { + _core.Actions.AddChatText("[RynthAi] No RAM timers active.", 1); + return; + } + + foreach (var kvp in _ramBuffTimers) + { + var info = kvp.Value; + double total = GetCustomSpellDuration(info.SpellLevel); + TimeSpan left = info.Expiration - DateTime.Now; + double passed = total - left.TotalSeconds; + + _core.Actions.AddChatText($"[RynthAi] {info.SpellName} (Lvl {info.SpellLevel}): {Math.Round(passed / 60, 1)}m passed, {Math.Round(left.TotalMinutes, 1)}m left. Total: {total / 60}m", 1); + } + } + + private List BuildDynamicBuffList() + { + List step1_CreatureMastery = new List(); + List step2_Focus = new List(); + List step3_Willpower = new List(); + List step4_OtherCreature = new List(); + List step5_LifeAndItem = new List(); + List step6_WeaponAuras = new List(); + List step7_ArmorBanes = new List(); + + foreach (string attr in BaseCreatureBuffs) + { + if (attr == "Focus Self") step2_Focus.Add(attr); + else if (attr == "Willpower Self") step3_Willpower.Add(attr); + else step4_OtherCreature.Add(attr); + } + + foreach (var kvp in CreatureSkillBuffs) + { + if (IsSkillUsable(kvp.Key)) + { + if (kvp.Value.Contains("Creature Enchantment Mastery")) + step1_CreatureMastery.Add(kvp.Value); + else if (!BaseCreatureBuffs.Contains(kvp.Value)) + step4_OtherCreature.Add(kvp.Value); + } + } + + step5_LifeAndItem.AddRange(new List { + "Regeneration Self", "Rejuvenation Self", "Mana Renewal Self", + "Armor Self", "Acid Protection Self", "Fire Protection Self", + "Cold Protection Self", "Lightning Protection Self", + "Blade Protection Self", "Piercing Protection Self", + "Bludgeoning Protection Self", "Impregnability Self" + }); + + step6_WeaponAuras.AddRange(new List { + "Blood Drinker Self", "Hermetic Link Self", "Heart Seeker Self", + "Spirit Drinker Self", "Swift Killer Self", "Defender Self" + }); + + step7_ArmorBanes.AddRange(new List { + "Impenetrability", "Acid Bane", "Blade Bane", "Bludgeoning Bane", + "Flame Bane", "Frost Bane", "Lightning Bane", "Piercing Bane" + }); + + List final = new List(); + final.AddRange(step1_CreatureMastery); + final.AddRange(step2_Focus); + final.AddRange(step3_Willpower); + final.AddRange(step4_OtherCreature); + final.AddRange(step5_LifeAndItem); + final.AddRange(step6_WeaponAuras); + final.AddRange(step7_ArmorBanes); + return final; + } + + private void OnChatMsg(object sender, ChatTextInterceptEventArgs e) + { + string text = e.Text.ToLower(); + if (text.Contains("you cast ") || text.Contains("you say, ")) + { + if (_pendingSpellId != 0) + { + var fs = _core.Filter(); + var spellInfo = fs.SpellTable.GetById(_pendingSpellId); + if (spellInfo != null) + { + int level = GetSpellLevel(spellInfo); + double dur = GetCustomSpellDuration(level); + + _ramBuffTimers[spellInfo.Family] = new RamTimerInfo + { + Expiration = DateTime.Now.AddSeconds(dur), + SpellLevel = level, + SpellName = spellInfo.Name + }; + SaveBuffTimers(); + } + _pendingSpellId = 0; + } + } + else if (text.Contains("fizzle") || text.Contains("fail") || text.Contains("component") || text.Contains("lack the mana")) + { + _lastCastAttempt = DateTime.MinValue; + _pendingSpellId = 0; + } + } + + private bool IsSkillUsable(CharFilterSkillType s) => (int)_core.CharacterFilter.Skills[s].Training >= 2; + + private CharFilterSkillType SkillForBuff(string name) + { + if (name.Contains("Impregnability") || name.Contains("Blood Drinker") || + name.Contains("Hermetic Link") || name.Contains("Heart Seeker") || + name.Contains("Spirit Drinker") || name.Contains("Swift Killer") || + name.Contains("Defender") || name.Contains("Impenetrability") || + name.Contains("Bane")) + return CharFilterSkillType.ItemEnchantment; + + if (name.Contains("Protection") || name.Contains("Armor") || + name.Contains("Regeneration") || name.Contains("Rejuvenation") || + name.Contains("Renewal") || name == "Harlune's Blessing" || + name.Contains("Stamina to Mana") || name.Contains("Revitalize") || + name.Contains("Stamina to Health") || name == "Heal Self") + return CharFilterSkillType.LifeMagic; + + return CharFilterSkillType.CreatureEnchantment; + } + + private bool EnsureMagicMode() + { + if (_core.Actions.CombatMode == CombatState.Magic) + return true; // We are in magic mode and ready to cast + + bool wandEquipped = false; + int wandToEquip = 0; + + // 1. Check ItemRules for a preferred wand + foreach (var rule in _settings.ItemRules) + { + var ruleItem = _core.WorldFilter[rule.Id]; + if (ruleItem != null && ruleItem.ObjectClass == ObjectClass.WandStaffOrb) + { + wandToEquip = ruleItem.Id; + if (ruleItem.Values(LongValueKey.EquippedSlots, 0) > 0) + { + wandEquipped = true; + } + break; // Found the preferred wand + } + } + + // 2. Fallback: Find any wand in inventory if no rule matches + if (wandToEquip == 0 && !wandEquipped) + { + foreach (WorldObject wo in _core.WorldFilter.GetInventory()) + { + if (wo.ObjectClass == ObjectClass.WandStaffOrb) + { + if (wo.Values(LongValueKey.EquippedSlots, 0) > 0) + { + wandEquipped = true; + break; + } + if (wandToEquip == 0) wandToEquip = wo.Id; + } + } + } + + // 3. Equip the wand if we aren't holding one + if (!wandEquipped && wandToEquip != 0) + { + _core.Actions.UseItem(wandToEquip, 0); + _lastCastAttempt = DateTime.Now; + return false; // Yield tick to let the server equip the item + } + + // 4. Safe to switch modes (we either have a wand equipped, or are empty-handed) + _core.Actions.SetCombatMode(CombatState.Magic); + _lastCastAttempt = DateTime.Now; + return false; // Yield tick to let the stance animation finish + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Combat/CombatActionHelper.cs b/Plugins/RynthAi/Combat/CombatActionHelper.cs new file mode 100644 index 0000000..83f8ed0 --- /dev/null +++ b/Plugins/RynthAi/Combat/CombatActionHelper.cs @@ -0,0 +1,356 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace NexSuite.Plugins.RynthAi +{ + /// + /// Direct calls to acclient.exe CM_Combat functions for attack actions. + /// Derived entirely from Turbine's acclient.exe decompilation — no VTank code involved. + /// + /// Uses runtime pattern scanning to find function addresses in any client build. + /// Each CM_Combat::Event_* function writes a unique opcode DWORD into a packed buffer + /// before calling Proto_UI::SendToWeenie. We search acclient.exe's .text section for + /// these opcode write patterns, then walk backwards to find the function prologue. + /// + /// Source: acclient.exe CM_Combat namespace (IDA decompilation of Turbine's client) + /// Event_TargetedMeleeAttack — opcode 0x08, 3 args (targetID, height, power) + /// Event_TargetedMissileAttack — opcode 0x0A, 3 args (targetID, height, accuracy) + /// Event_ChangeCombatMode — opcode 0x53, 1 arg (combatMode) + /// Event_CancelAttack — opcode 0x1B7, 0 args + /// Event_QueryHealth — opcode 0x1BF, 1 arg (targetID) + /// + /// All functions are __cdecl with standard prologue: sub esp,0Ch; push ebx; push esi; push edi + /// Signature bytes: 83 EC 0C 53 56 57 E8 + /// + internal static class CombatActionHelper + { + // ── Delegate types matching __cdecl signatures ─────────────────────── + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelTargetedMeleeAttack(uint targetID, int attackHeight, float powerLevel); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelTargetedMissileAttack(uint targetID, int attackHeight, float accuracyLevel); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelChangeCombatMode(int combatMode); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelCancelAttack(); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DelQueryHealth(uint targetID); + + // ── Cached delegates (created once at init) ───────────────────────── + private static DelTargetedMeleeAttack _meleeAttack; + private static DelTargetedMissileAttack _missileAttack; + private static DelChangeCombatMode _changeCombatMode; + private static DelCancelAttack _cancelAttack; + private static DelQueryHealth _queryHealth; + + private static bool _initialized; + private static Action _log; + + // ── ATTACK_HEIGHT enum values (from acclient.exe) ─────────────────── + public const int ATTACK_HEIGHT_HIGH = 1; + public const int ATTACK_HEIGHT_MEDIUM = 2; + public const int ATTACK_HEIGHT_LOW = 3; + + // ── COMBAT_MODE enum values (from acclient.exe) ───────────────────── + public const int COMBAT_MODE_NONCOMBAT = 1; + public const int COMBAT_MODE_MELEE = 2; + public const int COMBAT_MODE_MISSILE = 4; + public const int COMBAT_MODE_MAGIC = 8; + + // ── Shared function prologue for all CM_Combat::Event_* functions ─── + // sub esp, 0Ch; push ebx; push esi; push edi; call OrderHdr_ctor + private static readonly byte[] CM_COMBAT_PROLOGUE = { 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8 }; + + /// + /// Scans acclient.exe's loaded image at runtime to find CM_Combat functions. + /// Call once at plugin startup. + /// + public static void Initialize(Action chatLog = null) + { + _log = chatLog; + + try + { + // Find acclient.exe's base address in memory + Process proc = Process.GetCurrentProcess(); + IntPtr baseAddr = IntPtr.Zero; + int imageSize = 0; + + foreach (ProcessModule mod in proc.Modules) + { + if (mod.ModuleName.Equals("acclient.exe", StringComparison.OrdinalIgnoreCase)) + { + baseAddr = mod.BaseAddress; + imageSize = mod.ModuleMemorySize; + break; + } + } + + if (baseAddr == IntPtr.Zero) + { + Log("Pattern scan FAILED: acclient.exe module not found"); + return; + } + + Log($"acclient.exe base: 0x{baseAddr.ToInt32():X8}, size: 0x{imageSize:X}"); + + // Read the .text section into managed memory for scanning + // .text typically starts at offset 0x1000 from base + int textRva = 0x1000; + int textSize = imageSize - textRva; + if (textSize <= 0 || textSize > 0x500000) + { + Log($"Text section size suspect: 0x{textSize:X}, clamping"); + textSize = Math.Min(imageSize - textRva, 0x400000); + } + + IntPtr textBase = new IntPtr(baseAddr.ToInt32() + textRva); + byte[] text = new byte[textSize]; + Marshal.Copy(textBase, text, 0, textSize); + + int textBaseVA = baseAddr.ToInt32() + textRva; + + // ── Step 1: Find CancelAttack via unique opcode 0x1B7 ────── + // Pattern: C7 02 B7 01 00 00 (mov dword ptr [edx], 1B7h) + // This opcode value is unique in the entire binary. + byte[] cancelOpcode = { 0xC7, 0x02, 0xB7, 0x01, 0x00, 0x00 }; + int cancelOpcodeOff = FindPattern(text, cancelOpcode); + if (cancelOpcodeOff < 0) + { + Log("Pattern scan FAILED: CancelAttack opcode 0x1B7 not found"); + return; + } + + int cancelFuncOff = FindPrologueBefore(text, cancelOpcodeOff); + if (cancelFuncOff < 0) + { + Log("Pattern scan FAILED: CancelAttack prologue not found"); + return; + } + + int cancelVA = textBaseVA + cancelFuncOff; + Log($"CancelAttack found at 0x{cancelVA:X8}"); + + // ── Step 2: Search near CancelAttack for the others ──────── + // All CM_Combat::Event_* functions cluster within ~0x500 bytes + int regionStart = Math.Max(0, cancelOpcodeOff - 0x500); + int regionEnd = Math.Min(text.Length, cancelOpcodeOff + 0x500); + + // ChangeCombatMode: opcode 0x53 (unique in CM_Combat region) + byte[] changeModeOpcode = { 0xC7, 0x02, 0x53, 0x00, 0x00, 0x00 }; + int changeModeOff = FindPatternInRegion(text, changeModeOpcode, regionStart, regionEnd); + int changeModeFuncOff = changeModeOff >= 0 ? FindPrologueBefore(text, changeModeOff) : -1; + + // QueryHealth: opcode 0x1BF (unique in entire binary) + byte[] queryHealthOpcode = { 0xC7, 0x02, 0xBF, 0x01, 0x00, 0x00 }; + int queryHealthOff = FindPatternInRegion(text, queryHealthOpcode, regionStart, regionEnd); + int queryHealthFuncOff = queryHealthOff >= 0 ? FindPrologueBefore(text, queryHealthOff) : -1; + + // MeleeAttack: opcode 0x08 (common globally, but unique in CM_Combat region) + byte[] meleeOpcode = { 0xC7, 0x02, 0x08, 0x00, 0x00, 0x00 }; + int meleeOff = FindPatternInRegion(text, meleeOpcode, regionStart, regionEnd); + int meleeFuncOff = meleeOff >= 0 ? FindPrologueBefore(text, meleeOff) : -1; + + // MissileAttack: opcode 0x0A (search in CM_Combat region only) + byte[] missileOpcode = { 0xC7, 0x02, 0x0A, 0x00, 0x00, 0x00 }; + int missileOff = FindPatternInRegion(text, missileOpcode, regionStart, regionEnd); + int missileFuncOff = missileOff >= 0 ? FindPrologueBefore(text, missileOff) : -1; + + // ── Step 3: Verify all found ─────────────────────────────── + if (changeModeFuncOff < 0 || queryHealthFuncOff < 0 || + meleeFuncOff < 0 || missileFuncOff < 0) + { + Log($"Pattern scan INCOMPLETE: CancelAttack=OK, " + + $"ChangeCombatMode={changeModeFuncOff >= 0}, " + + $"QueryHealth={queryHealthFuncOff >= 0}, " + + $"MeleeAttack={meleeFuncOff >= 0}, " + + $"MissileAttack={missileFuncOff >= 0}"); + return; + } + + int changeModeVA = textBaseVA + changeModeFuncOff; + int queryHealthVA = textBaseVA + queryHealthFuncOff; + int meleeVA = textBaseVA + meleeFuncOff; + int missileVA = textBaseVA + missileFuncOff; + + Log($"ChangeCombatMode at 0x{changeModeVA:X8}"); + Log($"QueryHealth at 0x{queryHealthVA:X8}"); + Log($"MeleeAttack at 0x{meleeVA:X8}"); + Log($"MissileAttack at 0x{missileVA:X8}"); + + // Verify all have the expected prologue bytes + if (!VerifyPrologue(text, cancelFuncOff) || + !VerifyPrologue(text, changeModeFuncOff) || + !VerifyPrologue(text, queryHealthFuncOff) || + !VerifyPrologue(text, meleeFuncOff) || + !VerifyPrologue(text, missileFuncOff)) + { + Log("Pattern scan FAILED: prologue verification failed"); + return; + } + + // ── Step 4: Create delegates ─────────────────────────────── + _cancelAttack = (DelCancelAttack)Marshal.GetDelegateForFunctionPointer( + new IntPtr(cancelVA), typeof(DelCancelAttack)); + _changeCombatMode = (DelChangeCombatMode)Marshal.GetDelegateForFunctionPointer( + new IntPtr(changeModeVA), typeof(DelChangeCombatMode)); + _queryHealth = (DelQueryHealth)Marshal.GetDelegateForFunctionPointer( + new IntPtr(queryHealthVA), typeof(DelQueryHealth)); + _meleeAttack = (DelTargetedMeleeAttack)Marshal.GetDelegateForFunctionPointer( + new IntPtr(meleeVA), typeof(DelTargetedMeleeAttack)); + _missileAttack = (DelTargetedMissileAttack)Marshal.GetDelegateForFunctionPointer( + new IntPtr(missileVA), typeof(DelTargetedMissileAttack)); + + _initialized = true; + Log("CombatActionHelper initialized — all 5 CM_Combat functions found via pattern scan"); + } + catch (Exception ex) + { + _initialized = false; + Log("CombatActionHelper init FAILED: " + ex.Message); + } + } + + public static bool IsInitialized => _initialized; + + // ══════════════════════════════════════════════════════════════════════ + // PUBLIC API + // ══════════════════════════════════════════════════════════════════════ + + public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel) + { + if (!_initialized) return false; + try + { + return _meleeAttack(targetId, attackHeight, Math.Max(0f, Math.Min(1f, powerLevel))); + } + catch (Exception ex) { Log("MeleeAttack failed: " + ex.Message); return false; } + } + + public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel) + { + if (!_initialized) return false; + try + { + return _missileAttack(targetId, attackHeight, Math.Max(0f, Math.Min(1f, accuracyLevel))); + } + catch (Exception ex) { Log("MissileAttack failed: " + ex.Message); return false; } + } + + public static bool ChangeCombatMode(int combatMode) + { + if (!_initialized) return false; + try { return _changeCombatMode(combatMode); } + catch (Exception ex) { Log("ChangeCombatMode failed: " + ex.Message); return false; } + } + + public static bool CancelAttack() + { + if (!_initialized) return false; + try { return _cancelAttack(); } + catch (Exception ex) { Log("CancelAttack failed: " + ex.Message); return false; } + } + + public static bool QueryHealth(uint targetId) + { + if (!_initialized) return false; + try { return _queryHealth(targetId); } + catch (Exception ex) { Log("QueryHealth failed: " + ex.Message); return false; } + } + + /// + /// Maps UISettings height (0=Low, 1=Medium, 2=High) to AC ATTACK_HEIGHT enum. + /// + public static int MapAttackHeight(int uiHeight) + { + switch (uiHeight) + { + case 0: return ATTACK_HEIGHT_LOW; + case 2: return ATTACK_HEIGHT_HIGH; + default: return ATTACK_HEIGHT_MEDIUM; + } + } + + // ══════════════════════════════════════════════════════════════════════ + // PATTERN SCANNER + // ══════════════════════════════════════════════════════════════════════ + + private static int FindPattern(byte[] data, byte[] pattern) + { + return FindPatternInRegion(data, pattern, 0, data.Length); + } + + private static int FindPatternInRegion(byte[] data, byte[] pattern, int start, int end) + { + int limit = Math.Min(end, data.Length) - pattern.Length; + for (int i = Math.Max(0, start); i <= limit; i++) + { + bool match = true; + for (int j = 0; j < pattern.Length; j++) + { + if (data[i + j] != pattern[j]) + { + match = false; + break; + } + } + if (match) return i; + } + return -1; + } + + /// + /// Walks backwards from an opcode write to find the CM_Combat function prologue. + /// Must be preceded by CC (int3), 90 (nop), or C3 (ret). + /// + private static int FindPrologueBefore(byte[] data, int opcodeOffset) + { + for (int back = 1; back < 300; back++) + { + int pos = opcodeOffset - back; + if (pos < 1 || pos + CM_COMBAT_PROLOGUE.Length > data.Length) + continue; + + bool match = true; + for (int j = 0; j < CM_COMBAT_PROLOGUE.Length; j++) + { + if (data[pos + j] != CM_COMBAT_PROLOGUE[j]) + { + match = false; + break; + } + } + + if (match) + { + byte prev = data[pos - 1]; + if (prev == 0xCC || prev == 0x90 || prev == 0xC3) + return pos; + } + } + return -1; + } + + private static bool VerifyPrologue(byte[] data, int offset) + { + if (offset < 0 || offset + CM_COMBAT_PROLOGUE.Length > data.Length) + return false; + for (int i = 0; i < CM_COMBAT_PROLOGUE.Length; i++) + { + if (data[offset + i] != CM_COMBAT_PROLOGUE[i]) + return false; + } + return true; + } + + private static void Log(string msg) + { + try { _log?.Invoke($"[RynthAi] {msg}"); } catch { } + } + } +} diff --git a/Plugins/RynthAi/Combat/CombatManager.cs b/Plugins/RynthAi/Combat/CombatManager.cs new file mode 100644 index 0000000..d248ee7 --- /dev/null +++ b/Plugins/RynthAi/Combat/CombatManager.cs @@ -0,0 +1,1302 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; +using NexSuite.Plugins.RynthAi.Raycasting; + +namespace NexSuite.Plugins.RynthAi +{ + public class CombatManager : IDisposable + { + private CoreManager _coreManager; + private PluginHost _host; + private RynthAiUI _ui; + private UISettings _settings; + private SpellManager _spellManager; + + private MainLogic _raycastSystem; + public bool RaycastInitialized { get; private set; } + + public int activeTargetId = 0; + private DateTime lastAttackCmd = DateTime.MinValue; + private DateTime lastStanceAttempt = DateTime.MinValue; + private DateTime _lastPeaceAttempt = DateTime.MinValue; + private DateTime lastTargetSearchTime = DateTime.MinValue; + private const int TARGET_SEARCH_INTERVAL_MS = 500; + + // --- Magic Combat --- + private DateTime _lastSpellCast = DateTime.MinValue; + private const double SPELL_CAST_COOLDOWN_MS = 1500.0; // Debuff cast recovery + private const double ATTACK_SPELL_COOLDOWN_MS = 100.0; // War/void spam as fast as possible + + // Flag: when melee/missile needs debuffs, we temporarily switch to wand. + // After debuffs are done, switch back. + private bool _returnToPhysicalCombat = false; + private int _savedWeaponId = 0; // Weapon to re-equip after debuffs + + // Element vulnerability spell bases (used by V light) + private static readonly Dictionary VulnSpells = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "Fire", new[] { "Fire Vulnerability Other" } }, + { "Cold", new[] { "Cold Vulnerability Other" } }, + { "Lightning", new[] { "Lightning Vulnerability Other" } }, + { "Acid", new[] { "Acid Vulnerability Other" } }, + { "Blade", new[] { "Blade Vulnerability Other" } }, + { "Slash", new[] { "Blade Vulnerability Other" } }, + { "Pierce", new[] { "Piercing Vulnerability Other" } }, + { "Bludgeon", new[] { "Bludgeoning Vulnerability Other" } }, + }; + + private Dictionary blacklistedTargets = new Dictionary(); + + // Configurable blacklist manager — uses UISettings.BlacklistAttempts/BlacklistTimeoutSec + private Raycasting.BlacklistManager _blacklistManager = new Raycasting.BlacklistManager(); + private DateTime _lastAttackFeedbackCheck = DateTime.MinValue; + private int _lastAttackedTargetId = 0; + + public int RaycastBlockCount { get; private set; } + public int RaycastCheckCount { get; private set; } + + + + private class BlacklistedTarget + { + public int TargetId { get; set; } + public DateTime BlacklistedTime { get; set; } + public bool IsLosBlocked { get; set; } + public bool IsExpired() + { + // LOS-blocked targets get a shorter blacklist (5s) since player moves + double duration = IsLosBlocked ? 5000 : 20000; + return (DateTime.Now - BlacklistedTime).TotalMilliseconds > duration; + } + } + + public CombatManager(CoreManager coreManager, UISettings settings, PluginHost host = null, SpellManager spellManager = null) + { + _coreManager = coreManager ?? throw new ArgumentNullException(nameof(coreManager)); + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _host = host; + _spellManager = spellManager; + } + + public void SetSpellManager(SpellManager spellManager) + { + _spellManager = spellManager; + } + + // --- Monster Weaknesses (from monsters.json) --- + private Dictionary _monsterWeaknesses = new Dictionary(StringComparer.OrdinalIgnoreCase); + + public void SetMonsterWeaknesses(Dictionary weaknesses) + { + _monsterWeaknesses = weaknesses ?? new Dictionary(StringComparer.OrdinalIgnoreCase); + } + + // --- Debuff tracking (chat-driven: spam until confirmed) --- + // Tracks which debuffs have been CONFIRMED on the current target via chat + // Key: "targetId_debuffKey" — only added on "You cast X" chat message + private HashSet _confirmedDebuffs = new HashSet(); + private int _lastDebuffTargetId = 0; + + // Pending debuff: cast sent, waiting for chat result + private string _pendingDebuffKey = null; + private int _pendingDebuffTargetId = 0; + private int _pendingDebuffTier = 0; + private bool _waitingForDebuffResult = false; + private DateTime _pendingDebuffCastTime = DateTime.MinValue; + private const double DEBUFF_RESULT_TIMEOUT_MS = 3000.0; // Safety: assume success after 3s + + // Debuff spell definitions — base name for tiered resolution, plus optional lore name + // Format: { key, (tieredBase, loreName) } + // Resolver order: Incantation of [base] → [lore] → [base] VII → VI → ... → I + private static readonly Dictionary DebuffSpells = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + // { key, { tieredBase, loreName } } + { "Fester", new[] { "Fester Other", "Decrepitude's Grasp" } }, + { "Broadside", new[] { "Missile Weapon Ineptitude Other", "Broadside of a Barn" } }, + { "Gravity", new[] { "Vulnerability Other", "Gravity Well" } }, + { "Imperil", new[] { "Imperil Other", "Gossamer Flesh" } }, + { "Yield", new[] { "Magic Yield Other", "Yield" } }, + }; + + // Spell shape base names for war/void + // Arc spells: "X Arc" pattern + // Ring spells: "X Ring" pattern (+ lore names for T6/T7/T8) + // Streak spells: "X Streak" pattern + // Bolt spells: "X Bolt" pattern (default) + private static readonly Dictionary SpellShapes = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + // element → { Arc, Ring, Streak, Bolt } base patterns + { "Fire", new[] { "Flame Arc", "Ring of Fire", "Flame Streak", "Flame Bolt" } }, + { "Cold", new[] { "Frost Arc", "Frost Ring", "Frost Streak", "Frost Bolt" } }, + { "Lightning", new[] { "Lightning Arc", "Shock Ring", "Lightning Streak", "Shock Wave" } }, + { "Acid", new[] { "Acid Arc", "Acid Ring", "Acid Streak", "Acid Stream" } }, + { "Blade", new[] { "Blade Arc", "Blade Ring", "Blade Streak", "Whirling Blade" } }, + { "Pierce", new[] { "Force Arc", "Force Ring", "Force Streak", "Force Bolt" } }, + { "Bludgeon", new[] { "Bludgeoning Arc", "Bludgeoning Ring", "Bludgeoning Streak", "Shock Wave" } }, + { "Slash", new[] { "Blade Arc", "Blade Ring", "Blade Streak", "Whirling Blade" } }, + }; + + // Ring spell LORE NAMES — AC ring spells use unique names at T6/T7 + // These don't follow the standard "Base VII" pattern + // Format: element → { T6 lore, T7 lore } + private static readonly Dictionary RingLoreNames = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "Fire", new[] { "Cassius' Ring of Fire", "Cassius' Ring of Fire II" } }, + { "Cold", new[] { "Halo of Frost", "Halo of Frost II" } }, + { "Lightning", new[] { "Eye of the Storm", "Eye of the Storm II" } }, + { "Acid", new[] { "Searing Disc", "Searing Disc II" } }, + { "Blade", new[] { "Horizon's Blades", "Horizon's Blades II" } }, + { "Slash", new[] { "Horizon's Blades", "Horizon's Blades II" } }, + { "Pierce", new[] { "Nuhumudira's Spines", "Nuhumudira's Spines II" } }, + { "Bludgeon", new[] { "Tectonic Rifts", "Tectonic Rifts II" } }, + }; + + // Void Magic equivalents + private static readonly Dictionary VoidSpellShapes = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "Nether", new[] { "Nether Arc", "Nether Ring", "Nether Streak", "Nether Bolt" } }, + { "Fire", new[] { "Corrosion Arc", "Corrosion Ring", "Corrosion Streak", "Nether Bolt" } }, + }; + + public void InitializeRaycasting(string acFolderPath = null) + { + try + { + _raycastSystem = new MainLogic(); + if (string.IsNullOrEmpty(acFolderPath)) acFolderPath = @"C:\Turbine\Asheron's Call"; + RaycastInitialized = _raycastSystem.Initialize(acFolderPath); + } + catch { RaycastInitialized = false; } + } + + public void AttachUI(RynthAiUI ui) { _ui = ui; } + + /// + /// Called by PluginCore when chat messages arrive. Tracks debuff results: + /// "You cast X on Y" → SUCCESS → add to confirmed set, immediately ready for next + /// "Your spell fizzled" → FIZZLE → clear pending, recast same debuff + /// "Y resists your spell" → RESIST → clear pending, recast same debuff + /// + public void HandleChatForDebuffs(string text) + { + if (!_waitingForDebuffResult || string.IsNullOrEmpty(text)) return; + + // SUCCESS: "You cast Incantation of Imperil Other on Drudge Skulker" + if (text.StartsWith("You cast ", StringComparison.OrdinalIgnoreCase)) + { + string key = $"{_pendingDebuffTargetId}_{_pendingDebuffKey}"; + _confirmedDebuffs.Add(key); + _waitingForDebuffResult = false; + _lastSpellCast = DateTime.Now; // Reset cooldown from this moment + return; + } + + // FIZZLE: "Your spell fizzled." + if (text.IndexOf("fizzle", StringComparison.OrdinalIgnoreCase) >= 0) + { + try { _host?.Actions?.AddChatText($"[RynthAi] Fizzled: {_pendingDebuffKey} — recasting", 2); } catch { } + _waitingForDebuffResult = false; + _lastSpellCast = DateTime.Now; // Reset cooldown from this moment + return; + } + + // RESIST: "X resists your spell" + if (text.IndexOf("resists your spell", StringComparison.OrdinalIgnoreCase) >= 0) + { + try { _host?.Actions?.AddChatText($"[RynthAi] Resisted: {_pendingDebuffKey} — recasting", 2); } catch { } + _waitingForDebuffResult = false; + _lastSpellCast = DateTime.Now; + return; + } + } + + /// + /// Called by PluginCore when a health ratio update is received for a target. + /// Clears the blacklist failure counter since the mob is taking damage. + /// + public void ReportDamageOnTarget(int targetId) + { + _blacklistManager.ClearFailure(targetId); + } + + /// + /// Called internally after an attack command is sent. If no damage feedback + /// arrives within a window, the next attack attempt increments the failure count. + /// + private void TrackAttackAttempt(int targetId) + { + if (_lastAttackedTargetId != 0 && _lastAttackedTargetId == targetId) + { + // We attacked this same target last tick too — if no damage feedback + // was received since last attack, count it as a failure + if (_lastAttackFeedbackCheck != DateTime.MinValue && + (DateTime.Now - _lastAttackFeedbackCheck).TotalMilliseconds > 2500) + { + _blacklistManager.ReportFailure(targetId); + if (_blacklistManager.IsBlacklisted(targetId)) + { + try { _host?.Actions?.AddChatText($"[RynthAi] Blacklisted mob (no damage feedback): id={targetId}", 2); } catch { } + } + } + } + _lastAttackedTargetId = targetId; + _lastAttackFeedbackCheck = DateTime.Now; + } + + public bool Think() + { + if (!_settings.EnableCombat) return false; + + double acDistanceLimit = (_settings.MonsterRange) / 240.0; + CleanupExpiredBlacklist(); + + // Sync configurable blacklist settings from UI + _blacklistManager.AttemptThreshold = _settings.BlacklistAttempts; + _blacklistManager.TimeoutSeconds = _settings.BlacklistTimeoutSec; + + // Update raycast scan distance: MonsterRange + 40m buffer + // MonsterRange is in yards ≈ meters. Convert to actual meters for the scan radius. + if (_raycastSystem?.TargetingFSM != null) + _raycastSystem.TargetingFSM.MaxScanDistanceMeters = _settings.MonsterRange + 40.0f; + + // Validate current target + if (activeTargetId != 0) + { + var target = _coreManager.WorldFilter[activeTargetId]; + if (target == null || (int)target.ObjectClass != 5 || blacklistedTargets.ContainsKey(activeTargetId) || _blacklistManager.IsBlacklisted(activeTargetId)) + activeTargetId = 0; + // Target lock: don't drop a target we're actively fighting just because + // it moved slightly. Use 1.5x range for disengage so we finish the kill. + else if (_coreManager.WorldFilter.Distance(_coreManager.CharacterFilter.Id, activeTargetId) > acDistanceLimit * 1.5) + activeTargetId = 0; + } + + // Find a new target if we don't have one + if (activeTargetId == 0) + { + if ((DateTime.Now - lastTargetSearchTime).TotalMilliseconds > TARGET_SEARCH_INTERVAL_MS) + { + HandleCombatTrigger(); + lastTargetSearchTime = DateTime.Now; + } + + if (activeTargetId == 0 && _settings.PeaceModeWhenIdle) + { + if (_coreManager.Actions.CombatMode != Decal.Adapter.Wrappers.CombatState.Peace) + { + if ((DateTime.Now - _lastPeaceAttempt).TotalMilliseconds > 2000) + { + _coreManager.Actions.SetCombatMode(Decal.Adapter.Wrappers.CombatState.Peace); + _lastPeaceAttempt = DateTime.Now; + } + } + } + return true; + } + + var targetObj = _coreManager.WorldFilter[activeTargetId]; + if (targetObj == null) { activeTargetId = 0; return true; } + + // If still in Peace mode, force combat mode based on what's equipped + if (_coreManager.Actions.CombatMode == Decal.Adapter.Wrappers.CombatState.Peace) + { + if ((DateTime.Now - _lastPeaceAttempt).TotalMilliseconds > 1500) + { + _lastPeaceAttempt = DateTime.Now; + EquipWeaponAndSetStance(targetObj, "Auto"); + + // If STILL in peace, scan equipped items and force the right stance + if (_coreManager.Actions.CombatMode == Decal.Adapter.Wrappers.CombatState.Peace) + { + foreach (var inv in _coreManager.WorldFilter.GetInventory()) + { + if (inv.Values(LongValueKey.EquippedSlots, 0) <= 0) continue; + if (inv.ObjectClass == ObjectClass.WandStaffOrb) + { _coreManager.Actions.SetCombatMode(CombatState.Magic); break; } + else if (inv.ObjectClass == ObjectClass.MeleeWeapon) + { _coreManager.Actions.SetCombatMode(CombatState.Melee); break; } + else if (inv.ObjectClass == ObjectClass.MissileWeapon) + { _coreManager.Actions.SetCombatMode(CombatState.Missile); break; } + } + } + } + return true; // Yield this tick — let stance change process + } + + if ((DateTime.Now - lastAttackCmd).TotalMilliseconds >= 1000) + { + // LOS gate: verify EVERY shot + if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem != null) + { + // Determine attack type: weapon-based for melee/missile, shape-based for magic + TargetingFSM.AttackType attackType = DetermineAttackTypeForLOS(targetObj); + + RaycastCheckCount++; + if (_raycastSystem.IsTargetBlocked(_coreManager, targetObj, attackType)) + { + RaycastBlockCount++; + try { _host?.Actions?.AddChatText($"[RynthAi] LOS blocked: {targetObj.Name} — dropping", 1); } catch { } + activeTargetId = 0; + return true; + } + } + + FaceTarget(targetObj); + _coreManager.Actions.SelectItem(activeTargetId); + + // MAGIC COMBAT: If we're in magic mode with a wand, cast spells + if (_coreManager.Actions.CombatMode == CombatState.Magic && _spellManager != null) + { + AttackWithMagic(targetObj); + + // If we were in magic mode for debuffs only, check if done → switch back + if (_returnToPhysicalCombat) + { + var rule2 = GetRuleForTarget(targetObj); + string elem2 = GetPreferredElement(targetObj, rule2); + if (rule2 != null && !HasPendingDebuffs(rule2, elem2)) + { + // All debuffs confirmed — switch back to physical weapon + _returnToPhysicalCombat = false; + if (_savedWeaponId != 0) + { + _coreManager.Actions.UseItem(_savedWeaponId, 0); + _savedWeaponId = 0; + } + EquipWeaponAndSetStance(targetObj, "Auto"); + } + } + } + else + { + // Melee / Missile mode + var rule = GetRuleForTarget(targetObj); + + // Check if debuffs need casting before physical attack + if (rule != null && _spellManager != null && !_returnToPhysicalCombat) + { + string elem = GetPreferredElement(targetObj, rule); + if (HasPendingDebuffs(rule, elem)) + { + // Find wand in ItemRules to cast debuffs + int wandId = FindWandInItems(); + if (wandId != 0) + { + // Save current weapon, switch to wand for debuffs + var equipped = _coreManager.WorldFilter.GetInventory() + .FirstOrDefault(w => w.Values(LongValueKey.EquippedSlots, 0) > 0 && + (w.ObjectClass == ObjectClass.MeleeWeapon || w.ObjectClass == ObjectClass.MissileWeapon)); + _savedWeaponId = equipped?.Id ?? 0; + _returnToPhysicalCombat = true; + _coreManager.Actions.UseItem(wandId, 0); + _coreManager.Actions.SetCombatMode(CombatState.Magic); + lastAttackCmd = DateTime.Now; + return true; // Yield — next tick will be in magic mode + } + } + } + + bool anyAttackLight = (rule == null) || rule.UseArc || rule.UseBolt || rule.UseRing || rule.UseStreak; + if (!anyAttackLight) + { + // No attack shape selected — do not attack in melee/missile mode + } + else + { + AttackTarget(); + } + } + TrackAttackAttempt(activeTargetId); + lastAttackCmd = DateTime.Now; + } + return true; + } + + public void OnHeartbeat() + { + if (!_settings.IsMacroRunning) return; + + // === YIELD to any higher-priority system that has claimed the state === + if (_settings.CurrentState != "Idle" && _settings.CurrentState != "Combat") return; + + if (_settings.EnableCombat) + { + Think(); + + // If Think() found or maintained a target, we are in combat + if (activeTargetId != 0) + { + _settings.CurrentState = "Combat"; + var target = _coreManager.WorldFilter[activeTargetId]; + if (target != null) EquipWeaponAndSetStance(target, "Auto"); + } + // If no target, leave state as-is (dispatcher resets to Idle each frame) + } + } + + public void HandleCombatTrigger() + { + double acDistanceLimit = (_settings.MonsterRange) / 240.0; + + // For target SEARCH, use weapon/mode-based attack type (no specific rule yet) + TargetingFSM.AttackType attackType = TargetingFSM.AttackType.Linear; + if (RaycastInitialized && _raycastSystem?.TargetingFSM != null) + attackType = _raycastSystem.GetAttackType(_coreManager); + + int targetId = FindBestVisibleTarget(acDistanceLimit, attackType); + if (targetId != 0 && targetId != activeTargetId) + { + activeTargetId = targetId; + + var target = _coreManager.WorldFilter[targetId]; + if (target != null) EquipWeaponAndSetStance(target, "Auto"); + } + } + + private int FindBestVisibleTarget(double maxDist, TargetingFSM.AttackType attackType) + { + int foundId = 0; + int playerId = _coreManager.CharacterFilter.Id; + var candidates = new List>(); + + foreach (var wo in _coreManager.WorldFilter.GetLandscape()) + { + if ((int)wo.ObjectClass != 5 || blacklistedTargets.ContainsKey(wo.Id) || _blacklistManager.IsBlacklisted(wo.Id)) continue; + double dist = _coreManager.WorldFilter.Distance(playerId, wo.Id); + if (dist <= maxDist) candidates.Add(new KeyValuePair(wo.Id, dist)); + } + + candidates.Sort((a, b) => a.Value.CompareTo(b.Value)); + + foreach (var candidate in candidates) + { + int id = candidate.Key; + if (_settings.EnableRaycasting && RaycastInitialized) + { + RaycastCheckCount++; + if (_raycastSystem.IsTargetBlocked(_coreManager, _coreManager.WorldFilter[id], attackType)) + { + RaycastBlockCount++; + continue; + } + } + foundId = id; + break; + } + return foundId; + } + + private DateTime _lastEquipTime = DateTime.MinValue; + private DateTime _lastStanceTime = DateTime.MinValue; + + private void EquipWeaponAndSetStance(WorldObject target, string monsterWeakness = "Auto") + { + if (target == null) return; + + int targetWeaponId = 0; + + // 1. Target Resolution + var rule = _settings.MonsterRules.FirstOrDefault(r => target.Name.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0); + + if (rule == null) + { + rule = _settings.MonsterRules.FirstOrDefault(m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + } + + string desired = (rule != null && rule.DamageType != "Auto") ? rule.DamageType : monsterWeakness; + + if (rule != null && rule.WeaponId != 0) + { + targetWeaponId = rule.WeaponId; + } + else + { + var bestWeapon = _settings.ItemRules.FirstOrDefault(i => i.Element.Equals(desired, StringComparison.OrdinalIgnoreCase)) + ?? _settings.ItemRules.FirstOrDefault(); + if (bestWeapon != null) targetWeaponId = bestWeapon.Id; + } + + if (targetWeaponId == 0) return; + + var weaponObj = _coreManager.WorldFilter[targetWeaponId]; + if (weaponObj == null) return; + + // 2. Equipment Enforcement + bool isEquipped = weaponObj.Values(LongValueKey.EquippedSlots, 0) > 0; + + if (!isEquipped) + { + // Reverted to 1000ms (1 second) to prevent bare-hand attacks during slow animations + if ((DateTime.Now - _lastEquipTime).TotalMilliseconds > 1000) + { + _coreManager.Actions.UseItem(targetWeaponId, 0); + _lastEquipTime = DateTime.Now; + _lastStanceTime = DateTime.Now; // Reset stance timer to sync with new equip + } + return; + } + + // 3. Stance Enforcement + // Increased to 1000ms to allow the server to finish the "Draw Weapon" animation + if ((DateTime.Now - _lastStanceTime).TotalMilliseconds > 1000) + { + bool changedStance = false; + + if (weaponObj.ObjectClass == ObjectClass.MeleeWeapon && _coreManager.Actions.CombatMode != CombatState.Melee) + { + _coreManager.Actions.SetCombatMode(CombatState.Melee); + changedStance = true; + } + else if (weaponObj.ObjectClass == ObjectClass.MissileWeapon && _coreManager.Actions.CombatMode != CombatState.Missile) + { + _coreManager.Actions.SetCombatMode(CombatState.Missile); + changedStance = true; + } + else if (weaponObj.ObjectClass == ObjectClass.WandStaffOrb && _coreManager.Actions.CombatMode != CombatState.Magic) + { + _coreManager.Actions.SetCombatMode(CombatState.Magic); + changedStance = true; + } + + if (changedStance) _lastStanceTime = DateTime.Now; + } + } + + public string GetRaycastStatus() + { + if (_raycastSystem == null) return "Raycasting: NOT INITIALIZED"; + string status = _settings.EnableRaycasting ? "ACTIVE" : "DISABLED"; + return "Raycasting: " + status + "\n Status: " + _raycastSystem.StatusMessage + "\n" + + " Checks: " + RaycastCheckCount + ", Blocks: " + RaycastBlockCount; + } + + public List GetRaycastDiagLog() + { + var lines = new List(); + if (_raycastSystem?.GeometryLoader?.DiagLog != null) + foreach (var line in _raycastSystem.GeometryLoader.DiagLog) lines.Add(line); + return lines; + } + + /// + /// Determines the correct LOS check type based on combat mode and spell shape. + /// - Magic + Arc spell shape → MagicArc (same trajectory as missiles) + /// - Magic + Bolt/Streak/Ring → Linear (straight line) + /// - Missile mode → delegates to FSM (BowArc, ThrownArc, or Linear for crossbow) + /// - Melee/Peace → Linear + /// + private TargetingFSM.AttackType DetermineAttackTypeForLOS(WorldObject target) + { + // Magic mode: check spell shape from monster rule + if (_coreManager.Actions.CombatMode == CombatState.Magic) + { + var rule = GetRuleForTarget(target); + if (rule != null && rule.UseArc) + return TargetingFSM.AttackType.MagicArc; + + // Bolts, Streaks, Rings = straight line + return TargetingFSM.AttackType.Linear; + } + + // Missile/Melee: use weapon-based detection + if (_raycastSystem?.TargetingFSM != null) + return _raycastSystem.GetAttackType(_coreManager); + + return TargetingFSM.AttackType.Linear; + } + + private void FaceTarget(WorldObject target) + { + try + { + var p = _coreManager.WorldFilter[_coreManager.CharacterFilter.Id]; + double dx = target.Coordinates().EastWest - p.Coordinates().EastWest; + double dy = target.Coordinates().NorthSouth - p.Coordinates().NorthSouth; + double heading = Math.Atan2(dx, dy) * (180.0 / Math.PI); + if (heading < 0) heading += 360.0; + _coreManager.Actions.Heading = (float)heading; + } + catch { } + } + + private void AttackTarget() + { + try + { + if (!CombatActionHelper.IsInitialized) return; + + bool isMissile = _coreManager.Actions.CombatMode == CombatState.Missile; + uint targetId = (uint)activeTargetId; + + // Resolve attack power (0.0–1.0) + int powerPct = isMissile ? _settings.MissileAttackPower : _settings.MeleeAttackPower; + float power; + if (powerPct < 0) + { + // Auto mode: 100% unless Recklessness is enabled and trained + power = 1.0f; + if (_settings.UseRecklessness) + { + try + { + int reckTraining = (int)_coreManager.CharacterFilter + .Skills[CharFilterSkillType.Recklessness].Training; + if (reckTraining >= 2) // Trained or Specialized + power = 0.8f; + } + catch { } + } + } + else + { + power = powerPct / 100f; + } + + // Map UI height (0=Low,1=Med,2=High) → AC ATTACK_HEIGHT enum + int uiHeight = isMissile ? _settings.MissileAttackHeight : _settings.MeleeAttackHeight; + int acHeight = CombatActionHelper.MapAttackHeight(uiHeight); + + // Send attack directly via acclient.exe CM_Combat functions + if (isMissile) + CombatActionHelper.MissileAttack(targetId, acHeight, power); + else + CombatActionHelper.MeleeAttack(targetId, acHeight, power); + } + catch { } + } + + // ══════════════════════════════════════════════════════════════════════════ + // MAGIC COMBAT SYSTEM + // Supports: debuff lights (F/B/G/I/Y/V), spell shapes (A/R/S/B=default Bolt), + // monsters.json weakness lookup, War + Void magic + // If none of A/R/S/B are set → no attack (buff bot mode) + // ══════════════════════════════════════════════════════════════════════════ + + /// + /// Resolves the MonsterRule for a target (specific rule first, then Default). + /// Cached per-target so we don't re-scan every frame. + /// + private MonsterRule GetRuleForTarget(WorldObject target) + { + if (target == null) return null; + // Specific name match first + var rule = _settings.MonsterRules.FirstOrDefault( + r => !r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase) && + target.Name.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0); + if (rule != null) return rule; + // Fall back to Default + return _settings.MonsterRules.FirstOrDefault( + m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + } + + private void AttackWithMagic(WorldObject target) + { + if (_spellManager == null || target == null) return; + if ((DateTime.Now - _lastSpellCast).TotalMilliseconds < SPELL_CAST_COOLDOWN_MS) return; + + // If waiting for debuff result, check timeout only + if (_waitingForDebuffResult) + { + if ((DateTime.Now - _pendingDebuffCastTime).TotalMilliseconds > DEBUFF_RESULT_TIMEOUT_MS) + { + // Timed out — assume success, add to confirmed + _confirmedDebuffs.Add($"{_pendingDebuffTargetId}_{_pendingDebuffKey}"); + _waitingForDebuffResult = false; + } + else + { + return; // Still waiting for chat — don't cast anything + } + } + + // Clear confirmed debuffs if target changed + if (activeTargetId != _lastDebuffTargetId) + { + _confirmedDebuffs.Clear(); + _lastDebuffTargetId = activeTargetId; + } + + var rule = GetRuleForTarget(target); + string element = GetPreferredElement(target, rule); + + // ── Phase 1: Debuffs — spam until chat confirms each one ── + if (rule != null) + { + var pendingDebuffs = BuildDebuffList(rule, element); + + foreach (var debuffKey in pendingDebuffs) + { + string key = $"{activeTargetId}_{debuffKey}"; + + if (_confirmedDebuffs.Contains(key)) + continue; // Chat confirmed this one — move on + + int spellId = 0; + int castTier = 0; + if (debuffKey.StartsWith("Vuln:")) + spellId = FindBestVulnSpellWithTier(debuffKey.Substring(5), out castTier); + else + spellId = FindBestDebuffSpellWithTier(debuffKey, out castTier); + + if (spellId == 0) continue; + + try + { + _coreManager.Actions.CastSpell(spellId, activeTargetId); + _lastSpellCast = DateTime.Now; + _pendingDebuffKey = debuffKey; + _pendingDebuffTargetId = activeTargetId; + _pendingDebuffTier = castTier; + _waitingForDebuffResult = true; + _pendingDebuffCastTime = DateTime.Now; + try { _host?.Actions?.AddChatText($"[RynthAi] Casting: {debuffKey} (T{castTier}) on {target.Name}", 5); } catch { } + } + catch { } + return; // Wait for chat result + } + } + + // ── Phase 2: War/Void spell spam — faster cooldown ── + if ((DateTime.Now - _lastSpellCast).TotalMilliseconds < ATTACK_SPELL_COOLDOWN_MS) return; + + if (rule != null && !rule.UseArc && !rule.UseRing && !rule.UseStreak && !rule.UseBolt) + return; + + int offensiveSpellId = FindBestShapedSpell(element, rule); + if (offensiveSpellId != 0) + { + try + { + _coreManager.Actions.CastSpell(offensiveSpellId, activeTargetId); + _lastSpellCast = DateTime.Now; + } + catch { } + } + else + { + AttackTarget(); + } + } + + private string GetPreferredElement(WorldObject target, MonsterRule rule) + { + // 1. Explicit element from rule + if (rule != null && !string.IsNullOrEmpty(rule.DamageType) && + !rule.DamageType.Equals("Auto", StringComparison.OrdinalIgnoreCase)) + { + return rule.DamageType; + } + + // 2. Auto: check monsters.json weakness database + if (target != null && _monsterWeaknesses != null && _monsterWeaknesses.Count > 0) + { + foreach (var entry in _monsterWeaknesses) + { + if (target.Name.IndexOf(entry.Key, StringComparison.OrdinalIgnoreCase) >= 0) + { + return entry.Value; + } + } + } + + // 3. Ultimate fallback + return "Fire"; + } + + // ── DEBUFF SYSTEM ──────────────────────────────────────────────────────── + + /// + /// Returns true if any debuff in the rule's list still needs casting on the active target. + /// + private bool HasPendingDebuffs(MonsterRule rule, string element) + { + if (rule == null) return false; + var debuffs = BuildDebuffList(rule, element); + foreach (var debuffKey in debuffs) + { + string key = $"{activeTargetId}_{debuffKey}"; + if (!_confirmedDebuffs.Contains(key)) + return true; + } + return false; + } + + /// + /// Finds the first wand/staff/orb in ItemRules for debuff casting. + /// + private int FindWandInItems() + { + foreach (var item in _settings.ItemRules) + { + var wo = _coreManager.WorldFilter[item.Id]; + if (wo != null && wo.ObjectClass == ObjectClass.WandStaffOrb) + return item.Id; + } + return 0; + } + + /// + /// Builds the ordered debuff list from a MonsterRule's lights. + /// + private List BuildDebuffList(MonsterRule rule, string element) + { + var list = new List(); + if (rule.Imperil) list.Add("Imperil"); + if (rule.Vuln) list.Add("Vuln:" + element); + if (!string.IsNullOrEmpty(rule.ExVuln) && !rule.ExVuln.Equals("None", StringComparison.OrdinalIgnoreCase)) + list.Add("Vuln:" + rule.ExVuln); + if (rule.Fester) list.Add("Fester"); + if (rule.Yield) list.Add("Yield"); + if (rule.Broadside) list.Add("Broadside"); + if (rule.GravityWell) list.Add("Gravity"); + return list; + } + + // ── DEBUFF SPELL RESOLUTION (with tier output for duration tracking) ── + + private int FindBestDebuffSpellWithTier(string debuffType, out int tier) + { + tier = 0; + if (_spellManager == null) return 0; + + string[] spellInfo; + if (!DebuffSpells.TryGetValue(debuffType, out spellInfo) || spellInfo.Length < 2) + return 0; + + string tieredBase = spellInfo[0]; // e.g., "Imperil Other" + string loreName = spellInfo[1]; // e.g., "Gossamer Flesh" + + CharFilterSkillType skill = CharFilterSkillType.CreatureEnchantment; + int maxTier = _spellManager.GetHighestSpellTier(skill); + + // 1. Tier 8: Incantation of [tieredBase] + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {tieredBase}"); + if (id != 0) { tier = 8; return id; } + } + + // 2. Tier 7: Lore name (direct lookup) + if (maxTier >= 7 && !string.IsNullOrEmpty(loreName)) + { + int id = TrySpellByName(loreName); + if (id != 0) { tier = 7; return id; } + } + + // 3. Tier 7 numbered fallback, then VI → I + for (int t = Math.Min(maxTier, 7); t >= 1; t--) + { + string numeral = GetRomanNumeral(t); + int id = TrySpellByName($"{tieredBase} {numeral}"); + if (id != 0) { tier = t; return id; } + } + + return 0; + } + + private int FindBestVulnSpellWithTier(string element, out int tier) + { + tier = 0; + if (_spellManager == null) return 0; + + string[] vulnBases; + if (!VulnSpells.TryGetValue(element, out vulnBases)) + return 0; + + CharFilterSkillType skill = CharFilterSkillType.CreatureEnchantment; + int maxTier = _spellManager.GetHighestSpellTier(skill); + + foreach (string baseName in vulnBases) + { + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {baseName}"); + if (id != 0) { tier = 8; return id; } + } + + for (int t = Math.Min(maxTier, 7); t >= 1; t--) + { + int id = TrySpellByName($"{baseName} {GetRomanNumeral(t)}"); + if (id != 0) { tier = t; return id; } + } + } + return 0; + } + + /// + /// Tries to find a spell by exact name. Returns spell ID if known, 0 if not. + /// + private int TrySpellByName(string name) + { + int id; + if (_spellManager.SpellDictionary.TryGetValue(name, out id)) + { + if (_coreManager.CharacterFilter.IsSpellKnown(id)) + return id; + } + return 0; + } + + // ── SPELL SHAPE SELECTION (A/R/S/B lights) ────────────────────────── + + /// + /// Counts monsters within the given AC distance (yards/240). + /// + private int CountMonstersInRange(double rangeYards) + { + double acDist = rangeYards / 240.0; + int count = 0; + int playerId = _coreManager.CharacterFilter.Id; + foreach (var wo in _coreManager.WorldFilter.GetLandscape()) + { + if ((int)wo.ObjectClass != 5) continue; + if (_coreManager.WorldFilter.Distance(playerId, wo.Id) <= acDist) + count++; + } + return count; + } + + /// + /// Finds the best offensive spell using the rule's shape lights. + /// A = Arc, R = Ring, S = Streak, B = Bolt. + /// RING OVERRIDE: If >= MinRingTargets monsters are within RingRange, forces Ring spells. + /// If none are set, returns 0 (no attack - buff bot mode). + /// Uses Void Magic for Nether element, War Magic for everything else. + /// + private int FindBestShapedSpell(string element, MonsterRule rule) + { + if (_spellManager == null) return 0; + + // Determine skill: Void or War + bool useVoid = element.Equals("Nether", StringComparison.OrdinalIgnoreCase); + // Also check if character has Void trained but not War (or vice versa) + bool warTrained = false, voidTrained = false; + try { warTrained = (int)_coreManager.CharacterFilter.Skills[CharFilterSkillType.WarMagic].Training >= 2; } catch { } + try { voidTrained = (int)_coreManager.CharacterFilter.Skills[CharFilterSkillType.VoidMagic].Training >= 2; } catch { } + + if (useVoid && !voidTrained && warTrained) useVoid = false; // fallback to war + if (!useVoid && !warTrained && voidTrained) useVoid = true; // fallback to void + + CharFilterSkillType skill = useVoid ? CharFilterSkillType.VoidMagic : CharFilterSkillType.WarMagic; + + // Determine shape index: 0=Arc, 1=Ring, 2=Streak, 3=Bolt + // Priority: A > R > S > B. If none set, caller already blocked attack. + int shapeIdx = 3; // default = Bolt + if (rule != null) + { + if (rule.UseArc) shapeIdx = 0; + else if (rule.UseRing) shapeIdx = 1; + else if (rule.UseStreak) shapeIdx = 2; + else if (rule.UseBolt) shapeIdx = 3; + else return 0; // No attack shape selected + } + + // RING OVERRIDE: only if R light is on for this rule, and enough monsters nearby + if (rule != null && rule.UseRing && _settings.MinRingTargets > 0 && _settings.RingRange > 0) + { + int nearbyCount = CountMonstersInRange(_settings.RingRange); + if (nearbyCount >= _settings.MinRingTargets) + shapeIdx = 1; // Force Ring + } + + // Look up shape patterns + var shapes = useVoid ? VoidSpellShapes : SpellShapes; + string[] elementShapes; + if (!shapes.TryGetValue(element, out elementShapes)) + { + // Fallback element + if (!SpellShapes.TryGetValue("Fire", out elementShapes)) + return 0; + skill = CharFilterSkillType.WarMagic; + } + + // Clamp index + if (shapeIdx >= elementShapes.Length) shapeIdx = elementShapes.Length - 1; + + // Try preferred shape first + // SPECIAL: Ring spells (shapeIdx==1) have unique lore names that don't follow "Base VII" pattern + if (shapeIdx == 1) + { + int ringId = FindBestRingSpell(element, skill); + if (ringId != 0) return ringId; + } + + // Standard resolution: try preferred shape, then fall back to others + int id = FindBestOffensiveSpellId(elementShapes[shapeIdx], skill); + if (id != 0) return id; + + // Fallback: try bolt (index 3), then any shape that works + for (int i = elementShapes.Length - 1; i >= 0; i--) + { + if (i == shapeIdx) continue; + id = FindBestOffensiveSpellId(elementShapes[i], skill); + if (id != 0) return id; + } + + return 0; + } + + // ── SPELL RESOLUTION ───────────────────────────────────────────────────── + + /// + /// Resolves ring spells using AC's unique lore names. + /// Order: Incantation of [lore] (T8) → [lore] II (T7) → [lore] (T6) → generic tiers V→I + /// + private int FindBestRingSpell(string element, CharFilterSkillType skill) + { + string[] loreNames; + if (!RingLoreNames.TryGetValue(element, out loreNames) || loreNames.Length < 2) + return 0; + + int maxTier = _spellManager.GetHighestSpellTier(skill); + + // T7: [lore name] II (try first — most likely to be known) + if (maxTier >= 7) + { + int id = TrySpellByName(loreNames[1]); + if (id != 0) return id; + // Try with smart apostrophe variants + id = TrySpellByName(loreNames[1].Replace("'", "\u2019")); + if (id != 0) return id; + id = TrySpellByName(loreNames[1].Replace("'", "`")); + if (id != 0) return id; + } + + // T6: [lore name] + if (maxTier >= 6) + { + int id = TrySpellByName(loreNames[0]); + if (id != 0) return id; + id = TrySpellByName(loreNames[0].Replace("'", "\u2019")); + if (id != 0) return id; + id = TrySpellByName(loreNames[0].Replace("'", "`")); + if (id != 0) return id; + } + + // T8: Incantation of [lore name] + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {loreNames[0]}"); + if (id != 0) return id; + } + + // Fallback: try generic ring names (e.g., "Ring of Fire V") + string[] genericRingBases; + if (SpellShapes.TryGetValue(element, out genericRingBases) && genericRingBases.Length > 1) + { + string ringBase = genericRingBases[1]; // Index 1 = Ring + for (int t = Math.Min(maxTier, 5); t >= 1; t--) + { + int id = TrySpellByName($"{ringBase} {GetRomanNumeral(t)}"); + if (id != 0) return id; + } + } + + // Debug: if we get here, log what we tried + try { _host?.Actions?.AddChatText($"[RynthAi] Ring spell not found for {element} (tried: {loreNames[1]}, {loreNames[0]})", 2); } catch { } + return 0; + } + + /// + /// Searches for the highest tier of a spell the character knows. + /// Order: Incantation (8) → VII → VI → V → IV → III → II → I + /// Respects skill level — won't try tiers the character can't cast. + /// + private int FindBestOffensiveSpellId(string baseName, CharFilterSkillType skill) + { + if (_spellManager == null) return 0; + + int maxTier = _spellManager.GetHighestSpellTier(skill); + + // Tier 8: Incantation + if (maxTier >= 8) + { + int id = TrySpellByName($"Incantation of {baseName}"); + if (id != 0) return id; + id = TrySpellByName(baseName + " VIII"); + if (id != 0) return id; + } + + // Tiers 7 → 1 + for (int tier = Math.Min(maxTier, 7); tier >= 1; tier--) + { + string numeral = GetRomanNumeral(tier); + int id = TrySpellByName($"{baseName} {numeral}"); + if (id != 0) return id; + } + + return 0; + } + + private static string GetRomanNumeral(int tier) + { + switch (tier) + { + case 1: return "I"; + case 2: return "II"; + case 3: return "III"; + case 4: return "IV"; + case 5: return "V"; + case 6: return "VI"; + case 7: return "VII"; + case 8: return "VIII"; + default: return "I"; + } + } + + private void CleanupExpiredBlacklist() + { + var expired = new List(); + foreach (var kvp in blacklistedTargets) if (kvp.Value.IsExpired()) expired.Add(kvp.Key); + foreach (var id in expired) blacklistedTargets.Remove(id); + // _confirmedDebuffs is cleared automatically when target changes + } + + + + public void Dispose() { _raycastSystem?.Dispose(); } + + /// + /// Diagnostic: runs a full LOS test against the currently selected target + /// and reports all coordinates, geometry volumes, and intersection results. + /// + public List RunLosTestDiag(CoreManager core) + { + var lines = new List(); + try + { + if (_raycastSystem == null || !RaycastInitialized) + { + lines.Add("Raycast system not initialized"); + return lines; + } + + int targetId = core.Actions.CurrentSelection; + if (targetId == 0) + { + lines.Add("No target selected — select a monster first"); + return lines; + } + + var target = core.WorldFilter[targetId]; + if (target == null) + { + lines.Add($"Target {targetId} not found in WorldFilter"); + return lines; + } + + lines.Add($"Target: {target.Name} (id={targetId})"); + + // Player position + uint landcell = (uint)core.Actions.Landcell; + uint blockX = (landcell >> 24) & 0xFF; + uint blockY = (landcell >> 16) & 0xFF; + float locX = (float)core.Actions.LocationX; + float locY = (float)core.Actions.LocationY; + float locZ = (float)core.Actions.LocationZ; + float playerGX = blockX * 192.0f + locX; + float playerGY = blockY * 192.0f + locY; + lines.Add($"Player Landcell=0x{landcell:X8} Block=({blockX},{blockY})"); + lines.Add($"Player Local=({locX:F1},{locY:F1},{locZ:F1})"); + lines.Add($"Player Global=({playerGX:F1},{playerGY:F1},{locZ:F1})"); + + // Target position + var coords = target.Coordinates(); + double ew = coords.EastWest; + double ns = coords.NorthSouth; + float targetGX = (float)((ew * 10.0 + 1019.5) * 24.0); + float targetGY = (float)((ns * 10.0 + 1019.5) * 24.0); + float targetZ = locZ; // approximate + try { targetZ = (float)target.RawCoordinates().Z; } catch { } + lines.Add($"Target EW={ew:F3} NS={ns:F3}"); + lines.Add($"Target Global=({targetGX:F1},{targetGY:F1},{targetZ:F1})"); + + float dx = targetGX - playerGX; + float dy = targetGY - playerGY; + float dist = (float)Math.Sqrt(dx * dx + dy * dy); + lines.Add($"Distance: {dist:F1}m, Delta=({dx:F1},{dy:F1})"); + + // Load geometry + var geometry = _raycastSystem.GeometryLoader.GetLandblockGeometry(landcell); + lines.Add($"Geometry: {geometry?.Count ?? 0} volumes loaded"); + + if (geometry != null && geometry.Count > 0) + { + var origin = new Raycasting.Vector3(playerGX, playerGY, locZ + 1.0f); + var targetPos = new Raycasting.Vector3(targetGX, targetGY, targetZ + 1.0f); + + var rayDir = targetPos - origin; + float rayLen = rayDir.Length(); + if (rayLen > 0.001f) rayDir = rayDir / rayLen; + + float pathMinX = Math.Min(playerGX, targetGX) - 15f; + float pathMaxX = Math.Max(playerGX, targetGX) + 15f; + float pathMinY = Math.Min(playerGY, targetGY) - 15f; + float pathMaxY = Math.Max(playerGY, targetGY) + 15f; + + int nearCount = 0; + int hitCount = 0; + var hitVolumes = new List(); + var nearVolumes = new List(); + + foreach (var vol in geometry) + { + bool nearPath = vol.Center.X >= pathMinX && vol.Center.X <= pathMaxX && + vol.Center.Y >= pathMinY && vol.Center.Y <= pathMaxY; + + float volDist; + bool hit = vol.RayIntersect(origin, rayDir, rayLen, out volDist); + + if (hit) hitCount++; + if (nearPath) nearCount++; + + // ALWAYS capture hitting volumes + if (hit && hitVolumes.Count < 10) + { + hitVolumes.Add($" ** HIT at {volDist:F2}yd: center=({vol.Center.X:F1},{vol.Center.Y:F1},{vol.Center.Z:F1}) " + + $"dim=({vol.Dimensions.X:F1},{vol.Dimensions.Y:F1},{vol.Dimensions.Z:F1}) type={vol.Type}"); + } + + if (nearPath && !hit && nearVolumes.Count < 10) + { + nearVolumes.Add($" NEAR: center=({vol.Center.X:F0},{vol.Center.Y:F0},{vol.Center.Z:F0}) " + + $"r={vol.Dimensions.X:F1} type={vol.Type}"); + } + } + + // Show hits first + if (hitVolumes.Count > 0) + { + lines.Add("=== BLOCKING VOLUMES ==="); + foreach (var hv in hitVolumes) lines.Add(hv); + } + + if (nearVolumes.Count > 0) + { + lines.Add($"=== NEAR (non-hit, showing {nearVolumes.Count} of {nearCount}) ==="); + foreach (var nv in nearVolumes) lines.Add(nv); + } + + if (hitVolumes.Count == 0 && nearVolumes.Count == 0) + lines.Add(" NO volumes found near path!"); + + lines.Add($"Summary: {geometry.Count} total, {nearCount} near path, {hitCount} ray hits"); + + bool nearby = Raycasting.RaycastEngine.HasNearbyGeometry(origin, targetPos, geometry); + bool blocked = Raycasting.RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry); + lines.Add($"HasNearbyGeometry: {nearby}"); + lines.Add($"IsLinearPathBlocked: {blocked}"); + } + } + catch (Exception ex) + { + lines.Add($"Error: {ex.Message}"); + } + return lines; + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Combat/FellowshipTracker.cs b/Plugins/RynthAi/Combat/FellowshipTracker.cs new file mode 100644 index 0000000..ab1a797 --- /dev/null +++ b/Plugins/RynthAi/Combat/FellowshipTracker.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using Decal.Adapter; + +namespace NexSuite.Plugins.RynthAi +{ + /// + /// Reads fellowship membership directly from AC client memory. + /// + /// Memory layout (from UB's AcClient structs / acclient.exe analysis): + /// + /// Static pointers: + /// 0x0087150C = ClientFellowshipSystem** s_pFellowshipSystem + /// 0x00844C08 = UInt32* player_iid (our character ID) + /// + /// ClientFellowshipSystem: + /// +0x10 = CFellowship* m_pFellowship (null if not in fellowship) + /// + /// CFellowship / Fellowship: + /// +0x0C = PackableHashData** _buckets (hash table bucket array) + /// +0x10 = UInt32 _table_size (number of buckets) + /// +0x14 = UInt32 _currNum (member count) + /// +0x18 = PStringBase _name (fellowship name, char*) + /// +0x1C = UInt32 _leader (leader character ID) + /// +0x20 = int _share_xp + /// +0x24 = int _even_xp_split + /// +0x28 = int _open_fellow + /// +0x2C = int _locked + /// + /// PackableHashData (hash table entry for each member): + /// +0x00 = UInt32 _key (member character ID) + /// +0x04 = Fellow _data: + /// +0x04 = Fellow.PackObj vtable (4 bytes) + /// +0x08 = Fellow._name (PStringBase = char*, 4 bytes) + /// +0x0C = Fellow._level (UInt32) + /// +0x1C = Fellow._share_loot (int) + /// +0x20 = Fellow._max_health (UInt32) + /// +0x28 = Fellow._max_mana (UInt32) + /// +0x2C = Fellow._current_health (UInt32) + /// +0x34 = PackableHashData* _next (next in chain, null = end) + /// + public class FellowshipTracker : IDisposable + { + // Static memory addresses in acclient.exe + private static readonly IntPtr ADDR_FELLOWSHIP_SYSTEM = new IntPtr(0x0087150C); + private static readonly IntPtr ADDR_PLAYER_IID = new IntPtr(0x00844C08); + + // Struct offsets + private const int OFF_SYS_FELLOWSHIP = 0x10; // ClientFellowshipSystem → m_pFellowship + private const int OFF_FEL_BUCKETS = 0x0C; // Fellowship → _buckets + private const int OFF_FEL_TABLE_SIZE = 0x10; // Fellowship → _table_size + private const int OFF_FEL_CURR_NUM = 0x14; // Fellowship → _currNum + private const int OFF_FEL_NAME = 0x18; // Fellowship → _name (char*) + private const int OFF_FEL_LEADER = 0x1C; // Fellowship → _leader + private const int OFF_FEL_SHARE_XP = 0x20; // Fellowship → _share_xp + private const int OFF_FEL_EVEN_SPLIT = 0x24; // Fellowship → _even_xp_split + private const int OFF_FEL_OPEN = 0x28; // Fellowship → _open_fellow + private const int OFF_FEL_LOCKED = 0x2C; // Fellowship → _locked + + // Hash entry offsets (PackableHashData) + private const int OFF_ENTRY_KEY = 0x00; // _key (member character ID) + private const int OFF_ENTRY_NAME_PTR = 0x08; // Fellow._name (char*) + private const int OFF_ENTRY_LEVEL = 0x0C; // Fellow._level + private const int OFF_ENTRY_NEXT = 0x34; // _next pointer + + // Cached member data + private Dictionary _memberCache = new Dictionary(); + private DateTime _lastRefresh = DateTime.MinValue; + private const double REFRESH_INTERVAL_MS = 2000; + + private CoreManager _core; + + public FellowshipTracker(CoreManager core) + { + _core = core; + } + + public void Dispose() { } + + // ══════════════════════════════════════════════════════════════ + // PUBLIC API — matches the UB expression interface + // ══════════════════════════════════════════════════════════════ + + /// True if the player is currently in a fellowship. + public bool IsInFellowship + { + get + { + try { return GetFellowshipPtr() != IntPtr.Zero; } + catch { return false; } + } + } + + /// Number of members in the current fellowship. + public int MemberCount + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return 0; + return Marshal.ReadInt32(fel + OFF_FEL_CURR_NUM); + } + catch { return 0; } + } + } + + /// Name of the current fellowship. + public string FellowshipName + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return ""; + return ReadPString(fel + OFF_FEL_NAME); + } + catch { return ""; } + } + } + + /// Character ID of the fellowship leader. + public int LeaderId + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return 0; + return Marshal.ReadInt32(fel + OFF_FEL_LEADER); + } + catch { return 0; } + } + } + + /// True if the player is the fellowship leader. + public bool IsLeader + { + get + { + try + { + int leader = LeaderId; + if (leader == 0) return false; + int myId = Marshal.ReadInt32(ADDR_PLAYER_IID); + return leader == myId; + } + catch { return false; } + } + } + + /// True if the fellowship is open for recruitment. + public bool IsOpen + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return false; + return Marshal.ReadInt32(fel + OFF_FEL_OPEN) == 1; + } + catch { return false; } + } + } + + /// True if the fellowship is locked. + public bool IsLocked + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return false; + return Marshal.ReadInt32(fel + OFF_FEL_LOCKED) == 1; + } + catch { return false; } + } + } + + /// True if the fellowship is sharing XP. + public bool ShareXP + { + get + { + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return false; + return Marshal.ReadInt32(fel + OFF_FEL_SHARE_XP) == 1; + } + catch { return false; } + } + } + + /// Check if a character name is a fellowship member. + public bool IsMember(string name) + { + if (string.IsNullOrEmpty(name)) return false; + RefreshIfNeeded(); + foreach (var kvp in _memberCache) + { + if (kvp.Value.Equals(name, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } + + /// Check if a character ID is a fellowship member. + public bool IsMember(int characterId) + { + RefreshIfNeeded(); + return _memberCache.ContainsKey(characterId); + } + + /// Get all member names. + public IEnumerable GetMemberNames() + { + RefreshIfNeeded(); + return _memberCache.Values; + } + + /// Get member name by index (0-based). + public string GetMemberName(int index) + { + RefreshIfNeeded(); + int i = 0; + foreach (var kvp in _memberCache) + { + if (i == index) return kvp.Value; + i++; + } + return ""; + } + + /// Get member character ID by index (0-based). + public int GetMemberId(int index) + { + RefreshIfNeeded(); + int i = 0; + foreach (var kvp in _memberCache) + { + if (i == index) return kvp.Key; + i++; + } + return 0; + } + + // ══════════════════════════════════════════════════════════════ + // NATIVE MEMORY READING + // ══════════════════════════════════════════════════════════════ + + /// + /// Gets the CFellowship pointer. Returns IntPtr.Zero if not in a fellowship. + /// Chain: [s_pFellowshipSystem] → ClientFellowshipSystem → [+0x10] → CFellowship + /// + private IntPtr GetFellowshipPtr() + { + int sysPtr = Marshal.ReadInt32(ADDR_FELLOWSHIP_SYSTEM); + if (sysPtr == 0) return IntPtr.Zero; + + int felPtr = Marshal.ReadInt32(new IntPtr(sysPtr + OFF_SYS_FELLOWSHIP)); + if (felPtr == 0) return IntPtr.Zero; + + return new IntPtr(felPtr); + } + + /// + /// Refreshes the member cache by iterating the hash table in client memory. + /// Only refreshes every REFRESH_INTERVAL_MS to avoid overhead. + /// + private void RefreshIfNeeded() + { + if ((DateTime.Now - _lastRefresh).TotalMilliseconds < REFRESH_INTERVAL_MS) + return; + _lastRefresh = DateTime.Now; + + _memberCache.Clear(); + + try + { + IntPtr fel = GetFellowshipPtr(); + if (fel == IntPtr.Zero) return; + + int bucketsPtr = Marshal.ReadInt32(fel + OFF_FEL_BUCKETS); + int tableSize = Marshal.ReadInt32(fel + OFF_FEL_TABLE_SIZE); + int currNum = Marshal.ReadInt32(fel + OFF_FEL_CURR_NUM); + + if (bucketsPtr == 0 || tableSize == 0 || currNum == 0) return; + + // Safety: don't iterate more than 9 members (AC fellowship max) + int maxMembers = Math.Min(currNum, 9); + int found = 0; + + // Walk each bucket in the hash table + for (int b = 0; b < tableSize && found < maxMembers; b++) + { + // Read bucket pointer: _buckets[b] + int entryPtr = Marshal.ReadInt32(new IntPtr(bucketsPtr + b * 4)); + + // Walk the chain for this bucket + while (entryPtr != 0 && found < maxMembers) + { + // Read _key (member character ID) at entry + 0x00 + int memberId = Marshal.ReadInt32(new IntPtr(entryPtr + OFF_ENTRY_KEY)); + + // Read _name pointer at entry + 0x08 (Fellow._name = char*) + string name = ReadPString(new IntPtr(entryPtr + OFF_ENTRY_NAME_PTR)); + + if (memberId != 0 && !string.IsNullOrEmpty(name)) + { + _memberCache[memberId] = name; + found++; + } + + // Follow _next pointer at entry + 0x34 + entryPtr = Marshal.ReadInt32(new IntPtr(entryPtr + OFF_ENTRY_NEXT)); + } + } + } + catch { } + } + + /// + /// Reads a PStringBase<char> from a memory address. + /// + /// PStringBase contains a single m_buffer pointer to PSRefBuffer<char>. + /// PSRefBuffer layout (verified from acclient.exe binary analysis — + /// PStringBase ctor at 0x48C3E0 copies chars to buf+0x14, + /// allocation helper at 0x403560 initializes the header): + /// +0x00: vtable (ReferenceCountTemplate vftable, e.g. 0x7CAE34) + /// +0x04: m_cRef (int32 — reference count) + /// +0x08: m_Length (int32 — string length INCLUDING null terminator) + /// +0x0C: m_Capacity (int32 — allocated buffer capacity) + /// +0x10: m_Hash (int32 — initialized to 0xFFFFFFFF) + /// +0x14: char[] (actual string data, null-terminated) + /// + private string ReadPString(IntPtr addr) + { + try + { + // Step 1: Read PSRefBuffer* from PStringBase.m_buffer + int bufPtr = Marshal.ReadInt32(addr); + if (bufPtr == 0) return ""; + + // Step 2: Read string data from PSRefBuffer + 0x14 (after 20-byte header) + // Use null-terminated read with safety cap at 64 chars + string raw = Marshal.PtrToStringAnsi(new IntPtr(bufPtr + 0x14)); + if (raw == null) return ""; + if (raw.Length > 64) raw = raw.Substring(0, 64); + return raw; + } + catch { return ""; } + } + } +} diff --git a/Plugins/RynthAi/Combat/MissileCraftingManager.cs b/Plugins/RynthAi/Combat/MissileCraftingManager.cs new file mode 100644 index 0000000..c62d735 --- /dev/null +++ b/Plugins/RynthAi/Combat/MissileCraftingManager.cs @@ -0,0 +1,521 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; + +namespace NexSuite.Plugins.RynthAi +{ + /// + /// Automates missile ammunition management. + /// + /// Triggers when ammo slot is empty: + /// 1. Can craft better ammo than loose inventory? → Craft (up to 2x), then equip + /// 2. Loose ammo available? → Equip best one + /// 3. Can craft anything? → Craft, then equip + /// + /// Crafting is chat-driven: issues ApplyItem, waits for "You make" chat message, + /// then advances to next combine or equips. Retries every 2s if no response. + /// + public class MissileCraftingManager + { + private CoreManager _core; + private UISettings _settings; + private PluginHost _host; + + public enum CraftState + { + Idle, + Evaluating, + Combining, // ApplyItem issued, waiting for "You make" in chat + EquippingAmmo + } + + public CraftState State { get; private set; } = CraftState.Idle; + public bool IsCrafting => State != CraftState.Idle; + public string StatusMessage { get; private set; } = ""; + + // ── Timing ───────────────────────────────────────────────────────── + private DateTime _phaseStart = DateTime.MinValue; + private DateTime _lastAmmoCheck = DateTime.MinValue; + private DateTime _lastApplyAttempt = DateTime.MinValue; + private const int AMMO_CHECK_INTERVAL_MS = 5000; + private const int APPLY_RETRY_MS = 2000; + private const int CRAFT_TIMEOUT_MS = 15000; + private const int EQUIP_DELAY_MS = 500; + + // ── Current craft job ────────────────────────────────────────────── + private int _headBundleId = 0; + private int _shaftBundleId = 0; + private AmmoRecipe _currentRecipe = null; + private int _equipTargetId = 0; + private bool _allCombinesDone = false; + + // Pre-identified bundle pairs (up to 2). Populated before first combine. + private Queue _pendingBundlePairs = new Queue(); + private int _totalCombines = 0; + private int _combinesCompleted = 0; + + // ══════════════════════════════════════════════════════════════════ + // RECIPE DATABASE + // ══════════════════════════════════════════════════════════════════ + + public enum WeaponCategory { Bow, Crossbow, Atlatl } + + public class AmmoRecipe + { + public string HeadBundleName; + public string ShaftBundleName; + public string OutputName; + public WeaponCategory Category; + public bool RequiresSpecialized; + public int Priority; + } + + public static readonly List AllRecipes = new List + { + // ── ARROWS (Bow) ─────────────────────────────────────────── + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Lethal Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Lethal Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = true, Priority = 40 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Deadly Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Deadly Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = true, Priority = 30 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Greater Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Greater Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 20 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Prismatic Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Prismatic Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 10 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Armor Piercing Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Armor Piercing Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 6 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Broad Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Broad Head Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 5 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Blunt Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Blunt Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 4 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Frog Crotch Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Frog Crotch Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 3 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Arrowheads", ShaftBundleName = "Wrapped Bundle of Arrowshafts", OutputName = "Arrow", Category = WeaponCategory.Bow, RequiresSpecialized = false, Priority = 1 }, + + // ── QUARRELS (Crossbow) ──────────────────────────────────── + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Lethal Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Lethal Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = true, Priority = 40 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Deadly Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Deadly Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = true, Priority = 30 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Greater Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Greater Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 20 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Prismatic Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Prismatic Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 10 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Armor Piercing Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Armor Piercing Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 6 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Broad Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Broad Head Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 5 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Blunt Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Blunt Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 4 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Quarrelheads", ShaftBundleName = "Wrapped Bundle of Quarrelshafts", OutputName = "Quarrel", Category = WeaponCategory.Crossbow, RequiresSpecialized = false, Priority = 1 }, + + // ── DARTS (Atlatl) ───────────────────────────────────────── + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Lethal Prismatic Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Lethal Prismatic Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = true, Priority = 40 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Deadly Prismatic Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Deadly Prismatic Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = true, Priority = 30 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Greater Prismatic Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Greater Prismatic Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 20 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Prismatic Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Prismatic Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 10 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Armor Piercing Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Armor Piercing Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 6 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Broad Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Broad Head Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 5 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Blunt Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Blunt Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 4 }, + new AmmoRecipe { HeadBundleName = "Wrapped Bundle of Atlatl Dart Heads", ShaftBundleName = "Wrapped Bundle of Atlatl Dart Shafts", OutputName = "Atlatl Dart", Category = WeaponCategory.Atlatl, RequiresSpecialized = false, Priority = 1 }, + }; + + // ══════════════════════════════════════════════════════════════════ + // CONSTRUCTOR + // ══════════════════════════════════════════════════════════════════ + + public MissileCraftingManager(CoreManager core, UISettings settings, PluginHost host) + { + _core = core; + _settings = settings; + _host = host; + } + + // ══════════════════════════════════════════════════════════════════ + // MAIN TICK + // ══════════════════════════════════════════════════════════════════ + + public void ProcessCrafting() + { + if (!_settings.EnableMissileCrafting) return; + if (_core.Actions.BusyState != 0) return; + + switch (State) + { + case CraftState.Idle: ProcessIdle(); break; + case CraftState.Evaluating: ProcessEvaluating(); break; + case CraftState.Combining: ProcessCombining(); break; + case CraftState.EquippingAmmo: ProcessEquippingAmmo(); break; + } + } + + // ══════════════════════════════════════════════════════════════════ + // CHAT HANDLER — called from PluginCore.OnChatBoxMessage + // Listens for "You make" to confirm a successful combine. + // ══════════════════════════════════════════════════════════════════ + + public void HandleChat(string text) + { + if (State != CraftState.Combining) return; + if (string.IsNullOrEmpty(text)) return; + + // AC craft success: "You make a big bundle of deadly prismatic arrows." + if (text.IndexOf("You make", StringComparison.OrdinalIgnoreCase) < 0) return; + + _combinesCompleted++; + ChatLog($"Craft confirmed ({_combinesCompleted}/{_totalCombines})"); + + // More pairs to combine? + if (_pendingBundlePairs.Count > 0) + { + var pair = _pendingBundlePairs.Dequeue(); + _headBundleId = pair[0]; + _shaftBundleId = pair[1]; + _lastApplyAttempt = DateTime.MinValue; // Force immediate ApplyItem next tick + StatusMessage = $"Crafting {_currentRecipe.OutputName} (batch {_combinesCompleted + 1})..."; + } + else + { + // All combines done — signal ProcessCombining to transition + _allCombinesDone = true; + } + } + + // ══════════════════════════════════════════════════════════════════ + // IDLE — only triggers when ammo slot is empty + // ══════════════════════════════════════════════════════════════════ + + private void ProcessIdle() + { + if ((DateTime.Now - _lastAmmoCheck).TotalMilliseconds < AMMO_CHECK_INTERVAL_MS) return; + _lastAmmoCheck = DateTime.Now; + + WeaponCategory? category = GetEquippedMissileCategory(); + if (category == null) return; + if (HasWieldedAmmo(category.Value)) return; + + ChatLog($"No {GetCategoryLabel(category.Value)}s equipped. Evaluating..."); + SetState(CraftState.Evaluating); + } + + // ══════════════════════════════════════════════════════════════════ + // EVALUATING — decide: craft or equip existing? + // ══════════════════════════════════════════════════════════════════ + + private void ProcessEvaluating() + { + WeaponCategory? category = GetEquippedMissileCategory(); + if (category == null) { Reset("No missile weapon equipped"); return; } + + int trainingLevel = 0; + try { trainingLevel = (int)_core.CharacterFilter.Skills[CharFilterSkillType.Fletching].Training; } catch { } + + var inv = _core.WorldFilter.GetInventory().ToList(); + + // Find best craftable recipe + AmmoRecipe bestCraftable = null; + foreach (var recipe in AllRecipes + .Where(r => r.Category == category.Value) + .OrderByDescending(r => r.Priority)) + { + if (recipe.RequiresSpecialized && trainingLevel < 3) continue; + if (!recipe.RequiresSpecialized && trainingLevel < 2) continue; + + bool hasHead = inv.Any(i => i.Name != null && i.Name.Equals(recipe.HeadBundleName, StringComparison.OrdinalIgnoreCase)); + bool hasShaft = inv.Any(i => i.Name != null && i.Name.Equals(recipe.ShaftBundleName, StringComparison.OrdinalIgnoreCase)); + + if (hasHead && hasShaft) { bestCraftable = recipe; break; } + } + + // Find best loose ammo + int bestExistingPriority = 0; + WorldObject bestExistingAmmo = null; + foreach (var item in inv) + { + if (!IsLooseAmmo(item, category.Value)) continue; + int pri = GetAmmoPriority(item, category.Value); + if (pri > bestExistingPriority) { bestExistingPriority = pri; bestExistingAmmo = item; } + } + + // Can craft better? → Craft. + if (bestCraftable != null && bestCraftable.Priority > bestExistingPriority) + { StartCrafting(bestCraftable, inv); return; } + + // Loose ammo? → Equip. + if (bestExistingAmmo != null) + { + _equipTargetId = bestExistingAmmo.Id; + ChatLog($"Equipping {bestExistingAmmo.Name} (x{bestExistingAmmo.Values(LongValueKey.StackCount, 1)})"); + SetState(CraftState.EquippingAmmo); + return; + } + + // Can craft anything? → Craft. + if (bestCraftable != null) + { StartCrafting(bestCraftable, inv); return; } + + Reset("No ammo and no bundles available"); + } + + private void StartCrafting(AmmoRecipe recipe, List inv) + { + _currentRecipe = recipe; + _pendingBundlePairs.Clear(); + _combinesCompleted = 0; + _allCombinesDone = false; + + // Enter Peace mode so the game client doesn't auto-fire arrows mid-craft + try { _core.Actions.SetCombatMode(CombatState.Peace); } catch { } + + // Find head and shaft bundles. Bundles are stackable — a single WorldObject + // can have StackCount=2+, meaning multiple combines from the same item ID. + var headItems = inv.Where(i => i.Name != null && i.Name.Equals(recipe.HeadBundleName, StringComparison.OrdinalIgnoreCase)).ToList(); + var shaftItems = inv.Where(i => i.Name != null && i.Name.Equals(recipe.ShaftBundleName, StringComparison.OrdinalIgnoreCase)).ToList(); + + // Sum total available across all stacks + int totalHeads = 0; + foreach (var h in headItems) totalHeads += h.Values(LongValueKey.StackCount, 1); + int totalShafts = 0; + foreach (var s in shaftItems) totalShafts += s.Values(LongValueKey.StackCount, 1); + + int pairCount = Math.Min(2, Math.Min(totalHeads, totalShafts)); + if (pairCount <= 0) { Reset("No bundles available"); return; } + + // Queue up pairs. Each combine uses the same IDs if stacked — the server + // decrements the stack. Only need different IDs if we exhaust one stack. + int headIdx = 0, shaftIdx = 0; + int headRemaining = headItems[0].Values(LongValueKey.StackCount, 1); + int shaftRemaining = shaftItems[0].Values(LongValueKey.StackCount, 1); + + for (int i = 0; i < pairCount; i++) + { + // Advance to next stack if current one is exhausted + while (headRemaining <= 0 && headIdx < headItems.Count - 1) + { headIdx++; headRemaining = headItems[headIdx].Values(LongValueKey.StackCount, 1); } + while (shaftRemaining <= 0 && shaftIdx < shaftItems.Count - 1) + { shaftIdx++; shaftRemaining = shaftItems[shaftIdx].Values(LongValueKey.StackCount, 1); } + + _pendingBundlePairs.Enqueue(new[] { headItems[headIdx].Id, shaftItems[shaftIdx].Id }); + headRemaining--; + shaftRemaining--; + } + + _totalCombines = pairCount; + + // Pop first pair + var first = _pendingBundlePairs.Dequeue(); + _headBundleId = first[0]; + _shaftBundleId = first[1]; + + ChatLog($"Crafting {recipe.OutputName} x{_totalCombines}"); + StatusMessage = $"Crafting {recipe.OutputName}..."; + _lastApplyAttempt = DateTime.MinValue; + SetState(CraftState.Combining); + } + + // ══════════════════════════════════════════════════════════════════ + // COMBINING — issues ApplyItem, retries until "You make" in chat. + // HandleChat advances to next pair or signals done. + // ══════════════════════════════════════════════════════════════════ + + private void ProcessCombining() + { + // HandleChat flagged all combines done → equip + if (_allCombinesDone) + { + StatusMessage = $"Equipping {_currentRecipe.OutputName}..."; + _equipTargetId = 0; + SetState(CraftState.EquippingAmmo); + return; + } + + // Timeout safety + if ((DateTime.Now - _phaseStart).TotalMilliseconds > CRAFT_TIMEOUT_MS) + { + if (_combinesCompleted > 0) + { + ChatLog($"Timeout after {_combinesCompleted} combine(s). Equipping what we have."); + _equipTargetId = 0; + SetState(CraftState.EquippingAmmo); + } + else + { + Reset("Craft timed out — no response from server"); + } + return; + } + + // Issue / retry ApplyItem every APPLY_RETRY_MS + if ((DateTime.Now - _lastApplyAttempt).TotalMilliseconds >= APPLY_RETRY_MS) + { + try + { + _host.Actions.ApplyItem(_headBundleId, _shaftBundleId); + _lastApplyAttempt = DateTime.Now; + StatusMessage = $"Combining → {_currentRecipe.OutputName} ({_combinesCompleted + 1}/{_totalCombines})..."; + } + catch (Exception ex) + { + Reset($"Combine failed: {ex.Message}"); + } + } + } + + // ══════════════════════════════════════════════════════════════════ + // EQUIPPING — UseItem on the ammo to wield it + // ══════════════════════════════════════════════════════════════════ + + private void ProcessEquippingAmmo() + { + if ((DateTime.Now - _phaseStart).TotalMilliseconds < EQUIP_DELAY_MS) return; + + try + { + int targetId = _equipTargetId; + + if (targetId == 0) + { + WeaponCategory? cat = GetEquippedMissileCategory(); + if (cat != null) + { + var ammo = FindBestAmmoInInventory(cat.Value); + if (ammo != null) targetId = ammo.Id; + } + } + + if (targetId != 0) + { + var ammoItem = _core.WorldFilter[targetId]; + if (ammoItem != null) + { + if (ammoItem.Values((LongValueKey)10, 0) > 0) + { + ChatLog($"Already equipped: {ammoItem.Name}"); + } + else + { + _host.Actions.UseItem(targetId, 0); + ChatLog($"Equipped {ammoItem.Name} (x{ammoItem.Values(LongValueKey.StackCount, 1)})"); + } + } + else + { + ChatLog("Ammo item no longer exists."); + } + } + else + { + ChatLog("Could not find ammo to equip."); + } + } + catch (Exception ex) + { + ChatLog($"Equip error: {ex.Message}"); + } + + Reset($"Done: {_currentRecipe?.OutputName ?? "ammo"}"); + } + + // ══════════════════════════════════════════════════════════════════ + // HELPERS + // ══════════════════════════════════════════════════════════════════ + + private bool HasWieldedAmmo(WeaponCategory category) + { + try + { + foreach (var item in _core.WorldFilter.GetInventory()) + { + if (item.Values((LongValueKey)10, 0) <= 0) continue; + if (IsLooseAmmo(item, category)) return true; + } + } + catch { } + return false; + } + + private bool IsLooseAmmo(WorldObject item, WeaponCategory category) + { + if (item.Name == null) return false; + string n = item.Name; + + if (n.Contains("Bundle") || n.Contains("Wrapped")) return false; + if (n.Contains("Arrowhead") || n.Contains("Arrowshaft")) return false; + if (n.Contains("Quarrelhead") || n.Contains("Quarrelshaft")) return false; + if (n.Contains("Dart Head") || n.Contains("Dart Shaft")) return false; + + switch (category) + { + case WeaponCategory.Bow: return n.Contains("Arrow"); + case WeaponCategory.Crossbow: return n.Contains("Quarrel") || n.Contains("Bolt"); + case WeaponCategory.Atlatl: return n.Contains("Dart"); + default: return false; + } + } + + private int GetAmmoPriority(WorldObject item, WeaponCategory category) + { + if (item.Name == null) return 0; + foreach (var recipe in AllRecipes.Where(r => r.Category == category).OrderByDescending(r => r.Priority)) + { + if (item.Name.Equals(recipe.OutputName, StringComparison.OrdinalIgnoreCase)) + return recipe.Priority; + } + return 1; + } + + private WorldObject FindBestAmmoInInventory(WeaponCategory category) + { + int bestPri = 0; + WorldObject best = null; + foreach (var item in _core.WorldFilter.GetInventory()) + { + if (!IsLooseAmmo(item, category)) continue; + int pri = GetAmmoPriority(item, category); + if (pri > bestPri) { bestPri = pri; best = item; } + } + return best; + } + + private WeaponCategory? GetEquippedMissileCategory() + { + try + { + foreach (var wo in _core.WorldFilter.GetInventory()) + { + if (wo.Values((LongValueKey)10, 0) <= 0) continue; + if (wo.ObjectClass != ObjectClass.MissileWeapon) continue; + string name = wo.Name?.ToLower() ?? ""; + if (name.Contains("crossbow")) return WeaponCategory.Crossbow; + if (name.Contains("atlatl")) return WeaponCategory.Atlatl; + return WeaponCategory.Bow; + } + } + catch { } + return null; + } + + private string GetCategoryLabel(WeaponCategory cat) + { + switch (cat) + { + case WeaponCategory.Bow: return "Arrow"; + case WeaponCategory.Crossbow: return "Quarrel"; + case WeaponCategory.Atlatl: return "Dart"; + default: return "Ammo"; + } + } + + private void SetState(CraftState newState) + { + State = newState; + _phaseStart = DateTime.Now; + } + + private void Reset(string reason) + { + StatusMessage = reason; + State = CraftState.Idle; + _currentRecipe = null; + _headBundleId = 0; + _shaftBundleId = 0; + _equipTargetId = 0; + _allCombinesDone = false; + _combinesCompleted = 0; + _totalCombines = 0; + _pendingBundlePairs.Clear(); + } + + private void ChatLog(string msg) + { + try { _host.Actions.AddChatText($"[RynthAi Craft] {msg}", 1); } catch { } + } + } +} diff --git a/Plugins/RynthAi/Combat/SpellDatabase.cs b/Plugins/RynthAi/Combat/SpellDatabase.cs new file mode 100644 index 0000000..9e1ad05 --- /dev/null +++ b/Plugins/RynthAi/Combat/SpellDatabase.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Reflection; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public static class SpellDatabase + { + private static Dictionary _spellNames = new Dictionary(); + private static bool _loaded = false; + + private static readonly Dictionary _builtinSpells = new Dictionary + { + { 47, "Primary Portal Tie" }, { 48, "Primary Portal Recall" }, + { 157, "Summon Primary Portal I" }, { 158, "Summon Primary Portal II" }, + { 1634, "Portal Sending" }, { 1635, "Lifestone Recall" }, + { 1636, "Lifestone Sending" }, { 1637, "Summon Primary Portal III" }, + { 2023, "Recall the Sanctuary" }, { 2041, "Aerlinthe Recall" }, + { 2358, "Lyceum Recall" }, { 2644, "Lifestone Tie" }, + { 2645, "Portal Recall" }, { 2646, "Secondary Portal Tie" }, + { 2647, "Secondary Portal Recall" }, { 2648, "Summon Secondary Portal I" }, + { 2649, "Summon Secondary Portal II" }, { 2650, "Summon Secondary Portal III" }, + { 2813, "Mount Lethe Recall" }, { 2931, "Recall Aphus Lassel" }, + { 2941, "Ulgrim's Recall" }, { 2943, "Recall to the Singularity Caul" }, + { 3865, "Glenden Wood Recall" }, { 3929, "Rossu Morta Chapterhouse Recall" }, + { 3930, "Whispering Blade Chapterhouse Recall" }, { 4084, "Bur Recall" }, + { 4198, "Paradox-touched Olthoi Infested Area Recall" }, { 4213, "Colosseum Recall" }, + { 4907, "Celestial Hand Stronghold Recall" }, { 4908, "Eldrytch Web Stronghold Recall" }, + { 4909, "Radiant Blood Stronghold Recall" }, { 5175, "Facility Hub Recall" }, + { 5330, "Gear Knight Invasion Area Camp Recall" }, { 5541, "Lost City of Neftet Recall" }, + { 6150, "Rynthid Recall" }, { 6321, "Viridian Rise Recall" }, + { 6322, "Viridian Rise Great Tree Recall" }, + }; + + public static bool IsLoaded => _loaded; + + public static void Load(PluginHost host) + { + _spellNames.Clear(); + _loaded = false; + + try + { + Assembly assembly = Assembly.GetExecutingAssembly(); + string resourceName = "NexSuite.Plugins.RynthAi.Combat.Vtank spelldump.txt"; + + using (Stream stream = assembly.GetManifestResourceStream(resourceName)) + { + if (stream == null) + { + host.Actions.AddChatText($"[RynthAi] ERROR: Could not find embedded resource: {resourceName}", 2); + return; + } + + using (StreamReader reader = new StreamReader(stream, true)) + { + string line; + while ((line = reader.ReadLine()) != null) + { + if (string.IsNullOrWhiteSpace(line)) continue; + + // Split the line by tabs to isolate the columns + string[] columns = line.Split('\t'); + + // Column 0 is ID, Column 1 is Name + if (columns.Length >= 2) + { + if (int.TryParse(columns[0].Trim(), out int spellId)) + { + string spellName = columns[1].Trim(); + _spellNames[spellId] = spellName; + } + } + } + } + } + + _loaded = _spellNames.Count > 0; + + } + catch (Exception ex) + { + host.Actions.AddChatText($"[RynthAi] Spell Load Error: {ex.Message}", 2); + } + } + + public static string GetSpellName(int spellId) + { + if (_spellNames.TryGetValue(spellId, out string name)) return name; + if (_builtinSpells.TryGetValue(spellId, out string builtin)) return builtin; + return $"Unknown Spell ({spellId})"; + } + + public static string GetSpellNameOrId(int spellId) + { + if (_spellNames.TryGetValue(spellId, out string name)) return name; + if (_builtinSpells.TryGetValue(spellId, out string builtin)) return builtin; + return spellId.ToString(); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Combat/SpellManager.cs b/Plugins/RynthAi/Combat/SpellManager.cs new file mode 100644 index 0000000..1244dd7 --- /dev/null +++ b/Plugins/RynthAi/Combat/SpellManager.cs @@ -0,0 +1,215 @@ +using System; +using System.Collections.Generic; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; + +namespace NexSuite.Plugins.RynthAi +{ + public class SpellManager + { + private CoreManager _core; + + public Dictionary SpellDictionary { get; private set; } = new Dictionary(StringComparer.OrdinalIgnoreCase); + + // Map base spell names to their exact Level 7 Lore counterparts + private readonly Dictionary LoreNames = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + // Attributes (Using the exact AC names you provided) + { "Strength", new[] { "Might of the Lugians" } }, + { "Endurance", new[] { "Preservance", "Perseverance" } }, + { "Coordination", new[] { "Honed Control" } }, + { "Quickness", new[] { "Hastening" } }, + { "Focus", new[] { "Inner Calm" } }, + { "Willpower", new[] { "Mind Blossom" } }, + + // Defenses + { "Invulnerability", new[] { "Aura of Defense" } }, + { "Impregnability", new[] { "Aura of Deflection" } }, + { "Magic Resistance", new[] { "Aura of Resistance" } }, + + // Life Magic + { "Armor", new[] { "Executor's Blessing" } }, + { "Acid Protection", new[] { "Caustic Blessing" } }, + { "Blade Protection", new[] { "Blessing of the Blade Turner" } }, + { "Bludgeoning Protection", new[] { "Blessing of the Mace Turner" } }, + { "Cold Protection", new[] { "Icy Blessing" } }, + { "Fire Protection", new[] { "Fiery Blessing" } }, + { "Lightning Protection", new[] { "Storm's Blessing" } }, + { "Mana Renewal", new[] { "Battlemage's Blessing" } }, + { "Piercing Protection", new[] { "Blessing of the Arrow Turner" } }, + { "Regeneration", new[] { "Robustify" } }, + { "Rejuvenation", new[] { "Unflinching Persistence", "Unfinching Persistance" } }, + + // Vitals + { "Heal", new[] { "Adja's Intervention" } }, + { "Revitalize", new[] { "Robustification" } }, + { "Stamina to Mana", new[] { "Meditative Trance" } }, + { "Stamina to Health", new[] { "Rushed Recovery" } }, + + // Skills & Masteries + { "Monster Attunement", new[] { "Topheron's Blessing" } }, + { "Person Attunement", new[] { "Kaluhc's Blessing" } }, + { "Arcane Enlightenment", new[] { "Aliester's Blessing" } }, + { "Armor Tinkering Expertise", new[] { "Jibril's Blessing" } }, + { "Item Tinkering Expertise", new[] { "Yoshi's Blessing" } }, + { "Weapon Tinkering Expertise", new[] { "Koga's Blessing" } }, + { "Mana Conversion Mastery", new[] { "Nuhmidura's Blessing" } }, + { "Sprint", new[] { "Saladur's Blessing" } }, + { "Jumping Mastery", new[] { "Jahannan's Blessing" } }, + { "Fealty", new[] { "Odif's Blessing", "Odif's Boon" } }, + { "Leadership Mastery", new[] { "Ar-Pei's Blessing" } }, + { "Deception Mastery", new[] { "Ketnan's Blessing" } }, + { "Healing Mastery", new[] { "Avalenne's Blessing" } }, + { "Lockpick Mastery", new[] { "Oswald's Blessing" } }, + { "Cooking Mastery", new[] { "Morimoto's Blessing" } }, + { "Fletching Mastery", new[] { "Lilitha's Blessing" } }, + { "Alchemy Mastery", new[] { "Silencia's Blessing" } }, + { "Creature Enchantment Mastery", new[] { "Adja's Blessing" } }, + { "Item Enchantment Mastery", new[] { "Celcynd's Blessing" } }, + { "Life Magic Mastery", new[] { "Harlune's Blessing" } }, + { "War Magic Mastery", new[] { "Hieromancer's Blessing" } }, + + // Weapon Auras (Item Enchantment) + { "Blood Drinker", new[] { "Aura of Infected Caress" } }, + { "Hermetic Link", new[] { "Aura of Mystic's Blessing" } }, + { "Heart Seeker", new[] { "Aura of Elysa's Sight" } }, + { "Spirit Drinker", new[] { "Aura of Infected Spirit Carress", "Aura of Infected Spirit Caress" } }, + { "Swift Killer", new[] { "Aura of Atlan's Alacrity" } }, + { "Defender", new[] { "Aura of Cragstone's Will" } }, + + // Armor Banes (Item Enchantment) + { "Impenetrability", new[] { "Brogard's Defiance" } }, + { "Acid Bane", new[] { "Olthoi's Bane" } }, + { "Blade Bane", new[] { "Swordsman's Bane", "Swordman's Bane" } }, + { "Bludgeoning Bane", new[] { "Tusker's Bane" } }, + { "Flame Bane", new[] { "Inferno's Bane" } }, + { "Frost Bane", new[] { "Gelidite's Bane" } }, + { "Lightning Bane", new[] { "Astyrrian's Bane" } }, + { "Piercing Bane", new[] { "Archer's Bane" } } + }; + + public SpellManager(CoreManager core) + { + _core = core; + } + + public void InitializeNatively() + { + try + { + var fs = _core.Filter(); + if (fs == null) return; + + for (int i = 1; i <= 40000; i++) + { + try + { + var spell = fs.SpellTable.GetById(i); + if (spell != null && !string.IsNullOrWhiteSpace(spell.Name)) + { + SpellDictionary[spell.Name] = spell.Id; + } + } + catch { } + } + + _core.Actions.AddChatText($"[RynthAi] Magic System Online: {SpellDictionary.Count} spells loaded.", 1); + } + catch (Exception ex) { _core.Actions.AddChatText("[RynthAi] Native load error: " + ex.Message, 2); } + } + + public int GetHighestSpellTier(CharFilterSkillType skill) + { + try + { + int buffedSkill = _core.CharacterFilter.Skills[skill].Buffed; + if (buffedSkill >= 400) return 8; + if (buffedSkill >= 315) return 7; // Adjusted to common AC skill requirements + if (buffedSkill >= 250) return 6; + if (buffedSkill >= 200) return 5; + if (buffedSkill >= 150) return 4; + if (buffedSkill >= 100) return 3; + if (buffedSkill >= 50) return 2; + return 1; + } + catch { return 1; } + } + + private string GetRomanNumeral(int tier) + { + switch (tier) + { + case 1: return "I"; + case 2: return "II"; + case 3: return "III"; + case 4: return "IV"; + case 5: return "V"; + case 6: return "VI"; + case 7: return "VII"; + case 8: return "VIII"; + default: return "I"; + } + } + + // Spell resolution for self-buffs. Capped by skill level. + // Within each tier tries standard names first, then "Aura of" prefixed variants + // (weapon enchantments like Blood Drinker, Heart Seeker use "Aura of" prefix). + public int GetDynamicSelfBuffId(string baseSpellName, CharFilterSkillType magicSkill) + { + int maxTier = GetHighestSpellTier(magicSkill); + string cleanBase = baseSpellName.Replace(" Self", "").Trim(); + + for (int tier = maxTier; tier >= 1; tier--) + { + if (tier == 8) + { + // Standard: "Incantation of Focus Self" + if (TryGetId($"Incantation of {cleanBase} Self", out int id1)) return id1; + if (TryGetId($"Incantation of {cleanBase}", out int id2)) return id2; + // Aura variant: "Aura of Incantation of Blood Drinker Self" + if (TryGetId($"Aura of Incantation of {cleanBase} Self", out int id3)) return id3; + if (TryGetId($"Aura of Incantation of {cleanBase}", out int id4)) return id4; + } + else if (tier == 7) + { + // Lore names first (already includes "Aura of" where needed) + if (LoreNames.TryGetValue(cleanBase, out string[] lores)) + { + foreach (string lore in lores) + { + if (TryGetId(lore, out int idL)) return idL; + } + } + // Standard VII + if (TryGetId($"{cleanBase} Self VII", out int id7a)) return id7a; + if (TryGetId($"{cleanBase} VII", out int id7b)) return id7b; + // Aura variant VII + if (TryGetId($"Aura of {cleanBase} Self VII", out int id7c)) return id7c; + if (TryGetId($"Aura of {cleanBase} VII", out int id7d)) return id7d; + } + else + { + // Standard: "Focus Self VI" + string numeral = GetRomanNumeral(tier); + if (TryGetId($"{cleanBase} Self {numeral}", out int idNum1)) return idNum1; + if (TryGetId($"{cleanBase} {numeral}", out int idNum2)) return idNum2; + // Aura variant: "Aura of Blood Drinker Self VI" + if (TryGetId($"Aura of {cleanBase} Self {numeral}", out int idNum3)) return idNum3; + if (TryGetId($"Aura of {cleanBase} {numeral}", out int idNum4)) return idNum4; + } + } + return 0; + } + + private bool TryGetId(string exactName, out int spellId) + { + if (SpellDictionary.TryGetValue(exactName, out spellId)) + { + if (_core.CharacterFilter.IsSpellKnown(spellId)) return true; + } + spellId = 0; + return false; + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Combat/Vtank spelldump.txt b/Plugins/RynthAi/Combat/Vtank spelldump.txt new file mode 100644 index 0000000..f6873ca Binary files /dev/null and b/Plugins/RynthAi/Combat/Vtank spelldump.txt differ diff --git a/Plugins/RynthAi/DecalInspector.cs b/Plugins/RynthAi/DecalInspector.cs new file mode 100644 index 0000000..84b5ede --- /dev/null +++ b/Plugins/RynthAi/DecalInspector.cs @@ -0,0 +1,38 @@ +using System; +using System.Reflection; +using Decal.Adapter; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi +{ + public static class DecalInspector + { + public static void DumpType(Type t, CoreManager core) + { + core.Actions.AddChatText("====== " + t.FullName + " ======", 3); + + core.Actions.AddChatText("-- PROPERTIES --", 3); + foreach (var p in t.GetProperties()) + { + core.Actions.AddChatText(p.PropertyType.Name + " " + p.Name, 3); + } + + core.Actions.AddChatText("-- METHODS --", 3); + foreach (var m in t.GetMethods()) + { + core.Actions.AddChatText(m.ReturnType.Name + " " + m.Name, 3); + } + } + + public static void DumpDecalAPI(CoreManager core) + { + DumpType(typeof(WorldObject), core); + DumpType(typeof(CharacterFilter), core); + DumpType(typeof(CoreManager), core); + + // These are the important ones for navigation + DumpType(typeof(HooksWrapper), core); + DumpType(typeof(WorldFilter), core); + } + } +} diff --git a/Plugins/RynthAi/Logic/BackgroundFpsUnlocker.cs b/Plugins/RynthAi/Logic/BackgroundFpsUnlocker.cs new file mode 100644 index 0000000..d018b03 --- /dev/null +++ b/Plugins/RynthAi/Logic/BackgroundFpsUnlocker.cs @@ -0,0 +1,81 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Decal.Adapter.Wrappers; + +namespace NexSuite.Plugins.RynthAi.Utility +{ + public class BackgroundFpsUnlocker : IDisposable + { + // --- THE FIX: Tell Windows to use the correct C++ memory standard --- + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + + [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")] + private static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong); + + [DllImport("user32.dll", EntryPoint = "SetWindowLong")] + private static extern IntPtr SetWindowLong32(IntPtr hWnd, int nIndex, IntPtr dwNewLong); + + private static IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong) + { + if (IntPtr.Size == 8) return SetWindowLongPtr64(hWnd, nIndex, dwNewLong); + return SetWindowLong32(hWnd, nIndex, dwNewLong); + } + + [DllImport("user32.dll")] + private static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); + + private const int GWLP_WNDPROC = -4; + private const uint WM_ACTIVATEAPP = 0x001C; + + private WndProcDelegate _newWndProc; + private IntPtr _oldWndProc = IntPtr.Zero; + private IntPtr _acWindowHandle; + private PluginHost _host; + private bool _isUnlocked = false; + + public void Start(PluginHost host) + { + _host = host; + if (_isUnlocked) return; + + try + { + _acWindowHandle = Process.GetCurrentProcess().MainWindowHandle; + + _newWndProc = new WndProcDelegate(CustomWndProc); + IntPtr pNewWndProc = Marshal.GetFunctionPointerForDelegate(_newWndProc); + + _oldWndProc = SetWindowLongPtr(_acWindowHandle, GWLP_WNDPROC, pNewWndProc); + + _isUnlocked = true; + _host.Actions.AddChatText("[RynthAi] Native Background FPS Unlocked.", 5); + } + catch (Exception ex) + { + _host.Actions.AddChatText("[RynthAi] Failed to unlock FPS: " + ex.Message, 1); + } + } + + public void Dispose() + { + if (_isUnlocked && _oldWndProc != IntPtr.Zero) + { + SetWindowLongPtr(_acWindowHandle, GWLP_WNDPROC, _oldWndProc); + _isUnlocked = false; + } + } + + private IntPtr CustomWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) + { + // When the game is told to sleep, we intercept it and tell it to stay awake + if (msg == WM_ACTIVATEAPP) + { + return CallWindowProc(_oldWndProc, hWnd, msg, (IntPtr)1, lParam); + } + + return CallWindowProc(_oldWndProc, hWnd, msg, wParam, lParam); + } + } +} \ No newline at end of file diff --git a/Plugins/RynthAi/Logic/CommandProcessor.cs b/Plugins/RynthAi/Logic/CommandProcessor.cs new file mode 100644 index 0000000..7a9779b --- /dev/null +++ b/Plugins/RynthAi/Logic/CommandProcessor.cs @@ -0,0 +1,812 @@ +using System; +using System.IO; +using System.Linq; +using System.Collections.Generic; +using Decal.Adapter; +using Decal.Adapter.Wrappers; +using Decal.Filters; +using RynthAi.Meta; + +namespace NexSuite.Plugins.RynthAi +{ + public class CommandProcessor + { + private readonly PluginCore _plugin; + private readonly UISettings _settings; + private readonly MetaManager _meta; + private readonly NavigationManager _nav; + private readonly BuffManager _buff; + private readonly CombatManager _combat; + private readonly LootManager _loot; + private readonly LuaManager _lua; + private readonly RynthJumper _jumper; + private readonly SpellManager _spellManager; + private readonly FellowshipTracker _fellowship; + + public CommandProcessor(PluginCore plugin, UISettings settings, MetaManager meta, NavigationManager nav, BuffManager buff, CombatManager combat, LootManager loot, LuaManager lua, RynthJumper jumper, SpellManager spellManager, FellowshipTracker fellowship) + { + _plugin = plugin; + _settings = settings; + _meta = meta; + _nav = nav; + _buff = buff; + _combat = combat; + _loot = loot; + _lua = lua; + _jumper = jumper; + _spellManager = spellManager; + _fellowship = fellowship; + } + + public void Execute(string text, ChatParserInterceptEventArgs e) + { + try + { + string trimmed = text.Trim(); + bool isNA = trimmed.StartsWith("/na", StringComparison.OrdinalIgnoreCase); + bool isVT = trimmed.StartsWith("/vt", StringComparison.OrdinalIgnoreCase); + bool isLua = trimmed.StartsWith("/lua", StringComparison.OrdinalIgnoreCase); + + if (!isNA && !isVT && !isLua) return; + + string[] parts = trimmed.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + + // --- Handle Top-Level /lua command --- + if (isLua) + { + e.Eat = true; + if (parts.Length < 2) + { + _plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /lua