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.
This commit is contained in:
tombohar 2026-04-10 18:38:07 -04:00
commit 80b71d295d
179 changed files with 52858 additions and 0 deletions

View file

@ -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<int, RamTimerInfo> _ramBuffTimers = new Dictionary<int, RamTimerInfo>();
private string _buffTimerPath;
private bool _isRechargingMana = false;
private bool _isRechargingStamina = false;
private bool _isHealingSelf = false;
private readonly List<string> BaseCreatureBuffs = new List<string>
{
"Strength Self", "Endurance Self", "Coordination Self",
"Quickness Self", "Focus Self", "Willpower Self",
"Magic Resistance Self", "Invulnerability Self", "Impregnability Self"
};
private readonly Dictionary<CharFilterSkillType, string> CreatureSkillBuffs = new Dictionary<CharFilterSkillType, string>
{
{ 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;
}
/// <summary>
/// Set the path for persisting buff timers. Call after settings path is known.
/// Automatically loads any existing timers from disk.
/// </summary>
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<string>();
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<string> 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<FileService>();
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<FileService>();
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<string> BuildDynamicBuffList()
{
List<string> step1_CreatureMastery = new List<string>();
List<string> step2_Focus = new List<string>();
List<string> step3_Willpower = new List<string>();
List<string> step4_OtherCreature = new List<string>();
List<string> step5_LifeAndItem = new List<string>();
List<string> step6_WeaponAuras = new List<string>();
List<string> step7_ArmorBanes = new List<string>();
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<string> {
"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<string> {
"Blood Drinker Self", "Hermetic Link Self", "Heart Seeker Self",
"Spirit Drinker Self", "Swift Killer Self", "Defender Self"
});
step7_ArmorBanes.AddRange(new List<string> {
"Impenetrability", "Acid Bane", "Blade Bane", "Bludgeoning Bane",
"Flame Bane", "Frost Bane", "Lightning Bane", "Piercing Bane"
});
List<string> final = new List<string>();
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<FileService>();
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
}
}
}

View file

@ -0,0 +1,356 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace NexSuite.Plugins.RynthAi
{
/// <summary>
/// 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
/// </summary>
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<string> _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 };
/// <summary>
/// Scans acclient.exe's loaded image at runtime to find CM_Combat functions.
/// Call once at plugin startup.
/// </summary>
public static void Initialize(Action<string> 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; }
}
/// <summary>
/// Maps UISettings height (0=Low, 1=Medium, 2=High) to AC ATTACK_HEIGHT enum.
/// </summary>
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;
}
/// <summary>
/// Walks backwards from an opcode write to find the CM_Combat function prologue.
/// Must be preceded by CC (int3), 90 (nop), or C3 (ret).
/// </summary>
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 { }
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,361 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Decal.Adapter;
namespace NexSuite.Plugins.RynthAi
{
/// <summary>
/// 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)
/// </summary>
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<UInt32, Fellow>)
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<int, string> _memberCache = new Dictionary<int, string>();
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
// ══════════════════════════════════════════════════════════════
/// <summary>True if the player is currently in a fellowship.</summary>
public bool IsInFellowship
{
get
{
try { return GetFellowshipPtr() != IntPtr.Zero; }
catch { return false; }
}
}
/// <summary>Number of members in the current fellowship.</summary>
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; }
}
}
/// <summary>Name of the current fellowship.</summary>
public string FellowshipName
{
get
{
try
{
IntPtr fel = GetFellowshipPtr();
if (fel == IntPtr.Zero) return "";
return ReadPString(fel + OFF_FEL_NAME);
}
catch { return ""; }
}
}
/// <summary>Character ID of the fellowship leader.</summary>
public int LeaderId
{
get
{
try
{
IntPtr fel = GetFellowshipPtr();
if (fel == IntPtr.Zero) return 0;
return Marshal.ReadInt32(fel + OFF_FEL_LEADER);
}
catch { return 0; }
}
}
/// <summary>True if the player is the fellowship leader.</summary>
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; }
}
}
/// <summary>True if the fellowship is open for recruitment.</summary>
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; }
}
}
/// <summary>True if the fellowship is locked.</summary>
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; }
}
}
/// <summary>True if the fellowship is sharing XP.</summary>
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; }
}
}
/// <summary>Check if a character name is a fellowship member.</summary>
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;
}
/// <summary>Check if a character ID is a fellowship member.</summary>
public bool IsMember(int characterId)
{
RefreshIfNeeded();
return _memberCache.ContainsKey(characterId);
}
/// <summary>Get all member names.</summary>
public IEnumerable<string> GetMemberNames()
{
RefreshIfNeeded();
return _memberCache.Values;
}
/// <summary>Get member name by index (0-based).</summary>
public string GetMemberName(int index)
{
RefreshIfNeeded();
int i = 0;
foreach (var kvp in _memberCache)
{
if (i == index) return kvp.Value;
i++;
}
return "";
}
/// <summary>Get member character ID by index (0-based).</summary>
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
// ══════════════════════════════════════════════════════════════
/// <summary>
/// Gets the CFellowship pointer. Returns IntPtr.Zero if not in a fellowship.
/// Chain: [s_pFellowshipSystem] → ClientFellowshipSystem → [+0x10] → CFellowship
/// </summary>
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);
}
/// <summary>
/// Refreshes the member cache by iterating the hash table in client memory.
/// Only refreshes every REFRESH_INTERVAL_MS to avoid overhead.
/// </summary>
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 { }
}
/// <summary>
/// Reads a PStringBase&lt;char&gt; from a memory address.
///
/// PStringBase contains a single m_buffer pointer to PSRefBuffer&lt;char&gt;.
/// 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)
/// </summary>
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 ""; }
}
}
}

View file

@ -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
{
/// <summary>
/// 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.
/// </summary>
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<int[]> _pendingBundlePairs = new Queue<int[]>();
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<AmmoRecipe> AllRecipes = new List<AmmoRecipe>
{
// ── 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<WorldObject> 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 { }
}
}
}

View file

@ -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<int, string> _spellNames = new Dictionary<int, string>();
private static bool _loaded = false;
private static readonly Dictionary<int, string> _builtinSpells = new Dictionary<int, string>
{
{ 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();
}
}
}

View file

@ -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<string, int> SpellDictionary { get; private set; } = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
// Map base spell names to their exact Level 7 Lore counterparts
private readonly Dictionary<string, string[]> LoreNames = new Dictionary<string, string[]>(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<FileService>();
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;
}
}
}

Binary file not shown.