feat: SK backlog from test through 2026.11.22.48 (Trade Shop + inventory/loot/chat/nav)

Squash of test/main-merge-2026-10-25 onto aelrynth main 2026.11.19.1 for the standing sk PR. Includes Trade Shop Storefront, loot checklist editor, chat routing, window placements, and related engine work. See Changelog/2026-11-22-sk-backlog-test-merge.md.
This commit is contained in:
BlankenshipG 2026-11-23 00:08:31 -05:00
commit c6e8bb8dbf
438 changed files with 39545 additions and 1271 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.

View file

@ -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);
}
}
}

View file

@ -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);
}
}
}

View file

@ -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 <script>", 1);
return;
}
string script = trimmed.Substring(5).Trim();
_lua?.ExecuteString(script);
return;
}
if (parts.Length < 2)
{
PrintHelp();
e.Eat = true;
return;
}
e.Eat = true;
string cmd = parts[1].ToLower();
switch (cmd)
{
// --- NEW COMMANDS ---
case "lua":
if (parts.Length >= 3)
{
string script = string.Join(" ", parts, 2, parts.Length - 2);
_lua?.ExecuteString(script);
}
break;
case "opt":
HandleOptCommand(parts);
break;
case "addnavpt":
HandleAddNavPoint();
break;
// --- CORE MACRO CONTROLS ---
case "start":
case "on":
_settings.IsMacroRunning = true;
_plugin.SaveSettings();
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Macro STARTED.", 5);
break;
case "stop":
case "off":
_settings.IsMacroRunning = false;
_buff?.CancelBuffing();
_nav?.Stop();
_plugin.SaveSettings();
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Macro STOPPED.", 5);
break;
case "status":
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Macro: {(_settings.IsMacroRunning ? "ON" : "OFF")} | State: {_settings.CurrentState} | Nav: {Path.GetFileName(_settings.CurrentNavPath)} | Meta: {Path.GetFileName(_settings.CurrentMetaPath)}", 1);
break;
// --- SUBSYSTEMS & PROFILES ---
case "settings":
HandleSettingsCommand(parts);
break;
case "nav":
case "loot":
case "meta":
HandleSubsystemCommand(cmd, parts, text);
break;
case "setmetastate":
if (parts.Length >= 3)
{
string newState = string.Join(" ", parts, 2, parts.Length - 2);
_settings.CurrentState = newState;
_settings.ForceStateReset = true;
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Meta State forced to: {newState}", 5);
}
break;
case "db":
case "debugbuffs":
_buff?.PrintBuffDebug();
break;
case "dn":
case "debugnav":
if (_nav != null)
{
_nav.DebugNav = !_nav.DebugNav;
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Nav debug: {(_nav.DebugNav ? "ON" : "OFF")}", 5);
}
break;
case "wd":
case "watchdog":
_meta?.PrintWatchdogStatus();
break;
case "fakedeath":
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Faking character death trigger...", 5);
_meta?.HandleChat("You have died.");
break;
case "rebuff":
case "forcebuff":
_buff?.ForceFullRebuff();
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Force-buff sequence initiated.", 5);
break;
case "cancelforcebuff":
_buff?.CancelBuffing();
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Force-buff sequence cancelled.", 5);
break;
case "raycast":
HandleRaycastCommand(parts);
break;
case "lostest":
if (_combat != null)
{
var diagLines = _combat.RunLosTestDiag(_plugin.PluginCoreManager);
foreach (var line in diagLines)
_plugin.PluginHost.Actions.AddChatText("[RynthAi LOS] " + line, 1);
}
else
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Combat manager not initialized", 1);
}
break;
case "blacklist":
if (parts.Length >= 3 && parts[2].ToLower() == "clear")
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Blacklist cleared.", 5);
}
else
{
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Blacklist: attempts={_settings.BlacklistAttempts}, timeout={_settings.BlacklistTimeoutSec}s", 1);
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na blacklist clear", 1);
}
break;
// --- COMBAT & UTILITY STUBS ---
case "deletemonster":
int targetId = _plugin.PluginHost.Actions.CurrentSelection;
if (targetId != 0) _plugin.PluginHost.Actions.AddChatText($"[RynthAi] DeleteMonster stubbed target: {targetId}", 5);
break;
case "setattackbar":
if (parts.Length >= 3)
{
string target = "melee"; // default
float rawVal;
if (parts.Length >= 4 && float.TryParse(parts[3], out rawVal))
{
target = parts[2].ToLower(); // "melee" or "missile"
}
else if (float.TryParse(parts[2], out rawVal))
{
// /na setattackbar 0.5 → sets both
target = "both";
}
else
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na setattackbar [melee|missile] 0-1", 1);
break;
}
int pct = Math.Max(0, Math.Min(100, (int)(rawVal * 100)));
if (target == "missile") { _settings.MissileAttackPower = pct; }
else if (target == "melee") { _settings.MeleeAttackPower = pct; }
else { _settings.MeleeAttackPower = pct; _settings.MissileAttackPower = pct; }
_plugin.SaveSettings();
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Attack power ({target}): {pct}%", 5);
}
else
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na setattackbar [melee|missile] 0-1", 1);
}
break;
case "autoattackpower":
if (parts.Length >= 3)
{
if (parts[2].Equals("auto", StringComparison.OrdinalIgnoreCase))
{
_settings.MeleeAttackPower = -1;
_settings.MissileAttackPower = -1;
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Attack power set to AUTO (full power) for both modes", 5);
}
else if (int.TryParse(parts[2], out int pwr))
{
pwr = Math.Max(0, Math.Min(100, pwr));
_settings.MeleeAttackPower = pwr;
_settings.MissileAttackPower = pwr;
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Attack power set to {pwr}% for both modes", 5);
}
_plugin.SaveSettings();
}
else
{
string mPwr = _settings.MeleeAttackPower < 0 ? "AUTO" : $"{_settings.MeleeAttackPower}%";
string rPwr = _settings.MissileAttackPower < 0 ? "AUTO" : $"{_settings.MissileAttackPower}%";
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Melee: {mPwr}, Missile: {rPwr}. Usage: /na autoattackpower [auto|0-100]", 1);
}
break;
case "tapjump":
if (_jumper != null) _jumper.TapJump();
break;
case "spelldump":
// /na spelldump Focus — shows all spells containing "Focus"
if (parts.Length >= 3 && _spellManager != null)
{
string keyword = string.Join(" ", parts, 2, parts.Length - 2).ToLower();
int found = 0;
foreach (var kvp in _spellManager.SpellDictionary)
{
if (kvp.Key.ToLower().Contains(keyword))
{
bool known = false;
try { known = _plugin.PluginCoreManager.CharacterFilter.IsSpellKnown(kvp.Value); } catch { }
_plugin.PluginHost.Actions.AddChatText($" {kvp.Key} (id={kvp.Value}) {(known ? "[KNOWN]" : "[unknown]")}", 1);
found++;
}
}
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Found {found} spells matching '{keyword}'", 1);
}
else
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na spelldump <keyword>", 1);
}
break;
case "bufftest":
// /na bufftest Focus Self — traces the full buff lookup path
if (parts.Length >= 3 && _spellManager != null)
{
string buffName = string.Join(" ", parts, 2, parts.Length - 2);
string cleanBase = buffName.Replace(" Self", "").Trim();
_plugin.PluginHost.Actions.AddChatText($"[BuffTest] Input: '{buffName}' → cleanBase: '{cleanBase}'", 1);
// Check what GetHighestSpellTier returns
var testSkills = new[] {
CharFilterSkillType.CreatureEnchantment,
CharFilterSkillType.LifeMagic,
CharFilterSkillType.ItemEnchantment
};
foreach (var sk in testSkills)
{
int tier = _spellManager.GetHighestSpellTier(sk);
_plugin.PluginHost.Actions.AddChatText($"[BuffTest] {sk} → maxTier={tier}", 1);
}
// Trace the exact lookups
string[] tries = new[] {
$"Incantation of {cleanBase} Self",
$"Incantation of {cleanBase}",
};
foreach (string tryName in tries)
{
bool inDict = _spellManager.SpellDictionary.ContainsKey(tryName);
int id = inDict ? _spellManager.SpellDictionary[tryName] : 0;
bool known = false;
if (id > 0) try { known = _plugin.PluginCoreManager.CharacterFilter.IsSpellKnown(id); } catch { }
_plugin.PluginHost.Actions.AddChatText($"[BuffTest] Try '{tryName}' → inDict={inDict}, id={id}, known={known}", 1);
}
// Now call the actual method
int result = _spellManager.GetDynamicSelfBuffId(buffName, CharFilterSkillType.CreatureEnchantment);
string resultName = "(none)";
if (result > 0 && _spellManager.SpellDictionary.Values.Contains(result))
{
foreach (var kvp in _spellManager.SpellDictionary)
{
if (kvp.Value == result) { resultName = kvp.Key; break; }
}
}
_plugin.PluginHost.Actions.AddChatText($"[BuffTest] GetDynamicSelfBuffId returned: {result} = '{resultName}'", 1);
}
else
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na bufftest Focus Self", 1);
}
break;
case "fellow":
case "fellowship":
// /na fellow [subcommand] — fellowship info and actions
if (_fellowship == null)
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Fellowship tracker not initialized.", 1);
break;
}
string fellowSub = (parts.Length >= 3) ? parts[2].ToLower() : "status";
if (!_fellowship.IsInFellowship && fellowSub != "help")
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Not in a fellowship.", 1);
break;
}
switch (fellowSub)
{
case "status":
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Fellowship: \"{_fellowship.FellowshipName}\"", 1);
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Members: {_fellowship.MemberCount} | Leader: {(_fellowship.IsLeader ? "ME" : $"0x{_fellowship.LeaderId:X8}")} | Open: {_fellowship.IsOpen} | Locked: {_fellowship.IsLocked} | ShareXP: {_fellowship.ShareXP}", 1);
{
int fidx = 0;
foreach (string mName in _fellowship.GetMemberNames())
{
int mId = _fellowship.GetMemberId(fidx);
bool isLdr = (mId == _fellowship.LeaderId);
_plugin.PluginHost.Actions.AddChatText($" [{fidx}] {mName} (0x{mId:X8}){(isLdr ? " [LEADER]" : "")}", 1);
fidx++;
}
}
break;
case "leader":
{
int leaderId = _fellowship.LeaderId;
string leaderName = "(unknown)";
int li = 0;
foreach (string mn in _fellowship.GetMemberNames())
{
if (_fellowship.GetMemberId(li) == leaderId) { leaderName = mn; break; }
li++;
}
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Leader: {leaderName} (0x{leaderId:X8}){(_fellowship.IsLeader ? " (you)" : "")}", 1);
}
break;
case "count":
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Fellowship member count: {_fellowship.MemberCount}", 1);
break;
case "names":
{
var names = new List<string>(_fellowship.GetMemberNames());
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Members ({names.Count}): {string.Join(", ", names)}", 1);
}
break;
case "name":
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Fellowship name: \"{_fellowship.FellowshipName}\"", 1);
break;
case "open":
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Open: {_fellowship.IsOpen}", 1);
break;
case "locked":
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Locked: {_fellowship.IsLocked}", 1);
break;
case "sharexp":
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] ShareXP: {_fellowship.ShareXP}", 1);
break;
case "ismember":
if (parts.Length >= 4)
{
string checkName = string.Join(" ", parts, 3, parts.Length - 3);
bool found = _fellowship.IsMember(checkName);
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] IsMember(\"{checkName}\"): {found}", 1);
}
else
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na fellow ismember <name>", 1);
}
break;
case "help":
_plugin.PluginHost.Actions.AddChatText("[RynthAi] /na fellow [status|leader|count|names|name|open|locked|sharexp|ismember <name>]", 1);
break;
default:
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Unknown fellow subcommand: {fellowSub}. Try /na fellow help", 1);
break;
}
break;
case "corpsedebug":
// /na corpsedebug — check the currently selected corpse's ownership info
{
int selId = _plugin.PluginHost.Actions.CurrentSelection;
if (selId == 0)
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Select a corpse first.", 1);
break;
}
var wo = _plugin.PluginCoreManager.WorldFilter[selId];
if (wo == null)
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Selected object not found.", 1);
break;
}
string corpName = wo.Name ?? "(null)";
string longDesc = "";
try { longDesc = wo.Values((StringValueKey)16, ""); } catch { }
string myName = _plugin.PluginCoreManager.CharacterFilter.Name;
// Extract killer
string killerName = "(unknown)";
const string prefix = "Killed by ";
int idx = longDesc.IndexOf(prefix, StringComparison.OrdinalIgnoreCase);
if (idx >= 0)
{
killerName = longDesc.Substring(idx + prefix.Length).TrimEnd('.', ' ', '\n', '\r');
}
bool isMe = killerName.Equals(myName, StringComparison.OrdinalIgnoreCase);
bool isFellow = _fellowship != null && _fellowship.IsMember(killerName);
_plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] Name: {corpName}", 1);
_plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] LongDesc: '{longDesc}'", 1);
_plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] Killer: '{killerName}'", 1);
_plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] IsMe: {isMe}, IsFellow: {isFellow}", 1);
_plugin.PluginHost.Actions.AddChatText($"[CorpseDebug] LootOwnership: {_settings.LootOwnership} (0=Mine, 1=Fellow, 2=All)", 1);
}
break;
// ── NATIVE JUMP SYSTEM ──
case "jump":
case "jumpsw":
case "jumpsx":
case "jumpswz":
case "jumpswx":
case "jumpswzx":
case "jumpswzxc":
HandleJumpCommand(cmd, parts);
break;
case "face":
if (parts.Length >= 3 && double.TryParse(parts[2], out double faceHeading))
{
_plugin.PluginCoreManager.Actions.Heading = (float)faceHeading;
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Facing {faceHeading:F0}", 5);
}
break;
case "reverseroute":
if (parts.Length >= 3)
{
bool rev = parts[2].ToLower() == "true";
_nav?.SetReverse(rev);
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Reverse Route: {rev}", 5);
}
break;
case "reverseroutequery":
bool isRev = _nav?.IsReversed ?? false;
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Reverse Route is: {isRev}", 5);
break;
case "mexec":
if (parts.Length >= 3)
{
string expr = text.Substring(text.IndexOf("mexec") + 5).Trim();
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] MEXEC: {expr}", 5);
try { _plugin.PluginHost.Actions.InvokeChatParser($"/ub mexec {expr}"); }
catch (Exception ex) { _plugin.PluginHost.Actions.AddChatText($"[RynthAi] UB Error: {ex.Message}", 1); }
}
break;
case "echo":
string echoText = string.Join(" ", parts, 2, parts.Length - 2);
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] {echoText}", 5);
break;
case "ui":
_plugin.ToggleUI();
break;
// ── COMBAT ACTION DIAGNOSTICS ──
case "probe":
// /na probe — show CombatActionHelper initialization status
{
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] CombatActionHelper initialized: {CombatActionHelper.IsInitialized}", 1);
_plugin.PluginHost.Actions.AddChatText("[RynthAi] (Check chat log at plugin load for detailed scan results)", 1);
if (!CombatActionHelper.IsInitialized)
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Pattern scan failed — CM_Combat functions not found in this acclient.exe build", 1);
}
break;
case "testattack":
// /na testattack — attempts a single melee attack on current selection
// Use this with combat OFF to isolate the direct call
{
int selId = _plugin.PluginHost.Actions.CurrentSelection;
if (selId == 0)
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Select a target first.", 1);
break;
}
if (!CombatActionHelper.IsInitialized)
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] CombatActionHelper not initialized.", 1);
break;
}
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Sending MeleeAttack to target 0x{selId:X8}, height=Medium, power=0.5...", 1);
bool ok = CombatActionHelper.MeleeAttack((uint)selId, CombatActionHelper.ATTACK_HEIGHT_MEDIUM, 0.5f);
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] MeleeAttack returned: {ok}", 1);
}
break;
default:
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Unknown command: {cmd}", 1);
break;
}
}
catch (Exception ex)
{
_plugin.PluginHost.Actions.AddChatText($"[RynthAi Cmd Error] {ex.Message}", 1);
}
}
private void HandleOptCommand(string[] parts)
{
if (parts.Length < 5 || !parts[2].Equals("set", StringComparison.OrdinalIgnoreCase))
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Usage: /na opt set <setting> <value>", 1);
return;
}
string setting = parts[3].ToLower();
string val = parts[4].ToLower();
switch (setting)
{
case "enablecombat": _settings.EnableCombat = (val == "true"); break;
case "enablenav": _settings.EnableNavigation = (val == "true"); break;
case "enablelooting": _settings.EnableLooting = (val == "true"); break;
case "summonpets": _settings.SummonPets = (val == "true"); break;
case "enablemeta": _settings.EnableMeta = (val == "true"); break;
case "attackdistance":
if (float.TryParse(val, out float dist)) _settings.FollowNavMin = dist;
break;
default:
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Unknown option: {setting}", 1);
return;
}
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Option {setting} set to {val}", 5);
_plugin.SaveSettings();
}
private void HandleAddNavPoint()
{
if (_settings.CurrentRoute == null)
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Error: No route loaded.", 1);
return;
}
var coords = _plugin.PluginCoreManager.WorldFilter[_plugin.PluginCoreManager.CharacterFilter.Id].Coordinates();
// FIX: Using Object Initializer to avoid constructor errors
var newPoint = new NavPoint
{
NS = (float)coords.NorthSouth,
EW = (float)coords.EastWest,
Z = (float)_plugin.PluginCoreManager.Actions.LocationZ
};
_settings.CurrentRoute.Points.Add(newPoint);
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Added Nav Point at: {newPoint.NS:F2}N, {newPoint.EW:F2}E", 5);
_plugin.UI?.RouteTab?.UpdateRouteGraphics();
}
private void HandleSettingsCommand(string[] parts)
{
if (parts.Length < 3) return;
string sub = parts[2].ToLower();
string fileName = (parts.Length >= 4) ? parts[3] : "default";
if (!fileName.EndsWith(".json")) fileName += ".json";
string server = _plugin.PluginCoreManager.CharacterFilter.Server;
string name = _plugin.PluginCoreManager.CharacterFilter.Name;
string globalDir = @"C:\Games\DecalPlugins\NexSuite\RynthAi\GlobalSettings";
string charDir = Path.Combine(@"C:\Games\DecalPlugins\NexSuite\RynthAi\SettingsProfiles", server, name);
if (!Directory.Exists(globalDir)) Directory.CreateDirectory(globalDir);
if (!Directory.Exists(charDir)) Directory.CreateDirectory(charDir);
string globalPath = Path.Combine(globalDir, fileName);
string charPath = Path.Combine(charDir, fileName);
switch (sub)
{
case "save": _plugin.SaveSettings(globalPath); break;
case "load": _plugin.LoadSettings(globalPath); break;
case "savechar": _settings.MineOnly = true; _plugin.SaveSettings(charPath); break;
case "loadchar": _settings.MineOnly = true; _plugin.LoadSettings(charPath); break;
}
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Settings {sub} successful: {fileName}", 5);
}
private void HandleSubsystemCommand(string type, string[] parts, string fullText)
{
if (parts.Length < 4) return;
string action = parts[2].ToLower();
string fileName = string.Join(" ", parts, 3, parts.Length - 3);
string folder = type == "nav" ? _plugin.NavFolder : (type == "meta" ? _plugin.MetaFolder : _plugin.LootFolder);
string ext = type == "nav" ? ".nav" : (type == "meta" ? ".met" : ".utl");
if (!fileName.EndsWith(ext)) fileName += ext;
string fullPath = Path.Combine(folder, fileName);
if (action == "save")
{
if (!File.Exists(fullPath)) File.WriteAllText(fullPath, "");
if (type == "nav") _settings.CurrentRoute?.Save(fullPath);
else if (type == "meta") { _settings.CurrentMetaPath = fullPath; _meta?.SaveCurrentProfile(); }
else if (type == "loot") { _settings.EnableLooting = true; _loot?.SaveProfile(fullPath); }
}
else if (action == "load")
{
if (!File.Exists(fullPath))
{
File.WriteAllText(fullPath, "");
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Created new {type} profile: {fileName}", 5);
}
if (type == "nav")
{
_settings.CurrentNavPath = fullPath;
_settings.CurrentRoute = VTankNavParser.Load(fullPath);
_nav?.ResetRouteState();
// Find nearest waypoint for Circular/Linear routes
if (_settings.CurrentRoute.RouteType == NavRouteType.Circular ||
_settings.CurrentRoute.RouteType == NavRouteType.Linear)
{
_settings.ActiveNavIndex = _nav != null ? _nav.FindNearestWaypoint(_settings.CurrentRoute) : 0;
}
else
{
_settings.ActiveNavIndex = 0;
}
// Refresh route graphics
if (_plugin.UI?.RouteTab != null)
_plugin.UI.RouteTab.NeedsRouteGraphicsRefresh = true;
}
else if (type == "meta") { _settings.CurrentMetaPath = fullPath; _meta?.LoadProfile(fullPath); }
else if (type == "loot") { _settings.EnableLooting = true; _loot?.LoadProfile(fullPath); }
}
SyncUI(type, fileName, folder);
_plugin.SaveSettings();
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] {type.ToUpper()} {action} successful: {fileName}", 5);
}
private void SyncUI(string type, string fileName, string folder)
{
if (_plugin.UI == null) return;
if (type == "nav") _plugin.UI.RefreshNavFiles();
if (type != "meta") return;
_plugin.UI.RefreshMetaFiles();
if (Directory.Exists(folder))
{
string[] files = Directory.GetFiles(folder, "*.met");
Array.Sort(files);
for (int i = 0; i < files.Length; i++)
{
if (Path.GetFileName(files[i]).Equals(fileName, StringComparison.OrdinalIgnoreCase))
{
_settings.MetaProfileIdx = i + 1;
break;
}
}
}
}
private void HandleRaycastCommand(string[] parts)
{
if (parts.Length > 2)
{
_settings.EnableRaycasting = (parts[2].ToLower() == "on");
_plugin.SaveSettings();
}
else
{
string rayStatus = _combat?.GetRaycastStatus() ?? "No info";
foreach (var line in rayStatus.Split('\n')) _plugin.PluginHost.Actions.AddChatText("[RynthAi] " + line.Trim(), 1);
}
}
/// <summary>
/// Handles /na jump commands natively using RynthJumper.
/// Format: /na jump[swzxc] [heading] [holdtime]
/// - /na jump = tap jump
/// - /na jumpsw 180 500 = face south, jump forward with 500/1000 power
/// - /na jumpsx 300 = jump backward with 300/1000 power
/// </summary>
private void HandleJumpCommand(string cmd, string[] parts)
{
if (_jumper == null) return;
if (_jumper.IsJumping)
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Already jumping — wait for completion", 1);
return;
}
// Simple tap jump
if (cmd == "jump" && parts.Length <= 2)
{
_jumper.TapJump();
return;
}
// Parse hold time
int holdMs = 0;
double heading = -1; // -1 = use current heading
if (parts.Length >= 4 && int.TryParse(parts[3], out int ht))
holdMs = ht;
else if (parts.Length >= 3 && int.TryParse(parts[2], out int ht2))
holdMs = ht2;
if (parts.Length >= 3 && double.TryParse(parts[2], out double hd))
{
heading = hd;
// If heading was parsed as first arg, holdtime is second
if (parts.Length >= 4 && int.TryParse(parts[3], out int ht3))
holdMs = ht3;
}
// Parse direction keys from command suffix
bool shift = cmd.Contains("s");
bool forward = cmd.Contains("w");
bool backward = cmd.Contains("x");
bool slideLeft = cmd.Contains("z");
bool slideRight = cmd.Contains("c");
_jumper.StartJump(heading, holdMs, shift, forward, backward, slideLeft, slideRight);
_plugin.PluginHost.Actions.AddChatText($"[RynthAi] Jumping: heading={heading:F0} hold={holdMs}ms keys={cmd.Replace("jump","")}", 5);
}
private void PrintHelp()
{
_plugin.PluginHost.Actions.AddChatText("[RynthAi] Commands: /na [start|stop|status], /na lostest, /na setattackbar 0-1, /na autoattackpower [auto|0-1]", 1);
_plugin.PluginHost.Actions.AddChatText("[RynthAi] /na fellow [status|leader|count|names|name|ismember <n>], /na probe, /na testattack", 1);
_plugin.PluginHost.Actions.AddChatText("[RynthAi] /na jump[sw|sx|swz|swx|swzx|swzxc] [heading] [holdtime], /na blacklist [clear], /lua <script>", 1);
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,256 @@
using System;
using System.Runtime.InteropServices;
using Decal.Adapter;
using Decal.Adapter.Wrappers;
namespace NexSuite.Plugins.RynthAi
{
/// <summary>
/// Native RynthAi jump system — no UB dependency.
/// Tier 1: Uses CM_Movement::Event_Jump_NonAutonomous for direct jump
/// commands when MovementActionHelper is initialized (no keyboard input).
/// Fallback: PostMessage keyboard simulation for legacy mode.
/// Direction keys (W/X/Z/C) still use PostMessage in Tier 1 since
/// they control local physics direction. Tier 2 will replace these.
/// Flow: Face heading → hold direction keys → jump → release → resume macro
/// </summary>
public class RynthJumper
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool PostMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam);
private const uint WM_KEYDOWN = 0x0100;
private const uint WM_KEYUP = 0x0101;
// AC key codes
private const uint VK_SPACE = 0x20; // Jump
private const uint VK_SHIFT = 0x10; // Run modifier
private const uint VK_W = 0x57; // Forward
private const uint VK_X = 0x58; // Backward
private const uint VK_Z = 0x5A; // Slide left
private const uint VK_C = 0x43; // Slide right
private enum JumpState { Idle, Turning, HoldingKeys, Done }
private JumpState _state = JumpState.Idle;
private PluginHost _host;
private UISettings _settings;
// Jump parameters
private double _targetHeading;
private int _holdTimeMs;
private bool _addShift, _addW, _addX, _addZ, _addC;
private DateTime _stateStart;
private int _turnRetries;
private const int MAX_TURN_RETRIES = 50; // 50 * 100ms = 5 seconds
public bool IsJumping => _state != JumpState.Idle;
public RynthJumper(PluginHost host, UISettings settings)
{
_host = host;
_settings = settings;
}
/// <summary>
/// Start a jump. Mirrors /ub jump[swzxc] [heading] [holdtime]
/// </summary>
/// <param name="heading">Heading to face (0-359), or -1 for current heading</param>
/// <param name="holdTimeMs">How long to hold jump key (0-1000ms)</param>
/// <param name="shift">S modifier — run</param>
/// <param name="forward">W — forward</param>
/// <param name="backward">X — backward</param>
/// <param name="slideLeft">Z — slide left</param>
/// <param name="slideRight">C — slide right</param>
public void StartJump(double heading, int holdTimeMs, bool shift, bool forward, bool backward, bool slideLeft, bool slideRight)
{
if (_state != JumpState.Idle) return;
_holdTimeMs = Math.Max(0, Math.Min(1000, holdTimeMs));
_addShift = shift;
_addW = forward;
_addX = backward;
_addZ = slideLeft;
_addC = slideRight;
_turnRetries = 0;
// Pause macro during jump
_settings.IsMacroRunning = false;
if (heading >= 0)
{
_targetHeading = heading;
_state = JumpState.Turning;
CoreManager.Current.Actions.Heading = (float)_targetHeading;
}
else
{
_targetHeading = CoreManager.Current.Actions.Heading;
// No turn needed — go straight to keys
_state = JumpState.HoldingKeys;
PressKeys();
}
_stateStart = DateTime.Now;
}
/// <summary>
/// Tap jump — no heading change, no hold time.
/// Uses CM_Movement::Event_Jump_NonAutonomous for a minimal jump
/// when available, falls back to PostMessage keyboard simulation.
/// </summary>
public void TapJump()
{
if (_state != JumpState.Idle) return;
// Tier 1: direct acclient.exe call — no keyboard input needed
if (MovementActionHelper.IsInitialized)
{
MovementActionHelper.JumpNonAutonomous(0.01f); // minimal extent = tap
return;
}
// Legacy fallback: keyboard simulation
IntPtr hwnd = _host?.Decal?.Hwnd ?? IntPtr.Zero;
if (hwnd == IntPtr.Zero) return;
PostMessage(hwnd, WM_KEYDOWN, VK_SPACE, 0x00390001);
PostMessage(hwnd, WM_KEYUP, VK_SPACE, 0xC0390001);
}
/// <summary>
/// Called every frame by PluginCore. Drives the jump state machine.
/// </summary>
public void Think()
{
if (_state == JumpState.Idle) return;
switch (_state)
{
case JumpState.Turning:
// Check if heading is close enough
double currentHeading = CoreManager.Current.Actions.Heading;
if (Math.Abs(_targetHeading - currentHeading) < 2.0 ||
Math.Abs(_targetHeading - currentHeading) > 358.0) // Handle 0/360 wrap
{
// Heading matched — start the jump
_state = JumpState.HoldingKeys;
_stateStart = DateTime.Now;
PressKeys();
}
else
{
_turnRetries++;
// Keep setting heading every 100ms
if (_turnRetries % 5 == 0)
CoreManager.Current.Actions.Heading = (float)_targetHeading;
// Timeout after 5 seconds
if (_turnRetries > MAX_TURN_RETRIES)
{
try { _host?.Actions?.AddChatText("[RynthAi] Jump: turn timed out", 2); } catch { }
Finish();
}
}
break;
case JumpState.HoldingKeys:
// Tier 1: jump already fired with correct extent in PressKeys().
// Direction keys only need ~100ms for physics to register direction.
// Legacy: space bar held to build power bar over holdTimeMs.
int effectiveHold = (MovementActionHelper.IsInitialized && _holdTimeMs > 100)
? 100 // Tier 1: brief hold for direction registration
: _holdTimeMs;
if ((DateTime.Now - _stateStart).TotalMilliseconds >= effectiveHold)
{
ReleaseKeys();
_state = JumpState.Done;
_stateStart = DateTime.Now;
}
break;
case JumpState.Done:
// Brief delay after releasing keys before resuming macro
if ((DateTime.Now - _stateStart).TotalMilliseconds >= 200)
{
Finish();
}
break;
}
}
private void PressKeys()
{
IntPtr hwnd = _host?.Decal?.Hwnd ?? IntPtr.Zero;
// Tier 1: Use direct jump call for the jump itself.
// Direction keys (W/X/Z/C) still need PostMessage since they control
// local movement direction during the jump, which DoMovementCommand
// doesn't handle (it's server-side only). Tier 2 will replace these
// with CPhysicsObj movement calls.
if (MovementActionHelper.IsInitialized)
{
// Press direction modifiers via PostMessage (needed for local physics)
if (hwnd != IntPtr.Zero)
{
if (_addShift) PostMessage(hwnd, WM_KEYDOWN, VK_SHIFT, 0x002A0001);
if (_addW) PostMessage(hwnd, WM_KEYDOWN, VK_W, 0x00110001);
if (_addX) PostMessage(hwnd, WM_KEYDOWN, VK_X, 0x002D0001);
if (_addZ) PostMessage(hwnd, WM_KEYDOWN, VK_Z, 0x002C0001);
if (_addC) PostMessage(hwnd, WM_KEYDOWN, VK_C, 0x002E0001);
}
// Map holdTimeMs to jump extent (0.0–1.0)
// AC power bar fills over ~1000ms, so holdTime/1000 approximates extent
float extent = Math.Max(0.01f, Math.Min(1.0f, _holdTimeMs / 1000.0f));
MovementActionHelper.JumpNonAutonomous(extent);
return;
}
// Legacy fallback: all keyboard simulation
if (hwnd == IntPtr.Zero) return;
PostMessage(hwnd, WM_KEYDOWN, VK_SPACE, 0x00390001);
if (_addShift) PostMessage(hwnd, WM_KEYDOWN, VK_SHIFT, 0x002A0001);
if (_addW) PostMessage(hwnd, WM_KEYDOWN, VK_W, 0x00110001);
if (_addX) PostMessage(hwnd, WM_KEYDOWN, VK_X, 0x002D0001);
if (_addZ) PostMessage(hwnd, WM_KEYDOWN, VK_Z, 0x002C0001);
if (_addC) PostMessage(hwnd, WM_KEYDOWN, VK_C, 0x002E0001);
}
private void ReleaseKeys()
{
IntPtr hwnd = _host?.Decal?.Hwnd ?? IntPtr.Zero;
if (hwnd == IntPtr.Zero) return;
// Legacy mode: release space bar (Tier 1 never pressed it)
if (!MovementActionHelper.IsInitialized)
PostMessage(hwnd, WM_KEYUP, VK_SPACE, 0xC0390001);
// Release direction keys (used by both Tier 1 and Legacy)
if (_addShift) PostMessage(hwnd, WM_KEYUP, VK_SHIFT, 0xC02A0001);
if (_addW) PostMessage(hwnd, WM_KEYUP, VK_W, 0xC0110001);
if (_addX) PostMessage(hwnd, WM_KEYUP, VK_X, 0xC02D0001);
if (_addZ) PostMessage(hwnd, WM_KEYUP, VK_Z, 0xC02C0001);
if (_addC) PostMessage(hwnd, WM_KEYUP, VK_C, 0xC02E0001);
}
private void Finish()
{
_state = JumpState.Idle;
_addShift = _addW = _addX = _addZ = _addC = false;
_turnRetries = 0;
// Resume macro
_settings.IsMacroRunning = true;
try { _host?.Actions?.AddChatText("[RynthAi] Jump complete", 5); } catch { }
}
public void Cancel()
{
if (_state != JumpState.Idle)
{
ReleaseKeys();
Finish();
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,285 @@
using System;
using System.IO;
using System.Collections.Generic;
using Decal.Adapter.Wrappers;
using System.Text.RegularExpressions;
namespace NexSuite.Plugins.RynthAi
{
public enum LootAction
{
Keep = 0,
Salvage = 1,
Sell = 2,
Read = 3,
User1 = 4
}
public class LootRule
{
public string Name { get; set; }
public LootAction Action { get; set; }
public int KeepCount { get; set; }
public string RawInfoLine { get; set; }
public List<string> RawDataLines { get; set; } = new List<string>();
public bool IsMatch(WorldObject item)
{
if (item == null || string.IsNullOrEmpty(RawInfoLine)) return false;
try
{
var parts = RawInfoLine.Split(';');
if (parts.Length < 2) return false;
// A rule with no requirement nodes (only Action;KeepCount) is unconditional.
// "Loot Everything" style profiles depend on this behavior.
if (parts.Length == 2) return true;
var data = new Queue<string>(RawDataLines);
var stack = new Stack<bool>();
// VTank stores requirement nodes in POSTFIX notation (Reverse Polish Notation)
// We start at index 2 to skip the Action and KeepCount numbers
for (int i = 2; i < parts.Length; i++)
{
if (!int.TryParse(parts[i], out int type)) continue;
if (type == 9998) // OR Operator
{
if (stack.Count < 2) return false;
bool right = stack.Pop();
bool left = stack.Pop();
stack.Push(left || right);
}
else if (type == 9999) // AND Operator
{
if (stack.Count < 2) return false;
bool right = stack.Pop();
bool left = stack.Pop();
stack.Push(left && right);
}
else
{
// Leaf Node: Dequeue its specific data, evaluate, and push to stack
bool result = false;
switch (type)
{
case 1: // StringValueMatch (Consumes 2 lines)
int sKey = int.Parse(data.Dequeue());
string sMatch = data.Dequeue();
string sVal = item.Values((StringValueKey)sKey, "");
result = Regex.IsMatch(sVal, sMatch, RegexOptions.IgnoreCase);
break;
case 2: // LongValKeyLE (Consumes 2 lines)
int lKeyLE = int.Parse(data.Dequeue());
int lValLE = int.Parse(data.Dequeue());
result = item.Values((LongValueKey)lKeyLE, 0) <= lValLE;
break;
case 3: // LongValKeyGE (Consumes 2 lines)
int lKeyGE = int.Parse(data.Dequeue());
int lValGE = int.Parse(data.Dequeue());
result = item.Values((LongValueKey)lKeyGE, 0) >= lValGE;
break;
case 4: // DoubleValKeyLE (Consumes 2 lines)
int dKeyLE = int.Parse(data.Dequeue());
double dValLE = double.Parse(data.Dequeue());
result = item.Values((DoubleValueKey)dKeyLE, 0.0) <= dValLE;
break;
case 5: // DoubleValKeyGE (Consumes 2 lines)
int dKeyGE = int.Parse(data.Dequeue());
double dValGE = double.Parse(data.Dequeue());
result = item.Values((DoubleValueKey)dKeyGE, 0.0) >= dValGE;
break;
case 7: // ObjectClass (Consumes 1 line)
int objClass = int.Parse(data.Dequeue());
result = (int)item.ObjectClass == objClass;
break;
case 12: // LongValKeyE (Consumes 2 lines)
int lKeyE = int.Parse(data.Dequeue());
int lValE = int.Parse(data.Dequeue());
result = item.Values((LongValueKey)lKeyE, 0) == lValE;
break;
case 13: // LongValKeyNE (Consumes 2 lines)
int lKeyNE = int.Parse(data.Dequeue());
int lValNE = int.Parse(data.Dequeue());
result = item.Values((LongValueKey)lKeyNE, 0) != lValNE;
break;
default:
// If we encounter a VTank node type we haven't mapped yet, we MUST abort the rule.
// If we don't know how many lines of data it consumes, we can't safely
// process the rest of the queue, so we fail safely and skip to the next rule.
return false;
}
stack.Push(result);
}
}
// The final result of the tree will be the only item left sitting in the stack.
// If nodes existed but did not produce a valid expression, fail safely.
return stack.Count == 1 && stack.Pop();
}
catch
{
return false; // Failsafe for missing data or parsing exceptions
}
}
}
public class VTankLootProfile
{
public List<LootRule> Rules { get; set; } = new List<LootRule>();
}
public static class VTankLootParser
{
public static VTankLootProfile Load(string filePath)
{
var profile = new VTankLootProfile();
if (!File.Exists(filePath)) return profile;
string[] lines = File.ReadAllLines(filePath);
if (lines.Length < 3 || lines[0].Trim() != "UTL")
throw new Exception("Invalid UTL file format.");
int version = int.Parse(lines[1].Trim());
int ruleCount = int.Parse(lines[2].Trim());
int lineIndex = 3;
while (lineIndex < lines.Length && profile.Rules.Count < ruleCount)
{
LootRule rule = new LootRule();
// 1. Read Name (VTank sometimes leaves these blank, so we just trim the end)
rule.Name = lines[lineIndex++].TrimEnd();
// 2. Read the mandatory Empty Line VTank puts after names
if (lineIndex < lines.Length && string.IsNullOrWhiteSpace(lines[lineIndex]))
{
lineIndex++;
}
// 3. Read the InfoLine (e.g., "0;1;1;12")
if (lineIndex < lines.Length)
{
rule.RawInfoLine = lines[lineIndex++].Trim();
string[] parts = rule.RawInfoLine.Split(';');
if (parts.Length >= 2 && int.TryParse(parts[0], out int act) && int.TryParse(parts[1], out int count))
{
rule.Action = (LootAction)act;
rule.KeepCount = count;
}
}
// 4. Read Requirement Data using node-token arity when possible.
// This is more reliable than heuristic rule boundary detection for complex profiles.
int requiredDataLines = TryGetRequiredDataLineCount(rule.RawInfoLine);
if (requiredDataLines >= 0)
{
for (int i = 0; i < requiredDataLines && lineIndex < lines.Length; i++)
{
rule.RawDataLines.Add(lines[lineIndex++].TrimEnd());
}
}
else
{
// Fallback for unknown token types: heuristic boundary detection.
while (lineIndex < lines.Length)
{
if (IsStartOfNextRule(lines, lineIndex))
{
break;
}
rule.RawDataLines.Add(lines[lineIndex++].TrimEnd());
}
}
profile.Rules.Add(rule);
}
return profile;
}
private static bool IsStartOfNextRule(string[] lines, int index)
{
// We need at least 3 lines to form a valid rule start: [Name], [Empty Line], [InfoLine]
if (index + 2 >= lines.Length) return false;
// lines[index] is the Name. It can be literally anything, so we skip checking it.
// lines[index+1] MUST be an empty line in the VTank format
if (!string.IsNullOrWhiteSpace(lines[index + 1])) return false;
// lines[index+2] MUST be an InfoLine containing semicolons
string infoLine = lines[index + 2].Trim();
if (!infoLine.Contains(";")) return false;
string[] parts = infoLine.Split(';');
if (parts.Length >= 2)
{
// An InfoLine always starts with two integers (Action and KeepCount)
if (int.TryParse(parts[0], out int action) && int.TryParse(parts[1], out int _))
{
// Valid VTank Actions are 0 to 4 (Allowing up to 10 just for forward compatibility)
if (action >= 0 && action <= 10) return true;
}
}
return false;
}
private static int TryGetRequiredDataLineCount(string rawInfoLine)
{
if (string.IsNullOrWhiteSpace(rawInfoLine)) return -1;
var parts = rawInfoLine.Split(';');
if (parts.Length < 2) return -1;
if (parts.Length == 2) return 0; // unconditional rule
int required = 0;
for (int i = 2; i < parts.Length; i++)
{
if (!int.TryParse(parts[i], out int type)) continue;
int lines = GetDataLinesForNodeType(type);
if (lines < 0) return -1;
required += lines;
}
return required;
}
private static int GetDataLinesForNodeType(int type)
{
switch (type)
{
case 9998: // OR
case 9999: // AND
return 0;
case 1: // StringValueMatch
case 2: // LongValKeyLE
case 3: // LongValKeyGE
case 4: // DoubleValKeyLE
case 5: // DoubleValKeyGE
case 12: // LongValKeyE
case 13: // LongValKeyNE
return 2;
case 7: // ObjectClass
return 1;
default:
return -1;
}
}
}
}

View file

@ -0,0 +1,115 @@
using System;
using System.Text.RegularExpressions;
using Decal.Adapter.Wrappers;
namespace NexSuite.Plugins.RynthAi
{
public class LuaBridge
{
private readonly PluginCore _core;
// Returns the actual North/South coordinate (e.g. 42.5)
public double GetPlayerNS()
{
return Decal.Adapter.CoreManager.Current.WorldFilter[Decal.Adapter.CoreManager.Current.CharacterFilter.Id].Coordinates().NorthSouth;
}
// Returns the actual East/West coordinate (e.g. -33.7)
public double GetPlayerEW()
{
return Decal.Adapter.CoreManager.Current.WorldFilter[Decal.Adapter.CoreManager.Current.CharacterFilter.Id].Coordinates().EastWest;
}
// Returns the altitude in meters
public double GetPlayerZ()
{
return Decal.Adapter.CoreManager.Current.Actions.LocationZ;
}
public LuaBridge(PluginCore core)
{
_core = core;
}
// --- MOVEMENT ---
public void GoTo(string ns, string ew)
{
double dNS = ParseCoord(ns);
double dEW = ParseCoord(ew);
_core.UI.Settings.CurrentRoute.Points.Clear();
_core.UI.Settings.CurrentRoute.Points.Add(new NavPoint { NS = dNS, EW = dEW, Type = NavPointType.Point });
_core.UI.Settings.CurrentRoute.RouteType = NavRouteType.Once;
_core.UI.Settings.ActiveNavIndex = 0;
_core.UI.Settings.IsMacroRunning = true;
_core.UI.Settings.EnableNavigation = true;
if (_core.UI?.RouteTab != null) _core.UI.RouteTab.NeedsRouteGraphicsRefresh = true;
_core.PluginHost.Actions.AddChatText($"[RynthLua] Navigating to: {ns}, {ew}", 1);
}
public void Stop()
{
_core.UI.Settings.IsMacroRunning = false;
_core.UI.Settings.EnableNavigation = false;
_core.PluginHost.Actions.AddChatText("[RynthLua] Macro Stopped.", 1);
}
// --- INTERACTION ---
public void UsePortal(string portalName)
{
foreach (WorldObject wo in _core.PluginCoreManager.WorldFilter.GetLandscape())
{
if (wo.Name.IndexOf(portalName, StringComparison.OrdinalIgnoreCase) >= 0)
{
if (wo.ObjectClass == ObjectClass.Portal || wo.ObjectClass == ObjectClass.Npc)
{
// The correct Decal API call: UseItem(GUID, ContainerID)
// We use 0 for the container because portals are in the world.
_core.PluginHost.Actions.UseItem(wo.Id, 0);
return;
}
}
}
}
// --- UTILS ---
private double ParseCoord(string val)
{
if (string.IsNullOrEmpty(val)) return 0;
string clean = Regex.Replace(val, "[^0-9.-]", "");
if (!double.TryParse(clean, out double result)) return 0;
return (val.ToUpper().Contains("S") || val.ToUpper().Contains("W")) ? -result : result;
}
public bool IsPathClear(double startNS, double startEW, double startZ, double endNS, double endEW, double endZ)
{
try
{
// Use '_core' instead of '_plugin'
if (_core.Raycast == null || !_core.Raycast.IsInitialized)
return true;
// Convert EW/NS to Global Meters
float startX = (float)((startEW * 10.0 + 1019.5) * 24.0);
float startY = (float)((startNS * 10.0 + 1019.5) * 24.0);
var origin = new RynthAi.Raycasting.Vector3(startX, startY, (float)startZ + 1.0f);
float endX = (float)((endEW * 10.0 + 1019.5) * 24.0);
float endY = (float)((endNS * 10.0 + 1019.5) * 24.0);
var destination = new RynthAi.Raycasting.Vector3(endX, endY, (float)endZ + 1.0f);
// Access Landcell safely via CoreManager
uint landcell = (uint)Decal.Adapter.CoreManager.Current.Actions.Landcell;
var geometry = _core.Raycast.GeometryLoader.GetLandblockGeometry(landcell);
// Test the line
return !RynthAi.Raycasting.RaycastEngine.IsLinearPathBlocked(origin, destination, geometry);
}
catch
{
return true; // Default to assuming clear if it fails, to prevent the bot from freezing
}
}
}
}

View file

@ -0,0 +1,154 @@
using System;
using System.Text;
using NLua;
using Decal.Adapter;
using Decal.Adapter.Wrappers;
using System.IO;
namespace NexSuite.Plugins.RynthAi
{
public class LuaManager : IDisposable
{
private Lua _lua;
private readonly PluginCore _core;
private bool _isDisposed;
public void Execute(string script) => ExecuteString(script);
public LuaManager(PluginCore core)
{
_core = core;
Init();
}
public void Init()
{
try
{
// 1. Clean up old state if re-initializing to prevent memory leaks
_lua?.Dispose();
// 2. Initialize the fresh NLua state
_lua = new Lua();
_lua.LoadCLRPackage();
// 3. Instantiate the Bridge
// This class acts as the middle-man, housing GoTo, Stop, and UsePortal logic
var bridge = new LuaBridge(_core);
// --- THE API BRIDGE: Expose the Bridge as "RynthAi" ---
// Usage in Lua: RynthAi:GoTo("33.5N", "44.8E")
_lua["RynthAi"] = bridge;
// --- SHORTCUTS: Direct manager access for advanced scripting ---
if (_core.UI != null)
{
_lua["Combat"] = _core.UI.CombatManager;
_lua["Settings"] = _core.UI.Settings;
_lua["Nav"] = _core.UI.Settings.CurrentRoute;
}
// Expose the raw Decal CoreManager (e.g., Core.WorldFilter)
_lua["Core"] = _core.PluginCoreManager;
// --- REDIRECT PRINT ---
// Replaces Lua's default print() with our custom C# method
// which sends text to both AC Chat and the UI Console.
_lua.RegisterFunction("print", this, typeof(LuaManager).GetMethod("LuaPrint"));
LuaPrint("Lua Engine Initialized.");
}
catch (Exception ex)
{
LogError("Init Error: " + ex.Message);
}
}
public void ExecuteString(string script)
{
try
{
if (string.IsNullOrEmpty(script) || _lua == null) return;
_lua.DoString(script);
}
catch (NLua.Exceptions.LuaException ex)
{
// This will now show you the EXACT line number and error in AC chat
LogError("Lua Script Error: " + ex.Message);
}
catch (Exception ex)
{
LogError("Engine Error: " + ex.Message);
}
}
public void LuaPrint(object msg)
{
// 1. Format the basic string and timestamp
string text = msg?.ToString() ?? "nil";
string timestamp = DateTime.Now.ToString("HH:mm:ss");
string formattedMsg = $"[{timestamp}] {text}";
// 2. Always output to Asheron's Call Chat (Green text)
// This is safe even if the UI window isn't open yet
_core.PluginHost.Actions.AddChatText($"[RynthLua] {text}", 5);
// 3. Safely update the ImGui Console Tab
// We wrap everything in this check so the plugin doesn't crash
// if you try to print something before the UI is fully loaded.
if (_core.UI?.Settings != null)
{
// Append the new line to the console
_core.UI.Settings.LuaConsoleOutput += $"\n{formattedMsg}";
// Limit console size to roughly 10k characters to prevent memory bloat
if (_core.UI.Settings.LuaConsoleOutput.Length > 10000)
{
// Trims the oldest 5,000 characters
_core.UI.Settings.LuaConsoleOutput = _core.UI.Settings.LuaConsoleOutput.Substring(5000);
}
}
}
public void LoadMainScript()
{
try
{
string scriptDir = Path.Combine(_core.AssemblyDirectory, "Scripts");
if (!Directory.Exists(scriptDir)) Directory.CreateDirectory(scriptDir);
string path = Path.Combine(scriptDir, "main.lua");
if (File.Exists(path))
{
string code = File.ReadAllText(path);
ExecuteString(code);
LuaPrint("Main script loaded from: " + path);
}
else
{
// Create a dummy file so the user has a template
File.WriteAllText(path, "-- RynthAi Main Lua Script\nfunction OnBotTick()\nend");
LuaPrint("Created template main.lua at: " + path);
}
}
catch (Exception ex)
{
LogError("LoadMainScript Error: " + ex.Message);
}
}
private void LogError(string msg)
{
_core.PluginHost.Actions.AddChatText($"[RynthLua Error] {msg}", 2);
_core.UI.Settings.LuaConsoleOutput += $"\n[ERROR] {msg}";
}
public void Dispose()
{
if (!_isDisposed)
{
_lua?.Dispose();
_isDisposed = true;
}
}
}
}

View file

@ -0,0 +1,684 @@
using System;
using System.Collections.Generic;
using System.IO;
using Decal.Adapter;
using Decal.Adapter.Wrappers;
using Newtonsoft.Json;
using NexSuite.Plugins.RynthAi;
using System.Numerics;
using System.Linq;
namespace RynthAi.Meta
{
public class MetaManager
{
private CoreManager _core;
private UISettings _settings;
private PluginHost _host;
private string _lastChatText = "";
private DateTime _lastChatTime = DateTime.MinValue;
private System.Text.RegularExpressions.Match _lastChatMatch = null;
// Timer tracking for "Seconds in State"
private DateTime _lastStateChange = DateTime.Now;
private string _previousState = "";
// Tracks if the meta was turned off so we can clean the slate when turned back on
private bool _wasMetaEnabled = false;
public Action OnRouteDynamicallyLoaded;
private Stack<string> _stateStack = new Stack<string>();
private bool _watchdogActive = false;
private string _watchdogState = "";
private float _watchdogMetersRequired = 0f;
private double _watchdogSecondsConfig = 0;
private DateTime _watchdogExpiration;
private Vector3 _lastWatchdogPos; // Requires 'using System.Numerics;'
private string _lastState = "";
private DateTime _stateStartTime = DateTime.Now;
public MetaManager(CoreManager core, UISettings settings, PluginHost host)
{
_core = core;
_settings = settings;
_host = host;
}
public void OnHeartbeat()
{
// 1. If Meta is disabled, reset our tracker and do absolutely nothing
if (!_settings.IsMacroRunning || !_settings.EnableMeta || _settings.MetaRules == null)
{
_wasMetaEnabled = false;
return;
}
// 2. If Meta was just turned on, we need a clean slate so old timers don't instantly trigger
if (!_wasMetaEnabled)
{
_wasMetaEnabled = true;
_lastStateChange = DateTime.Now;
_previousState = _settings.CurrentState;
// Reset all rules so they can fire again
foreach (var r in _settings.MetaRules) r.HasFired = false;
}
// 3. Normal State Change OR Forced Reset from UI
if (!string.Equals(_settings.CurrentState, _previousState, StringComparison.OrdinalIgnoreCase) || _settings.ForceStateReset)
{
_settings.ForceStateReset = false; // Consume the flag so it only resets once
_lastStateChange = DateTime.Now;
_previousState = _settings.CurrentState;
// Reset all rules so they can fire again in the new/reset state
foreach (var r in _settings.MetaRules)
{
r.HasFired = false;
}
}
// Calculate the time ONCE per heartbeat to pass into evaluations,
// saving CPU cycles on deep 'Any'/'All' recursive checks.
double currentSecondsInState = (DateTime.Now - _lastStateChange).TotalSeconds;
// 4. Evaluate Rules
foreach (var rule in _settings.MetaRules)
{
// Case-insensitive check so "Default" and "default" don't break the meta
if (string.Equals(rule.State, _settings.CurrentState, StringComparison.OrdinalIgnoreCase))
{
// Check our boolean to prevent chat/action spam
if (!rule.HasFired)
{
if (EvaluateCondition(rule, currentSecondsInState))
{
ExecuteAction(rule);
// Mark this specific rule as fired so it glows red in UI and stops spamming
rule.HasFired = true;
break; // Process one successful rule per heartbeat
}
}
}
}
}
private bool EvaluateCondition(MetaRule rule, double secondsInState)
{
try
{
// Explicitly using Decal.Adapter for Vitals
dynamic actions = _host.Actions;
switch (rule.Condition)
{
case MetaConditionType.Always: return true;
case MetaConditionType.Never: return false;
case MetaConditionType.All:
{
if (rule.Children == null || rule.Children.Count == 0) return false;
foreach (var child in rule.Children)
if (!EvaluateCondition(child, secondsInState)) return false;
return true;
}
case MetaConditionType.Any:
{
if (rule.Children == null || rule.Children.Count == 0) return false;
foreach (var child in rule.Children)
if (EvaluateCondition(child, secondsInState)) return true;
return false;
}
case MetaConditionType.Not:
{
if (rule.Children == null || rule.Children.Count == 0) return false;
return !EvaluateCondition(rule.Children[0], secondsInState);
}
// --- VITAL CHECKS (Value) ---
case MetaConditionType.MainHealthLE:
{
if (int.TryParse(rule.ConditionData, out int hVal))
return _core.CharacterFilter.Health <= hVal;
return false;
}
case MetaConditionType.MainManaLE:
{
if (int.TryParse(rule.ConditionData, out int mVal))
return _core.CharacterFilter.Mana <= mVal;
return false;
}
case MetaConditionType.MainStamLE:
{
if (int.TryParse(rule.ConditionData, out int sVal))
return _core.CharacterFilter.Stamina <= sVal;
return false;
}
// --- VITAL CHECKS (Percentage) ---
case MetaConditionType.MainHealthPHE:
{
if (int.TryParse(rule.ConditionData, out int hPct))
{
double cur = _core.CharacterFilter.Health; // Live HP
double max = _core.CharacterFilter.Vitals[Decal.Adapter.Wrappers.CharFilterVitalType.Health].Current; // Max HP
return max > 0 && (cur / max) * 100 <= hPct;
}
return false;
}
case MetaConditionType.MainManaPHE:
{
if (int.TryParse(rule.ConditionData, out int mPct))
{
double cur = _core.CharacterFilter.Mana; // Live MP
double max = _core.CharacterFilter.Vitals[Decal.Adapter.Wrappers.CharFilterVitalType.Mana].Current; // Max MP
return max > 0 && (cur / max) * 100 <= mPct;
}
return false;
}
case MetaConditionType.CharacterDeath:
return _core.CharacterFilter.Health <= 0;
// --- TIME & CHAT ---
case MetaConditionType.SecondsInState_GE:
case MetaConditionType.SecondsInStateP_GE:
{
if (double.TryParse(rule.ConditionData, out double reqSecs))
return secondsInState >= reqSecs;
return false;
}
case MetaConditionType.ChatMessage:
case MetaConditionType.ChatMessageCapture:
{
if ((DateTime.Now - _lastChatTime).TotalSeconds > 1.0) return false;
try
{
var regex = new System.Text.RegularExpressions.Regex(rule.ConditionData);
var match = regex.Match(_lastChatText);
if (match.Success)
{
if (rule.Condition == MetaConditionType.ChatMessageCapture) _lastChatMatch = match;
return true;
}
}
catch { }
return false;
}
// --- WORLD & INVENTORY ---
case MetaConditionType.BurdenPercentage_GE:
{
if (int.TryParse(rule.ConditionData, out int targetB))
return _core.CharacterFilter.Burden >= targetB;
return false;
}
case MetaConditionType.PackSlots_LE:
{
if (int.TryParse(rule.ConditionData, out int targetSlots))
{
int myId = _core.CharacterFilter.Id;
int usedGridSquares = 0;
foreach (var item in _core.WorldFilter.GetInventory())
{
if (item.Container == myId)
{
int slot = item.Values(Decal.Adapter.Wrappers.LongValueKey.Slot, -1);
bool isEquipped = item.Values(Decal.Adapter.Wrappers.LongValueKey.EquippedSlots, 0) > 0;
bool isBag = item.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Container;
bool isFoci = item.Name != null && item.Name.Contains("Foci");
if (slot >= 0 && slot <= 101 && !isEquipped && !isBag && !isFoci)
usedGridSquares++;
}
}
int freeSlots = 102 - usedGridSquares;
return freeSlots <= targetSlots;
}
return false;
}
case MetaConditionType.InventoryItemCount_LE:
case MetaConditionType.InventoryItemCount_GE:
{
if (string.IsNullOrEmpty(rule.ConditionData)) return false;
string[] invParts = rule.ConditionData.Split(',');
if (invParts.Length >= 2)
{
string itemName = invParts[0].Trim();
if (!int.TryParse(invParts[1], out int targetCount)) return false;
int currentCount = 0;
int myId = _core.CharacterFilter.Id;
foreach (var item in _core.WorldFilter.GetInventory())
{
bool isMine = (item.Container == myId);
if (!isMine)
{
var parentBag = _core.WorldFilter[item.Container];
if (parentBag != null && parentBag.Container == myId) isMine = true;
}
if (isMine && item.Name != null && item.Name.Equals(itemName, StringComparison.OrdinalIgnoreCase))
currentCount += item.Values(Decal.Adapter.Wrappers.LongValueKey.StackCount, 1);
}
if (rule.Condition == MetaConditionType.InventoryItemCount_LE)
return currentCount <= targetCount;
else
return currentCount >= targetCount;
}
return false;
}
case MetaConditionType.TimeLeftOnSpell_GE:
case MetaConditionType.TimeLeftOnSpell_LE:
{
if (string.IsNullOrEmpty(rule.ConditionData)) return false;
string[] spellParts = rule.ConditionData.Split(',');
if (spellParts.Length >= 2)
{
if (int.TryParse(spellParts[0], out int spellId) && double.TryParse(spellParts[1], out double reqSecs))
{
double remaining = 0;
bool found = false;
foreach (var ench in _core.CharacterFilter.Enchantments)
{
if (ench.SpellId == spellId)
{
remaining = ench.TimeRemaining;
found = true;
break;
}
}
if (rule.Condition == MetaConditionType.TimeLeftOnSpell_GE)
return found && remaining >= reqSecs;
else
return !found || remaining <= reqSecs;
}
}
return false;
}
case MetaConditionType.MonsterNameCountWithinDistance:
{
if (string.IsNullOrEmpty(rule.ConditionData)) return false;
string[] mParts = rule.ConditionData.Split(',');
if (mParts.Length >= 3)
{
string pattern = mParts[0];
if (!double.TryParse(mParts[1], out double dist) || !int.TryParse(mParts[2], out int count)) return false;
int matchCount = 0;
var regex = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
foreach (var obj in _core.WorldFilter.GetLandscape())
{
if (obj.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Monster && _core.WorldFilter.Distance(obj.Id, _core.CharacterFilter.Id) <= dist)
if (regex.IsMatch(obj.Name)) matchCount++;
}
return matchCount >= count;
}
return false;
}
case MetaConditionType.NoMonstersWithinDistance:
{
double maxD = 20.0;
double.TryParse(rule.ConditionData, out maxD);
foreach (var obj in _core.WorldFilter.GetLandscape())
{
if (obj.ObjectClass == Decal.Adapter.Wrappers.ObjectClass.Monster && _core.WorldFilter.Distance(obj.Id, _core.CharacterFilter.Id) <= maxD)
return false;
}
return true;
}
case MetaConditionType.NavrouteEmpty:
if (_settings.CurrentRoute == null || _settings.CurrentRoute.Points.Count == 0) return true;
return _settings.ActiveNavIndex >= _settings.CurrentRoute.Points.Count;
case MetaConditionType.AnyVendorOpen:
return actions.VendorId != 0;
case MetaConditionType.PortalspaceEntered:
return (actions.Status & 0x1) != 0;
case MetaConditionType.PortalspaceExited:
return (actions.Status & 0x1) == 0;
default:
return false;
}
}
catch (Exception ex)
{
_host.Actions.AddChatText($"[RynthAi] EvaluateCondition Error: {ex.Message}", 2);
}
return false;
}
private void ExecuteAction(MetaRule rule)
{
dynamic actions = _host.Actions;
// --- HELPER: Regex Variable Replacement ---
string ProcessData(string rawData)
{
if (string.IsNullOrEmpty(rawData)) return "";
if (_lastChatMatch == null || !_lastChatMatch.Success) return rawData;
string result = rawData;
for (int i = 0; i < _lastChatMatch.Groups.Count; i++)
{
result = result.Replace($"{{{i}}}", _lastChatMatch.Groups[i].Value);
}
return result;
}
switch (rule.Action)
{
case MetaActionType.All:
if (rule.Children != null && rule.Children.Count > 0)
{
foreach (var childAction in rule.Children) ExecuteAction(childAction);
}
break;
case MetaActionType.ChatCommand:
string finalCommand = ProcessData(rule.ActionData);
if (!string.IsNullOrEmpty(finalCommand)) actions.InvokeChatParser(finalCommand);
break;
case MetaActionType.SetMetaState:
string nextState = ProcessData(rule.ActionData);
if (!string.IsNullOrEmpty(nextState))
{
_settings.CurrentState = nextState;
_settings.ForceStateReset = true;
actions.AddChatText($"[RynthAi] Meta State -> {nextState}", 5);
}
break;
case MetaActionType.CallMetaState:
string callState = ProcessData(rule.ActionData);
if (!string.IsNullOrEmpty(callState))
{
_stateStack.Push(_settings.CurrentState);
_settings.CurrentState = callState;
_settings.ForceStateReset = true;
actions.AddChatText($"[RynthAi] Calling State -> {callState}", 5);
}
break;
case MetaActionType.ReturnFromCall:
if (_stateStack.Count > 0)
{
string returnTo = _stateStack.Pop();
_settings.CurrentState = returnTo;
_settings.ForceStateReset = true;
actions.AddChatText($"[RynthAi] Returning to -> {returnTo}", 5);
}
else { actions.AddChatText("[RynthAi] Error: Return From Call failed (Stack Empty)", 2); }
break;
case MetaActionType.EmbeddedNavRoute:
if (string.IsNullOrWhiteSpace(rule.ActionData)) break;
string routeName = rule.ActionData.Split(';')[0];
string navFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\NavProfiles";
string fullPath = System.IO.Path.Combine(navFolder, routeName + ".nav");
if (System.IO.File.Exists(fullPath))
{
try
{
_settings.CurrentNavPath = fullPath;
_settings.CurrentRoute = VTankNavParser.Load(fullPath);
_settings.ActiveNavIndex = 0;
actions.AddChatText($"[RynthAi Meta] Switched to route: {routeName}", 5);
OnRouteDynamicallyLoaded?.Invoke();
}
catch (Exception ex) { actions.AddChatText($"[RynthAi Meta] Load Error: {ex.Message}", 2); }
}
else { actions.AddChatText($"[RynthAi Meta] Route file missing: {fullPath}", 2); }
break;
case MetaActionType.SetWatchdog:
// IGNITION SWITCH: If it's already ticking, do absolutely nothing.
// This prevents the rule from resetting the timer every single frame!
if (_watchdogActive) break;
string[] wdParts = (rule.ActionData ?? "").Split(';');
if (wdParts.Length >= 3)
{
_watchdogState = wdParts[0].Trim();
if (!float.TryParse(wdParts[1].Trim(), out _watchdogMetersRequired)) _watchdogMetersRequired = 5f;
if (!double.TryParse(wdParts[2].Trim(), out _watchdogSecondsConfig)) _watchdogSecondsConfig = 5.0;
_watchdogExpiration = DateTime.Now.AddSeconds(_watchdogSecondsConfig);
_lastWatchdogPos = new Vector3((float)actions.LocationX, (float)actions.LocationY, (float)actions.LocationZ);
_watchdogActive = true;
actions.AddChatText($"[RynthAi] Watchdog Started: To {_watchdogState} if not moved {_watchdogMetersRequired}m in {_watchdogSecondsConfig}s.", 5);
}
break;
case MetaActionType.ClearWatchdog:
_watchdogActive = false;
actions.AddChatText("[RynthAi] Watchdog Cleared", 5);
break;
case MetaActionType.SetNTOption:
string[] ntParts = (rule.ActionData ?? "").Split(';');
if (ntParts.Length >= 2) actions.AddChatText($"[RynthAi] Option Set: {ntParts[0]} = {ntParts[1]}", 5);
break;
case MetaActionType.ExpressionAction:
case MetaActionType.ChatExpression:
case MetaActionType.CreateView:
case MetaActionType.DestroyView:
case MetaActionType.DestroyAllViews:
break;
}
}
public void Think()
{
try
{
dynamic actions = _host.Actions;
// 1. THE KILL SWITCH (State Entry/Exit)
if (_settings.CurrentState != _lastState || _settings.ForceStateReset)
{
_lastState = _settings.CurrentState;
_stateStartTime = DateTime.Now;
_watchdogActive = false;
_settings.ForceStateReset = false;
// --- THE FIX: Wipe the slate clean for the new state ---
// This ensures rules can fire again if we leave the state and come back later
if (_settings.MetaRules != null)
{
foreach (var r in _settings.MetaRules)
{
r.HasFired = false;
}
}
}
double secondsInState = (DateTime.Now - _stateStartTime).TotalSeconds;
// 2. THE WATCHDOG TIMER
if (_watchdogActive)
{
Vector3 currentPos = new Vector3(
(float)actions.LocationX,
(float)actions.LocationY,
(float)actions.LocationZ
);
float distMoved = Vector3.Distance(currentPos, _lastWatchdogPos);
if (distMoved < _watchdogMetersRequired)
{
if (DateTime.Now > _watchdogExpiration)
{
_watchdogActive = false;
_settings.CurrentState = _watchdogState;
_settings.ForceStateReset = true;
actions.AddChatText($"[RynthAi] WATCHDOG TRIGGERED! Jumping to: {_watchdogState}", 5);
return;
}
}
else
{
_lastWatchdogPos = currentPos;
_watchdogExpiration = DateTime.Now.AddSeconds(_watchdogSecondsConfig);
}
}
// 3. RULE EVALUATION
if (!_settings.EnableMeta || _settings.MetaRules == null) return;
var currentRules = _settings.MetaRules.Where(r => r.State == _settings.CurrentState).ToList();
foreach (var rule in currentRules)
{
// --- THE FIX: Skip this rule if it already successfully fired during this state visit ---
if (rule.HasFired) continue;
if (EvaluateCondition(rule, secondsInState))
{
rule.HasFired = true; // Lock it out from firing again
ExecuteAction(rule);
if (_settings.CurrentState != _lastState || _settings.ForceStateReset)
{
break;
}
}
}
}
catch (Exception ex)
{
_host.Actions.AddChatText($"[RynthAi] ENGINE CRASH in Think(): {ex.Message}", 5);
}
}
public void PrintWatchdogStatus()
{
if (!_watchdogActive)
{
_host.Actions.AddChatText("[RynthAi] Watchdog Status: INACTIVE", 5);
return;
}
// Grab current coordinates
Vector3 currentPos = new Vector3(
(float)_host.Actions.LocationX,
(float)_host.Actions.LocationY,
(float)_host.Actions.LocationZ
);
// Calculate real-time stats
float distMoved = Vector3.Distance(currentPos, _lastWatchdogPos);
double secondsLeft = (_watchdogExpiration - DateTime.Now).TotalSeconds;
// Print the diagnostic readout
_host.Actions.AddChatText($"[RynthAi] Watchdog Status: ACTIVE", 5);
_host.Actions.AddChatText($" -> Target State: {_watchdogState}", 5);
_host.Actions.AddChatText($" -> Distance Moved: {distMoved:F2}m / {_watchdogMetersRequired}m", 5);
_host.Actions.AddChatText($" -> Time Left: {Math.Max(0, secondsLeft):F1}s", 5);
}
private Vector3 GetCurrentPosition()
{
// Accessing the host's actions coordinates directly
return new Vector3(
(float)_host.Actions.LocationX,
(float)_host.Actions.LocationY,
(float)_host.Actions.LocationZ
);
}
// --- PROFILE PERSISTENCE ---
public void LoadProfile(string path)
{
try
{
if (string.IsNullOrEmpty(path) || !File.Exists(path))
{
_settings.MetaRules = new List<MetaRule>();
return;
}
// Try VTank Parser first for .met files
if (path.EndsWith(".met", StringComparison.OrdinalIgnoreCase))
{
var vtankRules = VTankMetaParser.IntelligentlyLoad(path);
if (vtankRules != null)
{
_settings.MetaRules = vtankRules;
_host.Actions.AddChatText($"[RynthAi] Imported VTank Profile: {Path.GetFileName(path)}", 5);
return;
}
}
// Fallback to our native JSON loader
string json = File.ReadAllText(path);
var rules = JsonConvert.DeserializeObject<List<MetaRule>>(json);
if (rules != null) _settings.MetaRules = rules;
}
catch (Exception ex)
{
_host.Actions.AddChatText($"[RynthAi] Meta Load Error: {ex.Message}", 1);
}
}
public void SaveCurrentProfile()
{
try
{
if (string.IsNullOrEmpty(_settings.CurrentMetaPath)) return;
string directory = Path.GetDirectoryName(_settings.CurrentMetaPath);
if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
string json = JsonConvert.SerializeObject(_settings.MetaRules, Formatting.Indented);
File.WriteAllText(_settings.CurrentMetaPath, json);
}
catch (Exception ex)
{
_host.Actions.AddChatText($"[RynthAi] Meta Save Error: {ex.Message}", 1);
}
}
public void HandleChat(string text)
{
// TEMPORARY DEBUG: Uncomment this to see if text is hitting the manager
// _host.Actions.AddChatText($"[Meta Debug] Received: {text}", 5);
_lastChatText = text;
_lastChatTime = DateTime.Now;
}
}
}

View file

@ -0,0 +1,172 @@
using System;
using System.Collections.Generic;
using System.IO;
using NexSuite.Plugins.RynthAi;
namespace RynthAi.Meta
{
public static class VTankMetaParser
{
public static List<MetaRule> IntelligentlyLoad(string path)
{
if (!File.Exists(path)) return new List<MetaRule>();
try
{
using (StreamReader reader = new StreamReader(path))
{
string firstLine = reader.ReadLine();
if (firstLine != "1") return null; // Not a valid VTank file format
// Skip the 11-line header (CondAct schema metadata)
for (int i = 0; i < 11; i++) reader.ReadLine();
string countLine = reader.ReadLine();
int ruleCount = int.Parse(countLine ?? "0");
List<MetaRule> rules = new List<MetaRule>();
for (int i = 0; i < ruleCount; i++)
{
rules.Add(ParseCondAct(reader));
}
return rules;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[RynthAi] Meta Load Error: {ex.Message}");
return new List<MetaRule>();
}
}
private static MetaRule ParseCondAct(StreamReader reader)
{
MetaRule rule = new MetaRule();
// 1. CType (Condition Type - Integer)
reader.ReadLine(); // Consume 'i' type marker
rule.Condition = (MetaConditionType)int.Parse(reader.ReadLine());
// 2. AType (Action Type - Integer)
reader.ReadLine(); // Consume 'i' type marker
int vTankActionType = int.Parse(reader.ReadLine());
// Map VTank Action IDs to RynthAi Action Enums
if (vTankActionType == 1) rule.Action = MetaActionType.SetMetaState;
else if (vTankActionType == 2) rule.Action = MetaActionType.ChatCommand;
else if (vTankActionType == 3) rule.Action = MetaActionType.EmbeddedNavRoute;
// 3. CData (Condition Data - Variant)
object cData = ReadVariant(reader);
// Handle VTank Data Tables (Type 2) for complex conditions
if (cData is Dictionary<string, object> cDict)
{
// --- MONSTER COUNT TABLE ---
if (rule.Condition == MetaConditionType.MonsterNameCountWithinDistance)
{
string name = cDict.ContainsKey("n") ? cDict["n"].ToString() : "";
string dist = cDict.ContainsKey("d") ? cDict["d"].ToString() : "0";
string count = cDict.ContainsKey("c") ? cDict["c"].ToString() : "0";
rule.ConditionData = $"{name},{dist},{count}";
}
// --- INVENTORY COUNT TABLE ---
else if (rule.Condition == MetaConditionType.InventoryItemCount_LE ||
rule.Condition == MetaConditionType.InventoryItemCount_GE)
{
string name = cDict.ContainsKey("n") ? cDict["n"].ToString() : "";
string count = cDict.ContainsKey("c") ? cDict["c"].ToString() : "0";
rule.ConditionData = $"{name},{count}";
}
// --- SPELL TIME TABLE (NEW) ---
else if (rule.Condition == MetaConditionType.TimeLeftOnSpell_GE)
{
string id = cDict.ContainsKey("s") ? cDict["s"].ToString() : "0";
string time = cDict.ContainsKey("t") ? cDict["t"].ToString() : "0";
rule.ConditionData = $"{id},{time}";
}
else
{
rule.ConditionData = "TableData"; // Fallback for unsupported tables
}
}
else
{
rule.ConditionData = cData?.ToString() ?? "";
}
// 4. AData (Action Data - Variant)
object aData = ReadVariant(reader);
rule.ActionData = aData?.ToString() ?? "";
// 5. State (The State this rule belongs to - String)
reader.ReadLine(); // Consume 's' type marker
rule.State = reader.ReadLine();
// 6. Check for recursion (Children for Group conditions like All/Any/Not)
if (rule.Condition == MetaConditionType.All || rule.Condition == MetaConditionType.Any || rule.Condition == MetaConditionType.Not)
{
string nextType = reader.ReadLine();
if (nextType == "2") // Marker for the children table
{
// Skip table metadata (k, v, n, n)
for (int j = 0; j < 4; j++) reader.ReadLine();
int childCount = int.Parse(reader.ReadLine() ?? "0");
for (int j = 0; j < childCount; j++)
{
// Consume the table index key, then parse the child rule
ReadVariant(reader);
rule.Children.Add(ParseCondAct(reader));
}
}
}
return rule;
}
/// <summary>
/// Reads a VTank "Variant" which includes a type marker (s, i, d, 2, etc.)
/// followed by the data. This allows the parser to stay synchronized.
/// </summary>
private static object ReadVariant(StreamReader reader)
{
string typeMarker = reader.ReadLine();
if (typeMarker == null) return null;
// Handle standard scalar types
switch (typeMarker)
{
case "s": // String
case "i": // Integer
case "d": // Double
case "b": // Boolean
case "u": // Unsigned Int
case "f": // Float
return reader.ReadLine();
case "2": // Table / Dictionary
// Skip table metadata headers
for (int i = 0; i < 4; i++) reader.ReadLine();
int pairCount = int.Parse(reader.ReadLine() ?? "0");
Dictionary<string, object> table = new Dictionary<string, object>();
for (int j = 0; j < pairCount; j++)
{
object key = ReadVariant(reader);
object val = ReadVariant(reader);
if (key != null)
{
table[key.ToString()] = val;
}
}
return table;
default:
return null;
}
}
}
}

View file

@ -0,0 +1,310 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace NexSuite.Plugins.RynthAi
{
/// <summary>
/// Direct calls to acclient.exe CM_Movement functions.
/// Derived entirely from Turbine's acclient.exe decompilation.
///
/// Uses the same runtime pattern-scan approach as CombatActionHelper.
///
/// ═══ TIER 1: CM_Movement server events (Proto_UI::SendToWeenie) ═══
/// These send ordered game events to the server. They are __cdecl statics.
///
/// Event_DoMovementCommand(motion, speed, hold_key) — opcode 0xF61E
/// Event_StopMovementCommand(motion, hold_key) — opcode 0xF661
/// Event_Jump_NonAutonomous(extent) — opcode 0xF7C9
/// Event_AutonomyLevel(level) — opcode 0xF752
///
/// All share the CM prologue: 83 EC 0C 53 56 57 E8
/// Anchored by Event_StopMovementCommand (opcode 0xF661) which has a
/// unique-enough value in the CM_Movement cluster.
///
/// ═══ TIER 2: CPhysicsObj::MoveToPosition (planned) ═══
/// Client-side pathfinding via the player's physics object.
/// Requires tracing SmartBox::smartbox → player → MovementManager.
/// Would let the client handle all interpolation, heading, speed natively.
///
/// ═══ TIER 3: MoveToManager queue (planned) ═══
/// Direct movement node queue manipulation for maximum control.
///
/// Motion constants (from acclient.exe motion tables):
/// 0x45000005 = MoveForward (WalkForward)
/// 0x45000006 = MoveBackward (WalkBackward)
/// 0x6500000D = TurnRight
/// 0x6500000E = TurnLeft
/// 0x41000003 = RunForward
///
/// HoldKey values:
/// 0 = None
/// 1 = Run (hold shift)
/// 2 = AutoRun
/// </summary>
internal static class MovementActionHelper
{
// ── Motion constants ────────────────────────────────────────────────
public const uint MOTION_WALK_FORWARD = 0x45000005;
public const uint MOTION_WALK_BACKWARD = 0x45000006;
public const uint MOTION_RUN_FORWARD = 0x41000003;
public const uint MOTION_TURN_RIGHT = 0x6500000D;
public const uint MOTION_TURN_LEFT = 0x6500000E;
public const uint MOTION_SIDESTEP_RIGHT = 0x6500000F;
public const uint MOTION_SIDESTEP_LEFT = 0x65000010;
// ── HoldKey values ──────────────────────────────────────────────────
public const int HOLDKEY_NONE = 0;
public const int HOLDKEY_RUN = 1;
public const int HOLDKEY_AUTORUN = 2;
// ── Delegate types ──────────────────────────────────────────────────
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool DelDoMovementCommand(uint motion, float speed, int holdKey);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool DelStopMovementCommand(uint motion, int holdKey);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool DelJumpNonAutonomous(float extent);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool DelAutonomyLevel(uint level);
// ── Cached delegates ────────────────────────────────────────────────
private static DelDoMovementCommand _doMovement;
private static DelStopMovementCommand _stopMovement;
private static DelJumpNonAutonomous _jumpNonAutonomous;
private static DelAutonomyLevel _autonomyLevel;
private static bool _initialized;
private static Action<string> _log;
// ── Shared prologue for CM_Movement functions ───────────────────────
private static readonly byte[] CM_PROLOGUE = { 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8 };
/// <summary>
/// Pattern-scans acclient.exe for CM_Movement functions at runtime.
/// Call once at plugin startup (after CombatActionHelper.Initialize).
/// </summary>
public static void Initialize(Action<string> chatLog = null)
{
_log = chatLog;
try
{
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("Movement scan FAILED: acclient.exe not found");
return;
}
int textRva = 0x1000;
int 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;
// ── Anchor: StopMovementCommand via opcode 0xF661 ──────────
// This is unique enough in the CM_Movement region.
byte[] stopOpcode = { 0xC7, 0x02, 0x61, 0xF6, 0x00, 0x00 };
int stopOpcodeOff = FindPattern(text, stopOpcode);
if (stopOpcodeOff < 0)
{
Log("Movement scan FAILED: StopMovementCommand opcode 0xF661 not found");
return;
}
int stopFuncOff = FindPrologueBefore(text, stopOpcodeOff);
if (stopFuncOff < 0)
{
Log("Movement scan FAILED: StopMovementCommand prologue not found");
return;
}
int stopVA = textBaseVA + stopFuncOff;
Log($"StopMovementCommand at 0x{stopVA:X8}");
// ── Search near StopMovementCommand for the others ─────────
// CM_Movement functions cluster within ~0x700 bytes
int regionStart = Math.Max(0, stopOpcodeOff - 0x700);
int regionEnd = Math.Min(text.Length, stopOpcodeOff + 0x300);
// DoMovementCommand: opcode 0xF61E (63006 decimal)
byte[] doOpcode = { 0xC7, 0x02, 0x1E, 0xF6, 0x00, 0x00 };
int doOpcodeOff = FindPatternInRegion(text, doOpcode, regionStart, regionEnd);
int doFuncOff = doOpcodeOff >= 0 ? FindPrologueBefore(text, doOpcodeOff) : -1;
// Jump_NonAutonomous: opcode 0xF7C9 (63433 decimal)
byte[] jumpNAOpcode = { 0xC7, 0x02, 0xC9, 0xF7, 0x00, 0x00 };
int jumpNAOff = FindPatternInRegion(text, jumpNAOpcode, regionStart, regionEnd);
int jumpNAFuncOff = jumpNAOff >= 0 ? FindPrologueBefore(text, jumpNAOff) : -1;
// AutonomyLevel: opcode 0xF752 (63314 decimal)
byte[] autoLevelOpcode = { 0xC7, 0x02, 0x52, 0xF7, 0x00, 0x00 };
int autoLevelOff = FindPatternInRegion(text, autoLevelOpcode, regionStart, regionEnd);
int autoLevelFuncOff = autoLevelOff >= 0 ? FindPrologueBefore(text, autoLevelOff) : -1;
// ── Verify and create delegates ────────────────────────────
if (doFuncOff < 0)
{
Log("Movement scan INCOMPLETE: DoMovementCommand not found");
return;
}
int doVA = textBaseVA + doFuncOff;
Log($"DoMovementCommand at 0x{doVA:X8}");
_stopMovement = (DelStopMovementCommand)Marshal.GetDelegateForFunctionPointer(
new IntPtr(stopVA), typeof(DelStopMovementCommand));
_doMovement = (DelDoMovementCommand)Marshal.GetDelegateForFunctionPointer(
new IntPtr(doVA), typeof(DelDoMovementCommand));
if (jumpNAFuncOff >= 0)
{
int jumpNAVA = textBaseVA + jumpNAFuncOff;
_jumpNonAutonomous = (DelJumpNonAutonomous)Marshal.GetDelegateForFunctionPointer(
new IntPtr(jumpNAVA), typeof(DelJumpNonAutonomous));
Log($"Jump_NonAutonomous at 0x{jumpNAVA:X8}");
}
if (autoLevelFuncOff >= 0)
{
int autoLevelVA = textBaseVA + autoLevelFuncOff;
_autonomyLevel = (DelAutonomyLevel)Marshal.GetDelegateForFunctionPointer(
new IntPtr(autoLevelVA), typeof(DelAutonomyLevel));
Log($"AutonomyLevel at 0x{autoLevelVA:X8}");
}
_initialized = true;
Log("MovementActionHelper initialized — CM_Movement functions found via pattern scan");
}
catch (Exception ex)
{
_initialized = false;
Log("MovementActionHelper init FAILED: " + ex.Message);
}
}
public static bool IsInitialized => _initialized;
// ══════════════════════════════════════════════════════════════════════
// TIER 1 PUBLIC API — Server-side movement events
// ══════════════════════════════════════════════════════════════════════
/// <summary>
/// Sends a movement command to the server.
/// Replaces keyboard-driven movement for server authorization.
/// motion: one of MOTION_* constants
/// speed: 1.0 = normal, can scale
/// holdKey: HOLDKEY_NONE, HOLDKEY_RUN, or HOLDKEY_AUTORUN
/// </summary>
public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = HOLDKEY_RUN)
{
if (!_initialized || _doMovement == null) return false;
try { return _doMovement(motion, speed, holdKey); }
catch (Exception ex) { Log("DoMovement failed: " + ex.Message); return false; }
}
/// <summary>
/// Stops a specific movement command on the server.
/// motion: the motion to stop (same constant used in DoMovement)
/// holdKey: must match the holdKey used in the corresponding DoMovement
/// </summary>
public static bool StopMovement(uint motion, int holdKey = HOLDKEY_RUN)
{
if (!_initialized || _stopMovement == null) return false;
try { return _stopMovement(motion, holdKey); }
catch (Exception ex) { Log("StopMovement failed: " + ex.Message); return false; }
}
/// <summary>
/// Non-autonomous jump with specified extent (0.0–1.0).
/// Replaces keyboard-simulated jump in RynthJumper.
/// </summary>
public static bool JumpNonAutonomous(float extent)
{
if (!_initialized || _jumpNonAutonomous == null) return false;
try { return _jumpNonAutonomous(Math.Max(0f, Math.Min(1f, extent))); }
catch (Exception ex) { Log("JumpNA failed: " + ex.Message); return false; }
}
/// <summary>
/// Sets the autonomy level for the client.
/// 0 = server controls, 1 = client controls (normal play), 2 = full autonomy.
/// </summary>
public static bool SetAutonomyLevel(uint level)
{
if (!_initialized || _autonomyLevel == null) return false;
try { return _autonomyLevel(level); }
catch (Exception ex) { Log("AutonomyLevel failed: " + ex.Message); return false; }
}
// ══════════════════════════════════════════════════════════════════════
// PATTERN SCANNER (shared with CombatActionHelper design)
// ══════════════════════════════════════════════════════════════════════
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;
}
private static int FindPrologueBefore(byte[] data, int opcodeOffset)
{
for (int back = 1; back < 300; back++)
{
int pos = opcodeOffset - back;
if (pos < 1 || pos + CM_PROLOGUE.Length > data.Length) continue;
bool match = true;
for (int j = 0; j < CM_PROLOGUE.Length; j++)
{
if (data[pos + j] != CM_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 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,76 @@
using System;
using System.IO;
namespace NexSuite.Plugins.RynthAi
{
/// <summary>
/// Crash-safe file logger. Every write flushes immediately so the last
/// line survives a hard client crash. Writes to RynthAi\Logs\tier2.log,
/// rolls over at 1 MB.
/// </summary>
internal static class Tier2Log
{
private static readonly string LogDir =
@"C:\Games\DecalPlugins\NexSuite\RynthAi\Logs";
private static readonly string LogPath =
Path.Combine(LogDir, "tier2.log");
private const long MAX_SIZE = 1024 * 1024; // 1 MB rollover
private static readonly object _lock = new object();
private static bool _initialized;
/// <summary>
/// Write a timestamped line to tier2.log. Safe to call from any thread.
/// </summary>
public static void Log(string msg)
{
try
{
lock (_lock)
{
EnsureDir();
Rollover();
using (var sw = new StreamWriter(LogPath, true))
{
sw.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] {msg}");
sw.Flush();
}
}
}
catch { }
}
/// <summary>
/// Write a separator + header for a new session.
/// </summary>
public static void StartSession()
{
Log("════════════════════════════════════════════════════════════");
Log($"Session start — {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
}
private static void EnsureDir()
{
if (!_initialized)
{
if (!Directory.Exists(LogDir))
Directory.CreateDirectory(LogDir);
_initialized = true;
}
}
private static void Rollover()
{
try
{
if (File.Exists(LogPath) && new FileInfo(LogPath).Length > MAX_SIZE)
{
string backup = LogPath + ".old";
if (File.Exists(backup)) File.Delete(backup);
File.Move(LogPath, backup);
}
}
catch { }
}
}
}

View file

@ -0,0 +1,942 @@
using System;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security;
namespace NexSuite.Plugins.RynthAi
{
/// <summary>
/// Tier 2 movement: calls MovementManager::PerformMovement directly on the
/// player's CPhysicsObj. The client's own pathfinding handles interpolation,
/// heading, speed — producing smooth arcs instead of autorun + PD-controller
/// correction jitter.
///
/// Pointer chain (all from acclient.exe decompilation + binary verification):
/// [SmartBox::smartbox] → SmartBox*
/// [SmartBox+0xF8] → CPhysicsObj* (player)
/// [player+0xC4] → MovementManager*
/// PerformMovement(__thiscall, const MovementStruct*)
///
/// MovementTypes (from MovementStruct.type):
/// 6 = MoveToObject — approach a world object
/// 7 = MoveToPosition — walk/run to an (x,y,z) in a landblock cell
/// 8 = TurnToObject — face a world object
/// 9 = TurnToHeading — face a compass heading (degrees)
///
/// All structs are stack-allocated in unmanaged memory, filled, passed to the
/// native function, then freed. No persistent allocations.
///
/// Pattern scans (version-independent):
/// PerformMovement — anchored by its unique return-71 epilogue
/// CancelMoveTo — immediately follows PerformMovement (reads [ecx+4])
/// Position vtable — found in CPhysicsObj::MoveToObject's stack init
/// MovParams vtable — found in MovementParameters constructor (writes speed=1.0)
/// </summary>
internal static class Tier2MovementHelper
{
// ═══════════════════════════════════════════════════════════════════════
// MOVEMENT TYPE CONSTANTS
// ═══════════════════════════════════════════════════════════════════════
public const uint TYPE_MOVE_TO_OBJECT = 6;
public const uint TYPE_MOVE_TO_POSITION = 7;
public const uint TYPE_TURN_TO_OBJECT = 8;
public const uint TYPE_TURN_TO_HEADING = 9;
// ═══════════════════════════════════════════════════════════════════════
// STRUCT SIZES & OFFSETS
// ═══════════════════════════════════════════════════════════════════════
// ── SmartBox ──────────────────────────────────────────────────────────
private const int SB_PLAYER_ID = 0xF4;
private const int SB_PLAYER = 0xF8;
private const int SB_CMDINTERP = 0xB8;
// ── CPhysicsObj ───────────────────────────────────────────────────────
private const int PO_POSITION = 0x48; // Position (embedded, 72 bytes — starts at vtable)
private const int PO_MOVEMENT_MGR = 0xC4; // MovementManager*
// ── MovementStruct (0x64 = 100 bytes) ────────────────────────────────
private const int MS_SIZE = 0x64;
private const int MS_TYPE = 0x00; // uint MovementTypes::Type
private const int MS_MOTION = 0x04; // uint motion
private const int MS_OBJECT_ID = 0x08; // uint object_id
private const int MS_TOP_LEVEL_ID = 0x0C; // uint top_level_id
private const int MS_POS = 0x10; // Position (72 bytes, embedded)
private const int MS_RADIUS = 0x58; // float radius
private const int MS_HEIGHT = 0x5C; // float height
private const int MS_PARAMS = 0x60; // MovementParameters* (pointer)
// ── Position (0x48 = 72 bytes, embedded inside MovementStruct) ───────
// Relative to MS_POS:
// Frame layout: quaternion(16) → cache/matrix(36) → origin(12)
// (verified from binary: origin at Pos+0x3C, not Pos+0x18)
private const int POS_VTABLE = 0x00; // Position_vtbl*
private const int POS_OBJCELL_ID = 0x04; // uint32 landblock cell
private const int POS_QW = 0x08; // float Frame.qw (quaternion w)
private const int POS_QX = 0x0C; // float Frame.qx
private const int POS_QY = 0x10; // float Frame.qy
private const int POS_QZ = 0x14; // float Frame.qz
private const int POS_CACHE = 0x18; // float[9] (3×3 rotation matrix, 36 bytes)
private const int POS_ORIGIN_X = 0x3C; // float Frame.m_fOrigin.x
private const int POS_ORIGIN_Y = 0x40; // float Frame.m_fOrigin.y
private const int POS_ORIGIN_Z = 0x44; // float Frame.m_fOrigin.z
// ── MovementParameters (0x2C = 44 bytes) ────────────────────────────
private const int MP_SIZE = 0x2C;
private const int MP_VTABLE = 0x00; // MovementParameters_vtbl*
private const int MP_BITFIELD = 0x04; // uint flags
private const int MP_DIST_TO_OBJ = 0x08; // float distance_to_object
private const int MP_MIN_DIST = 0x0C; // float min_distance
private const int MP_HEADING = 0x10; // float desired_heading
private const int MP_SPEED = 0x14; // float speed
private const int MP_FAIL_DIST = 0x18; // float fail_distance
private const int MP_WR_THRESH = 0x1C; // float walk_run_threshhold
private const int MP_CONTEXT_ID = 0x20; // uint context_id
private const int MP_HOLD_KEY = 0x24; // int hold_key_to_apply
private const int MP_ACTION_STAMP = 0x28; // uint action_stamp
// ── MovementParameters defaults (from acclient.exe statics) ──────────
private const uint MP_DEFAULT_BITFIELD = 0x0001EE1F; // 0x10 bit = always autorun speed
private const float MP_DEFAULT_DIST_OBJ = 0.6f;
private const float MP_DEFAULT_MIN_DIST = 0.0f;
private const float MP_DEFAULT_FAIL_DIST = float.MaxValue;
private const float MP_DEFAULT_WR_THRESH = 0.0f; // 0 = never walk, always run
private const float MP_DEFAULT_SPEED = 1.0f;
// ═══════════════════════════════════════════════════════════════════════
// NATIVE DELEGATES
// ═══════════════════════════════════════════════════════════════════════
/// <summary>
/// MovementManager::PerformMovement(const MovementStruct*)
/// __thiscall — ECX = MovementManager*, stack arg = MovementStruct*
/// Returns 0 on success, non-zero error code on failure.
/// </summary>
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate uint DelPerformMovement(IntPtr thisPtr, IntPtr movementStruct);
/// <summary>
/// MovementManager::CancelMoveTo(unsigned int err)
/// __thiscall — ECX = MovementManager*, stack arg = error code
/// Error 0 = cancelled by user.
/// </summary>
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void DelCancelMoveTo(IntPtr thisPtr, uint err);
// ═══════════════════════════════════════════════════════════════════════
// CACHED STATE
// ═══════════════════════════════════════════════════════════════════════
private static DelPerformMovement _performMovement;
private static DelCancelMoveTo _cancelMoveTo;
private static IntPtr _smartboxStaticAddr; // Address of SmartBox::smartbox global
private static IntPtr _positionVtable; // Position::`vftable' address
private static IntPtr _movParamsVtable; // MovementParameters::`vftable' address
private static bool _initialized;
private static Action<string> _log;
public static bool IsInitialized => _initialized;
// ═══════════════════════════════════════════════════════════════════════
// INITIALIZATION (pattern scan)
// ═══════════════════════════════════════════════════════════════════════
/// <summary>
/// Scans acclient.exe at runtime for MovementManager functions and
/// struct vtable addresses. Call once at plugin startup, after
/// CombatActionHelper and MovementActionHelper have initialized.
///
/// smartboxAddr: if non-zero, use this as SmartBox::smartbox static
/// address instead of pattern scanning (pass UB's SmartBox.smartbox
/// pointer address for guaranteed correctness).
/// </summary>
public static void Initialize(Action<string> chatLog = null, IntPtr smartboxAddr = default)
{
_log = chatLog;
try
{
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("Tier2 scan FAILED: acclient.exe not found");
return;
}
int textRva = 0x1000;
int 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;
// ── 1. Find MovementManager::PerformMovement ─────────────────
// Unique epilogue: pop edi; mov eax, 71; pop esi; ret 4
// Hex: 5F B8 47 00 00 00 5E C2 04 00
byte[] pmEpilogue = { 0x5F, 0xB8, 0x47, 0x00, 0x00, 0x00, 0x5E, 0xC2, 0x04, 0x00 };
int pmEpiOff = -1;
// PerformMovement is in the MovementManager code region (~0x520000–0x530000)
// Narrow the search to avoid false positives in unrelated code.
for (int i = 0; i < text.Length - pmEpilogue.Length; i++)
{
if (!BytesMatch(text, i, pmEpilogue)) continue;
// Verify: the function should start with push esi; push edi; mov esi, ecx
// (56 57 8B F1) preceded by CC/90/C3 padding.
int funcOff = FindFuncStartBefore(text, i,
new byte[] { 0x56, 0x57, 0x8B, 0xF1 });
if (funcOff >= 0)
{
// Extra verify: function reads [esi+0x08] (physics_obj) then pushes 1
// Pattern at funcOff+4: 8B 4E 08 6A 01
if (funcOff + 9 < text.Length &&
text[funcOff + 4] == 0x8B &&
text[funcOff + 5] == 0x4E &&
text[funcOff + 6] == 0x08 &&
text[funcOff + 7] == 0x6A &&
text[funcOff + 8] == 0x01)
{
pmEpiOff = funcOff;
break;
}
}
}
if (pmEpiOff < 0)
{
Log("Tier2 scan FAILED: PerformMovement not found");
return;
}
int pmVA = textBaseVA + pmEpiOff;
Log($"PerformMovement at 0x{pmVA:X8}");
_performMovement = (DelPerformMovement)Marshal.GetDelegateForFunctionPointer(
new IntPtr(pmVA), typeof(DelPerformMovement));
// ── 2. Find CancelMoveTo ─────────────────────────────────────
// Immediately after PerformMovement's ret — small function:
// 8B 49 04 mov ecx, [ecx+4] (moveto_manager at MM+0x04)
// 85 C9 test ecx, ecx
// 74 XX jz skip
// E9 XX jmp MoveToManager::CancelMoveTo
// C2 04 00 ret 4
// Search forward from the epilogue for this pattern.
int cancelOff = -1;
int searchFrom = pmEpiOff + pmEpilogue.Length;
// Search up to 128 bytes past the epilogue — the switch jump table
// data sits between PerformMovement's ret and CancelMoveTo's start.
for (int i = searchFrom; i < Math.Min(searchFrom + 128, text.Length - 8); i++)
{
if (text[i] == 0x8B && text[i + 1] == 0x49 && text[i + 2] == 0x04 &&
text[i + 3] == 0x85 && text[i + 4] == 0xC9 && text[i + 5] == 0x74)
{
cancelOff = i;
break;
}
}
if (cancelOff < 0)
{
Log("Tier2 scan WARNING: CancelMoveTo not found (non-fatal)");
}
else
{
int cancelVA = textBaseVA + cancelOff;
Log($"CancelMoveTo at 0x{cancelVA:X8}");
_cancelMoveTo = (DelCancelMoveTo)Marshal.GetDelegateForFunctionPointer(
new IntPtr(cancelVA), typeof(DelCancelMoveTo));
}
// ── 3. Find SmartBox::smartbox static address ────────────────
if (smartboxAddr != IntPtr.Zero)
{
// Caller provided the address (e.g. from UB's AcClient.SmartBox)
_smartboxStaticAddr = smartboxAddr;
Log($"SmartBox::smartbox at 0x{_smartboxStaticAddr.ToInt32():X8} (provided by caller)");
}
else
{
// Fall back to pattern scan
_smartboxStaticAddr = FindSmartBoxStatic(text, textBaseVA, baseAddr.ToInt32());
if (_smartboxStaticAddr == IntPtr.Zero)
{
Log("Tier2 scan FAILED: SmartBox::smartbox static not found");
return;
}
Log($"SmartBox::smartbox at 0x{_smartboxStaticAddr.ToInt32():X8} (pattern scan)");
}
// ── 4. Find Position vtable ──────────────────────────────────
// CPhysicsObj movement functions init a stack Position with:
// C7 44 24 XX [vtable] ← .rdata pointer
// C7 44 24 XX 00 00 00 00 ← objcell_id = 0
// C7 44 24 XX 00 00 80 3F ← qw = 1.0f
// Search callers of PerformMovement for this pattern.
_positionVtable = FindPositionVtable(text, textBaseVA, pmVA);
if (_positionVtable == IntPtr.Zero)
{
Log("Tier2 scan FAILED: Position vtable not found");
return;
}
Log($"Position vtable at 0x{_positionVtable.ToInt32():X8}");
// ── 5. Find MovementParameters vtable ────────────────────────
// MovementParameters constructor writes vtable then speed = 1.0:
// C7 00 [vtable] ← mov [eax], vtable
// ...
// C7 40 14 00 00 80 3F ← mov [eax+0x14], 1.0f (speed)
_movParamsVtable = FindMovParamsVtable(text, textBaseVA);
if (_movParamsVtable == IntPtr.Zero)
{
Log("Tier2 scan FAILED: MovementParameters vtable not found");
return;
}
Log($"MovParams vtable at 0x{_movParamsVtable.ToInt32():X8}");
_initialized = true;
Log("Tier2MovementHelper initialized — all addresses found via pattern scan");
Tier2Log.StartSession();
Tier2Log.Log($"PerformMovement=0x{pmVA:X8} SmartBox=0x{_smartboxStaticAddr.ToInt32():X8} " +
$"PosVT=0x{_positionVtable.ToInt32():X8} MpVT=0x{_movParamsVtable.ToInt32():X8}");
}
catch (Exception ex)
{
_initialized = false;
Log("Tier2 init FAILED: " + ex.Message);
}
}
// ═══════════════════════════════════════════════════════════════════════
// PUBLIC API
// ═══════════════════════════════════════════════════════════════════════
/// <summary>
/// Tells the client's physics engine to walk/run to a world position.
/// The client handles all interpolation, heading changes, and speed
/// internally — no frame-by-frame steering required.
///
/// Parameters use AC's internal coordinate system:
/// objcell_id — landblock cell (e.g. 0xABCD0012 for outdoor cell)
/// x, y, z — local position within the cell (yards)
/// speed — movement speed multiplier (1.0 = normal)
/// distTo — stop this far from the target (yards, default 0.6)
///
/// Returns 0 on success, non-zero error code on failure.
/// </summary>
[HandleProcessCorruptedStateExceptions, SecurityCritical]
public static uint MoveToPosition(
uint objcell_id, float x, float y, float z,
float speed = 1.0f, float distTo = 0.5f, float walkRunThreshold = 15f)
{
if (!_initialized || _performMovement == null) return uint.MaxValue;
LogPointerChain(); // once — logs the full chain to file
IntPtr mm = GetMovementManager();
if (mm == IntPtr.Zero)
{
Tier2Log.Log("MoveToPosition: MovementManager is NULL — aborting");
return uint.MaxValue;
}
IntPtr msPtr = IntPtr.Zero;
IntPtr mpPtr = IntPtr.Zero;
try
{
msPtr = Marshal.AllocHGlobal(MS_SIZE);
mpPtr = Marshal.AllocHGlobal(MP_SIZE);
ZeroMemory(msPtr, MS_SIZE);
ZeroMemory(mpPtr, MP_SIZE);
// ── MovementParameters ────────────────────────────────────────
WriteMovementParams(mpPtr, speed, distTo, 0f, walkRunThreshold);
// ── MovementStruct ────────────────────────────────────────────
Marshal.WriteInt32(msPtr + MS_TYPE, (int)TYPE_MOVE_TO_POSITION);
WritePosition(msPtr + MS_POS, objcell_id, x, y, z, 1f, 0f, 0f, 0f);
Marshal.WriteIntPtr(msPtr + MS_PARAMS, mpPtr);
Tier2Log.Log($"MoveToPosition CALL: mm=0x{mm.ToInt32():X8} cell=0x{objcell_id:X8} " +
$"x={x:F2} y={y:F2} z={z:F2} speed={speed} distTo={distTo} wrTh={walkRunThreshold}");
uint result = _performMovement(mm, msPtr);
Tier2Log.Log($"MoveToPosition RETURNED: {result}");
return result;
}
catch (Exception ex)
{
Tier2Log.Log($"MoveToPosition EXCEPTION: {ex}");
Log("MoveToPosition failed: " + ex.Message);
return uint.MaxValue;
}
finally
{
if (msPtr != IntPtr.Zero) Marshal.FreeHGlobal(msPtr);
if (mpPtr != IntPtr.Zero) Marshal.FreeHGlobal(mpPtr);
}
}
/// <summary>
/// Tells the client's physics engine to approach a world object by ID.
/// The client tracks the object's position and adjusts the path.
/// </summary>
public static uint MoveToObject(
uint objectId, float speed = 1.0f, float distTo = 0.5f)
{
if (!_initialized || _performMovement == null) return uint.MaxValue;
IntPtr mm = GetMovementManager();
if (mm == IntPtr.Zero) return uint.MaxValue;
IntPtr msPtr = IntPtr.Zero;
IntPtr mpPtr = IntPtr.Zero;
try
{
msPtr = Marshal.AllocHGlobal(MS_SIZE);
mpPtr = Marshal.AllocHGlobal(MP_SIZE);
ZeroMemory(msPtr, MS_SIZE);
ZeroMemory(mpPtr, MP_SIZE);
WriteMovementParams(mpPtr, speed, distTo, 0f);
Marshal.WriteInt32(msPtr + MS_TYPE, (int)TYPE_MOVE_TO_OBJECT);
Marshal.WriteInt32(msPtr + MS_OBJECT_ID, (int)objectId);
WriteIdentityPosition(msPtr + MS_POS);
Marshal.WriteIntPtr(msPtr + MS_PARAMS, mpPtr);
return _performMovement(mm, msPtr);
}
catch (Exception ex)
{
Log("MoveToObject failed: " + ex.Message);
return uint.MaxValue;
}
finally
{
if (msPtr != IntPtr.Zero) Marshal.FreeHGlobal(msPtr);
if (mpPtr != IntPtr.Zero) Marshal.FreeHGlobal(mpPtr);
}
}
/// <summary>
/// Tells the client to turn the player to face a compass heading.
/// heading: 0 = North, 90 = East, 180 = South, 270 = West (degrees).
/// </summary>
public static uint TurnToHeading(float heading, float speed = 1.0f)
{
if (!_initialized || _performMovement == null) return uint.MaxValue;
IntPtr mm = GetMovementManager();
if (mm == IntPtr.Zero) return uint.MaxValue;
IntPtr msPtr = IntPtr.Zero;
IntPtr mpPtr = IntPtr.Zero;
try
{
msPtr = Marshal.AllocHGlobal(MS_SIZE);
mpPtr = Marshal.AllocHGlobal(MP_SIZE);
ZeroMemory(msPtr, MS_SIZE);
ZeroMemory(mpPtr, MP_SIZE);
// For TurnToHeading, the heading goes in MovementParameters.desired_heading
WriteMovementParams(mpPtr, speed, 0f, heading);
Marshal.WriteInt32(msPtr + MS_TYPE, (int)TYPE_TURN_TO_HEADING);
WriteIdentityPosition(msPtr + MS_POS);
Marshal.WriteIntPtr(msPtr + MS_PARAMS, mpPtr);
return _performMovement(mm, msPtr);
}
catch (Exception ex)
{
Log("TurnToHeading failed: " + ex.Message);
return uint.MaxValue;
}
finally
{
if (msPtr != IntPtr.Zero) Marshal.FreeHGlobal(msPtr);
if (mpPtr != IntPtr.Zero) Marshal.FreeHGlobal(mpPtr);
}
}
/// <summary>
/// Cancels any in-progress MoveToPosition / MoveToObject / TurnToHeading.
/// Safe to call if nothing is in progress.
/// </summary>
public static void CancelMoveTo()
{
if (!_initialized || _cancelMoveTo == null) return;
try
{
IntPtr mm = GetMovementManager();
if (mm != IntPtr.Zero)
_cancelMoveTo(mm, 0);
}
catch (Exception ex)
{
Log("CancelMoveTo failed: " + ex.Message);
}
}
/// <summary>
/// Returns true if the player has a MovementManager and its MoveToManager
/// is non-null (meaning some Tier 2 movement is potentially active).
/// </summary>
public static bool IsMovingTo()
{
try
{
IntPtr mm = GetMovementManager();
if (mm == IntPtr.Zero) return false;
// MoveToManager* at MovementManager+0x04
IntPtr mtm = Marshal.ReadIntPtr(mm + 0x04);
return mtm != IntPtr.Zero;
}
catch { return false; }
}
/// <summary>
/// Reads the player's current internal Position struct.
/// Uses Marshal.ReadInt32 + BitConverter (safe) instead of unsafe pointers
/// to avoid SEH crashes that bypass managed try/catch.
/// </summary>
[HandleProcessCorruptedStateExceptions, SecurityCritical]
public static bool GetPlayerPosition(
out uint objcell_id, out float x, out float y, out float z)
{
objcell_id = 0; x = y = z = 0;
try
{
IntPtr player = GetPlayerPtr();
if (player == IntPtr.Zero) return false;
IntPtr pos = new IntPtr(player.ToInt32() + PO_POSITION);
objcell_id = (uint)Marshal.ReadInt32(pos + POS_OBJCELL_ID);
x = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_X));
y = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_Y));
z = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_Z));
return true;
}
catch (Exception ex)
{
Tier2Log.Log($"GetPlayerPos EXCEPTION: {ex.Message}");
return false;
}
}
/// <summary>Reinterpret int32 bits as float (safe alternative to unsafe pointer cast).</summary>
private static float IntToFloat(int bits)
{
byte[] b = BitConverter.GetBytes(bits);
return BitConverter.ToSingle(b, 0);
}
/// <summary>
/// Returns the player's current landblock cell ID, or 0 if unavailable.
/// HPCSE attribute required: Marshal.ReadInt32 is unsafe under the hood —
/// AccessViolationException is a Corrupted State Exception on .NET 4.8
/// and bypasses normal try/catch without this attribute.
/// </summary>
[HandleProcessCorruptedStateExceptions, SecurityCritical]
public static uint GetPlayerCellId()
{
try
{
IntPtr sb = Marshal.ReadIntPtr(_smartboxStaticAddr);
if (sb == IntPtr.Zero) return 0;
IntPtr player = Marshal.ReadIntPtr(sb + SB_PLAYER);
if (player == IntPtr.Zero) return 0;
return (uint)Marshal.ReadInt32(new IntPtr(
player.ToInt32() + PO_POSITION + POS_OBJCELL_ID));
}
catch (Exception ex)
{
Tier2Log.Log($"GetPlayerCellId CRASHED: {ex.GetType().Name}: {ex.Message}");
return 0;
}
}
// ═══════════════════════════════════════════════════════════════════════
// POINTER CHAIN HELPERS
// ═══════════════════════════════════════════════════════════════════════
[HandleProcessCorruptedStateExceptions, SecurityCritical]
private static IntPtr GetSmartBox()
{
try
{
if (_smartboxStaticAddr == IntPtr.Zero) return IntPtr.Zero;
return Marshal.ReadIntPtr(_smartboxStaticAddr);
}
catch (Exception ex)
{
Tier2Log.Log($"GetSmartBox CRASHED: {ex.GetType().Name}");
return IntPtr.Zero;
}
}
[HandleProcessCorruptedStateExceptions, SecurityCritical]
private static IntPtr GetPlayerPtr()
{
try
{
IntPtr sb = GetSmartBox();
if (sb == IntPtr.Zero) return IntPtr.Zero;
return Marshal.ReadIntPtr(sb + SB_PLAYER);
}
catch (Exception ex)
{
Tier2Log.Log($"GetPlayerPtr CRASHED: {ex.GetType().Name}");
return IntPtr.Zero;
}
}
[HandleProcessCorruptedStateExceptions, SecurityCritical]
private static IntPtr GetMovementManager()
{
try
{
IntPtr player = GetPlayerPtr();
if (player == IntPtr.Zero) return IntPtr.Zero;
return Marshal.ReadIntPtr(player + PO_MOVEMENT_MGR);
}
catch (Exception ex)
{
Tier2Log.Log($"GetMovementManager CRASHED: {ex.GetType().Name}");
return IntPtr.Zero;
}
}
/// <summary>
/// Logs the full pointer chain once. Call before first movement.
/// </summary>
private static bool _chainLogged;
[HandleProcessCorruptedStateExceptions, SecurityCritical]
public static void LogPointerChain()
{
if (_chainLogged) return;
_chainLogged = true;
try
{
IntPtr sb = Marshal.ReadIntPtr(_smartboxStaticAddr);
IntPtr player = (sb != IntPtr.Zero) ? Marshal.ReadIntPtr(sb + SB_PLAYER) : IntPtr.Zero;
IntPtr mm = (player != IntPtr.Zero) ? Marshal.ReadIntPtr(player + PO_MOVEMENT_MGR) : IntPtr.Zero;
uint cell = 0; float px = 0, py = 0, pz = 0;
if (player != IntPtr.Zero)
{
IntPtr pos = new IntPtr(player.ToInt32() + PO_POSITION);
cell = (uint)Marshal.ReadInt32(pos + POS_OBJCELL_ID);
px = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_X));
py = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_Y));
pz = IntToFloat(Marshal.ReadInt32(pos + POS_ORIGIN_Z));
}
Tier2Log.Log($"CHAIN: [0x{_smartboxStaticAddr.ToInt32():X8}]→sb=0x{sb.ToInt32():X8} " +
$"[sb+0x{SB_PLAYER:X2}]→player=0x{player.ToInt32():X8} " +
$"[player+0x{PO_MOVEMENT_MGR:X2}]→mm=0x{mm.ToInt32():X8}");
Tier2Log.Log($"CHAIN: playerPos cell=0x{cell:X8} origin=({px:F2},{py:F2},{pz:F2})");
}
catch (Exception ex)
{
Tier2Log.Log($"CHAIN FAILED: {ex.GetType().Name}: {ex.Message}");
_chainLogged = false; // retry next time
}
}
// ═══════════════════════════════════════════════════════════════════════
// STRUCT WRITERS
// ═══════════════════════════════════════════════════════════════════════
/// <summary>
/// Fills a 44-byte MovementParameters at the given unmanaged address.
/// walkRunThreshold: distance in yards at which to switch from run to walk.
/// 0 = always run. Default AC value is 15.0.
/// </summary>
private static void WriteMovementParams(
IntPtr ptr, float speed, float distTo, float heading, float walkRunThreshold = 15f)
{
Marshal.WriteIntPtr(ptr + MP_VTABLE, _movParamsVtable);
WriteInt(ptr + MP_BITFIELD, MP_DEFAULT_BITFIELD);
WriteFloat(ptr + MP_DIST_TO_OBJ, distTo);
WriteFloat(ptr + MP_MIN_DIST, MP_DEFAULT_MIN_DIST);
WriteFloat(ptr + MP_HEADING, heading);
WriteFloat(ptr + MP_SPEED, speed);
WriteFloat(ptr + MP_FAIL_DIST, MP_DEFAULT_FAIL_DIST);
WriteFloat(ptr + MP_WR_THRESH, walkRunThreshold);
WriteInt(ptr + MP_CONTEXT_ID, 0);
WriteInt(ptr + MP_HOLD_KEY, 0); // 0 = let walk_run_threshold decide
WriteInt(ptr + MP_ACTION_STAMP, 0);
}
/// <summary>
/// Fills a 72-byte Position at the given unmanaged address.
/// Computes the Frame cache (3×3 rotation matrix from quaternion).
/// </summary>
private static void WritePosition(
IntPtr ptr, uint objcell_id,
float x, float y, float z,
float qw, float qx, float qy, float qz)
{
Marshal.WriteIntPtr(ptr + POS_VTABLE, _positionVtable);
WriteInt(ptr + POS_OBJCELL_ID, objcell_id);
WriteFloat(ptr + POS_QW, qw);
WriteFloat(ptr + POS_QX, qx);
WriteFloat(ptr + POS_QY, qy);
WriteFloat(ptr + POS_QZ, qz);
WriteFloat(ptr + POS_ORIGIN_X, x);
WriteFloat(ptr + POS_ORIGIN_Y, y);
WriteFloat(ptr + POS_ORIGIN_Z, z);
// Frame::cache — quaternion → 3×3 rotation matrix (row-major)
float xx = qx * qx, yy = qy * qy, zz = qz * qz;
float xy = qx * qy, xz = qx * qz, yz = qy * qz;
float wx = qw * qx, wy = qw * qy, wz = qw * qz;
IntPtr c = ptr + POS_CACHE;
WriteFloat(c + 0x00, 1f - 2f * (yy + zz)); // m00
WriteFloat(c + 0x04, 2f * (xy - wz)); // m01
WriteFloat(c + 0x08, 2f * (xz + wy)); // m02
WriteFloat(c + 0x0C, 2f * (xy + wz)); // m10
WriteFloat(c + 0x10, 1f - 2f * (xx + zz)); // m11
WriteFloat(c + 0x14, 2f * (yz - wx)); // m12
WriteFloat(c + 0x18, 2f * (xz - wy)); // m20
WriteFloat(c + 0x1C, 2f * (yz + wx)); // m21
WriteFloat(c + 0x20, 1f - 2f * (xx + yy)); // m22
}
/// <summary>
/// Writes an identity Position (objcell_id=0, identity quaternion).
/// </summary>
private static void WriteIdentityPosition(IntPtr ptr)
{
WritePosition(ptr, 0, 0f, 0f, 0f, 1f, 0f, 0f, 0f);
}
// ═══════════════════════════════════════════════════════════════════════
// PATTERN SCAN HELPERS
// ═══════════════════════════════════════════════════════════════════════
/// <summary>
/// Finds SmartBox::smartbox by looking for the Cleanup pattern:
/// A1 [addr] ; load smartbox
/// 85 C0 ; test eax, eax
/// 74 XX ; jz skip
/// ... ; vtable destructor call
/// C7 05 [addr] 00 00 00 00 ; store 0 to smartbox
/// C3 ; ret
/// </summary>
private static IntPtr FindSmartBoxStatic(byte[] text, int textBaseVA, int imageBase)
{
int dataLo = imageBase + 0x400000; // rough .data start
int dataHi = imageBase + 0x510000; // rough .data end
// Search for: C7 05 [addr] 00 00 00 00 C3
// where [addr] is also loaded with A1 [addr] within 30 bytes before
for (int i = 0; i < text.Length - 12; i++)
{
if (text[i] != 0xC7 || text[i + 1] != 0x05) continue;
int addr = BitConverter.ToInt32(text, i + 2);
if (addr < dataLo || addr > dataHi) continue;
// Check imm32 = 0 and next byte = C3 (ret)
if (BitConverter.ToInt32(text, i + 6) != 0) continue;
if (text[i + 10] != 0xC3) continue;
// Verify: A1 [same addr] appears within 40 bytes before
byte[] loadPat = new byte[5];
loadPat[0] = 0xA1;
BitConverter.GetBytes(addr).CopyTo(loadPat, 1);
for (int back = 5; back < 40; back++)
{
int j = i - back;
if (j < 0) break;
if (BytesMatch(text, j, loadPat))
{
// Also verify: 85 C0 (test eax,eax) appears after the load
for (int k = j + 5; k < j + 10 && k < text.Length - 1; k++)
{
if (text[k] == 0x85 && text[k + 1] == 0xC0)
{
// Extra verify: the load is near a vtable dtor call
// SmartBox::Cleanup does: lea ecx,[eax+4]; mov eax,[ecx];
// push 1; call [eax] — the push 1 is the destructor flag,
// distinguishing this from other cleanup patterns.
bool hasDtorCall = false;
for (int m = k; m < i - 2 && m < text.Length - 3; m++)
{
if (text[m] == 0x6A && text[m + 1] == 0x01 &&
text[m + 2] == 0xFF && text[m + 3] == 0x10)
{
hasDtorCall = true; // push 1; call [eax]
break;
}
}
if (hasDtorCall)
return new IntPtr(addr);
}
}
}
}
}
return IntPtr.Zero;
}
/// <summary>
/// Finds Position::`vftable' by scanning PerformMovement callers
/// for the stack-init pattern that writes a .rdata pointer followed
/// by objcell_id=0 then qw=1.0f.
/// </summary>
private static IntPtr FindPositionVtable(byte[] text, int textBaseVA, int pmVA)
{
int rdataLo = textBaseVA + 0x390000; // .rdata region
int rdataHi = rdataLo + 0x80000;
// Find callers of PerformMovement (E8 relative calls)
for (int i = 0; i < text.Length - 5; i++)
{
if (text[i] != 0xE8) continue;
int rel = BitConverter.ToInt32(text, i + 1);
int target = textBaseVA + i + 5 + rel;
if (target != pmVA) continue;
// Found a caller. Search backwards up to 300 bytes for:
// C7 44 24 XX [rdata_addr] (Position vtable)
// C7 44 24 YY 00 00 00 00 (objcell_id = 0)
// C7 44 24 ZZ 00 00 80 3F (qw = 1.0f)
int searchStart = Math.Max(0, i - 300);
for (int j = searchStart; j < i - 8; j++)
{
// Look for C7 44 24 XX followed by .rdata address
if (text[j] != 0xC7 || text[j + 1] != 0x44 || text[j + 2] != 0x24)
continue;
int val = BitConverter.ToInt32(text, j + 4);
if (val < rdataLo || val > rdataHi) continue;
// Check: within 16 bytes, there should be C7 44 24 XX 00 00 80 3F (qw=1.0)
for (int k = j + 8; k < Math.Min(j + 40, i); k++)
{
if (text[k] == 0xC7 && text[k + 1] == 0x44 && text[k + 2] == 0x24 &&
text[k + 4] == 0x00 && text[k + 5] == 0x00 &&
text[k + 6] == 0x80 && text[k + 7] == 0x3F)
{
return new IntPtr(val);
}
}
}
}
return IntPtr.Zero;
}
/// <summary>
/// Finds MovementParameters::`vftable' by searching for the constructor
/// that writes a .rdata vtable to [eax+0] then speed=1.0 to [eax+0x14]:
/// C7 00 [vtable] ← mov [eax], vtable
/// ... (field inits) ...
/// C7 40 14 00 00 80 3F ← mov [eax+0x14], 1.0f
/// </summary>
private static IntPtr FindMovParamsVtable(byte[] text, int textBaseVA)
{
int rdataLo = textBaseVA + 0x390000;
int rdataHi = rdataLo + 0x80000;
// Search for: C7 40 14 00 00 80 3F (speed = 1.0f at +0x14)
byte[] speedPat = { 0xC7, 0x40, 0x14, 0x00, 0x00, 0x80, 0x3F };
for (int i = 0; i < text.Length - speedPat.Length; i++)
{
if (!BytesMatch(text, i, speedPat)) continue;
// Walk backwards up to 40 bytes for C7 00 [rdata_addr]
for (int back = 4; back < 40; back++)
{
int j = i - back;
if (j < 0) break;
if (text[j] == 0xC7 && text[j + 1] == 0x00)
{
int val = BitConverter.ToInt32(text, j + 2);
if (val >= rdataLo && val <= rdataHi)
return new IntPtr(val);
}
}
}
return IntPtr.Zero;
}
/// <summary>
/// Walks backwards from an offset to find a function start.
/// The function must begin with the given prologue bytes, preceded
/// by CC/90/C3 alignment padding.
/// </summary>
private static int FindFuncStartBefore(byte[] data, int fromOffset, byte[] prologue)
{
for (int back = 1; back < 400; back++)
{
int pos = fromOffset - back;
if (pos < 1 || pos + prologue.Length > data.Length) continue;
if (!BytesMatch(data, pos, prologue)) continue;
byte prev = data[pos - 1];
if (prev == 0xCC || prev == 0x90 || prev == 0xC3)
return pos;
}
return -1;
}
// ═══════════════════════════════════════════════════════════════════════
// LOW-LEVEL HELPERS
// ═══════════════════════════════════════════════════════════════════════
private static bool BytesMatch(byte[] data, int offset, byte[] pattern)
{
if (offset + pattern.Length > data.Length) return false;
for (int i = 0; i < pattern.Length; i++)
if (data[offset + i] != pattern[i]) return false;
return true;
}
private static unsafe void WriteFloat(IntPtr addr, float value)
{
*(float*)addr.ToPointer() = value;
}
private static unsafe float ReadFloat(IntPtr addr)
{
return *(float*)addr.ToPointer();
}
private static void WriteInt(IntPtr addr, uint value)
{
Marshal.WriteInt32(addr, (int)value);
}
private static void ZeroMemory(IntPtr addr, int size)
{
byte[] zeros = new byte[size];
Marshal.Copy(zeros, 0, addr, size);
}
private static void Log(string msg)
{
try { _log?.Invoke($"[RynthAi] {msg}"); } catch { }
}
}
}

View file

@ -0,0 +1,163 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
namespace NexSuite.Plugins.RynthAi
{
public enum NavRouteType
{
Circular = 1,
Linear = 2,
Follow = 3,
Once = 4
}
public enum NavPointType
{
Point = 0,
Recall = 2,
Pause = 3,
Chat = 4,
PortalNPC = 6
}
public class NavPoint
{
public NavPointType Type { get; set; }
public double NS { get; set; }
public double EW { get; set; }
public double Z { get; set; }
public int SpellId { get; set; }
public int PauseTimeMs { get; set; }
public string ChatCommand { get; set; }
public string TargetName { get; set; }
public int ObjectClass { get; set; }
public bool IsTie { get; set; }
// PortalNPC extra coordinate blocks (exit/destination coords)
public double PortalExitNS { get; set; }
public double PortalExitEW { get; set; }
public double PortalExitZ { get; set; }
public double PortalLandNS { get; set; }
public double PortalLandEW { get; set; }
public double PortalLandZ { get; set; }
public override string ToString()
{
switch (Type)
{
// UI display converted to exact 3-decimal precision
case NavPointType.Point: return $"[Point] {NS:F3}, {EW:F3}";
case NavPointType.Recall:
{
string spellName = SpellDatabase.GetSpellName(SpellId);
return $"[Recall] {spellName} ({SpellId})";
}
case NavPointType.Pause: return $"[Pause] {PauseTimeMs / 1000.0}s";
case NavPointType.Chat: return $"[Chat] {ChatCommand}";
case NavPointType.PortalNPC: return $"[Portal] {TargetName}";
default: return $"[Unknown] {Type}";
}
}
}
public class VTankNavParser
{
public NavRouteType RouteType { get; set; }
public List<NavPoint> Points { get; set; } = new List<NavPoint>();
public static VTankNavParser Load(string filePath)
{
var route = new VTankNavParser();
string[] lines = File.ReadAllLines(filePath);
if (lines.Length < 3) return route;
if (!lines[0].Contains("uTank2 NAV 1.2"))
throw new Exception("Invalid or unsupported VTank .nav file format.");
route.RouteType = (NavRouteType)int.Parse(lines[1]);
int pointCount = int.Parse(lines[2]);
int idx = 3;
for (int i = 0; i < pointCount && idx < lines.Length; i++)
{
var pt = new NavPoint();
pt.Type = (NavPointType)int.Parse(lines[idx++]);
pt.EW = double.Parse(lines[idx++], CultureInfo.InvariantCulture); // First coord is EW
pt.NS = double.Parse(lines[idx++], CultureInfo.InvariantCulture); // Second coord is NS
pt.Z = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
idx++; // Skip the 0 spacer line
switch (pt.Type)
{
case NavPointType.Point: break;
case NavPointType.Recall: pt.SpellId = int.Parse(lines[idx++]); break;
case NavPointType.Pause: pt.PauseTimeMs = int.Parse(lines[idx++]); break;
case NavPointType.Chat: pt.ChatCommand = lines[idx++]; break;
case NavPointType.PortalNPC:
pt.TargetName = lines[idx++];
pt.ObjectClass = int.Parse(lines[idx++]);
pt.IsTie = bool.Parse(lines[idx++]);
// Two extra coordinate blocks (exit + landing) - also EW/NS/Z format
pt.PortalExitEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.PortalExitNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.PortalExitZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
idx++; // spacer
pt.PortalLandEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.PortalLandNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.PortalLandZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
idx++; // spacer
break;
}
route.Points.Add(pt);
}
return route;
}
public void Save(string filePath)
{
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath, false))
{
writer.WriteLine("uTank2 NAV 1.2");
writer.WriteLine((int)RouteType);
writer.WriteLine(Points.Count);
foreach (var pt in Points)
{
writer.WriteLine((int)pt.Type);
writer.WriteLine(pt.EW.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteLine(pt.NS.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteLine(pt.Z.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteLine("0");
switch (pt.Type)
{
case NavPointType.Recall: writer.WriteLine(pt.SpellId); break;
case NavPointType.Pause: writer.WriteLine(pt.PauseTimeMs); break;
case NavPointType.Chat: writer.WriteLine(pt.ChatCommand); break;
case NavPointType.PortalNPC:
writer.WriteLine(pt.TargetName);
writer.WriteLine(pt.ObjectClass);
writer.WriteLine(pt.IsTie.ToString());
writer.WriteLine(pt.PortalExitEW.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteLine(pt.PortalExitNS.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteLine(pt.PortalExitZ.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteLine("0");
writer.WriteLine(pt.PortalLandEW.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteLine(pt.PortalLandNS.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteLine(pt.PortalLandZ.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteLine("0");
break;
}
}
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
public class BlacklistManager
{
/// <summary>
/// Tracks consecutive failures for specific WorldObjects.
/// Incremented when an attack on a target produces no server feedback.
/// </summary>
private readonly Dictionary<int, int> _failureCounts = new Dictionary<int, int>();
/// <summary>
/// Tracks the expiration time for blacklisted targets.
/// Targets are temporarily ignored if they're stuck in walls or ghosts.
/// </summary>
private readonly Dictionary<int, DateTime> _blacklistExpirations = new Dictionary<int, DateTime>();
/// <summary>
/// Number of consecutive attack failures before a target is blacklisted.
/// Default: 3 attempts (adjustable for different difficulty settings).
/// </summary>
public int AttemptThreshold { get; set; } = 3;
/// <summary>
/// Duration in seconds that a target remains blacklisted after threshold is breached.
/// Default: 30 seconds (allows time for stuck/ghost detection to resolve).
/// </summary>
public int TimeoutSeconds { get; set; } = 30;
/// <summary>
/// Increments the failure count for a target.
/// Call this if an attack is launched but yields no server feedback (damage, XP, etc.).
/// If the failure count reaches the threshold, the target is automatically blacklisted.
/// </summary>
public void ReportFailure(int targetId)
{
if (!_failureCounts.ContainsKey(targetId))
_failureCounts[targetId] = 0;
_failureCounts[targetId]++;
// Log the failure for debugging
System.Diagnostics.Debug.WriteLine($"Target {targetId} failure count: {_failureCounts[targetId]}/{AttemptThreshold}");
// If the threshold is breached, blacklist the target
if (_failureCounts[targetId] >= AttemptThreshold)
{
BlacklistTarget(targetId);
}
}
/// <summary>
/// Immediately blacklists a target for the configured timeout duration.
/// </summary>
private void BlacklistTarget(int targetId)
{
DateTime expirationTime = DateTime.Now.AddSeconds(TimeoutSeconds);
_blacklistExpirations[targetId] = expirationTime;
System.Diagnostics.Debug.WriteLine($"Target {targetId} blacklisted until {expirationTime:HH:mm:ss}");
}
/// <summary>
/// Checks if a target should be ignored by the targeting system.
/// Returns true if the target is currently blacklisted (timeout not expired).
/// Returns false if the target is not blacklisted or if its timeout has expired.
/// </summary>
public bool IsBlacklisted(int targetId)
{
if (!_blacklistExpirations.TryGetValue(targetId, out var expiration))
return false; // Target not in blacklist
// Check if blacklist timeout has expired
if (DateTime.Now >= expiration)
{
// Timeout expired - remove from blacklist and allow re-evaluation
_blacklistExpirations.Remove(targetId);
_failureCounts.Remove(targetId);
System.Diagnostics.Debug.WriteLine($"Target {targetId} blacklist expired, re-evaluating");
return false;
}
// Target still blacklisted
return true;
}
/// <summary>
/// Clears the failure count and blacklist status for a target.
/// Call this when a target successfully takes damage or shows other server feedback.
/// This allows the target to be re-engaged if it becomes blocked again later.
/// </summary>
public void ClearFailure(int targetId)
{
_failureCounts.Remove(targetId);
_blacklistExpirations.Remove(targetId);
System.Diagnostics.Debug.WriteLine($"Target {targetId} failure cleared");
}
/// <summary>
/// Completely clears all blacklist and failure tracking data.
/// Useful when transitioning between combat zones or resetting the bot state.
/// </summary>
public void ClearAll()
{
_failureCounts.Clear();
_blacklistExpirations.Clear();
System.Diagnostics.Debug.WriteLine("All blacklist data cleared");
}
/// <summary>
/// Returns the number of currently blacklisted targets.
/// Useful for debugging and monitoring bot behavior.
/// </summary>
public int GetBlacklistCount()
{
int count = 0;
var expiredKeys = new List<int>();
foreach (var kvp in _blacklistExpirations)
{
if (DateTime.Now < kvp.Value)
{
count++;
}
else
{
expiredKeys.Add(kvp.Key);
}
}
// Clean up expired entries while we're here
foreach (var key in expiredKeys)
{
_blacklistExpirations.Remove(key);
_failureCounts.Remove(key);
}
return count;
}
}
}

View file

@ -0,0 +1,245 @@
using System;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Bounding volume for collision detection
/// Supports ray-volume intersection testing for raycasting
/// </summary>
public class BoundingVolume
{
public enum VolumeType
{
Sphere = 1,
Cylinder = 2,
Ellipsoid = 3,
Polygon = 4,
AxisAlignedBox = 5,
Torus = 6
}
public VolumeType Type { get; set; }
public Vector3 Center { get; set; } // X, Y, Z
public Vector3 Dimensions { get; set; } // Radius, Height, etc
public Vector3[] Vertices { get; set; } // For polygons
// Additional properties for geometry loading
public Vector3 Min { get; set; } // Minimum bounds
public Vector3 Max { get; set; } // Maximum bounds
public bool IsDoor { get; set; } // Whether this is a door (passable)
public BoundingVolume()
{
Center = new Vector3(0, 0, 0);
Dimensions = new Vector3(0, 0, 0);
Min = new Vector3(0, 0, 0);
Max = new Vector3(0, 0, 0);
IsDoor = false;
}
/// <summary>
/// Test if a ray intersects this volume
/// Returns true if collision detected
/// </summary>
public bool RayIntersect(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
try
{
switch (Type)
{
case VolumeType.Sphere:
return RayIntersectSphere(rayStart, rayDir, maxDist, out hitDist);
case VolumeType.Cylinder:
return RayIntersectCylinder(rayStart, rayDir, maxDist, out hitDist);
case VolumeType.AxisAlignedBox:
return RayIntersectAABB(rayStart, rayDir, maxDist, out hitDist);
case VolumeType.Polygon:
return RayIntersectPolygon(rayStart, rayDir, maxDist, out hitDist);
default:
return false;
}
}
catch
{
return false;
}
}
/// <summary>
/// Overload to accept float arrays for backwards compatibility
/// </summary>
public bool RayIntersect(float[] rayStart, float[] rayDir, float maxDist, out float hitDist)
{
return RayIntersect(
Vector3.FromArray(rayStart),
Vector3.FromArray(rayDir),
maxDist,
out hitDist
);
}
/// <summary>
/// Ray-Sphere intersection
/// </summary>
private bool RayIntersectSphere(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
Vector3 oc = rayStart - Center;
float a = Vector3.Dot(rayDir, rayDir);
float b = 2.0f * Vector3.Dot(oc, rayDir);
float c = Vector3.Dot(oc, oc) - (Dimensions.X * Dimensions.X);
float discriminant = b * b - 4 * a * c;
if (discriminant < 0)
return false;
float sqrt_disc = (float)Math.Sqrt(discriminant);
float t1 = (-b - sqrt_disc) / (2 * a);
float t2 = (-b + sqrt_disc) / (2 * a);
if (t1 > 0 && t1 < maxDist)
{
hitDist = t1;
return true;
}
// Ray starts inside sphere (t1 < 0, t2 > 0)
if (t1 <= 0 && t2 > 0 && t2 < maxDist)
{
hitDist = 0;
return true;
}
return false;
}
/// <summary>
/// Ray-Cylinder intersection
/// </summary>
private bool RayIntersectCylinder(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
return false;
}
/// <summary>
/// Ray-AABB intersection
/// </summary>
private bool RayIntersectAABB(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
float tmin = 0, tmax = maxDist;
for (int i = 0; i < 3; i++)
{
float rayStartCoord = i == 0 ? rayStart.X : (i == 1 ? rayStart.Y : rayStart.Z);
float rayDirCoord = i == 0 ? rayDir.X : (i == 1 ? rayDir.Y : rayDir.Z);
float minCoord = i == 0 ? Min.X : (i == 1 ? Min.Y : Min.Z);
float maxCoord = i == 0 ? Max.X : (i == 1 ? Max.Y : Max.Z);
if (Math.Abs(rayDirCoord) < 0.00001f)
{
if (rayStartCoord < minCoord || rayStartCoord > maxCoord)
return false;
}
else
{
float t1 = (minCoord - rayStartCoord) / rayDirCoord;
float t2 = (maxCoord - rayStartCoord) / rayDirCoord;
if (t1 > t2)
{
float temp = t1;
t1 = t2;
t2 = temp;
}
tmin = Math.Max(tmin, t1);
tmax = Math.Min(tmax, t2);
if (tmin > tmax)
return false;
}
}
if (tmin > 0 && tmin < maxDist)
{
hitDist = tmin;
return true;
}
// Ray starts inside the box (tmin <= 0 but tmax > 0)
// This means the player is inside/overlapping the obstacle
if (tmin <= 0 && tmax > 0 && tmax < maxDist)
{
hitDist = 0;
return true;
}
return false;
}
/// <summary>
/// Ray-Polygon intersection
/// </summary>
private bool RayIntersectPolygon(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
if (Vertices == null || Vertices.Length < 3)
return false;
for (int i = 0; i < Vertices.Length - 2; i++)
{
if (RayIntersectTriangle(rayStart, rayDir, Vertices[0], Vertices[i + 1], Vertices[i + 2], out float t))
{
if (t >= 0 && t < maxDist && t < hitDist)
{
hitDist = t;
return true;
}
}
}
return false;
}
/// <summary>
/// Ray-Triangle intersection (Möller-Trumbore algorithm)
/// </summary>
private bool RayIntersectTriangle(Vector3 rayStart, Vector3 rayDir, Vector3 v0, Vector3 v1, Vector3 v2, out float t)
{
t = float.MaxValue;
const float EPSILON = 0.0000001f;
Vector3 edge1 = v1 - v0;
Vector3 edge2 = v2 - v0;
Vector3 h = Vector3.Cross(rayDir, edge2);
float a = Vector3.Dot(edge1, h);
if (a > -EPSILON && a < EPSILON)
return false;
float f = 1.0f / a;
Vector3 s = rayStart - v0;
float u = f * Vector3.Dot(s, h);
if (u < 0 || u > 1)
return false;
Vector3 q = Vector3.Cross(s, edge1);
float v = f * Vector3.Dot(rayDir, q);
if (v < 0 || u + v > 1)
return false;
t = f * Vector3.Dot(edge2, q);
return t >= 0;
}
}
}

View file

@ -0,0 +1,321 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// AC .dat file reader — ported directly from ACEmulator's DatLoader.
///
/// Key format details (from ACE source):
/// - Header at file offset 0x140
/// - Block chain: FIRST 4 bytes of each block = next block address (byte offset)
/// Remaining (BlockSize - 4) bytes = data
/// - B-tree node (DatDirectoryHeader): 62 branches, entry count, 61 entries × 24 bytes = 1716 total
/// - All pointers (BTree root, chain pointers, file offsets) are byte offsets
/// </summary>
public class DatDatabase : IDisposable
{
private FileStream _stream;
private readonly object _lock = new object();
private const uint DAT_HEADER_OFFSET = 0x140;
// B-tree geometry (from ACE DatDirectoryHeader.cs):
// 0x3E (62) branches, 0x3D (61) max entries, each entry = 6 × uint32 = 24 bytes
// ObjectSize = (4 * 62) + 4 + (24 * 61) = 248 + 4 + 1464 = 1716
private const int BTREE_BRANCH_COUNT = 0x3E; // 62
private const int BTREE_MAX_ENTRIES = 0x3D; // 61
private const int BTREE_ENTRY_SIZE = 24; // 6 × uint32
private const int BTREE_NODE_SIZE = (4 * BTREE_BRANCH_COUNT) + 4 + (BTREE_ENTRY_SIZE * BTREE_MAX_ENTRIES); // 1716
// Header fields
public uint FileType { get; private set; }
public uint BlockSize { get; private set; }
public uint FileSize { get; private set; }
public uint DataSet { get; private set; }
public uint BTreeRoot { get; private set; } // Byte offset
public bool IsLoaded { get; private set; }
public string FilePath { get; private set; }
public int RecordCount { get; private set; }
// All files indexed by ObjectId (populated during Open)
private readonly Dictionary<uint, DatBTreeEntry> _allFiles = new Dictionary<uint, DatBTreeEntry>();
public List<string> DiagLog { get; } = new List<string>();
public bool Open(string path)
{
try
{
if (!File.Exists(path))
{
Log($"File not found: {path}");
return false;
}
FilePath = path;
_stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Log($"File: {Path.GetFileName(path)}, Size: {_stream.Length:N0} bytes");
if (!ReadHeader())
{
Close();
return false;
}
// Read the entire B-tree directory and index all files
ReadDirectory(BTreeRoot);
RecordCount = _allFiles.Count;
IsLoaded = true;
Log($"SUCCESS: {RecordCount} files indexed, BlockSize={BlockSize}, Root=0x{BTreeRoot:X8}");
return true;
}
catch (Exception ex)
{
Log($"Error: {ex.Message}");
Close();
return false;
}
}
/// <summary>
/// Reads the dat header from offset 0x140.
/// Format matches ACE's DatDatabaseHeader.Unpack().
/// </summary>
private bool ReadHeader()
{
if (_stream.Length < DAT_HEADER_OFFSET + 64)
{
Log("File too small");
return false;
}
_stream.Seek(DAT_HEADER_OFFSET, SeekOrigin.Begin);
using (var reader = new BinaryReader(_stream, System.Text.Encoding.Default, true))
{
FileType = reader.ReadUInt32();
BlockSize = reader.ReadUInt32();
FileSize = reader.ReadUInt32();
DataSet = reader.ReadUInt32();
uint dataSubset = reader.ReadUInt32();
uint freeHead = reader.ReadUInt32();
uint freeTail = reader.ReadUInt32();
uint freeCount = reader.ReadUInt32();
BTreeRoot = reader.ReadUInt32();
}
Log($"FileType=0x{FileType:X8}, BlockSize={BlockSize}, DataSet={DataSet}, BTree=0x{BTreeRoot:X8}");
if (BlockSize == 0 || BTreeRoot == 0 || BTreeRoot >= (uint)_stream.Length)
{
Log("Invalid header values");
return false;
}
return true;
}
/// <summary>
/// Reads data from the dat file following the block chain.
/// Matches ACE's DatReader.ReadDat() exactly.
///
/// Block format:
/// [4 bytes: next block address] [BlockSize - 4 bytes: data]
///
/// The FIRST 4 bytes of each block are the chain pointer (next block address).
/// If 0, this is the last block.
/// </summary>
private byte[] ReadDatData(uint offset, int size)
{
if (offset + BlockSize > (uint)_stream.Length || size <= 0)
return null;
byte[] buffer = new byte[size];
_stream.Seek(offset, SeekOrigin.Begin);
// Read first 4 bytes = next block address
byte[] addrBuf = new byte[4];
_stream.Read(addrBuf, 0, 4);
uint nextAddress = BitConverter.ToUInt32(addrBuf, 0);
int bufferOffset = 0;
int remaining = size;
while (remaining > 0)
{
if (nextAddress == 0)
{
// Last block — read remaining data directly
int toRead = Math.Min(remaining, (int)(_stream.Length - _stream.Position));
if (toRead <= 0) break;
_stream.Read(buffer, bufferOffset, toRead);
remaining = 0;
}
else
{
// Read data portion of this block (BlockSize - 4 bytes)
int dataInBlock = (int)BlockSize - 4;
int toRead = Math.Min(dataInBlock, remaining);
_stream.Read(buffer, bufferOffset, toRead);
bufferOffset += toRead;
remaining -= toRead;
if (remaining > 0)
{
// Follow chain to next block
if (nextAddress >= (uint)_stream.Length) break;
_stream.Seek(nextAddress, SeekOrigin.Begin);
// Read next block's chain pointer
_stream.Read(addrBuf, 0, 4);
nextAddress = BitConverter.ToUInt32(addrBuf, 0);
}
}
}
return buffer;
}
/// <summary>
/// Recursively reads the B-tree directory and indexes all files.
/// Matches ACE's DatDirectory.Read() + AddFilesToList().
/// </summary>
private void ReadDirectory(uint sectorOffset)
{
if (sectorOffset == 0 || sectorOffset >= (uint)_stream.Length)
return;
// Read the directory header (B-tree node)
byte[] nodeData;
lock (_lock)
{
nodeData = ReadDatData(sectorOffset, BTREE_NODE_SIZE);
}
if (nodeData == null || nodeData.Length < BTREE_NODE_SIZE)
return;
// Parse branches (62 × uint32)
uint[] branches = new uint[BTREE_BRANCH_COUNT];
for (int i = 0; i < BTREE_BRANCH_COUNT; i++)
branches[i] = BitConverter.ToUInt32(nodeData, i * 4);
// Parse entry count
int countOffset = BTREE_BRANCH_COUNT * 4; // 248
uint entryCount = BitConverter.ToUInt32(nodeData, countOffset);
if (entryCount > BTREE_MAX_ENTRIES)
return; // Invalid node
// Parse entries
int entriesOffset = countOffset + 4; // 252
var entries = new DatBTreeEntry[entryCount];
for (int i = 0; i < entryCount; i++)
{
int eOff = entriesOffset + i * BTREE_ENTRY_SIZE;
entries[i] = new DatBTreeEntry
{
BitFlags = BitConverter.ToUInt32(nodeData, eOff),
ObjectId = BitConverter.ToUInt32(nodeData, eOff + 4),
FileOffset = BitConverter.ToUInt32(nodeData, eOff + 8),
FileSize = BitConverter.ToUInt32(nodeData, eOff + 12)
};
}
// Recurse into child directories (if branches[0] != 0, node has children)
if (branches[0] != 0)
{
for (int i = 0; i < entryCount + 1 && i < BTREE_BRANCH_COUNT; i++)
{
if (branches[i] != 0)
ReadDirectory(branches[i]);
}
}
// Add entries to the file index
for (int i = 0; i < entryCount; i++)
{
if (entries[i].ObjectId != 0)
_allFiles[entries[i].ObjectId] = entries[i];
}
}
/// <summary>
/// Finds a file by ID. O(1) lookup from the pre-built index.
/// </summary>
public DatBTreeEntry FindFile(uint fileId)
{
if (!IsLoaded) return null;
_allFiles.TryGetValue(fileId, out var entry);
return entry;
}
/// <summary>
/// Reads file data for a given entry.
/// </summary>
public byte[] ReadFileData(DatBTreeEntry entry)
{
if (!IsLoaded || entry == null || entry.FileSize == 0 || _stream == null)
return null;
lock (_lock)
{
return ReadDatData(entry.FileOffset, (int)entry.FileSize);
}
}
public byte[] GetFileData(uint fileId)
{
var entry = FindFile(fileId);
return entry != null ? ReadFileData(entry) : null;
}
/// <summary>
/// Returns sample file IDs from the index for diagnostics.
/// </summary>
public List<uint> GetSampleIds(int maxCount = 20)
{
var ids = new List<uint>();
foreach (var kvp in _allFiles)
{
ids.Add(kvp.Key);
if (ids.Count >= maxCount) break;
}
return ids;
}
public void Close()
{
_stream?.Dispose();
_stream = null;
IsLoaded = false;
_allFiles.Clear();
}
public void Dispose() { Close(); }
private void Log(string msg)
{
string line = $"[DatDB] {msg}";
System.Diagnostics.Debug.WriteLine(line);
if (DiagLog.Count < 100) DiagLog.Add(line);
}
}
public class DatBTreeEntry
{
public uint BitFlags;
public uint ObjectId;
public uint FileOffset; // Byte offset into file
public uint FileSize;
}
}

View file

@ -0,0 +1,658 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Extracts dungeon wall geometry from cell.dat Environment files for raycasting.
///
/// Pipeline:
/// EnvCell (0xXXYY01nn) → EnvironmentId (0x0Dxxxx) + CellStructure index
/// Environment (0x0Dxxxx) → CellStruct at index → Vertices + Polygons
/// Transform polygon vertices by cell position → BoundingVolumes for raycasting
///
/// Binary formats (from ACE source):
/// SWVertex: ushort numUVs, float3 Origin, float3 Normal, Vec2Duv[numUVs]
/// CVertexArray: int32 type=1, uint32 count, (ushort key + SWVertex)[count]
/// Polygon: byte numPts, byte stippling, int32 sidesType, short posSurf, short negSurf,
/// short[numPts] vertexIds, byte[numPts] posUV (if !NoPos), byte[numPts] negUV (if clockwise+!NoNeg)
/// CellStruct: uint32 numPolygons, uint32 numPhysicsPolygons, uint32 numPortals,
/// CVertexArray, Dictionary{ushort,Polygon}[numPolygons], ...
/// </summary>
public class DungeonLOS
{
private DatDatabase _portalDat;
private DatDatabase _cellDat;
// Cache: EnvironmentId → parsed CellStruct geometry per structure index
private readonly Dictionary<uint, Dictionary<uint, CellGeometry>> _envCache =
new Dictionary<uint, Dictionary<uint, CellGeometry>>();
// Cache: landblock → dungeon wall volumes
private readonly Dictionary<uint, List<BoundingVolume>> _wallCache =
new Dictionary<uint, List<BoundingVolume>>();
private const int MAX_ENV_CACHE = 50;
private const int MAX_WALL_CACHE = 20;
public void Initialize(DatDatabase portalDat, DatDatabase cellDat)
{
_portalDat = portalDat;
_cellDat = cellDat;
}
/// <summary>
/// Gets dungeon wall collision volumes for a landblock.
/// Returns empty list for outdoor-only landblocks.
/// </summary>
public List<BoundingVolume> GetDungeonWalls(uint landblockKey)
{
if (_wallCache.TryGetValue(landblockKey, out var cached))
return cached;
var walls = LoadDungeonWalls(landblockKey);
if (_wallCache.Count >= MAX_WALL_CACHE)
{
foreach (var key in _wallCache.Keys) { _wallCache.Remove(key); break; }
}
_wallCache[landblockKey] = walls;
return walls;
}
private List<BoundingVolume> LoadDungeonWalls(uint landblockKey)
{
var volumes = new List<BoundingVolume>();
if (_cellDat == null || _portalDat == null) return volumes;
uint baseId = landblockKey << 16;
float globalOffsetX = ((landblockKey >> 8) & 0xFF) * 192.0f;
float globalOffsetY = (landblockKey & 0xFF) * 192.0f;
int consecutiveMisses = 0;
for (uint cellNum = 0x0100; cellNum <= 0xFFFD; cellNum++)
{
uint cellId = baseId | cellNum;
byte[] cellData = _cellDat.GetFileData(cellId);
if (cellData == null)
{
consecutiveMisses++;
if (consecutiveMisses > 10) break;
continue;
}
consecutiveMisses = 0;
if (cellData.Length < 20) continue;
try
{
var envCell = ParseEnvCellHeader(cellData);
if (envCell == null) continue;
var cellGeo = GetCellGeometry(envCell.EnvironmentId, envCell.CellStructureIndex);
if (cellGeo == null || cellGeo.Polygons.Count == 0) continue;
foreach (var poly in cellGeo.Polygons)
{
if (poly.Vertices.Count < 3) continue;
// Transform vertices to world space
var worldVerts = new List<Vector3>();
foreach (var localVert in poly.Vertices)
worldVerts.Add(TransformVertex(localVert, envCell, globalOffsetX, globalOffsetY));
// Compute AABB from all vertices of the polygon
var min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
var max = new Vector3(float.MinValue, float.MinValue, float.MinValue);
foreach (var wv in worldVerts)
{
min = Vector3.Min(min, wv);
max = Vector3.Max(max, wv);
}
var size = max - min;
if (size.X < 0.01f && size.Y < 0.01f && size.Z < 0.01f) continue;
// Thicken walls to seal corner gaps. Where two perpendicular walls meet,
// we may be missing one wall's geometry (unparsed CellStruct).
// 0.5 yards ensures the existing walls overlap at corners.
// Portal polygons are excluded so doorways stay open.
// 1.0 yard skin on thin axes — creates 2 yard total thickness.
// Seals corner jut-outs where perpendicular walls meet.
// Portal polygons are excluded so doorways stay open.
float wallSkin = 0.5f;
if (size.X < wallSkin) { min.X -= wallSkin; max.X += wallSkin; }
if (size.Y < wallSkin) { min.Y -= wallSkin; max.Y += wallSkin; }
volumes.Add(new BoundingVolume
{
Type = BoundingVolume.VolumeType.AxisAlignedBox,
Center = (min + max) * 0.5f,
Dimensions = max - min,
Min = min,
Max = max,
IsDoor = false
});
}
}
catch { }
}
if (volumes.Count > 0)
Log($"Landblock 0x{landblockKey:X4}: {volumes.Count} dungeon wall volumes");
return volumes;
}
private Vector3 TransformVertex(Vector3 local, EnvCellHeader cell, float gx, float gy)
{
Vector3 rotated = RotateByQuat(local, cell.RotW, cell.RotX, cell.RotY, cell.RotZ);
return new Vector3(
rotated.X + cell.PosX + gx,
rotated.Y + cell.PosY + gy,
rotated.Z + cell.PosZ
);
}
private Vector3 RotateByQuat(Vector3 v, float qw, float qx, float qy, float qz)
{
float cx = qy * v.Z - qz * v.Y;
float cy = qz * v.X - qx * v.Z;
float cz = qx * v.Y - qy * v.X;
float cx2 = qy * cz - qz * cy;
float cy2 = qz * cx - qx * cz;
float cz2 = qx * cy - qy * cx;
return new Vector3(
v.X + 2f * (qw * cx + cx2),
v.Y + 2f * (qw * cy + cy2),
v.Z + 2f * (qw * cz + cz2)
);
}
// ===================================================================
// EnvCell header parsing
// ===================================================================
private class EnvCellHeader
{
public uint EnvironmentId;
public uint CellStructureIndex;
public float PosX, PosY, PosZ;
public float RotW, RotX, RotY, RotZ;
}
private EnvCellHeader ParseEnvCellHeader(byte[] data)
{
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
uint id = reader.ReadUInt32();
uint flags = reader.ReadUInt32();
reader.ReadUInt32(); // duplicate CellId
byte numSurfaces = reader.ReadByte();
byte numPortals = reader.ReadByte();
ushort numVisibleCells = reader.ReadUInt16();
ms.Seek(numSurfaces * 2, SeekOrigin.Current);
ushort envIdShort = reader.ReadUInt16();
ushort cellStructure = reader.ReadUInt16();
return new EnvCellHeader
{
EnvironmentId = 0x0D000000u | envIdShort,
CellStructureIndex = cellStructure,
PosX = reader.ReadSingle(),
PosY = reader.ReadSingle(),
PosZ = reader.ReadSingle(),
RotW = reader.ReadSingle(),
RotX = reader.ReadSingle(),
RotY = reader.ReadSingle(),
RotZ = reader.ReadSingle()
};
}
}
catch { return null; }
}
// ===================================================================
// Environment + CellStruct parsing
// ===================================================================
private class CellGeometry
{
public List<CellPolygon> Polygons = new List<CellPolygon>();
}
private class CellPolygon
{
public List<Vector3> Vertices = new List<Vector3>();
}
private CellGeometry GetCellGeometry(uint environmentId, uint cellStructIndex)
{
if (_envCache.TryGetValue(environmentId, out var envCells))
{
if (envCells.TryGetValue(cellStructIndex, out var cached))
return cached;
}
byte[] envData = _portalDat.GetFileData(environmentId);
if (envData == null || envData.Length < 8) return null;
if (envCells == null)
{
envCells = ParseEnvironment(envData);
if (_envCache.Count >= MAX_ENV_CACHE)
{
foreach (var key in _envCache.Keys) { _envCache.Remove(key); break; }
}
_envCache[environmentId] = envCells;
}
envCells.TryGetValue(cellStructIndex, out var result);
return result;
}
private Dictionary<uint, CellGeometry> ParseEnvironment(byte[] data)
{
var result = new Dictionary<uint, CellGeometry>();
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
uint id = reader.ReadUInt32();
// Dictionary<uint, CellStruct>
uint numCells = reader.ReadUInt32();
if (numCells > 200) return result;
for (uint i = 0; i < numCells; i++)
{
if (ms.Position + 4 > ms.Length) break;
uint key = reader.ReadUInt32();
var geo = ParseCellStruct(reader, ms);
if (geo != null)
result[key] = geo;
else
{
Log($"Environment 0x{id:X8}: failed parsing CellStruct {i} (key={key}), stopping");
break; // Stream position unknown — can't continue
}
}
}
}
catch (Exception ex)
{
Log($"Environment parse error: {ex.Message}");
}
if (result.Count > 0)
Log($"Environment: parsed {result.Count} CellStructs successfully");
return result;
}
/// <summary>
/// Parses CellStruct: vertices + rendering polygons + portal indices.
/// NOW ALSO SKIPS BSP trees so we can continue to the next CellStruct.
/// </summary>
private CellGeometry ParseCellStruct(BinaryReader reader, MemoryStream ms)
{
var geo = new CellGeometry();
try
{
uint numPolygons = reader.ReadUInt32();
uint numPhysicsPolygons = reader.ReadUInt32();
uint numPortals = reader.ReadUInt32();
if (numPolygons > 5000 || numPhysicsPolygons > 5000) return null;
var vertices = ParseVertexArray(reader, ms);
if (vertices == null) return null;
var polygons = ParsePolygons(reader, ms, numPolygons);
if (polygons == null) return null;
// Read portal polygon indices
var portalIndices = new HashSet<ushort>();
for (uint p = 0; p < numPortals && ms.Position + 2 <= ms.Length; p++)
portalIndices.Add(reader.ReadUInt16());
// Align to 4-byte boundary
long aligned = (ms.Position + 3) & ~3L;
if (aligned <= ms.Length) ms.Position = aligned;
// BUILD polygon geometry NOW, before BSP skip attempt.
// If BSP skip fails we still have the wall data.
for (int i = 0; i < polygons.Count; i++)
{
var poly = polygons[i];
if (portalIndices.Contains(poly.Key)) continue;
if (poly.VertexIds == null || poly.VertexIds.Count < 3) continue;
var cellPoly = new CellPolygon();
foreach (var vid in poly.VertexIds)
{
if (vertices.ContainsKey(vid))
cellPoly.Vertices.Add(vertices[vid]);
}
if (cellPoly.Vertices.Count >= 3)
geo.Polygons.Add(cellPoly);
}
// Now attempt to skip BSP trees so ParseEnvironment can read the next CellStruct.
// If this fails, we still have this CellStruct's geometry — we just can't parse further.
bool canContinue = true;
// Skip CellBSP
if (!SkipBSPTree(reader, ms, BSPTreeType.Cell))
canContinue = false;
// Skip PhysicsPolygons
if (canContinue && !SkipPolygons(reader, ms, numPhysicsPolygons))
canContinue = false;
// Skip PhysicsBSP
if (canContinue && !SkipBSPTree(reader, ms, BSPTreeType.Physics))
canContinue = false;
// Skip optional DrawingBSP
if (canContinue && ms.Position + 4 <= ms.Length)
{
uint hasDrawingBSP = reader.ReadUInt32();
if (hasDrawingBSP != 0)
{
if (!SkipBSPTree(reader, ms, BSPTreeType.Drawing))
canContinue = false;
}
}
// Final alignment
if (canContinue)
{
aligned = (ms.Position + 3) & ~3L;
if (aligned <= ms.Length) ms.Position = aligned;
}
// Return geometry. If canContinue is false, ParseEnvironment will break
// at the next iteration (stream position wrong), but we keep this CellStruct's data.
return geo;
}
catch
{
return geo.Polygons.Count > 0 ? geo : null;
}
}
// ===================================================================
// BSP Tree Skipping — matches ACE BSPNode/BSPLeaf exactly
// ===================================================================
private enum BSPTreeType { Cell, Physics, Drawing }
// ACE's uint32 constants for BSP node types (read as LE uint32, stored reversed in file)
private const uint BSP_PORT = 0x504F5254;
private const uint BSP_LEAF = 0x4C454146;
private const uint BSP_BPnn = 0x42506E6E;
private const uint BSP_BPIn = 0x4250496E;
private const uint BSP_BpIN = 0x4270494E;
private const uint BSP_BpnN = 0x42706E4E;
private const uint BSP_BPIN = 0x4250494E;
private const uint BSP_BPnN = 0x42506E4E;
private bool SkipBSPTree(BinaryReader reader, MemoryStream ms, BSPTreeType treeType)
{
return SkipBSPNode(reader, ms, treeType);
}
private bool SkipBSPNode(BinaryReader reader, MemoryStream ms, BSPTreeType treeType)
{
if (ms.Position + 4 > ms.Length) return false;
uint typeTag = reader.ReadUInt32();
if (typeTag == BSP_LEAF)
{
return SkipBSPLeaf(reader, ms, treeType);
}
if (typeTag == BSP_PORT)
{
// Portal node — same as leaf for our purposes
return SkipBSPLeaf(reader, ms, treeType);
}
// Internal node: read splitting plane (float3 normal + float dist = 16 bytes)
if (ms.Position + 16 > ms.Length) return false;
ms.Seek(16, SeekOrigin.Current);
// Read children based on type — matches ACE's switch exactly
switch (typeTag)
{
case BSP_BPnn:
case BSP_BPIn:
// Pos child only
if (!SkipBSPNode(reader, ms, treeType)) return false;
break;
case BSP_BpIN:
case BSP_BpnN:
// Neg child only
if (!SkipBSPNode(reader, ms, treeType)) return false;
break;
case BSP_BPIN:
case BSP_BPnN:
// Both children: Pos then Neg
if (!SkipBSPNode(reader, ms, treeType)) return false;
if (!SkipBSPNode(reader, ms, treeType)) return false;
break;
default:
return false; // Unknown type
}
// Cell BSP internal nodes have NO sphere — done
if (treeType == BSPTreeType.Cell)
return true;
// Physics and Drawing: read Sphere (float3 center + float radius = 16 bytes)
if (ms.Position + 16 > ms.Length) return false;
ms.Seek(16, SeekOrigin.Current);
// Physics: done after sphere
if (treeType == BSPTreeType.Physics)
return true;
// Drawing: also read InPolys (uint32 count + ushort[count])
if (ms.Position + 4 > ms.Length) return false;
uint numPolys = reader.ReadUInt32();
if (numPolys > 100000) return false;
long skip = numPolys * 2L; // ushort per poly
if (ms.Position + skip > ms.Length) return false;
ms.Seek(skip, SeekOrigin.Current);
return true;
}
/// <summary>
/// BSPLeaf: uint32 type + int32 leafIndex + (Physics only: int32 solid + Sphere(16) + uint32 numPolys + ushort[numPolys])
/// Note: Physics leaf ALWAYS reads Sphere even when solid=0 (per ACE source).
/// Cell and Drawing leaves are just type + leafIndex.
/// </summary>
private bool SkipBSPLeaf(BinaryReader reader, MemoryStream ms, BSPTreeType treeType)
{
// Type tag already read by caller. Read leafIndex.
if (ms.Position + 4 > ms.Length) return false;
reader.ReadInt32(); // leafIndex
if (treeType == BSPTreeType.Physics)
{
// int32 Solid
if (ms.Position + 4 > ms.Length) return false;
reader.ReadInt32();
// Sphere: ALWAYS read (16 bytes), even when solid=0
if (ms.Position + 16 > ms.Length) return false;
ms.Seek(16, SeekOrigin.Current);
// uint32 numPolys + ushort[numPolys]
if (ms.Position + 4 > ms.Length) return false;
uint numPolys = reader.ReadUInt32();
if (numPolys > 100000) return false;
long skip = numPolys * 2L;
if (ms.Position + skip > ms.Length) return false;
ms.Seek(skip, SeekOrigin.Current);
}
// Cell and Drawing leaves: nothing more after leafIndex
return true;
}
/// <summary>
/// Skips a Dictionary{ushort, Polygon} block — same format as ParsePolygons
/// but doesn't store results.
/// </summary>
private bool SkipPolygons(BinaryReader reader, MemoryStream ms, uint count)
{
for (uint i = 0; i < count; i++)
{
if (ms.Position + 12 > ms.Length) return false;
ushort polyKey = reader.ReadUInt16();
byte numPts = reader.ReadByte();
byte stippling = reader.ReadByte();
int sidesType = reader.ReadInt32();
ms.Seek(4, SeekOrigin.Current); // posSurf + negSurf
if (numPts == 0 || numPts > 50) return false;
// Vertex IDs
long vertBytes = numPts * 2L;
if (ms.Position + vertBytes > ms.Length) return false;
ms.Seek(vertBytes, SeekOrigin.Current);
// PosUV
if ((stippling & 0x04) == 0)
{
if (ms.Position + numPts > ms.Length) return false;
ms.Seek(numPts, SeekOrigin.Current);
}
// NegUV
if (sidesType == 2 && (stippling & 0x08) == 0)
{
if (ms.Position + numPts > ms.Length) return false;
ms.Seek(numPts, SeekOrigin.Current);
}
}
return true;
}
/// <summary>
/// CVertexArray: int32 type(=1) + uint32 count + (ushort key + SWVertex)[count]
/// SWVertex: ushort numUVs + float3 Origin(12) + float3 Normal(12) + numUVs × 8 bytes
/// </summary>
private Dictionary<ushort, Vector3> ParseVertexArray(BinaryReader reader, MemoryStream ms)
{
var verts = new Dictionary<ushort, Vector3>();
int vertexType = reader.ReadInt32();
if (vertexType != 1) return null;
uint numVerts = reader.ReadUInt32();
if (numVerts > 50000) return null;
for (uint i = 0; i < numVerts; i++)
{
if (ms.Position + 28 > ms.Length) break; // key(2) + numUVs(2) + origin(12) + normal(12)
ushort key = reader.ReadUInt16();
ushort numUVs = reader.ReadUInt16();
float ox = reader.ReadSingle();
float oy = reader.ReadSingle();
float oz = reader.ReadSingle();
reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); // normal
long uvBytes = numUVs * 8L;
if (uvBytes > 0 && ms.Position + uvBytes <= ms.Length)
ms.Seek(uvBytes, SeekOrigin.Current);
verts[key] = new Vector3(ox, oy, oz);
}
return verts.Count > 0 ? verts : null;
}
/// <summary>
/// Dictionary{ushort, Polygon}: count × (ushort key + Polygon)
/// Polygon: byte numPts, byte stippling, int32 sidesType, short posSurf, short negSurf,
/// short[numPts] vertexIds, optional UV index arrays
/// </summary>
private List<ParsedPolygon> ParsePolygons(BinaryReader reader, MemoryStream ms, uint count)
{
var polys = new List<ParsedPolygon>();
for (uint i = 0; i < count; i++)
{
if (ms.Position + 12 > ms.Length) return polys; // key(2) + header(10 min)
ushort polyKey = reader.ReadUInt16();
byte numPts = reader.ReadByte();
byte stippling = reader.ReadByte();
int sidesType = reader.ReadInt32();
short posSurf = reader.ReadInt16();
short negSurf = reader.ReadInt16();
if (numPts == 0 || numPts > 50) return polys;
var poly = new ParsedPolygon { Key = polyKey, VertexIds = new List<ushort>() };
for (int v = 0; v < numPts; v++)
{
if (ms.Position + 2 > ms.Length) return polys;
poly.VertexIds.Add((ushort)reader.ReadInt16());
}
// Skip PosUVIndices (byte per point) unless NoPos flag (0x04)
if ((stippling & 0x04) == 0)
{
if (ms.Position + numPts > ms.Length) return polys;
ms.Seek(numPts, SeekOrigin.Current);
}
// Skip NegUVIndices if Clockwise(2) and not NoNeg(0x08)
if (sidesType == 2 && (stippling & 0x08) == 0)
{
if (ms.Position + numPts > ms.Length) return polys;
ms.Seek(numPts, SeekOrigin.Current);
}
polys.Add(poly);
}
return polys;
}
private class ParsedPolygon
{
public ushort Key;
public List<ushort> VertexIds;
}
public void FlushCache()
{
_wallCache.Clear();
_envCache.Clear();
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[DungeonLOS] {msg}");
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,751 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// A position + rotation in AC's 3D world.
/// Position is in local landblock meters (0-192 for outdoors).
/// Rotation is a quaternion (W, X, Y, Z).
/// </summary>
public class Frame
{
public float OriginX, OriginY, OriginZ;
public float RotW, RotX, RotY, RotZ;
public Frame()
{
RotW = 1.0f; // Identity quaternion
}
public void Unpack(BinaryReader reader)
{
OriginX = reader.ReadSingle();
OriginY = reader.ReadSingle();
OriginZ = reader.ReadSingle();
RotW = reader.ReadSingle();
RotX = reader.ReadSingle();
RotY = reader.ReadSingle();
RotZ = reader.ReadSingle();
}
/// <summary>
/// Rotates a point by this frame's quaternion.
/// q * v * q^-1 (for unit quaternion, q^-1 = conjugate)
/// </summary>
public Vector3 RotatePoint(Vector3 point)
{
// Quaternion rotation: v' = q * v * q*
float qw = RotW, qx = RotX, qy = RotY, qz = RotZ;
// Cross product of quaternion xyz with point
float cx = qy * point.Z - qz * point.Y;
float cy = qz * point.X - qx * point.Z;
float cz = qx * point.Y - qy * point.X;
// Result = point + 2 * (qw * cross + qxyz x cross)
float cx2 = qy * cz - qz * cy;
float cy2 = qz * cx - qx * cz;
float cz2 = qx * cy - qy * cx;
return new Vector3(
point.X + 2.0f * (qw * cx + cx2),
point.Y + 2.0f * (qw * cy + cy2),
point.Z + 2.0f * (qw * cz + cz2)
);
}
/// <summary>
/// Transforms a point: rotate then translate.
/// </summary>
public Vector3 TransformPoint(Vector3 localPoint)
{
Vector3 rotated = RotatePoint(localPoint);
return new Vector3(
rotated.X + OriginX,
rotated.Y + OriginY,
rotated.Z + OriginZ
);
}
public override string ToString()
{
return $"Pos({OriginX:F2}, {OriginY:F2}, {OriginZ:F2}) Rot({RotW:F3}, {RotX:F3}, {RotY:F3}, {RotZ:F3})";
}
}
/// <summary>
/// A static object placed on a landblock (building, tree, rock, structure, etc.)
/// </summary>
public class StaticObject
{
public uint InstanceId; // Unique placement ID
public uint SetupId; // Reference to 0x02xxxxxx Setup in portal.dat
public Frame Placement; // Position and rotation in landblock space
public StaticObject()
{
Placement = new Frame();
}
}
/// <summary>
/// Parsed landblock info from cell.dat (file ID = 0xXXYYFFFE).
/// Contains static object placements (Stabs) and building info for an outdoor landblock.
///
/// Format (from ACE.DatLoader.FileTypes.LandblockInfo):
/// uint32 Id
/// uint32 NumCells
/// uint32 NumObjects (List&lt;Stab&gt; count)
/// Stab[NumObjects]:
/// uint32 Id (model/setup reference, 0x01xx or 0x02xx)
/// Frame (7 floats: pos.xyz + rot.wxyz = 28 bytes)
/// ushort NumBuildings
/// ushort PackMask
/// BuildInfo[NumBuildings]:
/// uint32 ModelId
/// Frame (28 bytes)
/// uint32 NumLeaves
/// List&lt;CBldPortal&gt; Portals
/// if (PackMask &amp; 1):
/// PackedHashTable RestrictionTables
/// </summary>
public class LandblockInfo
{
public uint Id;
public uint NumCells;
public List<StaticObject> StaticObjects = new List<StaticObject>();
public bool HasObjects;
/// <summary>
/// Parse landblock info from raw .dat file data using the ACE format.
/// </summary>
public bool Unpack(byte[] data)
{
if (data == null || data.Length < 12)
return false;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
Id = reader.ReadUInt32();
NumCells = reader.ReadUInt32();
// Read List<Stab> — uint32 count + count × Stab entries
uint numObjects = reader.ReadUInt32();
if (numObjects > 5000) numObjects = 5000; // Sanity
for (uint i = 0; i < numObjects; i++)
{
if (ms.Position + 32 > ms.Length) break; // Need 4 (Id) + 28 (Frame)
var obj = new StaticObject();
obj.SetupId = reader.ReadUInt32();
obj.Placement.Unpack(reader);
StaticObjects.Add(obj);
}
HasObjects = StaticObjects.Count > 0;
Log($"Landblock 0x{Id:X8}: {StaticObjects.Count} static objects");
return true;
}
}
catch (Exception ex)
{
Log($"Error parsing landblock 0x{Id:X8}: {ex.Message}");
return false;
}
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[LandblockInfo] {msg}");
}
}
/// <summary>
/// Parsed environment cell from cell.dat (file ID = 0xXXYY0001 to 0xXXYYFFFE).
/// Represents an indoor dungeon room with walls, portals, and static objects.
/// </summary>
public class EnvCellInfo
{
public uint Id;
public uint Flags;
public List<Vector3> Vertices = new List<Vector3>();
public List<CellPolygon> Polygons = new List<CellPolygon>();
public List<ushort> PortalPolygonIndices = new List<ushort>();
public List<StaticObject> StaticObjects = new List<StaticObject>();
public List<uint> ConnectedCells = new List<uint>();
public uint EnvironmentId; // Reference to portal.dat environment
public uint StructureId; // Reference to portal.dat cell structure
/// <summary>
/// Parse environment cell from raw data.
///
/// Format (simplified):
/// uint32 id
/// uint32 flags
/// uint32 environmentId (0x0Dxxxxxx)
/// uint16 cellStructId
/// uint16 position (index into structure)
/// Frame placement
/// uint32 numPortals
/// for each portal:
/// uint16 polygonId (portal polygon index)
/// uint16 flags
/// uint32 connectedCell
/// uint32 numStaticObjects
/// for each static object:
/// uint32 setupId
/// Frame placement
/// </summary>
public bool Unpack(byte[] data)
{
if (data == null || data.Length < 12)
return false;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
Id = reader.ReadUInt32();
Flags = reader.ReadUInt32();
// Read environment/structure references
if (ms.Position + 8 > ms.Length) return false;
// The exact format depends on flags, but typically:
EnvironmentId = reader.ReadUInt32();
if (ms.Position + 4 > ms.Length) return false;
StructureId = reader.ReadUInt32();
// Read cell frame (position + rotation)
if ((Flags & 0x02) != 0 && ms.Position + 28 <= ms.Length)
{
var frame = new Frame();
frame.Unpack(reader);
}
// Read portals
if ((Flags & 0x04) != 0 || ms.Position + 4 <= ms.Length)
{
if (ms.Position + 4 <= ms.Length)
{
uint numPortals = reader.ReadUInt32();
if (numPortals > 1000) numPortals = 0; // Sanity
for (uint i = 0; i < numPortals && ms.Position + 8 <= ms.Length; i++)
{
ushort polyId = reader.ReadUInt16();
ushort portalFlags = reader.ReadUInt16();
uint connCell = reader.ReadUInt32();
PortalPolygonIndices.Add(polyId);
ConnectedCells.Add(connCell);
}
}
}
// Read static objects
if (ms.Position + 4 <= ms.Length)
{
uint numObjects = reader.ReadUInt32();
if (numObjects > 10000) numObjects = 0;
for (uint i = 0; i < numObjects && ms.Position + 32 <= ms.Length; i++)
{
var obj = new StaticObject();
obj.SetupId = reader.ReadUInt32();
obj.Placement.Unpack(reader);
StaticObjects.Add(obj);
}
}
Log($"EnvCell 0x{Id:X8}: {StaticObjects.Count} objects, " +
$"{PortalPolygonIndices.Count} portals");
return true;
}
}
catch (Exception ex)
{
Log($"Error parsing EnvCell 0x{Id:X8}: {ex.Message}");
return false;
}
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[EnvCell] {msg}");
}
}
/// <summary>
/// A polygon in a cell structure (wall, floor, ceiling).
/// </summary>
public class CellPolygon
{
public ushort[] VertexIndices;
public bool IsPortal; // Portal polygons are openings, not solid walls
}
/// <summary>
/// Parsed Setup file from portal.dat (file ID = 0x02xxxxxx).
/// Matches ACE.DatLoader.FileTypes.SetupModel.Unpack() exactly.
///
/// Format:
/// uint32 Id
/// uint32 Flags (SetupFlags)
/// uint32 numParts
/// uint32[numParts] Parts (GfxObj references, 0x01xxxxxx)
/// if (Flags & 0x01): uint32[numParts] ParentIndex
/// if (Flags & 0x02): Vector3[numParts] DefaultScale
/// Dictionary&lt;int,LocationType&gt; HoldingLocations (uint32 count + entries)
/// Dictionary&lt;int,LocationType&gt; ConnectionPoints (uint32 count + entries)
/// int32 placementsCount
/// PlacementType[placementsCount]: key(int32) + AnimFrame(numParts × Frame(28) + uint32 numHooks + hooks)
/// List&lt;CylSphere&gt; CylSpheres (uint32 count + count × 20 bytes)
/// List&lt;Sphere&gt; Spheres (uint32 count + count × 16 bytes)
/// float Height, Radius, StepUpHeight, StepDownHeight
/// Sphere SortingSphere (Vector3 + float = 16 bytes)
/// Sphere SelectionSphere (16 bytes)
/// Dictionary&lt;int,LightInfo&gt; Lights
/// uint32 × 5 defaults
/// </summary>
public class SetupInfo
{
public uint Id;
public uint Flags;
public int NumParts;
public uint[] PartIds;
// Bounding sphere (from SortingSphere)
public float BoundingSphereRadius;
public Vector3 BoundingSphereCenter;
// Physics dimensions
public float Height;
public float Radius; // Physics collision radius
// Collision spheres
public List<CollisionSphere> Spheres = new List<CollisionSphere>();
// Collision cylinders
public List<CollisionCylinder> Cylinders = new List<CollisionCylinder>();
public bool HasBounds;
public bool Unpack(byte[] data)
{
if (data == null || data.Length < 16)
return false;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
// --- Header ---
Id = reader.ReadUInt32();
Flags = reader.ReadUInt32();
uint numParts = reader.ReadUInt32();
if (numParts > 500) return false;
NumParts = (int)numParts;
PartIds = new uint[numParts];
for (int i = 0; i < numParts; i++)
PartIds[i] = reader.ReadUInt32();
// --- Optional arrays based on flags ---
// HasParent = 0x01
if ((Flags & 0x01) != 0)
ms.Seek(numParts * 4, SeekOrigin.Current);
// HasDefaultScale = 0x02
if ((Flags & 0x02) != 0)
ms.Seek(numParts * 12, SeekOrigin.Current); // Vector3 = 12 bytes
// --- Skip HoldingLocations: uint32 count + count × (key(4) + PartId(4) + Frame(28)) ---
if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data);
// --- Skip ConnectionPoints: same format ---
if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data);
// --- Skip PlacementFrames ---
if (ms.Position + 4 > ms.Length) return TryFallbackParse(data);
int placementsCount = reader.ReadInt32();
if (placementsCount < 0 || placementsCount > 100) return TryFallbackParse(data);
for (int p = 0; p < placementsCount; p++)
{
if (ms.Position + 4 > ms.Length) return TryFallbackParse(data);
reader.ReadInt32(); // key
// AnimationFrame: numParts × Frame(28 bytes) + uint32 numHooks
for (int part = 0; part < numParts; part++)
{
if (ms.Position + 28 > ms.Length) return TryFallbackParse(data);
ms.Seek(28, SeekOrigin.Current); // Skip Frame
}
if (ms.Position + 4 > ms.Length) return TryFallbackParse(data);
uint numHooks = reader.ReadUInt32();
if (numHooks > 0)
{
// AnimationHooks are variable-size; can't easily skip
// Fall back to tail scanning
return TryFallbackParse(data);
}
}
// --- NOW we're at the good stuff! ---
return ReadBoundsData(reader, ms, data);
}
}
catch
{
return TryFallbackParse(data);
}
}
/// <summary>
/// Reads CylSpheres, Spheres, Height, Radius, SortingSphere from current position.
/// </summary>
private bool ReadBoundsData(BinaryReader reader, MemoryStream ms, byte[] data)
{
try
{
// CylSpheres: uint32 count + count × (Vector3 origin(12) + float radius(4) + float height(4) = 20)
if (ms.Position + 4 > ms.Length) return false;
uint numCylSpheres = reader.ReadUInt32();
if (numCylSpheres > 50) return TryFallbackParse(data);
for (uint i = 0; i < numCylSpheres; i++)
{
if (ms.Position + 20 > ms.Length) break;
var cyl = new CollisionCylinder();
cyl.BottomCenter = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
cyl.Radius = reader.ReadSingle();
cyl.Height = reader.ReadSingle();
if (cyl.Radius > 0 && cyl.Height > 0 && !float.IsNaN(cyl.Radius))
Cylinders.Add(cyl);
}
// Spheres: uint32 count + count × (Vector3 origin(12) + float radius(4) = 16)
if (ms.Position + 4 > ms.Length) return false;
uint numSpheres = reader.ReadUInt32();
if (numSpheres > 50) return TryFallbackParse(data);
for (uint i = 0; i < numSpheres; i++)
{
if (ms.Position + 16 > ms.Length) break;
var sphere = new CollisionSphere();
sphere.Center = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
sphere.Radius = reader.ReadSingle();
if (sphere.Radius > 0 && !float.IsNaN(sphere.Radius))
Spheres.Add(sphere);
}
// Height, Radius, StepUpHeight, StepDownHeight
if (ms.Position + 16 > ms.Length) return false;
Height = reader.ReadSingle();
Radius = reader.ReadSingle();
float stepUp = reader.ReadSingle();
float stepDown = reader.ReadSingle();
// SortingSphere: Vector3 center + float radius
if (ms.Position + 16 > ms.Length) return false;
float sx = reader.ReadSingle(), sy = reader.ReadSingle(), sz = reader.ReadSingle();
float sr = reader.ReadSingle();
BoundingSphereCenter = new Vector3(sx, sy, sz);
BoundingSphereRadius = sr;
HasBounds = sr > 0.001f || Radius > 0.001f;
// If SortingSphere radius is 0, use the physics Radius
if (BoundingSphereRadius < 0.001f && Radius > 0.001f)
BoundingSphereRadius = Radius;
Log($"Setup 0x{Id:X8}: bounds OK — radius={BoundingSphereRadius:F2}, height={Height:F2}, " +
$"{Cylinders.Count} cyls, {Spheres.Count} spheres");
return true;
}
catch
{
return TryFallbackParse(data);
}
}
/// <summary>
/// Skip a hash table: uint32 count + count × entries of entrySize bytes.
/// </summary>
private bool SkipHashTable(BinaryReader reader, MemoryStream ms, int entrySize)
{
if (ms.Position + 4 > ms.Length) return false;
uint count = reader.ReadUInt32();
if (count > 1000) return false;
long skip = (long)count * entrySize;
if (ms.Position + skip > ms.Length) return false;
ms.Seek(skip, SeekOrigin.Current);
return true;
}
/// <summary>
/// Fallback: scan from the end of the file for the known tail structure.
/// The tail is always:
/// ... SortingSphere(16) + SelectionSphere(16) + Lights(uint32 count + entries) + 5×uint32(20)
/// If Lights is empty (count=0 → 4 bytes), tail is 56 bytes from end.
/// </summary>
private bool TryFallbackParse(byte[] data)
{
try
{
// Read header to get PartIds at minimum
if (PartIds == null && data.Length >= 16)
{
using (var ms2 = new MemoryStream(data))
using (var r2 = new BinaryReader(ms2))
{
Id = r2.ReadUInt32();
Flags = r2.ReadUInt32();
uint np = r2.ReadUInt32();
if (np <= 500)
{
NumParts = (int)np;
PartIds = new uint[np];
for (int i = 0; i < np && ms2.Position + 4 <= ms2.Length; i++)
PartIds[i] = r2.ReadUInt32();
}
}
}
// Try to find SortingSphere by scanning from end
// Known tail (if Lights empty): 5×uint32(20) + Lights(4) + SelectionSphere(16) + SortingSphere(16) + 4×float(16)
// = 72 bytes from end for start of Height/Radius/StepUp/StepDown
int[] tailOffsets = { 72, 78, 84 }; // Try different Lights sizes (4, 10, 16 bytes)
foreach (int tailOff in tailOffsets)
{
int offset = data.Length - tailOff;
if (offset < 16 || offset + 48 > data.Length) continue;
float h = BitConverter.ToSingle(data, offset);
float r = BitConverter.ToSingle(data, offset + 4);
float sx = BitConverter.ToSingle(data, offset + 16);
float sy = BitConverter.ToSingle(data, offset + 20);
float sz = BitConverter.ToSingle(data, offset + 24);
float sr = BitConverter.ToSingle(data, offset + 28);
// Validate: Height and Radius should be positive, sphere radius positive, center reasonable
if (h >= 0 && h < 100 && r > 0 && r < 200 &&
sr > 0 && sr < 500 &&
!float.IsNaN(h) && !float.IsNaN(r) && !float.IsNaN(sr) &&
Math.Abs(sx) < 1000 && Math.Abs(sy) < 1000 && Math.Abs(sz) < 1000)
{
Height = h;
Radius = r;
BoundingSphereCenter = new Vector3(sx, sy, sz);
BoundingSphereRadius = sr;
HasBounds = true;
Log($"Setup 0x{Id:X8}: FALLBACK found bounds at tailOff={tailOff} — radius={sr:F2}, height={h:F2}");
return true;
}
}
Log($"Setup 0x{Id:X8}: FALLBACK failed, no valid bounds found");
return false;
}
catch
{
return false;
}
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[Setup] {msg}");
}
}
/// <summary>
/// Parsed GfxObj from portal.dat (file ID = 0x01xxxxxx).
/// Contains 3D mesh data. We extract the bounding sphere and AABB.
/// </summary>
public class GfxObjInfo
{
public uint Id;
public uint Flags;
// Bounding data (what we need for raycasting)
public Vector3 SortingCenter;
public float SortingRadius;
public Vector3 BoundsMin;
public Vector3 BoundsMax;
public bool HasBounds;
// Vertex data (for precise bounds calculation)
public List<Vector3> Vertices = new List<Vector3>();
/// <summary>
/// Parse GfxObj to extract bounding information.
/// We don't need the full mesh/texture data for raycasting.
///
/// Format (simplified):
/// uint32 id
/// uint32 flags
/// -- surface data (skip) --
/// uint32 numVertices
/// for each vertex:
/// float3 position
/// float3 normal
/// (optional UV data based on flags)
/// -- polygon data (skip) --
/// -- BSP data (skip for now) --
/// float3 sortingCenter
/// float sortingRadius
/// </summary>
public bool Unpack(byte[] data)
{
if (data == null || data.Length < 12)
return false;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
Id = reader.ReadUInt32();
Flags = reader.ReadUInt32();
// Skip surface references
if (ms.Position + 4 > ms.Length) return false;
uint numSurfaces = reader.ReadUInt32();
if (numSurfaces > 10000) return false;
ms.Seek(numSurfaces * 4, SeekOrigin.Current); // uint32 per surface
// Read vertex count
if (ms.Position + 4 > ms.Length) return false;
uint numVertices = reader.ReadUInt32();
if (numVertices > 100000) return false;
// Read vertices and compute AABB
float minX = float.MaxValue, minY = float.MaxValue, minZ = float.MaxValue;
float maxX = float.MinValue, maxY = float.MinValue, maxZ = float.MinValue;
for (uint i = 0; i < numVertices; i++)
{
if (ms.Position + 12 > ms.Length) break;
float x = reader.ReadSingle();
float y = reader.ReadSingle();
float z = reader.ReadSingle();
if (float.IsNaN(x) || float.IsNaN(y) || float.IsNaN(z)) continue;
Vertices.Add(new Vector3(x, y, z));
minX = Math.Min(minX, x); maxX = Math.Max(maxX, x);
minY = Math.Min(minY, y); maxY = Math.Max(maxY, y);
minZ = Math.Min(minZ, z); maxZ = Math.Max(maxZ, z);
// Skip normal (3 floats) + UV data
if (ms.Position + 12 <= ms.Length)
ms.Seek(12, SeekOrigin.Current); // Skip normal
// UV data varies; skip based on flags
if ((Flags & 0x04) != 0 && ms.Position + 8 <= ms.Length)
ms.Seek(8, SeekOrigin.Current); // Skip UV
}
if (Vertices.Count > 0)
{
BoundsMin = new Vector3(minX, minY, minZ);
BoundsMax = new Vector3(maxX, maxY, maxZ);
HasBounds = true;
// Compute bounding sphere from AABB
SortingCenter = new Vector3(
(minX + maxX) * 0.5f,
(minY + maxY) * 0.5f,
(minZ + maxZ) * 0.5f
);
SortingRadius = (BoundsMax - SortingCenter).Length();
}
// Also try to find the explicit sorting sphere at the end of file
TryReadSortingSphere(data);
Log($"GfxObj 0x{Id:X8}: {Vertices.Count} verts, radius={SortingRadius:F2}");
return true;
}
}
catch (Exception ex)
{
Log($"Error parsing GfxObj 0x{Id:X8}: {ex.Message}");
return false;
}
}
/// <summary>
/// Scans the end of the file for the sorting sphere data.
/// The sorting center + radius are typically near the end of the GfxObj.
/// </summary>
private void TryReadSortingSphere(byte[] data)
{
// The last 16 bytes before any trailing data often contain the sorting sphere
if (data.Length < 20) return;
// Try reading from the last 16 bytes
for (int offset = data.Length - 16; offset >= Math.Max(0, data.Length - 64); offset -= 4)
{
if (offset + 16 > data.Length) continue;
float cx = BitConverter.ToSingle(data, offset);
float cy = BitConverter.ToSingle(data, offset + 4);
float cz = BitConverter.ToSingle(data, offset + 8);
float r = BitConverter.ToSingle(data, offset + 12);
if (r > 0.01f && r < 500f && !float.IsNaN(r) && !float.IsInfinity(r) &&
!float.IsNaN(cx) && !float.IsNaN(cy) && !float.IsNaN(cz) &&
Math.Abs(cx) < 1000 && Math.Abs(cy) < 1000 && Math.Abs(cz) < 1000)
{
SortingCenter = new Vector3(cx, cy, cz);
SortingRadius = r;
break;
}
}
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[GfxObj] {msg}");
}
}
/// <summary>
/// A spherical collision volume from a Setup file.
/// </summary>
public class CollisionSphere
{
public Vector3 Center;
public float Radius;
}
/// <summary>
/// A cylindrical collision volume from a Setup file.
/// </summary>
public class CollisionCylinder
{
public Vector3 BottomCenter;
public float Radius;
public float Height;
}
}

View file

@ -0,0 +1,98 @@
using System;
using Decal.Adapter;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Main integration point for the raycasting system.
/// Initializes the .dat file parsers, geometry loader, and targeting FSM.
///
/// Usage:
/// var raycast = new MainLogic();
/// raycast.Initialize(acFolderPath); // Call once at startup
///
/// // During combat:
/// bool blocked = raycast.IsTargetBlocked(core, targetWorldObject, attackType);
/// </summary>
public class MainLogic : IDisposable
{
private GeometryLoader _geoLoader;
private BlacklistManager _blacklist;
private TargetingFSM _targetingFSM;
private bool _disposed;
public GeometryLoader GeometryLoader => _geoLoader;
public BlacklistManager Blacklist => _blacklist;
public TargetingFSM TargetingFSM => _targetingFSM;
public bool IsInitialized => _geoLoader?.IsInitialized ?? false;
public string StatusMessage => _geoLoader?.StatusMessage ?? "Not created";
public MainLogic()
{
_geoLoader = new GeometryLoader();
_blacklist = new BlacklistManager();
_targetingFSM = new TargetingFSM(_geoLoader, _blacklist);
}
/// <summary>
/// Initializes the raycasting system by loading portal.dat and cell.dat.
///
/// acFolderPath: Optional explicit path to AC installation folder.
/// If null, will search common installation paths automatically.
///
/// Returns true if initialization succeeded (both .dat files loaded).
/// </summary>
public bool Initialize(string acFolderPath = null)
{
try
{
bool result = _geoLoader.Initialize(acFolderPath);
if (result)
{
System.Diagnostics.Debug.WriteLine("[Raycast] MainLogic initialized successfully");
}
else
System.Diagnostics.Debug.WriteLine($"[Raycast] MainLogic init failed: {_geoLoader.StatusMessage}");
return result;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Raycast] MainLogic init error: {ex.Message}");
return false;
}
}
/// <summary>
/// Quick check: is a specific target blocked by geometry?
/// Call this from CombatManager before engaging a target.
/// </summary>
public bool IsTargetBlocked(CoreManager core, Decal.Adapter.Wrappers.WorldObject target,
TargetingFSM.AttackType attackType)
{
if (!IsInitialized || _targetingFSM == null)
return false;
return _targetingFSM.IsTargetBlocked(core, target, attackType);
}
/// <summary>
/// Determines the attack type from the currently wielded weapon.
/// </summary>
public TargetingFSM.AttackType GetAttackType(CoreManager core)
{
return _targetingFSM?.DetermineAttackType(core) ?? TargetingFSM.AttackType.Linear;
}
public void Dispose()
{
if (_disposed) return;
_geoLoader?.Dispose();
_blacklist?.ClearAll();
_disposed = true;
System.Diagnostics.Debug.WriteLine("[Raycast] MainLogic disposed");
}
}
}

View file

@ -0,0 +1,235 @@
using System;
using System.Collections.Generic;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Core raycasting engine for line-of-sight checks.
/// Tests linear (spell/bolt) and parabolic (bow/thrown) trajectories
/// against the loaded collision geometry.
///
/// NOTE: Uses custom Vector3 from this namespace, NOT System.Numerics.
/// </summary>
public static class RaycastEngine
{
/// <summary>
/// Gravity constant for parabolic trajectory calculations.
/// AC's gravity is approximately 9.81 m/s² but may need empirical tuning.
/// </summary>
private const float GRAVITY = 9.81f;
/// <summary>
/// Number of sample points along an arc trajectory for collision testing.
/// Higher = more accurate but slower. 10 is a good balance.
/// </summary>
private const int ARC_SAMPLE_COUNT = 10;
/// <summary>
/// Tests if a straight-line path (magic spells, crossbow bolts) is blocked
/// by any collision geometry.
///
/// Returns true if the path IS blocked (an obstacle exists between origin and target).
/// Returns false if the path is clear.
/// </summary>
public static bool IsLinearPathBlocked(Vector3 origin, Vector3 target, List<BoundingVolume> geometry)
{
if (geometry == null || geometry.Count == 0)
return false;
// Validate inputs
if (float.IsNaN(origin.X) || float.IsNaN(origin.Y) || float.IsNaN(origin.Z) ||
float.IsNaN(target.X) || float.IsNaN(target.Y) || float.IsNaN(target.Z))
return false;
// Calculate direction and distance
Vector3 delta = target - origin;
float distanceToTarget = delta.Length();
// Origin and target are the same point — no obstruction possible
if (distanceToTarget < 1e-4f)
return false;
// Normalize direction
Vector3 direction = delta / distanceToTarget;
// Test ray against each bounding volume
foreach (var volume in geometry)
{
// Skip doors (state is unreliable, as per VTank's approach)
if (volume.IsDoor)
continue;
// Test intersection
float hitDist;
if (volume.RayIntersect(origin, direction, distanceToTarget, out hitDist))
{
// Ignore geometry within 2m of the player — prevents false blocks
// from walls/floors the player is standing on or touching.
// Only count geometry that's actually BETWEEN the player and target.
if (hitDist >= 2.0f && hitDist < distanceToTarget)
{
return true; // Path is blocked
}
}
}
return false; // Path is clear
}
/// <summary>
/// Tests if a parabolic arc path (bows, thrown weapons) is blocked by geometry.
///
/// This allows attacks to arc over low obstacles like walls and rocks.
/// The arc is sampled at discrete points and each segment is tested for
/// intersection with geometry.
///
/// Returns true if the arc IS blocked.
/// Returns false if the arc clears all obstacles.
/// </summary>
public static bool IsArcPathBlocked(Vector3 origin, Vector3 target, float initialVelocity,
List<BoundingVolume> geometry)
{
if (geometry == null || geometry.Count == 0)
return false;
if (initialVelocity <= 0)
return true; // Can't fire with no velocity
// Validate inputs
if (float.IsNaN(origin.X) || float.IsNaN(target.X))
return true;
Vector3 delta = target - origin;
float horizontalDist = delta.Length2D();
float verticalDist = delta.Z;
// Check maximum range: v² / g
float maxRange = (initialVelocity * initialVelocity) / GRAVITY;
if (horizontalDist > maxRange)
return true; // Out of range
if (horizontalDist < 0.1f)
return false; // Basically on top of target
// Calculate launch angle for the desired range
// Using the optimal angle that clears obstacles
// θ = 0.5 * arcsin(g * d / v²) for flat terrain
float sinArg = (GRAVITY * horizontalDist) / (initialVelocity * initialVelocity);
sinArg = Math.Min(sinArg, 1.0f); // Clamp for float precision
// Use the high arc (π/2 - θ) for better obstacle clearance
float launchAngle = (float)(0.5 * Math.Asin(sinArg));
if (launchAngle < 0.1f)
launchAngle = (float)(Math.PI / 4); // Default to 45° if calculation fails
float cosAngle = (float)Math.Cos(launchAngle);
float sinAngle = (float)Math.Sin(launchAngle);
// Calculate time of flight
float vHorizontal = initialVelocity * cosAngle;
float vVertical = initialVelocity * sinAngle;
if (vHorizontal < 0.01f)
return true; // Basically firing straight up
float totalTime = horizontalDist / vHorizontal;
// Horizontal direction (unit vector in XY plane)
float hdx = delta.X / horizontalDist;
float hdy = delta.Y / horizontalDist;
// Sample the arc at discrete points and test each segment
Vector3 prevPoint = origin;
for (int i = 1; i <= ARC_SAMPLE_COUNT; i++)
{
float t = (float)i / ARC_SAMPLE_COUNT;
float time = t * totalTime;
// Kinematic equations
float hDist = vHorizontal * time;
float height = origin.Z + vVertical * time - 0.5f * GRAVITY * time * time;
// Adjust height to interpolate between origin.Z and target.Z
// (accounts for height difference between origin and target)
float heightAdjust = verticalDist * t;
Vector3 arcPoint = new Vector3(
origin.X + hdx * hDist,
origin.Y + hdy * hDist,
height + heightAdjust * (1.0f - t) // Blend in height difference
);
// Test this segment for collisions
if (IsSegmentBlocked(prevPoint, arcPoint, geometry))
return true;
prevPoint = arcPoint;
}
// Test final segment to target
if (IsSegmentBlocked(prevPoint, target, geometry))
return true;
return false; // Arc clears all obstacles
}
/// <summary>
/// Tests if a line segment between two points intersects any geometry.
/// Used internally for arc sampling.
/// </summary>
private static bool IsSegmentBlocked(Vector3 start, Vector3 end, List<BoundingVolume> geometry)
{
Vector3 delta = end - start;
float dist = delta.Length();
if (dist < 0.01f) return false;
Vector3 dir = delta / dist;
foreach (var volume in geometry)
{
if (volume.IsDoor) continue;
float hitDist;
if (volume.RayIntersect(start, dir, dist, out hitDist))
{
if (hitDist > 0.05f && hitDist < dist - 0.05f)
return true;
}
}
return false;
}
/// <summary>
/// Quick distance-based pre-filter: checks if ANY geometry exists near the line
/// between origin and target. Used to skip the full raycast for wide-open areas.
/// Returns true if there is nearby geometry worth testing.
/// </summary>
public static bool HasNearbyGeometry(Vector3 origin, Vector3 target, List<BoundingVolume> geometry, float margin = 5.0f)
{
if (geometry == null || geometry.Count == 0)
return false;
// Compute a rough bounding box for the path
Vector3 pathMin = Vector3.Min(origin, target) - new Vector3(margin, margin, margin);
Vector3 pathMax = Vector3.Max(origin, target) + new Vector3(margin, margin, margin);
foreach (var vol in geometry)
{
if (vol.IsDoor) continue;
// Quick AABB overlap test
if (vol.Max.X >= pathMin.X && vol.Min.X <= pathMax.X &&
vol.Max.Y >= pathMin.Y && vol.Min.Y <= pathMax.Y &&
vol.Max.Z >= pathMin.Z && vol.Min.Z <= pathMax.Z)
{
return true;
}
}
return false;
}
}
}

View file

@ -0,0 +1,948 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Implements AC's deterministic scatter placement system for terrain objects (trees, rocks, etc).
/// Ported from ACE's Landblock.get_land_scenes() + ObjectDesc.Displace/Rotate/Scale.
///
/// Pipeline:
/// 1. Parse RegionDesc (0x13000000) from portal.dat → terrain-to-scene mapping tables
/// 2. Parse CellLandblock (0xXXYYFFFF) from cell.dat → 81 terrain values + 81 heights
/// 3. For each terrain cell, deterministically select and place scatter objects
/// 4. Look up bounding volumes for each placed object
/// </summary>
public class ScatterSystem
{
// LandDefs constants (from ACE)
private const int VertexDim = 9; // 9×9 vertices per landblock
private const int BlockSide = 8; // 8×8 cells per landblock
private const float CellLength = 24.0f; // Each cell is 24m
private const float BlockLength = 192.0f;
// RegionDesc data (parsed once)
private List<ScatterTerrainType> _terrainTypes;
private List<ScatterSceneType> _sceneTypes;
private float[] _landHeightTable;
private bool _initialized;
// Scene cache (portal.dat scenes)
private Dictionary<uint, List<ScatterObjectDesc>> _sceneCache = new Dictionary<uint, List<ScatterObjectDesc>>();
// Reference to dat files
private DatDatabase _portalDat;
private DatDatabase _cellDat;
public bool IsInitialized => _initialized;
public List<string> DiagLog { get; } = new List<string>();
public bool Initialize(DatDatabase portalDat, DatDatabase cellDat)
{
_portalDat = portalDat;
_cellDat = cellDat;
try
{
// Parse RegionDesc (0x13000000) from portal.dat
byte[] regionData = portalDat.GetFileData(0x13000000);
if (regionData == null || regionData.Length < 100)
{
Log($"RegionDesc 0x13000000 not found in portal.dat (data={regionData?.Length ?? 0})");
return false;
}
Log($"RegionDesc: {regionData.Length} bytes loaded");
// Dump first few uint32s for debugging
string header = "RegionDesc header: ";
for (int i = 0; i < Math.Min(32, regionData.Length); i += 4)
header += $"0x{BitConverter.ToUInt32(regionData, i):X8} ";
Log(header);
if (!ParseRegionDesc(regionData))
{
Log("Failed to parse RegionDesc");
return false;
}
_initialized = true;
Log($"Scatter system ready: {_terrainTypes?.Count ?? 0} terrain types, {_sceneTypes?.Count ?? 0} scene types");
return true;
}
catch (Exception ex)
{
Log($"Scatter init error: {ex.Message}");
return false;
}
}
/// <summary>
/// Generates scatter object bounding volumes for a landblock.
/// Replicates ACE's Landblock.get_land_scenes() algorithm.
/// </summary>
public List<BoundingVolume> GetScatterVolumes(uint landblockKey, GeometryLoader geoLoader)
{
var volumes = new List<BoundingVolume>();
if (!_initialized || _terrainTypes == null || _sceneTypes == null)
return volumes;
try
{
// Read CellLandblock (0xXXYYFFFF) from cell.dat
uint cellLandblockId = (landblockKey << 16) | 0xFFFF;
byte[] data = _cellDat.GetFileData(cellLandblockId);
if (data == null || data.Length < 170) // Minimum: 4+4+81*2+81*1 = 255
return volumes;
// Parse terrain and height arrays
ushort[] terrain = new ushort[81];
byte[] height = new byte[81];
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
uint id = reader.ReadUInt32();
uint hasObjects = reader.ReadUInt32();
for (int i = 0; i < 81; i++)
terrain[i] = reader.ReadUInt16();
for (int i = 0; i < 81; i++)
height[i] = reader.ReadByte();
}
// Compute block offsets (global cell coordinates)
uint blockX = ((landblockKey >> 8) & 0xFF) * 8;
uint blockY = (landblockKey & 0xFF) * 8;
float globalOffsetX = ((landblockKey >> 8) & 0xFF) * BlockLength;
float globalOffsetY = (landblockKey & 0xFF) * BlockLength;
int scatterCount = 0;
// Iterate all 81 terrain cells (matching ACE's get_land_scenes)
for (uint i = 0; i < 81; i++)
{
ushort t = terrain[i];
int terrainType = (t >> 2) & 0x1F; // 5 bits, 0-31
int sceneType = t >> 11; // 5 bits, 0-31
if (terrainType >= _terrainTypes.Count) continue;
var tt = _terrainTypes[terrainType];
if (sceneType >= tt.SceneTypeIndices.Count) continue;
int sceneInfoIdx = (int)tt.SceneTypeIndices[sceneType];
if (sceneInfoIdx >= _sceneTypes.Count) continue;
var scenes = _sceneTypes[sceneInfoIdx].SceneFileIds;
if (scenes.Count == 0) continue;
uint cellX = i / (uint)VertexDim;
uint cellY = i % (uint)VertexDim;
uint globalCellX = (uint)(cellX + blockX);
uint globalCellY = (uint)(cellY + blockY);
// Deterministic scene selection — uses uint32 overflow arithmetic
// matching AC client's C++ unsigned int behavior
uint cellMat = (uint)((long)globalCellY * (712977289L * globalCellX + 1813693831L) - 1109124029L * globalCellX + 2139937281L);
double offset = cellMat * 2.3283064e-10;
int sceneIdx = (int)(scenes.Count * offset);
if (sceneIdx < 0 || sceneIdx >= scenes.Count) sceneIdx = 0;
uint sceneId = scenes[sceneIdx];
// Load the Scene file
var sceneObjects = LoadScene(sceneId);
if (sceneObjects == null || sceneObjects.Count == 0) continue;
// Per-object noise seeds — uint32 overflow
uint cellXMat = (uint)(-1109124029L * globalCellX);
uint cellYMat = (uint)(1813693831L * globalCellY);
uint cellMat2 = (uint)(1360117743L * globalCellX * globalCellY + 1888038839L);
for (uint j = 0; j < sceneObjects.Count; j++)
{
var obj = sceneObjects[(int)j];
// Frequency check — uint32 overflow
double noise = (uint)(cellXMat + cellYMat - cellMat2 * (23399 + j)) * 2.3283064e-10;
if (noise >= obj.Freq || obj.WeenieObj != 0)
continue;
// Displace
var position = Displace(obj, globalCellX, globalCellY, j);
float lx = cellX * CellLength + position.X;
float ly = cellY * CellLength + position.Y;
// Bounds check
if (lx < 0 || ly < 0 || lx >= BlockLength || ly >= BlockLength)
continue;
// Get terrain height at this position
float z = GetTerrainHeight(height, lx, ly);
// World coordinates
float worldX = globalOffsetX + lx;
float worldY = globalOffsetY + ly;
// Get bounding volume for this object
var setupVolumes = geoLoader.GetSetupBoundingVolumesPublic(obj.ObjId);
foreach (var vol in setupVolumes)
{
// Create a frame for the scatter object
var frame = new Frame
{
OriginX = lx, OriginY = ly, OriginZ = z,
RotW = 1, RotX = 0, RotY = 0, RotZ = 0
};
// Apply rotation from scatter algorithm
ApplyScatterRotation(frame, obj, globalCellX, globalCellY, j);
var transformed = TransformScatterVolume(vol, frame, globalOffsetX, globalOffsetY);
if (transformed != null)
{
// Extend scatter volumes vertically to account for:
// 1. Terrain height imprecision (nearest-vertex vs polygon, can be 10-15m off)
// 2. Trees/rocks extend upward from ground level
// Use generous range to ensure ray intersection works
float extendBelow = 20.0f;
float extendAbove = 20.0f;
transformed.Min = new Vector3(transformed.Min.X, transformed.Min.Y, transformed.Min.Z - extendBelow);
transformed.Max = new Vector3(transformed.Max.X, transformed.Max.Y, transformed.Max.Z + extendAbove);
transformed.Center = new Vector3(transformed.Center.X, transformed.Center.Y,
(transformed.Min.Z + transformed.Max.Z) * 0.5f);
// Force AABB type so Min/Max Z extension is used by ray intersection
transformed.Type = BoundingVolume.VolumeType.AxisAlignedBox;
transformed.Dimensions = transformed.Max - transformed.Min;
volumes.Add(transformed);
}
}
scatterCount++;
}
}
if (scatterCount > 0)
Log($"Landblock 0x{landblockKey:X4}: {scatterCount} scatter objects -> {volumes.Count} volumes");
}
catch (Exception ex)
{
Log($"Scatter error for 0x{landblockKey:X4}: {ex.Message}");
}
return volumes;
}
// ===================================================================
// ObjectDesc.Displace — pseudo-random placement from ACE
// ===================================================================
private Vector3 Displace(ScatterObjectDesc obj, uint ix, uint iy, uint iq)
{
float x, y, z;
float locX = obj.BaseLocX, locY = obj.BaseLocY, locZ = obj.BaseLocZ;
// uint32 overflow arithmetic matching AC client C++ unsigned int
if (obj.DisplaceX <= 0)
x = locX;
else
x = (float)((uint)(1813693831L * iy - (iq + 45773) * (1360117743L * iy * ix + 1888038839L) - 1109124029L * ix)
* 2.3283064e-10 * obj.DisplaceX + locX);
if (obj.DisplaceY <= 0)
y = locY;
else
y = (float)((uint)(1813693831L * iy - (iq + 72719) * (1360117743L * iy * ix + 1888038839L) - 1109124029L * ix)
* 2.3283064e-10 * obj.DisplaceY + locY);
z = locZ;
double quadrant = (uint)(1813693831L * iy - ix * (1870387557L * iy + 1109124029L) - 402451965L) * 2.3283064e-10;
if (quadrant >= 0.75) return new Vector3(y, -x, z);
if (quadrant >= 0.5) return new Vector3(-x, -y, z);
if (quadrant >= 0.25) return new Vector3(-y, x, z);
return new Vector3(x, y, z);
}
private void ApplyScatterRotation(Frame frame, ScatterObjectDesc obj, uint x, uint y, uint k)
{
if (obj.MaxRotation > 0.0f)
{
float degrees = (float)((uint)(1813693831L * y - (k + 63127) * (1360117743L * y * x + 1888038839L) - 1109124029L * x) * 2.3283064e-10 * obj.MaxRotation);
float radians = degrees * (float)(Math.PI / 180.0);
float halfRad = radians * 0.5f;
frame.RotW = (float)Math.Cos(halfRad);
frame.RotZ = (float)Math.Sin(halfRad);
}
}
private float GetTerrainHeight(byte[] heights, float lx, float ly)
{
// Bilinear interpolation of height values
// LandHeightTable already contains actual in-game Z heights
// (the *2 factor from CellLandblock comments refers to raw bytes, not table values)
int ix = Math.Min((int)(lx / CellLength), BlockSide);
int iy = Math.Min((int)(ly / CellLength), BlockSide);
int idx = ix * VertexDim + iy;
if (idx >= 0 && idx < 81 && _landHeightTable != null)
{
byte h = heights[idx];
if (h < _landHeightTable.Length)
return _landHeightTable[h];
}
return 0;
}
private BoundingVolume TransformScatterVolume(BoundingVolume localVol, Frame placement,
float globalOffsetX, float globalOffsetY)
{
if (localVol == null) return null;
try
{
Vector3 worldCenter = placement.TransformPoint(localVol.Center);
worldCenter.X += globalOffsetX;
worldCenter.Y += globalOffsetY;
if (localVol.Type == BoundingVolume.VolumeType.Sphere)
{
float r = localVol.Dimensions.X;
return new BoundingVolume
{
Type = BoundingVolume.VolumeType.Sphere,
Center = worldCenter,
Dimensions = localVol.Dimensions,
Min = worldCenter - new Vector3(r, r, r),
Max = worldCenter + new Vector3(r, r, r),
IsDoor = false
};
}
// For non-sphere: transform corners to get new AABB
Vector3[] corners = {
new Vector3(localVol.Min.X, localVol.Min.Y, localVol.Min.Z),
new Vector3(localVol.Max.X, localVol.Min.Y, localVol.Min.Z),
new Vector3(localVol.Min.X, localVol.Max.Y, localVol.Min.Z),
new Vector3(localVol.Max.X, localVol.Max.Y, localVol.Min.Z),
new Vector3(localVol.Min.X, localVol.Min.Y, localVol.Max.Z),
new Vector3(localVol.Max.X, localVol.Min.Y, localVol.Max.Z),
new Vector3(localVol.Min.X, localVol.Max.Y, localVol.Max.Z),
new Vector3(localVol.Max.X, localVol.Max.Y, localVol.Max.Z),
};
Vector3 newMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
Vector3 newMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);
for (int c = 0; c < 8; c++)
{
Vector3 w = placement.TransformPoint(corners[c]);
w.X += globalOffsetX;
w.Y += globalOffsetY;
newMin = Vector3.Min(newMin, w);
newMax = Vector3.Max(newMax, w);
}
return new BoundingVolume
{
Type = BoundingVolume.VolumeType.AxisAlignedBox,
Center = (newMin + newMax) * 0.5f,
Dimensions = newMax - newMin,
Min = newMin,
Max = newMax,
IsDoor = false
};
}
catch { return null; }
}
// ===================================================================
// Scene loading
// ===================================================================
private List<ScatterObjectDesc> LoadScene(uint sceneId)
{
if (_sceneCache.TryGetValue(sceneId, out var cached))
return cached;
var objects = new List<ScatterObjectDesc>();
try
{
byte[] data = _portalDat.GetFileData(sceneId);
if (data == null || data.Length < 8)
{
_sceneCache[sceneId] = objects;
return objects;
}
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
uint id = reader.ReadUInt32(); // Scene ID
// List<ObjectDesc>: uint32 count + count × ObjectDesc
uint numObjects = reader.ReadUInt32();
if (numObjects > 200) numObjects = 200;
for (uint i = 0; i < numObjects; i++)
{
if (ms.Position + 72 > ms.Length) break; // ObjectDesc is 72 bytes
var obj = new ScatterObjectDesc();
obj.ObjId = reader.ReadUInt32();
// Frame (BaseLoc): 7 floats
obj.BaseLocX = reader.ReadSingle();
obj.BaseLocY = reader.ReadSingle();
obj.BaseLocZ = reader.ReadSingle();
obj.BaseLocW = reader.ReadSingle();
obj.BaseLocRX = reader.ReadSingle();
obj.BaseLocRY = reader.ReadSingle();
obj.BaseLocRZ = reader.ReadSingle();
obj.Freq = reader.ReadSingle();
obj.DisplaceX = reader.ReadSingle();
obj.DisplaceY = reader.ReadSingle();
obj.MinScale = reader.ReadSingle();
obj.MaxScale = reader.ReadSingle();
obj.MaxRotation = reader.ReadSingle();
obj.MinSlope = reader.ReadSingle();
obj.MaxSlope = reader.ReadSingle();
obj.Align = reader.ReadUInt32();
obj.Orient = reader.ReadUInt32();
obj.WeenieObj = reader.ReadUInt32();
objects.Add(obj);
}
}
}
catch (Exception ex)
{
Log($"Scene 0x{sceneId:X8} parse error: {ex.Message}");
}
_sceneCache[sceneId] = objects;
return objects;
}
// ===================================================================
// RegionDesc parsing (0x13000000)
// ===================================================================
private bool ParseRegionDesc(byte[] data)
{
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
uint id = reader.ReadUInt32(); // 0x13000000
uint regionNumber = reader.ReadUInt32();
uint version = reader.ReadUInt32();
Log($"RegionDesc: id=0x{id:X8}, region={regionNumber}, version={version}");
// PString RegionName ("Dereth")
SkipPString(reader, ms);
Log($"After RegionName: pos={ms.Position}");
// LandDefs
if (!ParseLandDefs(reader, ms))
{
Log($"LandDefs parse failed at pos={ms.Position}");
return ScanForTables(data);
}
Log($"After LandDefs: pos={ms.Position}");
// GameTime
if (!SkipGameTime(reader, ms))
{
Log($"GameTime skip failed at pos={ms.Position}");
return ScanForTables(data);
}
Log($"After GameTime: pos={ms.Position}");
// PartsMask
uint partsMask = reader.ReadUInt32();
Log($"PartsMask=0x{partsMask:X8}, pos={ms.Position}");
// Skip SkyDesc if present
if ((partsMask & 0x10) != 0)
{
Log("Skipping SkyDesc...");
if (!SkipSkyDesc(reader, ms))
{
Log($"SkyDesc skip failed at pos={ms.Position}, trying fallback");
return ScanForTables(data);
}
Log($"After SkyDesc: pos={ms.Position}");
}
// Skip SoundDesc if present
if ((partsMask & 0x01) != 0)
{
Log("Skipping SoundDesc...");
if (!SkipSoundDesc(reader, ms))
{
Log($"SoundDesc skip failed at pos={ms.Position}, trying fallback");
return ScanForTables(data);
}
Log($"After SoundDesc: pos={ms.Position}");
}
// Parse SceneDesc
if ((partsMask & 0x02) != 0)
{
Log("Parsing SceneDesc...");
if (!ParseSceneDesc(reader, ms))
{
Log($"SceneDesc parse failed at pos={ms.Position}, trying fallback");
return ScanForTables(data);
}
Log($"After SceneDesc: pos={ms.Position}");
}
// Parse TerrainDesc
Log("Parsing TerrainDesc...");
if (!ParseTerrainDesc(reader, ms))
{
Log($"TerrainDesc parse failed at pos={ms.Position}, trying fallback");
return ScanForTables(data);
}
Log($"RegionDesc parsed: {_terrainTypes?.Count} terrainTypes, {_sceneTypes?.Count} sceneTypes");
return _terrainTypes != null && _sceneTypes != null;
}
}
catch (Exception ex)
{
Log($"RegionDesc parse error at unknown pos: {ex.Message}");
return ScanForTables(data);
}
}
private bool ParseLandDefs(BinaryReader reader, MemoryStream ms)
{
if (ms.Position + 1056 > ms.Length) return false;
reader.ReadInt32(); // NumBlockLength
reader.ReadInt32(); // NumBlockWidth
reader.ReadSingle(); // SquareLength
reader.ReadInt32(); // LBlockLength
reader.ReadInt32(); // VertexPerCell
reader.ReadSingle(); // MaxObjHeight
reader.ReadSingle(); // SkyHeight
reader.ReadSingle(); // RoadWidth
_landHeightTable = new float[256];
for (int i = 0; i < 256; i++)
_landHeightTable[i] = reader.ReadSingle();
return true;
}
private bool SkipGameTime(BinaryReader reader, MemoryStream ms)
{
try
{
reader.ReadDouble(); // ZeroTimeOfYear
reader.ReadUInt32(); // ZeroYear
reader.ReadSingle(); // DayLength
reader.ReadUInt32(); // DaysPerYear
SkipPString(reader, ms); // YearSpec
// List<TimeOfDay> — uint32 count + entries
uint numTOD = reader.ReadUInt32();
if (numTOD > 100) return false;
for (uint i = 0; i < numTOD; i++)
{
reader.ReadSingle(); // Begin time
reader.ReadUInt32(); // IsNight flag
SkipPString(reader, ms); // Name
}
// DaysOfTheWeek — uint32 count + PStrings
uint numDays = reader.ReadUInt32();
if (numDays > 20) return false;
for (uint i = 0; i < numDays; i++)
SkipPString(reader, ms);
// List<Season> — uint32 count + entries
uint numSeasons = reader.ReadUInt32();
if (numSeasons > 20) return false;
for (uint i = 0; i < numSeasons; i++)
{
reader.ReadUInt32(); // StartDate
SkipPString(reader, ms); // Name
}
return true;
}
catch
{
return false;
}
}
private bool SkipSkyDesc(BinaryReader reader, MemoryStream ms)
{
// SkyDesc is complex (sky objects, colors, etc). Skip by searching for next recognizable section.
// Store position and try to skip it.
try
{
// SkyDesc format: TickSize(double) + LightTickSize(double) + DayGroup(SkyObjectReplace) + NightGroup + ...
// This is very complex. We'll use a heuristic: skip forward looking for SceneDesc signature.
// For now, try to skip a known minimum size
reader.ReadDouble(); // TickSize
reader.ReadDouble(); // LightTickSize
// DayGroup
SkipSkyObjectGroup(reader, ms);
// NightGroup
SkipSkyObjectGroup(reader, ms);
return true;
}
catch
{
return false;
}
}
private void SkipSkyObjectGroup(BinaryReader reader, MemoryStream ms)
{
// SkyObjectReplace: uint32 count + entries
uint count = reader.ReadUInt32();
for (uint i = 0; i < count && ms.Position < ms.Length; i++)
{
reader.ReadUInt32(); // object index
reader.ReadUInt32(); // GfxObj ID
reader.ReadSingle(); // rotate
reader.ReadSingle(); // transparent
reader.ReadSingle(); // luminosity
reader.ReadSingle(); // max bright
}
}
private bool SkipSoundDesc(BinaryReader reader, MemoryStream ms)
{
try
{
// SoundDesc: List<AmbientSoundDesc>
uint count = reader.ReadUInt32();
if (count > 200) return false;
for (uint i = 0; i < count && ms.Position < ms.Length; i++)
{
reader.ReadUInt32(); // SType
reader.ReadSingle(); // Volume
reader.ReadSingle(); // BaseChance
reader.ReadSingle(); // MinRate
reader.ReadSingle(); // MaxRate
}
return true;
}
catch
{
return false;
}
}
private bool ParseSceneDesc(BinaryReader reader, MemoryStream ms)
{
try
{
// SceneDesc: List<SceneType>
uint numSceneTypes = reader.ReadUInt32();
if (numSceneTypes > 500) return false;
_sceneTypes = new List<ScatterSceneType>();
for (uint i = 0; i < numSceneTypes; i++)
{
var st = new ScatterSceneType();
st.StbIndex = reader.ReadUInt32();
// List<uint> Scenes
uint numScenes = reader.ReadUInt32();
if (numScenes > 500) return false;
st.SceneFileIds = new List<uint>();
for (uint s = 0; s < numScenes; s++)
st.SceneFileIds.Add(reader.ReadUInt32());
_sceneTypes.Add(st);
}
Log($"SceneDesc: {_sceneTypes.Count} scene types parsed");
return true;
}
catch
{
return false;
}
}
private bool ParseTerrainDesc(BinaryReader reader, MemoryStream ms)
{
try
{
// TerrainDesc: List<TerrainType> + LandSurf
uint numTerrainTypes = reader.ReadUInt32();
if (numTerrainTypes > 100) return false;
_terrainTypes = new List<ScatterTerrainType>();
for (uint i = 0; i < numTerrainTypes; i++)
{
var tt = new ScatterTerrainType();
// PString TerrainName
SkipPString(reader, ms);
// uint32 TerrainColor
reader.ReadUInt32();
// List<uint> SceneTypes
uint numSceneTypes = reader.ReadUInt32();
if (numSceneTypes > 200) return false;
tt.SceneTypeIndices = new List<uint>();
for (uint s = 0; s < numSceneTypes; s++)
tt.SceneTypeIndices.Add(reader.ReadUInt32());
_terrainTypes.Add(tt);
}
Log($"TerrainDesc: {_terrainTypes.Count} terrain types parsed");
return true;
}
catch
{
return false;
}
}
// ===================================================================
// Fallback: scan RegionDesc data for recognizable table patterns
// ===================================================================
private bool ScanForTables(byte[] data)
{
Log("Attempting fallback scan for scatter tables...");
// Strategy: Scan for SceneDesc (uint32 count followed by entries with 0x12xxxxxx scene IDs)
// The real AC SceneDesc has ~89 entries. We require at least 20 to avoid false positives.
// TerrainDesc (~32 entries with PString names) follows right after SceneDesc.
for (int pos = 100; pos < data.Length - 100; pos += 4)
{
uint count = BitConverter.ToUInt32(data, pos);
if (count < 20 || count > 200) continue;
// Validate: try to read all entries as SceneType { uint32 StbIndex, uint32 numScenes, uint32[] sceneIds }
bool valid = true;
int scanPos = pos + 4;
int totalSceneIds = 0;
for (int i = 0; i < count && valid; i++)
{
if (scanPos + 8 > data.Length) { valid = false; break; }
uint stbIndex = BitConverter.ToUInt32(data, scanPos);
scanPos += 4;
uint numScenes = BitConverter.ToUInt32(data, scanPos);
scanPos += 4;
if (numScenes > 200) { valid = false; break; }
for (int s = 0; s < numScenes && valid; s++)
{
if (scanPos + 4 > data.Length) { valid = false; break; }
uint sceneId = BitConverter.ToUInt32(data, scanPos);
scanPos += 4;
// Scene files are 0x12xxxxxx
if ((sceneId & 0xFF000000) != 0x12000000) { valid = false; break; }
totalSceneIds++;
}
}
if (!valid || totalSceneIds < 10) continue;
// We found a candidate SceneDesc! Parse it fully.
_sceneTypes = new List<ScatterSceneType>();
int fullPos = pos + 4;
for (int i = 0; i < count; i++)
{
if (fullPos + 8 > data.Length) break;
uint stbIdx = BitConverter.ToUInt32(data, fullPos);
fullPos += 4;
uint nScenes = BitConverter.ToUInt32(data, fullPos);
fullPos += 4;
var st = new ScatterSceneType { StbIndex = stbIdx, SceneFileIds = new List<uint>() };
for (int s = 0; s < nScenes; s++)
{
if (fullPos + 4 > data.Length) break;
st.SceneFileIds.Add(BitConverter.ToUInt32(data, fullPos));
fullPos += 4;
}
_sceneTypes.Add(st);
}
Log($"Fallback found SceneDesc at offset {pos}: {_sceneTypes.Count} types, {totalSceneIds} total scene IDs");
// Now parse TerrainDesc starting right after SceneDesc
if (fullPos + 4 < data.Length)
{
if (ParseTerrainDescFromOffset(data, fullPos))
{
Log($"Fallback TerrainDesc succeeded: {_terrainTypes.Count} terrain types");
return true;
}
else
{
Log($"TerrainDesc failed at offset {fullPos}, continuing scan...");
_sceneTypes = null;
continue; // Try finding another SceneDesc
}
}
}
Log("Fallback scan failed to find scatter tables");
return false;
}
private bool ParseTerrainDescFromOffset(byte[] data, int startPos)
{
try
{
_terrainTypes = new List<ScatterTerrainType>();
int pos = startPos;
if (pos + 4 > data.Length) { _terrainTypes = null; return false; }
uint count = BitConverter.ToUInt32(data, pos);
pos += 4;
if (count < 5 || count > 100) { _terrainTypes = null; return false; }
for (int i = 0; i < count; i++)
{
var tt = new ScatterTerrainType();
// PString: ushort length + chars + align to 4
if (pos + 2 > data.Length) { _terrainTypes = null; return false; }
ushort strLen = BitConverter.ToUInt16(data, pos);
pos += 2;
if (strLen > 200 || pos + strLen > data.Length) { _terrainTypes = null; return false; }
// Verify it looks like a text string (ASCII printable)
if (i < 3 && strLen > 0)
{
bool isPrintable = true;
for (int c = 0; c < Math.Min((int)strLen, 10); c++)
{
byte b = data[pos + c];
if (b < 32 || b > 126) { isPrintable = false; break; }
}
if (!isPrintable) { _terrainTypes = null; return false; }
string name = System.Text.Encoding.ASCII.GetString(data, pos, strLen);
Log($" TerrainType[{i}]: \"{name}\"");
}
pos += strLen;
pos = (pos + 3) & ~3; // Align to 4
// uint32 TerrainColor
if (pos + 4 > data.Length) { _terrainTypes = null; return false; }
pos += 4;
// List<uint> SceneTypes
if (pos + 4 > data.Length) { _terrainTypes = null; return false; }
uint numST = BitConverter.ToUInt32(data, pos);
pos += 4;
if (numST > 200) { _terrainTypes = null; return false; }
tt.SceneTypeIndices = new List<uint>();
for (int s = 0; s < numST; s++)
{
if (pos + 4 > data.Length) { _terrainTypes = null; return false; }
tt.SceneTypeIndices.Add(BitConverter.ToUInt32(data, pos));
pos += 4;
}
_terrainTypes.Add(tt);
}
return _terrainTypes.Count >= 5;
}
catch
{
_terrainTypes = null;
return false;
}
}
// ===================================================================
// Helpers
// ===================================================================
private void SkipPString(BinaryReader reader, MemoryStream ms)
{
ushort len = reader.ReadUInt16();
if (len > 0 && ms.Position + len <= ms.Length)
ms.Seek(len, SeekOrigin.Current);
// Align to 4 bytes
long alignedPos = (ms.Position + 3) & ~3L;
if (alignedPos <= ms.Length)
ms.Position = alignedPos;
}
private void Log(string msg)
{
string line = $"[Scatter] {msg}";
System.Diagnostics.Debug.WriteLine(line);
if (DiagLog.Count < 100) DiagLog.Add(msg);
}
}
// ===================================================================
// Data structures for scatter system
// ===================================================================
public class ScatterTerrainType
{
public List<uint> SceneTypeIndices = new List<uint>();
}
public class ScatterSceneType
{
public uint StbIndex;
public List<uint> SceneFileIds = new List<uint>();
}
public class ScatterObjectDesc
{
public uint ObjId;
public float BaseLocX, BaseLocY, BaseLocZ;
public float BaseLocW, BaseLocRX, BaseLocRY, BaseLocRZ;
public float Freq;
public float DisplaceX, DisplaceY;
public float MinScale, MaxScale;
public float MaxRotation;
public float MinSlope, MaxSlope;
public uint Align, Orient, WeenieObj;
}
}

View file

@ -0,0 +1,364 @@
using Decal.Adapter;
using Decal.Adapter.Wrappers;
using System;
using System.Collections.Generic;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Provides line-of-sight checking for the combat system.
/// Converts Decal API coordinates to global meter space and
/// performs raycasting against loaded landblock geometry.
///
/// Coordinate system:
/// AC uses a landblock grid where each block is 192×192 meters.
/// Landcell ID format: 0xXXYYnnnn where XX=east-west block, YY=north-south block.
/// LocationX/Y are local offsets within the landblock (0-192 meters).
///
/// We convert everything to "global meters" for raycasting:
/// GlobalX = (XX * 192) + LocationX
/// GlobalY = (YY * 192) + LocationY
/// GlobalZ = LocationZ (altitude, 0 = sea level)
/// </summary>
public class TargetingFSM
{
private readonly GeometryLoader _geoLoader;
private readonly BlacklistManager _blacklist;
// Attack type determines which raycast to use
public enum AttackType
{
Linear, // Bolts, streaks, crossbow bolts, melee
BowArc, // Bows — moderate arc, arrows go higher than you'd think
ThrownArc, // Thrown weapons, atlatls — similar arc to bows
MagicArc // War/Void magic Arc spells — same trajectory as missile weapons
}
// AC arrows arc noticeably — they go HIGH. A lower velocity = higher arc.
// At 70 yard range, arrows visibly arc 3-4 meters above the direct line.
// This must match the actual game trajectory to detect ceiling hits in dungeons.
public float BowArcVelocity { get; set; } = 25.0f;
// Thrown weapons arc similarly to bows
public float ThrownArcVelocity { get; set; } = 22.0f;
// Magic arc spells (War/Void Arc) have the same trajectory as missile weapons
public float MagicArcVelocity { get; set; } = 25.0f;
// If true, use arc checks for missile weapons. If false, treat all as linear.
public bool UseArcs { get; set; } = true;
// Max scan distance in meters. Only check LOS for targets within this range.
// Set from CombatManager based on MonsterRange + buffer.
public float MaxScanDistanceMeters { get; set; } = 120.0f;
public TargetingFSM(GeometryLoader geoLoader, BlacklistManager blacklist)
{
_geoLoader = geoLoader ?? throw new ArgumentNullException(nameof(geoLoader));
_blacklist = blacklist ?? throw new ArgumentNullException(nameof(blacklist));
}
/// <summary>
/// Checks if line-of-sight to a target is blocked by geometry.
///
/// Returns true if the target IS blocked (should skip this target).
/// Returns false if the target is clear to attack.
/// </summary>
public bool IsTargetBlocked(CoreManager core, WorldObject target, AttackType attackType)
{
if (core == null || target == null)
return false;
if (!_geoLoader.IsInitialized)
return false;
try
{
Vector3 origin = GetPlayerPosition(core);
if (origin == Vector3.Zero)
return false;
Vector3 targetPos = GetObjectPosition(target, core);
if (targetPos == Vector3.Zero)
return false;
// Early-out: skip raycast if target is beyond scan distance
float dx = targetPos.X - origin.X;
float dy = targetPos.Y - origin.Y;
float flatDist = (float)Math.Sqrt(dx * dx + dy * dy);
if (flatDist > MaxScanDistanceMeters)
return false; // Too far to bother checking, let combat handle range
// Offset to chest height
origin.Z += 1.0f;
targetPos.Z += 1.0f;
uint landcell = GetPlayerLandcell(core);
uint cellPart = landcell & 0xFFFF;
bool isDungeon = cellPart >= 0x0100;
// Force linear checks indoors — arc trajectories hit ceilings
if (isDungeon)
attackType = AttackType.Linear;
var geometry = _geoLoader.GetLandblockGeometry(landcell);
if (geometry == null || geometry.Count == 0)
return false;
// Pre-filter: skip full ray test if no geometry near the path
float margin = Math.Min(flatDist * 0.3f, 15.0f);
margin = Math.Max(margin, 3.0f);
if (!RaycastEngine.HasNearbyGeometry(origin, targetPos, geometry, margin))
return false;
switch (attackType)
{
case AttackType.Linear:
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
case AttackType.BowArc:
if (UseArcs)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, BowArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
case AttackType.ThrownArc:
if (UseArcs)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, ThrownArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
case AttackType.MagicArc:
// Magic Arc spells have the same trajectory as missile weapons
if (UseArcs && !isDungeon) // Don't arc-check in dungeons (ceiling clips)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, MagicArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
default:
return false;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Error checking LOS: {ex.Message}");
return false;
}
}
/// <summary>
/// Finds the best unblocked target from a list of candidates.
/// Returns the target ID, or 0 if no clear target is found.
/// </summary>
public int FindBestTarget(CoreManager core, List<WorldObject> candidates, AttackType attackType)
{
if (core == null || candidates == null || candidates.Count == 0)
return 0;
foreach (var candidate in candidates)
{
try
{
int id = candidate.Id;
// Skip blacklisted targets
if (_blacklist.IsBlacklisted(id))
continue;
// Skip blocked targets
if (IsTargetBlocked(core, candidate, attackType))
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Target {id} blocked by geometry, skipping");
continue;
}
return id; // Found a clear target
}
catch
{
continue;
}
}
return 0; // No clear targets
}
/// <summary>
/// Gets the player's position in global meter coordinates.
/// Uses Decal's HooksWrapper (accessed via CoreManager.Actions).
///
/// Landcell format: 0xXXYYnnnn
/// XX = east-west block index (0-254)
/// YY = north-south block index (0-254)
///
/// LocationX/Y = offset within landblock (0-192 meters for outdoors)
/// LocationZ = altitude in meters (0 = sea level)
///
/// Global conversion:
/// GlobalX = XX * 192 + LocationX
/// GlobalY = YY * 192 + LocationY
/// GlobalZ = LocationZ
/// </summary>
private Vector3 GetPlayerPosition(CoreManager core)
{
try
{
uint landcell = (uint)core.Actions.Landcell;
uint blockX = (landcell >> 24) & 0xFF;
uint blockY = (landcell >> 16) & 0xFF;
float localX = (float)core.Actions.LocationX;
float localY = (float)core.Actions.LocationY;
float localZ = (float)core.Actions.LocationZ;
float globalX = blockX * 192.0f + localX;
float globalY = blockY * 192.0f + localY;
return new Vector3(globalX, globalY, localZ);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Error getting player pos: {ex.Message}");
return Vector3.Zero;
}
}
/// <summary>
/// Gets a world object's position in global meter coordinates.
/// Uses Decal's CoordsObject (EastWest/NorthSouth) and converts to meters.
///
/// From Decal docs:
/// EW = ((Landcell >> 24) + LocationX / 24.0 - 1019.5) / 10.0
/// NS = (((Landcell >> 16) & 0xFF) + LocationY / 24.0 - 1019.5) / 10.0
///
/// Reverse conversion (EW/NS → global meters):
/// GlobalX = (EW * 10.0 + 1019.5) * 24.0
/// GlobalY = (NS * 10.0 + 1019.5) * 24.0
/// </summary>
private Vector3 GetObjectPosition(WorldObject obj, CoreManager core)
{
try
{
var coords = obj.Coordinates();
if (coords == null)
return Vector3.Zero;
double ew = coords.EastWest;
double ns = coords.NorthSouth;
float globalX = (float)((ew * 10.0 + 1019.5) * 24.0);
float globalY = (float)((ns * 10.0 + 1019.5) * 24.0);
// Z coordinate: MUST come from RawCoordinates.
// If unavailable, return Zero to skip LOS (safer than guessing wrong Z).
float z = 0;
try
{
var raw = obj.RawCoordinates();
if (raw != null)
z = (float)raw.Z;
else
return Vector3.Zero; // Can't determine Z — skip LOS
}
catch
{
return Vector3.Zero; // Can't determine Z — skip LOS
}
return new Vector3(globalX, globalY, z);
}
catch
{
return Vector3.Zero;
}
}
/// <summary>
/// Gets the player's current Landcell value for geometry lookup.
/// </summary>
private uint GetPlayerLandcell(CoreManager core)
{
try
{
return (uint)core.Actions.Landcell;
}
catch
{
return 0;
}
}
/// <summary>
/// Determines the attack type based on combat mode and wielded weapon.
/// Magic mode ALWAYS returns Linear (spells travel straight).
/// Bows get a flat arc (high velocity). Thrown weapons arc more.
/// Melee and crossbows are Linear.
/// </summary>
public AttackType DetermineAttackType(CoreManager core)
{
try
{
// MAGIC MODE: Always linear — spells (bolts, streaks, arcs, rings)
// all use straight-line LOS in AC, regardless of equipped weapon
if (core.Actions.CombatMode == CombatState.Magic)
return AttackType.Linear;
// PEACE MODE: Default to linear
if (core.Actions.CombatMode == CombatState.Peace)
return AttackType.Linear;
// MELEE MODE: Linear (range check only, no projectile arc)
if (core.Actions.CombatMode == CombatState.Melee)
return AttackType.Linear;
// MISSILE MODE: Check the actual weapon for bow vs crossbow vs thrown
foreach (var wo in core.WorldFilter.GetInventory())
{
if (wo.Values((LongValueKey)10, 0) > 0) // CurrentWieldedLocation
{
if (wo.ObjectClass == ObjectClass.MissileWeapon)
{
string name = wo.Name?.ToLower() ?? "";
// Crossbows fire bolts in a straight line
if (name.Contains("crossbow"))
return AttackType.Linear;
// Atlatls and thrown weapons arc more
if (name.Contains("atlatl") || name.Contains("thrown") || name.Contains("dart"))
return UseArcs ? AttackType.ThrownArc : AttackType.Linear;
// Regular bows — fast, flat arc
if (name.Contains("bow"))
return UseArcs ? AttackType.BowArc : AttackType.Linear;
// Unknown missile weapon — treat as bow arc
return UseArcs ? AttackType.BowArc : AttackType.Linear;
}
// Wand in missile mode? Shouldn't happen, but treat as linear
if (wo.ObjectClass == ObjectClass.WandStaffOrb)
return AttackType.Linear;
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Error determining attack type: {ex.Message}");
}
return AttackType.Linear; // Default to linear
}
}
}

View file

@ -0,0 +1,143 @@
using System;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Custom Vector3 for the raycasting system.
///
/// IMPORTANT: This replaces System.Numerics.Vector3 in the Raycasting namespace.
/// All Raycasting/*.cs files must NOT import System.Numerics to avoid type conflicts.
/// </summary>
public struct Vector3
{
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
public static readonly Vector3 Zero = new Vector3(0, 0, 0);
public static readonly Vector3 One = new Vector3(1, 1, 1);
public static readonly Vector3 Up = new Vector3(0, 0, 1);
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
// --- Conversion ---
public static Vector3 FromNumerics(System.Numerics.Vector3 v)
=> new Vector3(v.X, v.Y, v.Z);
public System.Numerics.Vector3 ToNumerics()
=> new System.Numerics.Vector3(X, Y, Z);
public float[] ToArray()
=> new float[] { X, Y, Z };
public static Vector3 FromArray(float[] arr)
{
if (arr == null || arr.Length < 3) return Zero;
return new Vector3(arr[0], arr[1], arr[2]);
}
// --- Arithmetic operators ---
public static Vector3 operator +(Vector3 a, Vector3 b)
=> new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
public static Vector3 operator -(Vector3 a, Vector3 b)
=> new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
public static Vector3 operator -(Vector3 v)
=> new Vector3(-v.X, -v.Y, -v.Z);
public static Vector3 operator *(Vector3 v, float s)
=> new Vector3(v.X * s, v.Y * s, v.Z * s);
public static Vector3 operator *(float s, Vector3 v)
=> new Vector3(v.X * s, v.Y * s, v.Z * s);
public static Vector3 operator /(Vector3 v, float s)
{
float inv = 1.0f / s;
return new Vector3(v.X * inv, v.Y * inv, v.Z * inv);
}
// --- Vector math ---
public static float Dot(Vector3 a, Vector3 b)
=> a.X * b.X + a.Y * b.Y + a.Z * b.Z;
public static Vector3 Cross(Vector3 a, Vector3 b)
=> new Vector3(
a.Y * b.Z - a.Z * b.Y,
a.Z * b.X - a.X * b.Z,
a.X * b.Y - a.Y * b.X
);
public float Length()
=> (float)Math.Sqrt(X * X + Y * Y + Z * Z);
public float LengthSquared()
=> X * X + Y * Y + Z * Z;
public Vector3 Normalize()
{
float len = Length();
if (len < 1e-8f) return Zero;
return this * (1.0f / len);
}
public float Distance(Vector3 other)
=> (this - other).Length();
public static Vector3 Min(Vector3 a, Vector3 b)
=> new Vector3(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Min(a.Z, b.Z));
public static Vector3 Max(Vector3 a, Vector3 b)
=> new Vector3(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y), Math.Max(a.Z, b.Z));
public static Vector3 Lerp(Vector3 a, Vector3 b, float t)
=> a + (b - a) * t;
public float Length2D()
=> (float)Math.Sqrt(X * X + Y * Y);
// --- Equality ---
public override bool Equals(object obj)
{
if (obj is Vector3 other)
return X == other.X && Y == other.Y && Z == other.Z;
return false;
}
public override int GetHashCode()
=> X.GetHashCode() ^ (Y.GetHashCode() << 8) ^ (Z.GetHashCode() << 16);
public static bool operator ==(Vector3 a, Vector3 b)
=> a.X == b.X && a.Y == b.Y && a.Z == b.Z;
public static bool operator !=(Vector3 a, Vector3 b)
=> !(a == b);
public override string ToString()
=> $"({X:F3}, {Y:F3}, {Z:F3})";
public float this[int i]
{
get
{
switch (i)
{
case 0: return X;
case 1: return Y;
case 2: return Z;
default: throw new IndexOutOfRangeException();
}
}
}
}
}

View file

@ -0,0 +1,174 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProjectGuid>{AA060CDA-5478-4BFD-8CC3-B24827E19FC7}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>NexSuite.Plugins.RynthAi</RootNamespace>
<AssemblyName>RynthAi</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<LangVersion>8.0</LangVersion>
<FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Reference Include="Decal.Adapter">
<HintPath>..\..\..\..\Program Files (x86)\Decal 3.0\Decal.Adapter.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Decal.FileService">
<HintPath>..\..\..\..\Program Files (x86)\Decal 3.0\Decal.FileService.dll</HintPath>
</Reference>
<Reference Include="Decal.Interop.D3DService, Version=2.9.8.3, Culture=neutral, PublicKeyToken=481f17d392f1fb65, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<EmbedInteropTypes>False</EmbedInteropTypes>
<HintPath>..\..\..\..\Program Files (x86)\Decal 3.0\.NET 4.0 PIA\Decal.Interop.D3DService.DLL</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="KeraLua, Version=1.4.9.0, Culture=neutral, PublicKeyToken=6a194c04b9c89217, processorArchitecture=MSIL">
<HintPath>..\..\packages\KeraLua.1.4.9\lib\net46\KeraLua.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="NLua, Version=1.7.8.0, Culture=neutral, PublicKeyToken=6a194c04b9c89217, processorArchitecture=MSIL">
<HintPath>..\..\packages\NLua.1.7.8\lib\net46\NLua.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Numerics" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Serialization" />
<Reference Include="utank2-i">
<HintPath>..\..\..\..\Games\VirindiPlugins\VirindiTank\utank2-i.dll</HintPath>
</Reference>
<Reference Include="UtilityBelt.Scripting">
<HintPath>..\..\..\..\Games\DecalPlugins\UtilityBelt.Service\UtilityBelt.Scripting.dll</HintPath>
</Reference>
<Reference Include="UtilityBelt.Service">
<HintPath>..\..\..\..\Games\DecalPlugins\UtilityBelt.Service\UtilityBelt.Service.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="VTClassic">
<HintPath>..\..\..\..\Games\VirindiPlugins\VirindiTankClassicLooter\VTClassic.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Shared\NexSuite.Shared.csproj">
<Project>{11111111-1111-1111-1111-111111111111}</Project>
<Name>NexSuite.Shared</Name>
</ProjectReference>
<ProjectReference Include="..\..\Core\NexSuite.Core.csproj">
<Project>{22222222-2222-2222-2222-222222222222}</Project>
<Name>NexSuite.Core</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Compile Include="Combat\BuffManager.cs" />
<Compile Include="Combat\SpellDatabase.cs" />
<Compile Include="Combat\SpellManager.cs" />
<Compile Include="DecalInspector.cs" />
<Compile Include="Logic\BackgroundFpsUnlocker.cs" />
<Compile Include="Logic\CommandProcessor.cs" />
<Compile Include="Logic\RynthJumper.cs" />
<Compile Include="Loot\LootManager.cs" />
<Compile Include="Loot\VTankLootParser.cs" />
<Compile Include="Lua\LuaBridge.cs" />
<Compile Include="Lua\LuaManager.cs" />
<Compile Include="Meta\MetaManager.cs" />
<Compile Include="Meta\VTankMetaParser.cs" />
<Compile Include="Nav\NavigationManager.cs" />
<Compile Include="Nav\MovementActionHelper.cs" />
<Compile Include="Nav\Tier2Log.cs" />
<Compile Include="Nav\Tier2MovementHelper.cs" />
<Compile Include="Nav\VTankNavParser.cs" />
<Compile Include="Combat\CombatManager.cs" />
<Compile Include="Combat\MissileCraftingManager.cs" />
<Compile Include="Combat\CombatActionHelper.cs" />
<Compile Include="Combat\FellowshipTracker.cs" />
<Compile Include="PluginCore.cs" />
<Compile Include="Raycasting\DatDatabase.cs" />
<Compile Include="Raycasting\DungeonLOS.cs" />
<Compile Include="Raycasting\LandblockStructs.cs" />
<Compile Include="Raycasting\ScatterSystem.cs" />
<Compile Include="Raycasting\Vector3Helper.cs" />
<Compile Include="UI\AdvancedSettingsUI.cs" />
<Compile Include="UI\LuaUI.cs" />
<Compile Include="UI\MetaUI.cs" />
<Compile Include="UI\MonstersUI.cs" />
<Compile Include="UI\RynthAiUI.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="UI\RynthAiUI.Rendering.cs" />
<Compile Include="Raycasting\RaycastEngine.cs" />
<Compile Include="Raycasting\BoundingVolume.cs" />
<Compile Include="Raycasting\TargetingFSM.cs" />
<Compile Include="Raycasting\BlacklistManager.cs" />
<Compile Include="Raycasting\GeometryLoader.cs" />
<Compile Include="Raycasting\MainLogic.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UI\RouteUI.cs" />
<Compile Include="UI\UISettings.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Combat\Vtank spelldump.txt" />
</ItemGroup>
<ItemGroup>
<COMReference Include="Decal">
<Guid>{FF7F5F6D-34E0-4B6F-B3BB-8141DE2EF732}</Guid>
<VersionMajor>2</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>primary</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>True</EmbedInteropTypes>
</COMReference>
<COMReference Include="DecalNet">
<Guid>{572B87C4-93BD-46B3-A291-CD58181D25DC}</Guid>
<VersionMajor>2</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>primary</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>True</EmbedInteropTypes>
</COMReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\..\packages\KeraLua.1.4.9\build\net46\KeraLua.targets" Condition="Exists('..\..\packages\KeraLua.1.4.9\build\net46\KeraLua.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\KeraLua.1.4.9\build\net46\KeraLua.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\KeraLua.1.4.9\build\net46\KeraLua.targets'))" />
</Target>
</Project>

View file

@ -0,0 +1,483 @@
using System;
using System.Numerics;
using ImGuiNET;
namespace NexSuite.Plugins.RynthAi
{
public class AdvancedSettingsUI
{
private readonly UISettings _settings;
private MissileCraftingManager _missileCraftingManager;
public Action OnSettingsChanged;
private static readonly string[] _attackHeights = { "Low", "Medium", "High" };
private static readonly string[] _lootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
private static readonly string[] _movementModes = { "Legacy (Autorun)", "Tier 1 (CM_Movement)", "Tier 2 (MoveToPosition)" };
public AdvancedSettingsUI(UISettings settings)
{
_settings = settings;
}
public void SetMissileCraftingManager(MissileCraftingManager mgr)
{
_missileCraftingManager = mgr;
}
public void Render()
{
if (!_settings.ShowAdvancedWindow) return;
// Set a default size for the popup window
ImGui.SetNextWindowSize(new Vector2(600, 400), ImGuiCond.FirstUseEver);
if (ImGui.Begin("RynthAi Advanced Settings", ref _settings.ShowAdvancedWindow))
{
// --- LEFT COLUMN (Sidebar) ---
ImGui.BeginChild("AdvancedSidebar", new Vector2(150, 0), true);
for (int i = 0; i < _settings.AdvancedTabs.Length; i++)
{
if (ImGui.Selectable(_settings.AdvancedTabs[i], _settings.SelectedAdvancedTab == i))
{
_settings.SelectedAdvancedTab = i;
}
}
ImGui.EndChild();
ImGui.SameLine();
// --- RIGHT COLUMN (Content) ---
ImGui.BeginGroup();
ImGui.BeginChild("AdvancedContent", new Vector2(0, -ImGui.GetFrameHeightWithSpacing()), true);
RenderTabContent(_settings.SelectedAdvancedTab);
ImGui.EndChild();
// Bottom Buttons
if (ImGui.Button("Close")) _settings.ShowAdvancedWindow = false;
ImGui.EndGroup();
}
ImGui.End();
}
private void RenderTabContent(int tabIndex)
{
if (tabIndex < 0 || tabIndex >= _settings.AdvancedTabs.Length) return;
string tabName = _settings.AdvancedTabs[tabIndex];
ImGui.TextColored(new System.Numerics.Vector4(0.4f, 0.7f, 1.0f, 1.0f), $"Advanced Settings > {tabName}");
ImGui.Separator();
ImGui.Spacing();
// Note: Ensure your AdvancedSettingsUI class has an 'Action OnSettingsChanged'
// property that you set in the RynthAiUI constructor to handle auto-saving.
switch (tabName)
{
case "Misc":
// --- FPS THROTTLING ---
if (ImGui.Checkbox("Enable FPS Limit", ref _settings.EnableFPSLimit)) OnSettingsChanged?.Invoke();
if (_settings.EnableFPSLimit)
{
ImGui.Indent();
ImGui.SetNextItemWidth(150);
if (ImGui.SliderInt("Focused FPS", ref _settings.TargetFPSFocused, 10, 240)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(150);
if (ImGui.SliderInt("Background FPS", ref _settings.TargetFPSBackground, 5, 60)) OnSettingsChanged?.Invoke();
ImGui.Unindent();
}
ImGui.Separator();
ImGui.Spacing();
// --- INVENTORY MANAGEMENT ---
// Uses EnableAutocram from UISettings
if (ImGui.Checkbox("Auto Cram", ref _settings.EnableAutocram)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
{
ImGui.SetTooltip("Automatically moves items from your main pack into side packs.\n" +
"Note: Recently used weapons will stay in the main pack for quick access.");
}
ImGui.Spacing();
// --- GENERAL BEHAVIOR ---
if (ImGui.Checkbox("Peace Mode When Idle", ref _settings.PeaceModeWhenIdle)) OnSettingsChanged?.Invoke();
if (ImGui.Checkbox("Enable Raycasting", ref _settings.EnableRaycasting)) OnSettingsChanged?.Invoke();
ImGui.Separator();
ImGui.Spacing();
// --- COMBAT BLACKLIST ---
ImGui.Text("Monster Blacklist");
ImGui.SetNextItemWidth(150);
if (ImGui.SliderInt("Attempts Before Blacklist", ref _settings.BlacklistAttempts, 1, 20)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
{
ImGui.SetTooltip("How many failed attack attempts on a mob before it gets blacklisted.\n" +
"Helps avoid getting stuck on mobs clipped into walls or geometry.");
}
ImGui.SetNextItemWidth(150);
if (ImGui.SliderInt("Blacklist Timeout (sec)", ref _settings.BlacklistTimeoutSec, 5, 120)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
{
ImGui.SetTooltip("How long (seconds) a blacklisted mob is ignored before re-trying.");
}
break;
case "Recharge":
ImGui.Text("Self Vitals (%)");
ImGui.SetNextItemWidth(120);
if (ImGui.SliderInt("Heal At", ref _settings.HealAt, 0, 100)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.SliderInt("Re-stam At", ref _settings.RestamAt, 0, 100)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.SliderInt("Get Mana At", ref _settings.GetManaAt, 0, 100)) OnSettingsChanged?.Invoke();
ImGui.Spacing();
ImGui.Text("Top-Off Vitals (%)");
ImGui.SetNextItemWidth(120);
if (ImGui.SliderInt("Top HP", ref _settings.TopOffHP, 0, 100)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.SliderInt("Top Stam", ref _settings.TopOffStam, 0, 100)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.SliderInt("Top Mana", ref _settings.TopOffMana, 0, 100)) OnSettingsChanged?.Invoke();
ImGui.Spacing();
ImGui.Text("Helper Settings (%)");
ImGui.SetNextItemWidth(120);
if (ImGui.SliderInt("Heal Others", ref _settings.HealOthersAt, 0, 100)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.SliderInt("Re-stam Others", ref _settings.RestamOthersAt, 0, 100)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.SliderInt("Infuse Others", ref _settings.InfuseOthersAt, 0, 100)) OnSettingsChanged?.Invoke();
break;
case "Melee Combat":
ImGui.Text("Attack Power & Height");
ImGui.Separator();
// --- USE RECKLESSNESS ---
if (ImGui.Checkbox("Use Recklessness", ref _settings.UseRecklessness)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When enabled and Recklessness is trained,\nauto power is set to 80% instead of 100%.\nThis activates the Recklessness damage bonus.");
ImGui.Spacing();
// --- MELEE ATTACK POWER ---
bool meleeAuto = _settings.MeleeAttackPower < 0;
if (ImGui.Checkbox("Melee Auto Power", ref meleeAuto))
{
_settings.MeleeAttackPower = meleeAuto ? -1 : 100;
OnSettingsChanged?.Invoke();
}
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Auto = 100%, or 80% if Use Recklessness is on.");
if (!meleeAuto)
{
ImGui.Indent();
int mPwr = _settings.MeleeAttackPower;
ImGui.SetNextItemWidth(150);
if (ImGui.SliderInt("Melee Power %", ref mPwr, 0, 100))
{
_settings.MeleeAttackPower = mPwr;
OnSettingsChanged?.Invoke();
}
ImGui.Unindent();
}
// --- MELEE ATTACK HEIGHT ---
ImGui.SetNextItemWidth(120);
if (ImGui.Combo("Melee Attack Height", ref _settings.MeleeAttackHeight, _attackHeights, _attackHeights.Length))
OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Low = Delete, Medium = End, High = Page Down");
ImGui.Spacing();
// --- MISSILE ATTACK POWER ---
bool missileAuto = _settings.MissileAttackPower < 0;
if (ImGui.Checkbox("Missile Auto Power", ref missileAuto))
{
_settings.MissileAttackPower = missileAuto ? -1 : 100;
OnSettingsChanged?.Invoke();
}
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Auto = 100%, or 80% if Use Recklessness is on.");
if (!missileAuto)
{
ImGui.Indent();
int rPwr = _settings.MissileAttackPower;
ImGui.SetNextItemWidth(150);
if (ImGui.SliderInt("Missile Power %", ref rPwr, 0, 100))
{
_settings.MissileAttackPower = rPwr;
OnSettingsChanged?.Invoke();
}
ImGui.Unindent();
}
// --- MISSILE ATTACK HEIGHT ---
ImGui.SetNextItemWidth(120);
if (ImGui.Combo("Missile Attack Height", ref _settings.MissileAttackHeight, _attackHeights, _attackHeights.Length))
OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Low = Delete, Medium = End, High = Page Down");
ImGui.Separator();
ImGui.Spacing();
// You can add weapon-specific toggles here later
if (ImGui.Checkbox("Summon Pets", ref _settings.SummonPets)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Pet Min Monsters", ref _settings.PetMinMonsters)) OnSettingsChanged?.Invoke();
break;
case "Spell Combat":
ImGui.Text("War/Void Casting Settings");
ImGui.Separator();
if (ImGui.Checkbox("Cast Dispel Self", ref _settings.CastDispelSelf)) OnSettingsChanged?.Invoke();
ImGui.Spacing();
ImGui.Text("Ring Spell Override");
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Min Ring Targets", ref _settings.MinRingTargets)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
{
ImGui.SetTooltip("If this many monsters are within Ring Range,\nring spells are used instead of arc/bolt/streak.\nSet to 0 to disable the override.\nDefault: 4");
}
break;
case "Ranges":
ImGui.Text("Standard Ranges (Yards)");
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Monster Range", ref _settings.MonsterRange)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
{
ImGui.SetTooltip("Detection range in yards. Same units as VTank.\n" +
"Max bow range ≈ 70 yards. Magic ≈ 68 yards.\n" +
"AC internal = yards / 240");
}
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Ring Range", ref _settings.RingRange)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
{
ImGui.SetTooltip("Distance at which Ring spells are used instead of other shapes.");
}
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Approach Range", ref _settings.ApproachRange)) OnSettingsChanged?.Invoke();
ImGui.Spacing();
ImGui.Text("Corpse Acquisition (AC Units)");
ImGui.Separator();
// MOVED FROM MAIN TAB
ImGui.SetNextItemWidth(180);
if (ImGui.InputDouble("Corpse Max", ref _settings.CorpseApproachRangeMax, 0.005, 0.01, "%.6f")) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(180);
if (ImGui.InputDouble("Corpse Min", ref _settings.CorpseApproachRangeMin, 0.005, 0.01, "%.6f")) OnSettingsChanged?.Invoke();
break;
case "Navigation":
if (ImGui.Checkbox("Boost Nav Priority", ref _settings.BoostNavPriority)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.InputFloat("Follow/Nav Min", ref _settings.FollowNavMin, 0.1f, 1.0f, "%.1f")) OnSettingsChanged?.Invoke();
ImGui.Spacing();
ImGui.Text("Movement Engine");
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("Mode", ref _settings.MovementMode, _movementModes, _movementModes.Length))
OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Legacy: SetAutorun + TurnLeft/TurnRight (VTank-style)\n" +
"Tier 1: Direct CM_Movement server events\n" +
"Tier 2: Client physics MoveToPosition (smooth arcs, experimental)");
if (_settings.MovementMode == 2 && !Tier2MovementHelper.IsInitialized)
{
ImGui.SameLine();
ImGui.TextColored(new Vector4(1, 0.4f, 0.4f, 1), "(not initialized)");
}
// ── Steering (all modes) ─────────────────────────────────
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Steering");
ImGui.SetNextItemWidth(80);
if (ImGui.InputFloat("Stop & Turn Angle", ref _settings.NavStopTurnAngle, 1f, 5f, "%.0f")) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Stop forward motion and turn in place when heading error exceeds this many degrees.\nLower = more precise but stop-start. Higher = wider arcs.");
ImGui.SetNextItemWidth(80);
if (ImGui.InputFloat("Resume Run Angle", ref _settings.NavResumeTurnAngle, 1f, 5f, "%.0f")) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Resume running once the turn-in-place error drops below this.\nMust be less than Stop & Turn Angle.");
ImGui.SetNextItemWidth(80);
if (ImGui.InputFloat("Dead Zone", ref _settings.NavDeadZone, 0.5f, 1f, "%.1f")) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Ignore heading corrections smaller than this.\nSmaller = tighter line but more twitchy. Larger = smoother but wider path.");
ImGui.SetNextItemWidth(80);
if (ImGui.InputFloat("Sweep Detect Mult", ref _settings.NavSweepMult, 0.5f, 1f, "%.1f")) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Closest-approach detection radius = Arrival Radius * this.\nIf distance was decreasing and starts increasing within this radius, advance to next waypoint.\nHigher = more forgiving on tight turns. Lower = must pass closer.");
// ── Tier 2 tuning (only visible when mode 2 selected) ────
if (_settings.MovementMode == 2)
{
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Tier 2 Tuning");
ImGui.SetNextItemWidth(100);
if (ImGui.InputFloat("Speed##t2", ref _settings.T2Speed, 0.1f, 0.5f, "%.1f")) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Movement speed multiplier (1.0 = normal run speed)");
ImGui.SetNextItemWidth(100);
if (ImGui.InputFloat("Walk Within (yd)", ref _settings.T2WalkWithinYd, 1f, 5f, "%.0f")) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Switch from run to walk when within this many yards of the waypoint.\n0 = always run.");
ImGui.SetNextItemWidth(100);
if (ImGui.InputFloat("Stop Distance (yd)", ref _settings.T2DistanceTo, 0.1f, 0.5f, "%.1f")) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Stop this far from the target position (yards)");
ImGui.SetNextItemWidth(100);
if (ImGui.InputFloat("Reissue Timeout (ms)", ref _settings.T2ReissueMs, 100f, 500f, "%.0f")) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-send MoveToPosition if no progress after this many ms");
ImGui.SetNextItemWidth(100);
if (ImGui.InputFloat("Max Range (yd)", ref _settings.T2MaxRangeYd, 50f, 100f, "%.0f")) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Clamp waypoint distance to this. Will re-issue as you get closer.");
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Max Landblock Dist", ref _settings.T2MaxLandblocks, 1)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Skip MoveToPosition if target is more than N landblocks away");
}
break;
case "Buffing":
if (ImGui.Checkbox("Enable Buffing", ref _settings.EnableBuffing)) OnSettingsChanged?.Invoke();
if (ImGui.Checkbox("Rebuff When Idle", ref _settings.RebuffWhenIdle)) OnSettingsChanged?.Invoke();
break;
case "Looting":
if (ImGui.Checkbox("Enable Looting", ref _settings.EnableLooting)) OnSettingsChanged?.Invoke();
if (ImGui.Checkbox("Boost Loot Priority", ref _settings.BoostLootPriority)) OnSettingsChanged?.Invoke();
if (ImGui.Checkbox("Loot Only Rare Corpses", ref _settings.LootOnlyRareCorpses)) OnSettingsChanged?.Invoke();
ImGui.Spacing();
ImGui.Text("Corpse Ownership");
ImGui.SetNextItemWidth(180);
if (ImGui.Combo("Loot From", ref _settings.LootOwnership, _lootOwnershipModes, _lootOwnershipModes.Length))
OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
ImGui.SetTooltip("My Kills Only: Only loot corpses you killed.\nFellowship Kills: Loot kills by any fellowship member.\nAll Corpses: Loot everything within range.");
ImGui.Spacing();
ImGui.Text("Inventory Management");
if (ImGui.Checkbox("Enable Autostack", ref _settings.EnableAutostack)) OnSettingsChanged?.Invoke();
if (ImGui.Checkbox("Enable Autocram", ref _settings.EnableAutocram)) OnSettingsChanged?.Invoke();
if (ImGui.Checkbox("Combine Salvage Bags", ref _settings.EnableCombineSalvage)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
{
ImGui.SetTooltip("When enabled, salvage bags of the same material type\nare automatically combined after salvaging.");
}
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Loot Timers (ms)");
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Inter-Item Delay", ref _settings.LootInterItemDelayMs)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Delay between picking up each item from a corpse.");
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Content Settle", ref _settings.LootContentSettleMs)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Wait for corpse contents to populate after opening.");
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Empty Corpse Wait", ref _settings.LootEmptyCorpseMs)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("How long to wait before declaring a corpse empty.");
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Closing Delay", ref _settings.LootClosingDelayMs)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Delay before closing corpse after all items looted.");
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Assess Window", ref _settings.LootAssessWindowMs)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Max time to wait for item ID data from server.");
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Loot Retry Timeout", ref _settings.LootRetryTimeoutMs)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Retry picking up an item after this many ms.");
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Corpse Open Retry", ref _settings.LootOpenRetryMs)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("If corpse doesn't open, retry UseItem after this many ms.\nLower = faster but may toggle-close an already-opening corpse.");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Salvage Timers (ms) — First / Fast");
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Open (First)", ref _settings.SalvageOpenDelayFirstMs)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Open (Fast)", ref _settings.SalvageOpenDelayFastMs)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Add Item (First)", ref _settings.SalvageAddDelayFirstMs)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Add Item (Fast)", ref _settings.SalvageAddDelayFastMs)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Salvage Click", ref _settings.SalvageSalvageDelayMs)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Result (First)", ref _settings.SalvageResultDelayFirstMs)) OnSettingsChanged?.Invoke();
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Result (Fast)", ref _settings.SalvageResultDelayFastMs)) OnSettingsChanged?.Invoke();
break;
case "Crafting":
ImGui.Text("Missile Ammo Crafting");
ImGui.Separator();
ImGui.Spacing();
if (ImGui.Checkbox("Enable Missile Crafting", ref _settings.EnableMissileCrafting)) OnSettingsChanged?.Invoke();
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Auto-manage missile ammo when the ammo slot is empty:\n\n1. If better ammo can be crafted from bundles → craft it\n2. Otherwise equip the best loose ammo in inventory\n3. If no ammo exists → craft from bundles, then equip\n\nRequires Fletching skill (Trained or Specialized).\nEach combine: 1 head bundle + 1 shaft bundle = 1000 ammo.");
if (!_settings.EnableMissileCrafting) { ImGui.TextDisabled("(Disabled)"); break; }
ImGui.Spacing();
ImGui.Separator();
ImGui.Spacing();
if (_missileCraftingManager != null)
{
string stateLabel = _missileCraftingManager.State.ToString();
Vector4 stateColor = _missileCraftingManager.IsCrafting
? new Vector4(0.2f, 1.0f, 0.4f, 1.0f)
: new Vector4(0.6f, 0.6f, 0.6f, 1.0f);
ImGui.TextColored(stateColor, "State: " + stateLabel);
if (!string.IsNullOrEmpty(_missileCraftingManager.StatusMessage))
ImGui.TextWrapped(_missileCraftingManager.StatusMessage);
}
else
{
ImGui.TextDisabled("Crafting manager not initialized.");
}
ImGui.Spacing();
ImGui.Separator();
ImGui.Spacing();
ImGui.TextDisabled("Ammo Types (by priority, highest first):");
ImGui.BulletText("Lethal Prismatic (Specialized)");
ImGui.BulletText("Deadly Prismatic (Specialized)");
ImGui.BulletText("Greater Prismatic (Trained)");
ImGui.BulletText("Prismatic (Trained)");
ImGui.BulletText("Armor Piercing, Broad, Blunt, etc. (Trained)");
ImGui.Spacing();
ImGui.TextDisabled("Weapon → Ammo:");
ImGui.BulletText("Bow → Arrows (arrowheads + arrowshafts)");
ImGui.BulletText("Crossbow → Quarrels (quarrelheads + quarrelshafts)");
ImGui.BulletText("Atlatl → Darts (dart heads + dart shafts)");
break;
default:
ImGui.Text($"Settings for {tabName} are currently under development.");
break;
}
}
}
}

157
Plugins/RynthAi/UI/LuaUI.cs Normal file
View file

@ -0,0 +1,157 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using Decal.Adapter.Wrappers;
namespace NexSuite.Plugins.RynthAi
{
public class LuaUI
{
private readonly UISettings _settings;
private readonly Decal.Adapter.CoreManager _core;
// Delegates for PluginCore to hook into
public Action OnSettingsChanged;
public Action<string> OnExecuteRequested;
public Action OnStopRequested;
// Internal State
private string _luaFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\LuaScripts";
private string _newLuaFileName = "MyScript";
private int _selectedLuaIdx = 0;
public List<string> LuaFiles = new List<string>();
private string _selectedSnippetKey = "--- Select Snippet ---";
private Dictionary<string, string> _luaSnippets = new Dictionary<string, string>
{
{ "--- Select Snippet ---", "" },
{ "📍 Move to Coord", "RynthAi:GoTo(\"0.0N\", \"0.0E\")" },
{ "🌀 Use Portal/NPC", "RynthAi:UsePortal(\"Portal Name\")" },
{ "📏 Get Distance", "local dist = RynthAi:GetDistance(\"Object Name\")\nprint(\"Distance: \" .. dist)" },
{ "🛑 Emergency Stop", "RynthAi:Stop()" }
};
public LuaUI(UISettings settings, Decal.Adapter.CoreManager core)
{
_settings = settings;
_core = core;
RefreshLuaFiles();
}
public void RefreshLuaFiles()
{
LuaFiles.Clear();
LuaFiles.Add("None");
if (Directory.Exists(_luaFolder))
{
foreach (var file in Directory.GetFiles(_luaFolder, "*.lua"))
LuaFiles.Add(Path.GetFileNameWithoutExtension(file));
}
}
public void Render()
{
// Safety Checks
if (_settings.LuaScript == null) _settings.LuaScript = "";
if (_settings.LuaConsoleOutput == null) _settings.LuaConsoleOutput = "";
// 1. File & Snippet Bar
RenderTopBar();
ImGui.Separator();
// 2. Toolbar (Run, Stop, Clear)
RenderToolbar();
ImGui.Separator();
// 3. Editor & Console
RenderEditorAndConsole();
}
private void RenderTopBar()
{
ImGui.SetNextItemWidth(120);
string preview = (_selectedLuaIdx < LuaFiles.Count) ? LuaFiles[_selectedLuaIdx] : "None";
if (ImGui.BeginCombo("##LoadLua", preview))
{
for (int i = 0; i < LuaFiles.Count; i++)
{
if (ImGui.Selectable(LuaFiles[i], _selectedLuaIdx == i))
{
_selectedLuaIdx = i;
if (LuaFiles[i] != "None")
{
string path = Path.Combine(_luaFolder, LuaFiles[i] + ".lua");
if (File.Exists(path)) { _settings.LuaScript = File.ReadAllText(path); OnSettingsChanged?.Invoke(); }
}
}
}
ImGui.EndCombo();
}
ImGui.SameLine();
if (ImGui.Button("🔄")) RefreshLuaFiles();
ImGui.SameLine();
ImGui.SetNextItemWidth(120);
ImGui.InputText("##SaveAs", ref _newLuaFileName, 64);
ImGui.SameLine();
if (ImGui.Button("💾"))
{
if (!Directory.Exists(_luaFolder)) Directory.CreateDirectory(_luaFolder);
File.WriteAllText(Path.Combine(_luaFolder, _newLuaFileName + ".lua"), _settings.LuaScript);
RefreshLuaFiles();
}
ImGui.SameLine();
RenderSnippets();
}
private void RenderSnippets()
{
ImGui.SetNextItemWidth(150);
if (ImGui.BeginCombo("##Snippets", _selectedSnippetKey))
{
foreach (var s in _luaSnippets)
{
if (ImGui.Selectable(s.Key))
{
if (!string.IsNullOrEmpty(_settings.LuaScript) && !_settings.LuaScript.EndsWith("\n")) _settings.LuaScript += "\n";
_settings.LuaScript += s.Value;
OnSettingsChanged?.Invoke();
}
}
ImGui.EndCombo();
}
}
private void RenderToolbar()
{
if (ImGui.Button("▶ Run Script")) OnExecuteRequested?.Invoke(_settings.LuaScript);
ImGui.SameLine();
ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.7f, 0.1f, 0.1f, 1.0f));
if (ImGui.Button("🛑 Stop")) OnStopRequested?.Invoke();
ImGui.PopStyleColor();
ImGui.SameLine();
if (ImGui.Button("🧹 Clear Console")) { _settings.LuaConsoleOutput = "--- Console Cleared ---"; OnSettingsChanged?.Invoke(); }
}
private void RenderEditorAndConsole()
{
float editorH = ImGui.GetContentRegionAvail().Y - 150;
ImGui.InputTextMultiline("##LuaEditor", ref _settings.LuaScript, 50000, new Vector2(-1, editorH), ImGuiInputTextFlags.AllowTabInput);
ImGui.TextDisabled("Console Output:");
if (ImGui.BeginChild("LuaConsole", new Vector2(-1, 0), true, ImGuiWindowFlags.HorizontalScrollbar))
{
ImGui.TextUnformatted(_settings.LuaConsoleOutput);
if (ImGui.GetScrollY() >= ImGui.GetScrollMaxY()) ImGui.SetScrollHereY(1.0f);
}
ImGui.EndChild();
}
}
}

View file

@ -0,0 +1,650 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Linq;
using ImGuiNET;
using RynthAi.Meta;
namespace NexSuite.Plugins.RynthAi
{
public class MetaUI
{
private readonly UISettings _settings;
private readonly List<string> _navFiles; // Passed in so we can embed routes
public Action OnSettingsChanged;
public Action OnMetaRulesUpdated;
// --- META STATE ---
private bool _showMetaEditor = false;
private MetaRule _editingRule = new MetaRule();
private int _editingRuleIndex = -1;
private string _newStateName = "";
// --- META DICTIONARIES ---
private readonly string[] _metaConditionNames = {
"Never", "Always", "All", "Any", "Chat Message", "Pack Slots <=",
"Seconds in State >=", "Character Death", "Any Vendor Open",
"Vendor Closed", "Inventory Item Count <=", "Inventory Item Count >=",
"Monster Name Count Within Distance", "Monster Priority Count Within Distance",
"Need To Buff", "No Monsters Within Distance", "Landblock ==",
"Landcell ==", "Portalspace Entered", "Portalspace Exited", "Not",
"Seconds in State (P) >=", "Time Left On Spell >=", "Time Left On Spell <=",
"Burden Percentage >=", "Dist Any Route PT >=", "Expression",
"Chat Message Capture", "Navroute Empty"
};
private readonly string[] _metaActionNames = {
"None", "Chat Command", "Set Meta State", "Embedded Nav Route", "All",
"Call Meta State", "Return From Call", "Expression Action", "Chat Expression",
"Set Watchdog", "Clear Watchdog", "Get NT Option", "Set NT Option",
"Create View", "Destroy View", "Destroy All Views"
};
public MetaUI(UISettings settings, List<string> navFiles)
{
_settings = settings;
_navFiles = navFiles;
}
public void Render()
{
if (ImGui.BeginTable("MetaRulesTable", 6, ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY, new Vector2(0, -35)))
{
ImGui.TableSetupColumn("Up", ImGuiTableColumnFlags.WidthFixed, 20);
ImGui.TableSetupColumn("Dn", ImGuiTableColumnFlags.WidthFixed, 20);
ImGui.TableSetupColumn("Del", ImGuiTableColumnFlags.WidthFixed, 25);
ImGui.TableSetupColumn("State", ImGuiTableColumnFlags.WidthFixed, 100);
ImGui.TableSetupColumn("Condition", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Action", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableHeadersRow();
var groupedRules = _settings.MetaRules
.GroupBy(r => r.State)
.OrderBy(g => g.Key)
.ToList();
foreach (var group in groupedRules)
{
ImGui.TableNextRow();
ImGui.TableSetColumnIndex(3);
ImGui.TextColored(new Vector4(0, 1, 1, 1), $"--- State: {group.Key} ---");
var stateRules = group.ToList();
for (int i = 0; i < stateRules.Count; i++)
{
var rule = stateRules[i];
int globalIdx = _settings.MetaRules.IndexOf(rule);
ImGui.TableNextRow();
bool isFired = rule.HasFired;
if (isFired) ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(1f, 0.2f, 0.2f, 1f));
ImGui.TableNextColumn();
if (i > 0 && ImGui.Button($"^##up{globalIdx}"))
{
var prevRule = stateRules[i - 1];
int prevGlobalIdx = _settings.MetaRules.IndexOf(prevRule);
_settings.MetaRules[globalIdx] = prevRule;
_settings.MetaRules[prevGlobalIdx] = rule;
OnSettingsChanged?.Invoke();
}
ImGui.TableNextColumn();
if (i < stateRules.Count - 1 && ImGui.Button($"v##dn{globalIdx}"))
{
var nextRule = stateRules[i + 1];
int nextGlobalIdx = _settings.MetaRules.IndexOf(nextRule);
_settings.MetaRules[globalIdx] = nextRule;
_settings.MetaRules[nextGlobalIdx] = rule;
OnSettingsChanged?.Invoke();
}
ImGui.TableNextColumn();
ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(1, 0, 0, 1));
if (ImGui.Button($"X##delm{globalIdx}")) { _settings.MetaRules.Remove(rule); OnSettingsChanged?.Invoke(); }
ImGui.PopStyleColor();
ImGui.TableNextColumn();
if (ImGui.Selectable($"{rule.State}##edit{globalIdx}", false, ImGuiSelectableFlags.SpanAllColumns))
{
_editingRule = new MetaRule { State = rule.State, Condition = rule.Condition, ConditionData = rule.ConditionData, Action = rule.Action, ActionData = rule.ActionData };
if (rule.Children != null)
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(rule.Children);
_editingRule.Children = Newtonsoft.Json.JsonConvert.DeserializeObject<List<MetaRule>>(json);
}
_editingRuleIndex = globalIdx;
_showMetaEditor = true;
}
ImGui.TableNextColumn();
ImGui.Text(rule.Condition.ToString() + (string.IsNullOrEmpty(rule.ConditionData) ? "" : $": {rule.ConditionData}"));
ImGui.TableNextColumn();
if (rule.Action == MetaActionType.All)
{
int childCount = rule.Children?.Count ?? 0;
ImGui.TextColored(new Vector4(1, 1, 0, 1), $"All: [{childCount} actions]");
}
else if (rule.Action == MetaActionType.EmbeddedNavRoute && !string.IsNullOrEmpty(rule.ActionData) && rule.ActionData.Contains(";"))
{
var parts = rule.ActionData.Split(';');
ImGui.Text($"EmbeddedNavRoute: {parts[0]} ({parts[1]} pts)");
}
else
{
ImGui.Text(rule.Action.ToString() + (string.IsNullOrEmpty(rule.ActionData) ? "" : $": {rule.ActionData}"));
}
if (isFired) ImGui.PopStyleColor();
}
}
ImGui.EndTable();
}
ImGui.Separator();
bool isMetaEnabled = _settings.EnableMeta;
if (ImGui.Checkbox("Enable Meta", ref isMetaEnabled))
{
_settings.EnableMeta = isMetaEnabled;
OnSettingsChanged?.Invoke();
}
ImGui.SameLine();
ImGui.Text("Current State:");
ImGui.SameLine();
ImGui.SetNextItemWidth(150);
if (ImGui.BeginCombo("##CurrentStateDropdown", _settings.CurrentState))
{
if (ImGui.Selectable("< Create New State >"))
{
ImGui.OpenPopup("CreateStatePopup");
}
ImGui.Separator();
var uniqueStates = _settings.MetaRules.Select(r => r.State).Distinct().ToList();
if (!uniqueStates.Contains("Default")) uniqueStates.Insert(0, "Default");
foreach (var state in uniqueStates)
{
if (ImGui.Selectable(state, _settings.CurrentState == state))
{
if (_settings.CurrentState == state) _settings.ForceStateReset = true;
_settings.CurrentState = state;
OnSettingsChanged?.Invoke();
}
}
ImGui.EndCombo();
}
if (ImGui.BeginPopupModal("CreateStatePopup", ref _showMetaEditor, ImGuiWindowFlags.AlwaysAutoResize))
{
ImGui.Text("Enter New State Name:");
ImGui.InputText("##newStateIn", ref _newStateName, 64);
ImGui.Spacing();
if (ImGui.Button("Create", new Vector2(120, 0)))
{
if (!string.IsNullOrWhiteSpace(_newStateName))
{
_settings.CurrentState = _newStateName;
_newStateName = "";
OnSettingsChanged?.Invoke();
}
ImGui.CloseCurrentPopup();
}
ImGui.SameLine();
if (ImGui.Button("Cancel", new Vector2(120, 0))) { ImGui.CloseCurrentPopup(); }
ImGui.EndPopup();
}
ImGui.SameLine(ImGui.GetWindowWidth() - 100);
if (ImGui.Button("Create", new Vector2(80, 25)))
{
_editingRule = new MetaRule { State = _settings.CurrentState };
_editingRuleIndex = -1;
_showMetaEditor = true;
}
RenderMetaEditorPopup();
}
private void RenderMetaEditorPopup()
{
if (_showMetaEditor) ImGui.OpenPopup("Edit Meta Rule");
ImGui.SetNextWindowSize(new Vector2(650, 450), ImGuiCond.Appearing);
if (ImGui.BeginPopupModal("Edit Meta Rule", ref _showMetaEditor, ImGuiWindowFlags.NoCollapse))
{
float halfWidth = ImGui.GetContentRegionAvail().X / 2f - 4f;
var uniqueStates = _settings.MetaRules.Select(r => r.State).Distinct().ToList();
if (!uniqueStates.Contains("Default")) uniqueStates.Insert(0, "Default");
ImGui.BeginChild("ConditionPane", new Vector2(halfWidth, -35), true);
ImGui.TextColored(new Vector4(0, 1, 1, 1), "Condition Type:");
int condIdx = (int)_editingRule.Condition;
ImGui.SetNextItemWidth(-1);
if (ImGui.Combo("##CondCombo", ref condIdx, _metaConditionNames, _metaConditionNames.Length))
{
_editingRule.Condition = (MetaConditionType)condIdx;
ClearConditionDataIfNeeded(_editingRule);
}
ImGui.TextColored(new Vector4(0, 1, 1, 1), "State Name:");
ImGui.SetNextItemWidth(-30f);
string tempState = _editingRule.State ?? "";
if (ImGui.InputTextWithHint("##StateName", "State (e.g. Default)", ref tempState, 64))
_editingRule.State = tempState;
ImGui.SameLine();
ImGui.SetNextItemWidth(-1);
if (ImGui.BeginCombo("##StatePicker", "", ImGuiComboFlags.NoPreview))
{
foreach (var state in uniqueStates)
{
if (ImGui.Selectable(state)) _editingRule.State = state;
}
ImGui.EndCombo();
}
ImGui.Separator();
RenderRuleConditionNode(_editingRule, "root_cond");
ImGui.EndChild();
ImGui.SameLine();
ImGui.BeginChild("ActionPane", new Vector2(0, -35), true);
ImGui.TextColored(new Vector4(1, 1, 0, 1), "Action Type:");
RenderRuleActionNode(_editingRule, "root_action");
ImGui.EndChild();
ImGui.SetCursorPosY(ImGui.GetWindowHeight() - 30);
if (ImGui.Button(_editingRuleIndex == -1 ? "Add Rule" : "Save Rule", new Vector2(100, 25)))
{
if (_editingRuleIndex == -1) _settings.MetaRules.Add(_editingRule);
else _settings.MetaRules[_editingRuleIndex] = _editingRule;
OnSettingsChanged?.Invoke();
OnMetaRulesUpdated?.Invoke();
_showMetaEditor = false;
}
ImGui.SameLine();
if (ImGui.Button("Cancel", new Vector2(100, 25))) { _showMetaEditor = false; }
ImGui.EndPopup();
}
}
private void RenderRuleConditionNode(MetaRule rule, string idContext)
{
ImGui.PushID(idContext);
if (rule.Condition == MetaConditionType.Any ||
rule.Condition == MetaConditionType.All ||
rule.Condition == MetaConditionType.Not)
{
if (rule.Condition != MetaConditionType.Not || rule.Children.Count == 0)
{
if (ImGui.Button("+##add"))
{
rule.Children.Add(new MetaRule() { Condition = MetaConditionType.Always });
}
ImGui.SameLine();
}
ImGui.TextColored(new Vector4(1, 1, 0, 1), $"{rule.Condition} Sub-Conditions");
ImGui.Indent(15f);
for (int i = 0; i < rule.Children.Count; i++)
{
var child = rule.Children[i];
ImGui.PushID($"child_{i}");
int childCondIdx = (int)child.Condition;
ImGui.SetNextItemWidth(150);
if (ImGui.Combo("##Cond", ref childCondIdx, _metaConditionNames, _metaConditionNames.Length))
{
child.Condition = (MetaConditionType)childCondIdx;
ClearConditionDataIfNeeded(child);
}
ImGui.SameLine();
float startX = ImGui.GetCursorPosX();
float startY = ImGui.GetCursorPosY();
ImGui.SameLine(ImGui.GetWindowWidth() - 35f);
ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.8f, 0.1f, 0.1f, 1f));
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(1f, 0.2f, 0.2f, 1f));
bool deleteClicked = ImGui.Button("X");
ImGui.PopStyleColor(2);
ImGui.SetCursorPos(new Vector2(startX, startY));
RenderRuleConditionNode(child, $"node_{i}");
if (deleteClicked)
{
rule.Children.RemoveAt(i);
i--;
}
ImGui.Dummy(new Vector2(0, 2f));
ImGui.PopID();
}
ImGui.Unindent(15f);
}
else
{
bool needsData = true;
string condHint = "Data...";
if (rule.Condition == MetaConditionType.InventoryItemCount_LE ||
rule.Condition == MetaConditionType.InventoryItemCount_GE)
{
string[] parts = (rule.ConditionData ?? "").Split(',');
string itemName = parts[0];
string itemCount = parts.Length > 1 ? parts[1] : "0";
ImGui.Text("Item Name:");
ImGui.SetNextItemWidth(-1);
if (ImGui.InputText("##InvName", ref itemName, 64))
rule.ConditionData = $"{itemName},{itemCount}";
ImGui.Text("Item Count:");
ImGui.SetNextItemWidth(-1);
if (ImGui.InputText("##InvCount", ref itemCount, 16, ImGuiInputTextFlags.CharsDecimal))
rule.ConditionData = $"{itemName},{itemCount}";
needsData = false;
}
else if (rule.Condition == MetaConditionType.TimeLeftOnSpell_GE ||
rule.Condition == MetaConditionType.TimeLeftOnSpell_LE)
{
string[] parts = (rule.ConditionData ?? "").Split(',');
string spellId = parts[0];
string seconds = parts.Length > 1 ? parts[1] : "0";
ImGui.Text("Spell ID:");
ImGui.SetNextItemWidth(120);
if (ImGui.InputText("##SpellId", ref spellId, 16, ImGuiInputTextFlags.CharsDecimal))
rule.ConditionData = $"{spellId},{seconds}";
if (int.TryParse(spellId, out int id))
{
string sName = SpellDatabase.GetSpellName(id);
if (!string.IsNullOrEmpty(sName))
{
ImGui.SameLine();
ImGui.TextColored(new Vector4(0, 1, 1, 1), $"({sName})");
}
}
ImGui.Text("Seconds Remaining:");
ImGui.SetNextItemWidth(-1);
if (ImGui.InputText("##SpellTime", ref seconds, 16, ImGuiInputTextFlags.CharsDecimal))
rule.ConditionData = $"{spellId},{seconds}";
needsData = false;
}
else
{
switch (rule.Condition)
{
case MetaConditionType.Never:
case MetaConditionType.Always:
case MetaConditionType.CharacterDeath:
case MetaConditionType.AnyVendorOpen:
case MetaConditionType.VendorClosed:
case MetaConditionType.NeedToBuff:
case MetaConditionType.NoMonstersWithinDistance:
case MetaConditionType.PortalspaceEntered:
case MetaConditionType.PortalspaceExited:
case MetaConditionType.NavrouteEmpty:
needsData = false;
break;
case MetaConditionType.ChatMessage:
case MetaConditionType.ChatMessageCapture:
condHint = "Regex pattern...";
break;
case MetaConditionType.PackSlots_LE:
condHint = "Min slots (e.g. 5)";
break;
case MetaConditionType.BurdenPercentage_GE:
condHint = "Percentage (e.g. 250)";
break;
case MetaConditionType.SecondsInState_GE:
case MetaConditionType.SecondsInStateP_GE:
condHint = "Seconds (e.g. 10)";
break;
}
}
if (needsData)
{
float availableSpace = ImGui.GetWindowWidth() - ImGui.GetCursorPosX() - 40f;
ImGui.SetNextItemWidth(Math.Max(50f, availableSpace));
string cData = rule.ConditionData ?? "";
if (ImGui.InputTextWithHint("##Data", condHint, ref cData, 256))
rule.ConditionData = cData;
}
else
{
if (rule.Condition != MetaConditionType.InventoryItemCount_LE &&
rule.Condition != MetaConditionType.InventoryItemCount_GE &&
rule.Condition != MetaConditionType.TimeLeftOnSpell_GE &&
rule.Condition != MetaConditionType.TimeLeftOnSpell_LE)
{
ImGui.TextDisabled("(No extra data)");
}
}
}
ImGui.PopID();
}
private void RenderRuleActionNode(MetaRule rule, string idContext)
{
ImGui.PushID(idContext);
int actionIdx = (int)rule.Action;
ImGui.SetNextItemWidth(180);
if (ImGui.Combo("##ActionType", ref actionIdx, _metaActionNames, _metaActionNames.Length))
{
rule.Action = (MetaActionType)actionIdx;
if (rule.Action == MetaActionType.All) rule.ActionData = "";
else if (rule.Children != null) rule.Children.Clear();
}
ImGui.SameLine();
if (rule.Action == MetaActionType.All)
{
ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.2f, 0.6f, 0.2f, 1f));
if (ImGui.Button("+ Add Action"))
{
rule.Children.Add(new MetaRule { Action = MetaActionType.ChatCommand });
}
ImGui.PopStyleColor();
ImGui.Indent(20f);
for (int i = 0; i < rule.Children.Count; i++)
{
var child = rule.Children[i];
ImGui.PushID($"act_child_{i}");
if (ImGui.Button("X"))
{
rule.Children.RemoveAt(i);
i--;
}
else
{
ImGui.SameLine();
RenderRuleActionNode(child, $"child_node_{i}");
}
ImGui.PopID();
if (i < rule.Children.Count - 1) ImGui.Separator();
}
ImGui.Unindent(20f);
}
else
{
switch (rule.Action)
{
case MetaActionType.ChatCommand:
string cmd = rule.ActionData ?? "";
ImGui.SetNextItemWidth(-1);
if (ImGui.InputTextWithHint("##Cmd", "e.g. /tell {1} hello!", ref cmd, 256))
rule.ActionData = cmd;
break;
case MetaActionType.SetMetaState:
case MetaActionType.CallMetaState:
string state = rule.ActionData ?? "";
ImGui.SetNextItemWidth(-1);
if (ImGui.InputTextWithHint("##State", "Target State Name...", ref state, 64))
rule.ActionData = state;
break;
case MetaActionType.EmbeddedNavRoute:
if (ImGui.BeginCombo("##NavSelect", string.IsNullOrEmpty(rule.ActionData) ? "Select Route..." : rule.ActionData))
{
foreach (var navFile in _navFiles)
{
if (navFile == "None") continue;
if (ImGui.Selectable(navFile, rule.ActionData == navFile))
rule.ActionData = navFile;
}
ImGui.EndCombo();
}
break;
case MetaActionType.SetWatchdog:
string[] wdParts = (rule.ActionData ?? "Default;10;60").Split(';');
string wdState = wdParts[0];
string wdMeters = wdParts.Length > 1 ? wdParts[1] : "10";
string wdSeconds = wdParts.Length > 2 ? wdParts[2] : "60";
ImGui.Text("To State:");
ImGui.SetNextItemWidth(-1);
var wdStates = _settings.MetaRules.Select(r => r.State).Distinct().ToList();
if (!wdStates.Contains("Default")) wdStates.Insert(0, "Default");
if (!wdStates.Contains(wdState) && !string.IsNullOrEmpty(wdState)) wdStates.Add(wdState);
if (ImGui.BeginCombo("##WDStateCombo", wdState))
{
foreach (var s in wdStates)
{
if (ImGui.Selectable(s, wdState == s))
{
wdState = s;
}
}
ImGui.EndCombo();
}
ImGui.Spacing();
ImGui.Text("Meters in:");
ImGui.SetNextItemWidth(-1);
ImGui.InputText("##WDMeters", ref wdMeters, 8, ImGuiInputTextFlags.CharsDecimal);
ImGui.Spacing();
ImGui.Text("Seconds:");
ImGui.SetNextItemWidth(-1);
ImGui.InputText("##WDSecs", ref wdSeconds, 8, ImGuiInputTextFlags.CharsDecimal);
rule.ActionData = $"{wdState};{wdMeters};{wdSeconds}";
break;
case MetaActionType.SetNTOption:
string[] ntParts = (rule.ActionData ?? "EnableBuffing;False").Split(';');
string ntO = ntParts[0];
string ntV = ntParts.Length > 1 ? ntParts[1] : "False";
ImGui.Text("Option:");
ImGui.SetNextItemWidth(120);
if (ImGui.InputText("##NTOpt", ref ntO, 64)) rule.ActionData = $"{ntO};{ntV}";
ImGui.SameLine();
ImGui.Text("Val:");
ImGui.SetNextItemWidth(-1);
if (ImGui.InputText("##NTVal", ref ntV, 64)) rule.ActionData = $"{ntO};{ntV}";
break;
case MetaActionType.ExpressionAction:
case MetaActionType.ChatExpression:
string expr = rule.ActionData ?? "";
ImGui.SetNextItemWidth(-1);
if (ImGui.InputTextWithHint("##Expr", "Expression (e.g. [SlotCount] < 5)", ref expr, 256))
rule.ActionData = expr;
break;
case MetaActionType.GetNTOption:
case MetaActionType.CreateView:
case MetaActionType.DestroyView:
string vData = rule.ActionData ?? "";
ImGui.SetNextItemWidth(-1);
if (ImGui.InputText("##ViewData", ref vData, 128))
rule.ActionData = vData;
break;
case MetaActionType.ReturnFromCall:
case MetaActionType.ClearWatchdog:
case MetaActionType.DestroyAllViews:
ImGui.TextDisabled("(No extra data required)");
break;
case MetaActionType.None:
ImGui.TextDisabled("(Select an action type)");
break;
}
}
ImGui.PopID();
}
// ── Floating window wrapper (called from dashboard) ──────────────────
public void RenderAsWindow(ref bool open)
{
ImGui.SetNextWindowSize(new Vector2(600, 460), ImGuiCond.FirstUseEver);
if (ImGui.Begin("Macro Rules##RynthAiMeta", ref open))
Render();
ImGui.End();
}
private void ClearConditionDataIfNeeded(MetaRule rule)
{
switch (rule.Condition)
{
case MetaConditionType.Always:
case MetaConditionType.Never:
case MetaConditionType.CharacterDeath:
case MetaConditionType.AnyVendorOpen:
case MetaConditionType.VendorClosed:
case MetaConditionType.PortalspaceEntered:
case MetaConditionType.PortalspaceExited:
case MetaConditionType.NavrouteEmpty:
rule.ConditionData = "";
break;
case MetaConditionType.All:
case MetaConditionType.Any:
case MetaConditionType.Not:
rule.ConditionData = "";
break;
}
}
}
}

View file

@ -0,0 +1,282 @@
using System;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using Decal.Adapter;
using Decal.Adapter.Wrappers;
namespace NexSuite.Plugins.RynthAi
{
public class MonstersUI
{
private readonly UISettings _settings;
private readonly CoreManager _core;
public Action OnSettingsChanged;
// Local state just for this tab
private string _newMonsterName = "";
private readonly string[] _elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
public MonstersUI(UISettings settings, CoreManager core)
{
_settings = settings;
_core = core;
}
public void Render()
{
if (ImGui.BeginTable("MonstersGrid", 18, ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY, new Vector2(0, 300)))
{
ImGui.TableSetupColumn("F", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("B", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("G", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("I", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("Y", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("V", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("A", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("Bl", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("R", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("S", ImGuiTableColumnFlags.WidthFixed, 15);
ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("P", ImGuiTableColumnFlags.WidthFixed, 25);
ImGui.TableSetupColumn("Dmg type", ImGuiTableColumnFlags.WidthFixed, 80);
ImGui.TableSetupColumn("Ex Vuln", ImGuiTableColumnFlags.WidthFixed, 80);
ImGui.TableSetupColumn("Weapon", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Offhand", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("PetDmg", ImGuiTableColumnFlags.WidthFixed, 70);
ImGui.TableSetupColumn("Del", ImGuiTableColumnFlags.WidthFixed, 30);
ImGui.TableHeadersRow();
uint checkColor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.2f, 1.0f, 0.2f, 1.0f));
uint offColor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.3f, 0.3f, 0.3f, 1.0f));
for (int i = 0; i < _settings.MonsterRules.Count; i++)
{
var rule = _settings.MonsterRules[i];
bool isDefault = rule.Name.Equals("Default", StringComparison.OrdinalIgnoreCase);
ImGui.TableNextRow();
// --- 9 Toggle Lights ---
ImGui.TableNextColumn();
if (DrawToggleLight($"##F{i}", rule.Fester, checkColor, offColor, "F: Fester (Decrepitude's Grasp / Fester Other I-VIII)"))
{ rule.Fester = !rule.Fester; OnSettingsChanged?.Invoke(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##B{i}", rule.Broadside, checkColor, offColor, "B: Broadside (Broadside of a Barn / Missile Weapons Ineptitude I-VIII)"))
{ rule.Broadside = !rule.Broadside; OnSettingsChanged?.Invoke(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##G{i}", rule.GravityWell, checkColor, offColor, "G: Gravity Well (Vulnerability Other I-VIII)"))
{ rule.GravityWell = !rule.GravityWell; OnSettingsChanged?.Invoke(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##I{i}", rule.Imperil, checkColor, offColor, "I: Imperil (Gossamer Flesh / Imperil Other I-VIII)"))
{ rule.Imperil = !rule.Imperil; OnSettingsChanged?.Invoke(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##Y{i}", rule.Yield, checkColor, offColor, "Y: Yield (Magic Yield Other I-VIII)"))
{ rule.Yield = !rule.Yield; OnSettingsChanged?.Invoke(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##V{i}", rule.Vuln, checkColor, offColor, "V: Vulnerability (element-matched)"))
{ rule.Vuln = !rule.Vuln; OnSettingsChanged?.Invoke(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##A{i}", rule.UseArc, checkColor, offColor, "A: Arc spells (War/Void magic)\nFor Melee/Missile: Attack toggle"))
{ rule.UseArc = !rule.UseArc; OnSettingsChanged?.Invoke(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##Bl{i}", rule.UseBolt, checkColor, offColor, "Bl: Bolt spells (War/Void magic, default)\nIf none of A/Bl/R/S set in magic = no attack (buff bot)"))
{ rule.UseBolt = !rule.UseBolt; OnSettingsChanged?.Invoke(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##R{i}", rule.UseRing, checkColor, offColor, "R: Ring spells (uses Ring Range)"))
{ rule.UseRing = !rule.UseRing; OnSettingsChanged?.Invoke(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##S{i}", rule.UseStreak, checkColor, offColor, "S: Streak spells (War/Void magic)"))
{ rule.UseStreak = !rule.UseStreak; OnSettingsChanged?.Invoke(); }
// --- Name ---
ImGui.TableNextColumn();
if (isDefault) ImGui.TextColored(new Vector4(1, 1, 0, 1), rule.Name);
else ImGui.Text(rule.Name);
// --- Priority ---
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(25);
int p = rule.Priority;
if (ImGui.InputInt($"##P{i}", ref p, 0)) { rule.Priority = p; OnSettingsChanged?.Invoke(); }
// --- Dmg type ---
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(80);
if (ImGui.BeginCombo($"##Dmg{i}", rule.DamageType, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("Auto", rule.DamageType == "Auto")) { rule.DamageType = "Auto"; OnSettingsChanged?.Invoke(); }
foreach (var el in _elements)
{
if (ImGui.Selectable(el, rule.DamageType == el))
{ rule.DamageType = el; OnSettingsChanged?.Invoke(); }
}
ImGui.EndCombo();
}
// --- Ex Vuln (extra vulnerability element) ---
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(80);
if (ImGui.BeginCombo($"##Vuln{i}", rule.ExVuln, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("None", rule.ExVuln == "None")) { rule.ExVuln = "None"; OnSettingsChanged?.Invoke(); }
foreach (var el in _elements)
{
if (ImGui.Selectable(el, rule.ExVuln == el))
{ rule.ExVuln = el; OnSettingsChanged?.Invoke(); }
}
ImGui.EndCombo();
}
// --- Weapon Dropdown ---
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
string currentWeaponName = "<AUTO>";
if (rule.WeaponId != 0)
{
var matchedWep = _settings.ItemRules.FirstOrDefault(x => x.Id == rule.WeaponId);
if (matchedWep != null) currentWeaponName = matchedWep.Name;
}
if (ImGui.BeginCombo($"##Wep{i}", currentWeaponName, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("<AUTO>", rule.WeaponId == 0))
{ rule.WeaponId = 0; OnSettingsChanged?.Invoke(); }
foreach (var itemRule in _settings.ItemRules)
{
if (ImGui.Selectable(itemRule.Name, rule.WeaponId == itemRule.Id))
{ rule.WeaponId = itemRule.Id; OnSettingsChanged?.Invoke(); }
}
ImGui.EndCombo();
}
// --- Offhand Dropdown (shield or dual-wield weapon from ItemRules) ---
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
string currentOffhandName = "<AUTO>";
if (rule.OffhandId != 0)
{
var matchedOff = _settings.ItemRules.FirstOrDefault(x => x.Id == rule.OffhandId);
if (matchedOff != null) currentOffhandName = matchedOff.Name;
}
if (ImGui.BeginCombo($"##Off{i}", currentOffhandName, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("<AUTO>", rule.OffhandId == 0))
{ rule.OffhandId = 0; OnSettingsChanged?.Invoke(); }
foreach (var itemRule in _settings.ItemRules)
{
if (ImGui.Selectable(itemRule.Name + "##off", rule.OffhandId == itemRule.Id))
{ rule.OffhandId = itemRule.Id; OnSettingsChanged?.Invoke(); }
}
ImGui.EndCombo();
}
// --- PetDmg (pet damage element) ---
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(70);
if (ImGui.BeginCombo($"##PetDmg{i}", rule.PetDamage, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("PAuto", rule.PetDamage == "PAuto")) { rule.PetDamage = "PAuto"; OnSettingsChanged?.Invoke(); }
foreach (var el in _elements)
{
if (ImGui.Selectable(el, rule.PetDamage == el))
{ rule.PetDamage = el; OnSettingsChanged?.Invoke(); }
}
ImGui.EndCombo();
}
// --- Delete ---
ImGui.TableNextColumn();
if (isDefault)
{
ImGui.TextDisabled("-");
}
else
{
if (ImGui.Button($"X##del{i}"))
{
_settings.MonsterRules.RemoveAt(i);
OnSettingsChanged?.Invoke();
}
}
}
ImGui.EndTable();
}
ImGui.Separator();
if (ImGui.BeginTable("AddTable", 3))
{
ImGui.TableSetupColumn("NameIn", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("AddBtn", ImGuiTableColumnFlags.WidthFixed, 60);
ImGui.TableSetupColumn("AddSelBtn", ImGuiTableColumnFlags.WidthFixed, 80);
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
ImGui.InputTextWithHint("##NewMonName", "Enter monster name to add...", ref _newMonsterName, 64);
ImGui.TableNextColumn();
if (ImGui.Button("Add", new Vector2(60, 22)))
{
if (!string.IsNullOrWhiteSpace(_newMonsterName) && !_settings.MonsterRules.Any(m => m.Name.Equals(_newMonsterName, StringComparison.OrdinalIgnoreCase)))
{
_settings.MonsterRules.Add(new MonsterRule { Name = _newMonsterName, DamageType = "Auto", WeaponId = 0 });
_newMonsterName = "";
OnSettingsChanged?.Invoke();
}
}
ImGui.TableNextColumn();
if (ImGui.Button("Add Sel", new Vector2(80, 22)))
{
int selectedId = _core.Actions.CurrentSelection;
if (selectedId != 0)
{
var obj = _core.WorldFilter[selectedId];
if (obj != null && !_settings.MonsterRules.Any(m => m.Name.Equals(obj.Name, StringComparison.OrdinalIgnoreCase)))
{
_settings.MonsterRules.Add(new MonsterRule { Name = obj.Name, DamageType = "Auto", WeaponId = 0 });
OnSettingsChanged?.Invoke();
}
}
}
ImGui.EndTable();
}
}
// ── Floating window wrapper (called from dashboard) ──────────────────
public void RenderAsWindow(ref bool open)
{
ImGui.SetNextWindowSize(new Vector2(700, 400), ImGuiCond.FirstUseEver);
if (ImGui.Begin("Monster Config##RynthAiMonsters", ref open))
Render();
ImGui.End();
}
private bool DrawToggleLight(string id, bool isOn, uint onColor, uint offColor, string tooltip = null)
{
var pos = ImGui.GetCursorScreenPos();
ImGui.GetWindowDrawList().AddRectFilled(
pos + new Vector2(2, 2),
pos + new Vector2(12, 12),
isOn ? onColor : offColor, 10.0f
);
ImGui.InvisibleButton(id, new Vector2(14, 14));
if (tooltip != null && ImGui.IsItemHovered())
ImGui.SetTooltip(tooltip);
return ImGui.IsItemClicked();
}
}
}

View file

@ -0,0 +1,337 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using Decal.Adapter;
using Decal.Adapter.Wrappers;
namespace NexSuite.Plugins.RynthAi
{
public class RouteUI
{
private readonly UISettings _settings;
private readonly CoreManager _core;
public Action OnSettingsChanged;
// --- ROUTE STATE ---
private readonly string[] _routeTypes = { "Once", "Circular", "Linear", "Follow" };
private readonly string[] _addModes = { "End", "Above", "Below" };
private int _addModeIdx = 0;
private int _selectedRouteIndex = -1;
// --- GRAPHICS STATE ---
public bool NeedsRouteGraphicsRefresh = false;
private List<D3DObj> _routeGraphics = new List<D3DObj>();
public List<D3DObj> TestD3DObjects = new List<D3DObj>();
public RouteUI(UISettings settings, CoreManager core)
{
_settings = settings;
_core = core;
}
public void Render()
{
string activeNavName = string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None (Unsaved)" : Path.GetFileName(_settings.CurrentNavPath);
ImGui.TextColored(new Vector4(1, 1, 0, 1), $"Active Nav: {activeNavName}");
ImGui.Separator();
int rTypeIdx = 0;
if (_settings.CurrentRoute.RouteType == NavRouteType.Circular) rTypeIdx = 1;
else if (_settings.CurrentRoute.RouteType == NavRouteType.Linear) rTypeIdx = 2;
else if (_settings.CurrentRoute.RouteType == NavRouteType.Follow) rTypeIdx = 3;
ImGui.SetNextItemWidth(100);
if (ImGui.Combo("Route Type", ref rTypeIdx, _routeTypes, _routeTypes.Length))
{
if (rTypeIdx == 0) _settings.CurrentRoute.RouteType = NavRouteType.Once;
else if (rTypeIdx == 1) _settings.CurrentRoute.RouteType = NavRouteType.Circular;
else if (rTypeIdx == 2) _settings.CurrentRoute.RouteType = NavRouteType.Linear;
else if (rTypeIdx == 3) _settings.CurrentRoute.RouteType = NavRouteType.Follow;
TryAutoSaveNav();
}
ImGui.SameLine();
ImGui.SetNextItemWidth(100);
ImGui.Combo("Insert", ref _addModeIdx, _addModes, _addModes.Length);
ImGui.Spacing();
if (ImGui.Button("Add Waypoint", new Vector2(100, 25)))
{
var me = _core.WorldFilter[_core.CharacterFilter.Id];
if (me != null)
{
var newPt = new NavPoint
{
NS = me.Coordinates().NorthSouth,
EW = me.Coordinates().EastWest,
Z = me.Offset().Z
};
InsertPoint(newPt);
}
}
ImGui.SameLine();
if (ImGui.Button("Add Portal", new Vector2(100, 25)))
{
try
{
var me = _core.WorldFilter[_core.CharacterFilter.Id];
if (me != null)
{
var myPos = me.Coordinates();
WorldObject best = null;
double bestDist = double.MaxValue;
foreach (WorldObject wo in _core.WorldFilter.GetLandscape())
{
if (wo == null) continue;
if (wo.ObjectClass == ObjectClass.Portal || wo.ObjectClass == ObjectClass.Npc || wo.ObjectClass == ObjectClass.Vendor)
{
try
{
double dNS = wo.Coordinates().NorthSouth - myPos.NorthSouth;
double dEW = wo.Coordinates().EastWest - myPos.EastWest;
double d = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0;
if (d < bestDist) { bestDist = d; best = wo; }
}
catch { }
}
}
if (best != null && bestDist < 20.0)
{
var newPt = new NavPoint
{
Type = NavPointType.PortalNPC,
NS = myPos.NorthSouth,
EW = myPos.EastWest,
Z = me.Offset().Z,
TargetName = best.Name,
ObjectClass = (int)best.ObjectClass,
IsTie = false
};
InsertPoint(newPt);
_core.Actions.AddChatText($"[RynthAi] Added Portal/NPC: {best.Name} ({bestDist:F1}yd)", 1);
}
else
{
_core.Actions.AddChatText("[RynthAi] No portal/NPC found within 20 yards.", 1);
}
}
}
catch (Exception ex) { _core.Actions.AddChatText($"[RynthAi] Error: {ex.Message}", 1); }
}
ImGui.SameLine();
if (ImGui.Button("Add Recall", new Vector2(100, 25)))
{
ImGui.OpenPopup("RecallPopup");
}
if (ImGui.BeginPopup("RecallPopup"))
{
int[] ids = {
48, 2645, 2647,
1635, 1636,
157, 158, 1637,
2648, 2649, 2650,
2931, 2023, 2041, 2358, 2813, 2941, 2943,
3865, 3929, 3930, 4084, 4198, 4213,
4907, 4908, 4909,
5175, 5330, 5541, 6150, 6321, 6322
};
for (int ri = 0; ri < ids.Length; ri++)
{
string name = SpellDatabase.GetSpellName(ids[ri]);
if (ImGui.Selectable($"{name} ({ids[ri]})"))
{
var me = _core.WorldFilter[_core.CharacterFilter.Id];
if (me != null)
{
var newPt = new NavPoint
{
Type = NavPointType.Recall,
NS = me.Coordinates().NorthSouth,
EW = me.Coordinates().EastWest,
Z = me.Offset().Z,
SpellId = ids[ri]
};
InsertPoint(newPt);
_core.Actions.AddChatText($"[RynthAi] Added Recall: {name} ({ids[ri]})", 1);
}
}
}
ImGui.EndPopup();
}
ImGui.SameLine();
if (ImGui.Button("Clear Route", new Vector2(100, 25)))
{
_settings.CurrentRoute.Points.Clear();
_settings.ActiveNavIndex = 0;
TryAutoSaveNav();
DisposeRouteGraphics();
OnSettingsChanged?.Invoke();
}
ImGui.SameLine();
if (ImGui.Button("Save Route", new Vector2(100, 25)))
{
if (!string.IsNullOrEmpty(_settings.CurrentNavPath))
{
try { _settings.CurrentRoute.Save(_settings.CurrentNavPath); _core.Actions.AddChatText("[RynthAi] Route saved.", 1); } catch { }
}
}
if (ImGui.BeginListBox("##RoutePoints", new Vector2(-1, 200)))
{
for (int i = 0; i < _settings.CurrentRoute.Points.Count; i++)
{
// Push a unique ID so ImGui doesn't confuse the 50 different "X" buttons
ImGui.PushID($"route_pt_{i}");
// Draw the red "X" button
ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.8f, 0.2f, 0.2f, 1f));
if (ImGui.Button("X", new Vector2(20, 20)))
{
// 1. Remove the point
_settings.CurrentRoute.Points.RemoveAt(i);
// 2. Safely shift our selected/active indexes so we don't crash
if (_selectedRouteIndex == i) _selectedRouteIndex = -1;
else if (_selectedRouteIndex > i) _selectedRouteIndex--;
if (_settings.ActiveNavIndex == i) _settings.ActiveNavIndex = 0;
else if (_settings.ActiveNavIndex > i) _settings.ActiveNavIndex--;
// 3. Save, update 3D graphics, and notify the plugin
TryAutoSaveNav();
UpdateRouteGraphics();
OnSettingsChanged?.Invoke();
// 4. Pop the styles and break the loop for this single frame to prevent index out-of-range errors
ImGui.PopStyleColor();
ImGui.PopID();
break;
}
ImGui.PopStyleColor();
ImGui.SameLine();
// Draw the selectable row text
string prefix = " ";
if (i == _settings.ActiveNavIndex) prefix = "==>";
bool isSelected = (_selectedRouteIndex == i);
if (ImGui.Selectable($"{prefix} [{i}] {_settings.CurrentRoute.Points[i]}", isSelected))
{
_selectedRouteIndex = i;
}
ImGui.PopID();
}
ImGui.EndListBox();
}
}
public void InsertPoint(NavPoint newPt)
{
if (_addModeIdx == 0 || _settings.CurrentRoute.Points.Count == 0)
_settings.CurrentRoute.Points.Add(newPt);
else if (_addModeIdx == 1 && _selectedRouteIndex >= 0)
_settings.CurrentRoute.Points.Insert(_selectedRouteIndex, newPt);
else if (_addModeIdx == 2 && _selectedRouteIndex >= 0)
_settings.CurrentRoute.Points.Insert(_selectedRouteIndex + 1, newPt);
else
_settings.CurrentRoute.Points.Add(newPt);
TryAutoSaveNav();
UpdateRouteGraphics();
OnSettingsChanged?.Invoke();
}
public void TryAutoSaveNav()
{
if (!string.IsNullOrEmpty(_settings.CurrentNavPath))
{
try { _settings.CurrentRoute.Save(_settings.CurrentNavPath); } catch { }
}
}
public void UpdateRouteGraphics()
{
DisposeRouteGraphics();
if (_settings.CurrentRoute?.Points == null || _settings.CurrentRoute.Points.Count == 0)
return;
if (_core?.D3DService == null)
return;
int colorAqua = unchecked((int)0xFF00FFFF);
int colorBlue = unchecked((int)0xFF0088FF);
int colorRed = unchecked((int)0xFFFF2222);
float ringScale = Math.Max(0.5f, (float)_settings.FollowNavMin);
try
{
for (int i = 0; i < _settings.CurrentRoute.Points.Count; i++)
{
var pt = _settings.CurrentRoute.Points[i];
int wpColor = (i == _settings.ActiveNavIndex) ? colorRed : colorAqua;
var ring = _core.D3DService.MarkCoordsWithShape(
(float)pt.NS, (float)pt.EW, (float)pt.Z + 0.5f,
Decal.Adapter.Wrappers.D3DShape.Ring, wpColor);
ring.Visible = true;
ring.ScaleX = ringScale;
ring.ScaleY = ringScale;
ring.ScaleZ = 0.1f;
try { ring.Anchor((float)pt.NS, (float)pt.EW, (float)pt.Z + 0.5f); } catch { }
_routeGraphics.Add(ring);
int nextIdx = i + 1;
if (nextIdx >= _settings.CurrentRoute.Points.Count)
{
if (_settings.CurrentRoute.RouteType == NavRouteType.Circular) nextIdx = 0;
else continue;
}
var nextPt = _settings.CurrentRoute.Points[nextIdx];
double dNS = nextPt.NS - pt.NS;
double dEW = nextPt.EW - pt.EW;
double dZ = nextPt.Z - pt.Z;
double dist2D = Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0;
int dots = Math.Min(150, Math.Max(2, (int)dist2D));
for (int d = 1; d < dots; d++)
{
double f = (double)d / dots;
var dot = _core.D3DService.MarkCoordsWithShape(
(float)(pt.NS + dNS * f),
(float)(pt.EW + dEW * f),
(float)(pt.Z + dZ * f) + 0.5f,
Decal.Adapter.Wrappers.D3DShape.Sphere, colorBlue);
dot.Visible = true;
dot.Scale(0.15f);
_routeGraphics.Add(dot);
}
}
}
catch { }
}
public void DisposeRouteGraphics()
{
foreach (var o in _routeGraphics) { try { o.Visible = false; ((IDisposable)o).Dispose(); } catch { } }
_routeGraphics.Clear();
foreach (var o in TestD3DObjects) { try { o.Visible = false; ((IDisposable)o).Dispose(); } catch { } }
TestD3DObjects.Clear();
}
}
}

View file

@ -0,0 +1,9 @@
namespace NexSuite.Plugins.RynthAi
{
// This file intentionally left blank.
// The old "Unified Tabs" UI has been retired in favor of the clean Advanced Settings menu.
public partial class RynthAiUI
{
}
}

View file

@ -0,0 +1,997 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Numerics;
using System.Linq;
using ImGuiNET;
using Decal.Adapter;
using Decal.Adapter.Wrappers;
using RynthAi.Meta;
namespace NexSuite.Plugins.RynthAi
{
public static class DashWindows
{
public static bool ShowMacroRules = false;
public static bool ShowMonsters = false;
public static bool ShowNavigation = false;
public static bool ShowWeapons = false;
public static bool ShowLua = false;
}
public partial class RynthAiUI : IDisposable
{
public UISettings Settings { get; set; }
public CombatManager CombatManager { get; set; }
public CoreManager Core { get; set; }
public MetaManager MetaManager { get; set; }
public Action OnSettingsChanged;
public Action OnForceRebuffClicked;
public Action OnLootProfileSelected;
public Action OnMetaProfileSelected;
public Action OnMetaRulesUpdated;
public LuaUI LuaTab;
public MetaUI MetaTab;
public MonstersUI MonstersTab;
public RouteUI RouteTab;
private readonly AdvancedSettingsUI _advancedUI;
public List<string> Profiles = new List<string>();
public List<string> NavFiles = new List<string>();
public List<string> LootFiles = new List<string>();
public List<string> MetaFiles = new List<string>();
private int _selectedNavIdx = 0;
private string _navFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\NavProfiles";
private string _lootFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\LootProfiles";
private string _metaFolder = @"C:\Games\DecalPlugins\NexSuite\RynthAi\MetaProfiles";
private readonly string[] _elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
// ── Colour palette ───────────────────────────────────────────────────
private static readonly Vector4 ColTeal = new Vector4(0.15f, 0.85f, 0.90f, 1.00f);
private static readonly Vector4 ColAmber = new Vector4(0.91f, 0.70f, 0.20f, 1.00f);
private static readonly Vector4 ColRed = new Vector4(0.85f, 0.25f, 0.25f, 1.00f);
private static readonly Vector4 ColGreen = new Vector4(0.25f, 0.85f, 0.45f, 1.00f);
private static readonly Vector4 ColTextDim = new Vector4(0.85f, 0.90f, 0.95f, 1.00f);
private static readonly Vector4 ColTextMute = new Vector4(0.55f, 0.65f, 0.75f, 1.00f);
private static readonly Vector4 ColHp = new Vector4(0.85f, 0.20f, 0.20f, 1.00f);
private static readonly Vector4 ColStam = new Vector4(0.20f, 0.80f, 0.35f, 1.00f);
private static readonly Vector4 ColMana = new Vector4(0.15f, 0.55f, 0.95f, 1.00f);
private static readonly Vector4 ColBarBg = new Vector4(0.08f, 0.12f, 0.16f, 1.00f);
private static readonly Vector4 ColPanelBg = new Vector4(0.04f, 0.07f, 0.10f, 0.95f);
private static readonly Vector4 ColBtnOn = new Vector4(0.15f, 0.30f, 0.35f, 1.00f);
private static readonly Vector4 ColBtnFill = new Vector4(0.06f, 0.12f, 0.18f, 1.00f);
private static readonly Vector4 ColBtnHov = new Vector4(0.10f, 0.18f, 0.25f, 1.00f);
private static readonly Vector4 ColBtnAct = new Vector4(0.08f, 0.15f, 0.22f, 1.00f);
private static readonly Vector4 ColBtnBord = new Vector4(0.15f, 0.25f, 0.35f, 1.00f);
// ── DRAKHUD HEALTH ENGINE ────────────────────────────────────────────
private Dictionary<int, float> _healthRatioTracker = new Dictionary<int, float>();
private Dictionary<int, int> _maxHealthTracker = new Dictionary<int, int>();
private int _lastTargetId = 0;
private int _retryTargetId = 0;
private int _retryCount = 0;
private DateTime _lastRequestTime = DateTime.MinValue;
// ── UI STATE ─────────────────────────────────────────────────────────
private bool _isMinimized = false;
private bool _isLocked = false;
private float _bgOpacity = 0.95f;
private Vector2 _expandedSize = new Vector2(430, 420);
private bool _wasMinimized = false;
public RynthAiUI(UISettings settings, CombatManager combatManager, CoreManager core)
{
Settings = settings;
CombatManager = combatManager;
Core = core;
LuaTab = new LuaUI(settings, core);
_advancedUI = new AdvancedSettingsUI(settings) { OnSettingsChanged = () => OnSettingsChanged?.Invoke() };
MetaTab = new MetaUI(settings, NavFiles) { OnSettingsChanged = () => OnSettingsChanged?.Invoke(), OnMetaRulesUpdated = () => OnMetaRulesUpdated?.Invoke() };
MonstersTab = new MonstersUI(settings, core) { OnSettingsChanged = () => OnSettingsChanged?.Invoke() };
RouteTab = new RouteUI(settings, core) { OnSettingsChanged = () => OnSettingsChanged?.Invoke() };
RefreshProfilesList(); RefreshNavFiles(); RefreshLootFiles(); RefreshMetaFiles();
try { Core.EchoFilter.ServerDispatch += OnServerDispatch; } catch { }
}
public void Dispose()
{
try { Core.EchoFilter.ServerDispatch -= OnServerDispatch; } catch { }
}
public void SetMissileCraftingManager(MissileCraftingManager mgr) => _advancedUI.SetMissileCraftingManager(mgr);
public void Render()
{
UpdateTargetAppraisal();
if (RouteTab != null && RouteTab.NeedsRouteGraphicsRefresh)
{ RouteTab.NeedsRouteGraphicsRefresh = false; RouteTab.UpdateRouteGraphics(); }
RenderDashboard();
// Render all active popup windows based on the button toggles
try { if (Settings.ShowAdvancedWindow) _advancedUI?.Render(); } catch { Settings.ShowAdvancedWindow = false; }
try { if (DashWindows.ShowMacroRules) MetaTab?.RenderAsWindow(ref DashWindows.ShowMacroRules); } catch { DashWindows.ShowMacroRules = false; }
try { if (DashWindows.ShowMonsters) MonstersTab?.RenderAsWindow(ref DashWindows.ShowMonsters); } catch { DashWindows.ShowMonsters = false; }
try { if (DashWindows.ShowWeapons) RenderWeaponsWindow(); } catch { DashWindows.ShowWeapons = false; }
try { if (DashWindows.ShowNavigation) RenderNavigationWindow(); } catch { DashWindows.ShowNavigation = false; }
try { if (DashWindows.ShowLua) RenderLuaWindow(); } catch { DashWindows.ShowLua = false; }
}
private void RenderDashboard()
{
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 10));
ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 8.0f);
ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, 6.0f);
ImGui.PushStyleColor(ImGuiCol.WindowBg, new Vector4(0.04f, 0.06f, 0.08f, _bgOpacity));
ImGuiWindowFlags flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoCollapse;
if (_isMinimized)
{
flags |= ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoResize;
_wasMinimized = true;
}
else
{
if (_isLocked) flags |= ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove;
if (_wasMinimized)
{
ImGui.SetNextWindowSize(_expandedSize, ImGuiCond.Always);
_wasMinimized = false;
}
}
ImGui.SetNextWindowSizeConstraints(new Vector2(400, 0), new Vector2(1200, 2000));
if (!_wasMinimized && !_isMinimized && !_isLocked)
{
ImGui.SetNextWindowSize(_expandedSize, ImGuiCond.FirstUseEver);
}
if (ImGui.Begin("RynthAi Dashboard##Main", flags))
{
if (!_isMinimized && !_isLocked && !_wasMinimized)
{
_expandedSize = ImGui.GetWindowSize();
}
RenderDashHeader();
ImGui.PushStyleColor(ImGuiCol.ChildBg, ColPanelBg);
ImGui.PushStyleColor(ImGuiCol.Border, ColBtnBord);
ImGui.PushStyleVar(ImGuiStyleVar.ChildBorderSize, 1.0f);
if (ImGui.BeginChild("CombatPanel", new Vector2(-1, 154), true, ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse))
{
RenderCombatPanel();
ImGui.Dummy(new Vector2(0, 4));
}
ImGui.EndChild();
ImGui.PopStyleVar();
ImGui.PopStyleColor(2);
if (!_isMinimized)
{
ImGui.Spacing(); ImGui.Spacing();
RenderLauncherGrid();
}
}
ImGui.End();
ImGui.PopStyleColor();
ImGui.PopStyleVar(3);
}
private void RenderDashHeader()
{
float W = ImGui.GetContentRegionAvail().X;
float startY = ImGui.GetCursorPosY();
ImGui.SetWindowFontScale(1.4f);
ImGui.TextColored(ColTeal, "N"); ImGui.SameLine(0, 2);
ImGui.TextColored(new Vector4(1, 1, 1, 1), "NEXAI DASHBOARD");
ImGui.SetWindowFontScale(1.0f);
ImGui.SameLine();
ImGui.SetCursorPosY(startY + 5);
ImGui.TextColored(ColTextMute, "v4.0");
ImGui.SameLine(W - 130);
ImGui.SetCursorPosY(startY + 2);
if (ImGui.SmallButton(_isLocked ? "Unlk" : "Lock")) { _isLocked = !_isLocked; }
if (ImGui.IsItemHovered()) ImGui.SetTooltip(_isLocked ? "Unlock Window" : "Lock Window");
ImGui.SameLine();
if (ImGui.SmallButton("-")) _bgOpacity = Math.Max(0.1f, _bgOpacity - 0.1f);
ImGui.SameLine();
if (ImGui.SmallButton("+")) _bgOpacity = Math.Min(1.0f, _bgOpacity + 0.1f);
ImGui.SameLine();
if (ImGui.SmallButton(_isMinimized ? "^" : "_")) { _isMinimized = !_isMinimized; }
ImGui.SameLine();
if (ImGui.SmallButton("X")) { Settings.IsMacroRunning = false; }
ImGui.Dummy(new Vector2(0, 2));
if (!_isMinimized)
{
if (ImGui.BeginTable("HeaderGrid", 2))
{
ImGui.TableSetupColumn("Left", ImGuiTableColumnFlags.WidthFixed, W * 0.40f);
ImGui.TableSetupColumn("Right", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.SetWindowFontScale(1.3f);
ImGui.TextColored(ColTextMute, "Macro Status:");
ImGui.SetWindowFontScale(1.0f);
ImGui.TableNextColumn();
ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 2);
ImGui.TextColored(ColTextMute, "Profile:");
ImGui.SameLine(60);
ImGui.SetNextItemWidth(-1);
if (ImGui.BeginCombo("##ProfCombo", TruncateName(Settings.SelectedProfile, 16)))
{
foreach (var p in Profiles)
{
if (ImGui.Selectable(p, p == Settings.SelectedProfile))
{
Settings.SelectedProfile = p; OnSettingsChanged?.Invoke();
}
}
ImGui.EndCombo();
}
ImGui.TableNextRow();
ImGui.TableNextColumn();
var pos = ImGui.GetCursorScreenPos();
var dl = ImGui.GetWindowDrawList();
uint color = Settings.IsMacroRunning ? ImGui.ColorConvertFloat4ToU32(ColGreen) : ImGui.ColorConvertFloat4ToU32(ColTextMute);
dl.AddCircleFilled(pos + new Vector2(8, 12), 6, color);
if (Settings.IsMacroRunning) dl.AddCircle(pos + new Vector2(8, 12), 9, color, 12, 1.5f);
ImGui.SetCursorScreenPos(pos + new Vector2(24, 0));
if (ImGui.InvisibleButton("ToggleMacro", new Vector2(100, 24)))
{
Settings.IsMacroRunning = !Settings.IsMacroRunning;
OnSettingsChanged?.Invoke();
}
ImGui.SetCursorScreenPos(pos + new Vector2(26, 2));
ImGui.SetWindowFontScale(1.3f);
ImGui.TextColored(Settings.IsMacroRunning ? ColGreen : ColTextMute, Settings.IsMacroRunning ? "RUNNING" : "STOPPED");
ImGui.SetWindowFontScale(1.0f);
ImGui.TableNextColumn();
ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 4);
ImGui.TextColored(ColTextMute, "Nav:");
ImGui.SameLine(60);
ImGui.SetNextItemWidth(-1);
string navName = string.IsNullOrEmpty(Settings.CurrentNavPath) ? "None" : Path.GetFileNameWithoutExtension(Settings.CurrentNavPath);
if (ImGui.BeginCombo("##NavCombo", TruncateName(navName, 16)))
{
for (int i = 0; i < NavFiles.Count; i++)
{
if (ImGui.Selectable(NavFiles[i], _selectedNavIdx == i))
{
_selectedNavIdx = i; LoadSelectedNav();
}
}
ImGui.EndCombo();
}
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 4);
ImGui.TextColored(ColTextMute, "State:"); ImGui.SameLine(0, 8);
ImGui.TextColored(ColAmber, Settings.CurrentState ?? "Idle");
ImGui.TableNextColumn();
ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 6);
ImGui.TextColored(ColTextMute, "Loot:");
ImGui.SameLine(60);
ImGui.SetNextItemWidth(-1);
string lootName = string.IsNullOrEmpty(Settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(Settings.CurrentLootPath);
if (ImGui.BeginCombo("##LootCombo", TruncateName(lootName, 16)))
{
for (int i = 0; i < LootFiles.Count; i++)
{
if (ImGui.Selectable(LootFiles[i], Settings.LootProfileIdx == i))
{
Settings.LootProfileIdx = i;
Settings.CurrentLootPath = (i == 0) ? "" : Path.Combine(_lootFolder, LootFiles[i] + ".utl");
OnSettingsChanged?.Invoke(); OnLootProfileSelected?.Invoke();
}
}
ImGui.EndCombo();
}
ImGui.EndTable();
}
ImGui.Spacing();
}
}
private void RenderCombatPanel()
{
if (ImGui.BeginTable("CombatInnerTable", 2, ImGuiTableFlags.None))
{
ImGui.TableSetupColumn("Toggles", ImGuiTableColumnFlags.WidthFixed, 68);
ImGui.TableSetupColumn("Vitals", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableNextRow();
// --- COLUMN 1: TOGGLES ---
ImGui.TableNextColumn();
var tPos = ImGui.GetCursorScreenPos() + new Vector2(2, 28);
// 2x2 Grid
DrawSquareToggle("sword", ref Settings.EnableCombat, tPos, "CombatTgl");
DrawSquareToggle("buff", ref Settings.EnableBuffing, tPos + new Vector2(34, 0), "BuffTgl");
DrawSquareToggle("shoe", ref Settings.EnableNavigation, tPos + new Vector2(0, 34), "NavTgl");
DrawSquareToggle("bag", ref Settings.EnableLooting, tPos + new Vector2(34, 34), "LootTgl");
// Wide MACRO Button
DrawWideToggle("MACRO", "gear", ref Settings.EnableMeta, tPos + new Vector2(0, 68), "MetaTgl", 64f, 20f);
// --- COLUMN 2: MOB + PLAYER VITALS ---
ImGui.TableNextColumn();
string targetName = "NO TARGET";
float targetHpPct = 0f;
string mobHpDisplay = "0%";
int currentTarget = Core.Actions.CurrentSelection;
if (currentTarget != 0)
{
try
{
var wo = Core.WorldFilter[currentTarget];
if (wo != null)
{
targetName = wo.Name;
if (_healthRatioTracker.ContainsKey(currentTarget))
{
targetHpPct = _healthRatioTracker[currentTarget];
}
else
{
targetHpPct = (float)wo.Values((DoubleValueKey)0x92, 0.0);
}
if (_maxHealthTracker.ContainsKey(currentTarget) && _maxHealthTracker[currentTarget] > 0)
{
int maxHp = _maxHealthTracker[currentTarget];
int curHp = (int)Math.Round(targetHpPct * maxHp);
mobHpDisplay = $"{(int)(targetHpPct * 100)}% ({curHp}/{maxHp})";
}
else
{
mobHpDisplay = $"{(int)(targetHpPct * 100)}%";
}
}
}
catch { }
}
ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 4);
ImGui.TextColored(ColTextDim, TruncateName(targetName, 32).ToUpper());
float textWidth = ImGui.CalcTextSize(mobHpDisplay).X;
ImGui.SameLine(ImGui.GetContentRegionAvail().X - textWidth);
ImGui.TextColored(new Vector4(1, 1, 1, 1), mobHpDisplay);
DrawSegmentedBar(targetHpPct, ImGui.GetContentRegionAvail().X - 4);
ImGui.Spacing();
ImGui.TextColored(ColTextMute, "PLAYER VITALS");
int hp = 0, hpMax = 1, st = 0, stMax = 1, mn = 0, mnMax = 1;
try
{
if (Core?.CharacterFilter != null)
{
hp = Core.CharacterFilter.Health; hpMax = Math.Max(1, (int)Core.CharacterFilter.EffectiveVital[CharFilterVitalType.Health]);
st = Core.CharacterFilter.Stamina; stMax = Math.Max(1, (int)Core.CharacterFilter.EffectiveVital[CharFilterVitalType.Stamina]);
mn = Core.CharacterFilter.Mana; mnMax = Math.Max(1, (int)Core.CharacterFilter.EffectiveVital[CharFilterVitalType.Mana]);
}
}
catch { }
float hpPct = (float)hp / hpMax; float stPct = (float)st / stMax; float mnPct = (float)mn / mnMax;
DrawVitalRow("heart", "HP", hpPct, ColHp, $"{hp}/{hpMax}");
DrawVitalRow("run", "ST", stPct, ColGreen, $"{st}/{stMax}");
DrawVitalRow("drop", "MN", mnPct, ColMana, $"{mn}/{mnMax}");
ImGui.EndTable();
}
}
private void RenderLauncherGrid()
{
if (ImGui.BeginTable("LauncherGridTable", 3, ImGuiTableFlags.SizingStretchSame))
{
ImGui.TableNextRow();
ImGui.TableNextColumn(); GridBtn("Macro Rules", "gear", ref DashWindows.ShowMacroRules);
ImGui.TableNextColumn(); GridBtn("Monsters", "target", ref DashWindows.ShowMonsters);
ImGui.TableNextColumn(); GridBtn("Settings", "wrench", ref Settings.ShowAdvancedWindow);
ImGui.TableNextRow();
ImGui.TableNextColumn(); GridBtn("Navigation", "map", ref DashWindows.ShowNavigation);
ImGui.TableNextColumn(); GridBtn("Weapons", "shield", ref DashWindows.ShowWeapons);
ImGui.TableNextColumn(); GridBtn("Lua Scripts", "code", ref DashWindows.ShowLua);
ImGui.EndTable();
}
}
private void GridBtn(string label, string icon, ref bool flag)
{
bool wasOn = flag;
float bH = 30f;
float bW = -1f;
ImGui.PushStyleColor(ImGuiCol.Button, ColBtnFill);
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, ColBtnHov);
ImGui.PushStyleColor(ImGuiCol.ButtonActive, ColBtnAct);
ImGui.PushStyleColor(ImGuiCol.Border, wasOn ? ColTeal : ColBtnBord);
ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1.0f);
ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 4f);
var startPos = ImGui.GetCursorScreenPos();
if (ImGui.Button($"##{label}", new Vector2(bW, bH))) flag = !flag;
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(4);
float actualWidth = ImGui.GetItemRectSize().X;
var textSize = ImGui.CalcTextSize(label);
DrawIcon(icon, startPos + new Vector2(8, 6), wasOn ? ColTeal : ColTextMute, 16f);
ImGui.SetCursorScreenPos(startPos + new Vector2(30, (bH - textSize.Y) / 2));
ImGui.TextColored(wasOn ? ColTeal : ColTextDim, label);
ImGui.SetCursorScreenPos(startPos + new Vector2(0, bH + 2));
ImGui.Dummy(new Vector2(actualWidth, 0));
}
// ═════════════════════════════════════════════════════════════════════
// WEAPONS & ITEMS WINDOW
// ═════════════════════════════════════════════════════════════════════
private void RenderWeaponsWindow()
{
ImGui.SetNextWindowSize(new Vector2(480, 300), ImGuiCond.FirstUseEver);
if (ImGui.Begin("Weapons & Items##RynthAiWeapons", ref DashWindows.ShowWeapons))
{
ImGui.TextColored(ColAmber, "Weapons / Wands / Shields / Pets");
if (ImGui.BeginTable("ItemsTable", 3,
ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.Resizable))
{
ImGui.TableSetupColumn("Item Name", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Element", ImGuiTableColumnFlags.WidthFixed, 100);
ImGui.TableSetupColumn("Actions", ImGuiTableColumnFlags.WidthFixed, 60);
ImGui.TableHeadersRow();
for (int i = 0; i < Settings.ItemRules.Count; i++)
{
var rule = Settings.ItemRules[i];
ImGui.TableNextRow();
ImGui.TableNextColumn();
var wo = Core?.WorldFilter[rule.Id];
if (wo != null)
ImGui.Text(rule.Name);
else
{
ImGui.TextColored(ColRed, rule.Name);
ImGui.SameLine();
ImGui.TextColored(new Vector4(1f, 0.3f, 0.3f, 0.8f), "(Gone)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Weapon not in inventory!\nBot cannot equip this item.\nRemove and re-add the correct weapon.");
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
if (ImGui.BeginCombo($"##Elem{i}", rule.Element, ImGuiComboFlags.NoArrowButton))
{
foreach (var el in _elements)
if (ImGui.Selectable(el, rule.Element == el))
{ rule.Element = el; OnSettingsChanged?.Invoke(); }
ImGui.EndCombo();
}
ImGui.TableNextColumn();
if (ImGui.Button($"Del##{i}", new Vector2(-1, 0)))
{
foreach (var mr in Settings.MonsterRules)
{
if (mr.WeaponId == rule.Id) mr.WeaponId = 0;
if (mr.OffhandId == rule.Id) mr.OffhandId = 0;
}
Settings.ItemRules.RemoveAt(i);
OnSettingsChanged?.Invoke();
}
}
ImGui.EndTable();
}
ImGui.Separator();
if (ImGui.Button("Add Selected Item", new Vector2(150, 24)))
{
int sel = Core.Actions.CurrentSelection;
if (sel != 0)
{
var item = Core.WorldFilter[sel];
if (item != null)
{
if (IsValidEquipment(item))
{
if (!Settings.ItemRules.Any(x => x.Id == item.Id))
{
Settings.ItemRules.Add(new ItemRule
{
Id = item.Id,
Name = item.Name,
Element = GetElement(item),
KeepBuffed = true
});
OnSettingsChanged?.Invoke();
}
else Core.Actions.AddChatText($"[RynthAi] Item ID {item.Id} already in list.", 1);
}
else Core.Actions.AddChatText("[RynthAi] Selected item must be a weapon, wand, or shield.", 1);
}
}
}
ImGui.SameLine();
ImGui.TextDisabled("(Select item in-game first)");
}
ImGui.End();
}
// ═════════════════════════════════════════════════════════════════════
// NAVIGATION WINDOW
// ═════════════════════════════════════════════════════════════════════
private void RenderNavigationWindow()
{
ImGui.SetNextWindowSize(new Vector2(360, 400), ImGuiCond.FirstUseEver);
if (ImGui.Begin("Navigation##RynthAiNav", ref DashWindows.ShowNavigation))
RouteTab?.Render();
ImGui.End();
}
// ═════════════════════════════════════════════════════════════════════
// LUA SCRIPTS WINDOW
// ═════════════════════════════════════════════════════════════════════
private void RenderLuaWindow()
{
ImGui.SetNextWindowSize(new Vector2(400, 300), ImGuiCond.FirstUseEver);
if (ImGui.Begin("Lua Scripts##RynthAiLua", ref DashWindows.ShowLua))
{
if (LuaTab != null)
{
LuaTab.Render();
}
else
{
ImGui.TextColored(ColTextDim, "Lua Engine is currently unavailable.");
}
}
ImGui.End();
}
// ── DRAKHUD LOGIC (Embedded) ──────────────────────────────────────────
private void UpdateTargetAppraisal()
{
int currentTarget = Core.Actions.CurrentSelection;
bool isMonster = false;
if (currentTarget != 0)
{
try
{
WorldObject wo = Core.WorldFilter[currentTarget];
if (wo != null && wo.ObjectClass == ObjectClass.Monster)
isMonster = true;
}
catch { }
}
if (currentTarget != _lastTargetId)
{
_lastTargetId = currentTarget;
_retryTargetId = currentTarget;
_retryCount = 0;
if (currentTarget != 0 && isMonster)
{
try { Core.Actions.RequestId(currentTarget); _lastRequestTime = DateTime.Now; } catch { }
}
}
if (currentTarget != 0 && isMonster && currentTarget == _retryTargetId && _retryCount < 3 &&
!_maxHealthTracker.ContainsKey(currentTarget) && (DateTime.Now - _lastRequestTime).TotalSeconds >= 0.75)
{
try { Core.Actions.RequestId(currentTarget); _lastRequestTime = DateTime.Now; _retryCount++; } catch { }
}
}
private void OnServerDispatch(object sender, NetworkMessageEventArgs e)
{
try
{
if (e.Message.Type == 0xF7B0)
{
int eventType = (int)e.Message[2];
if (eventType == 0x1C0)
{
int targetId = (int)e.Message[3];
object rawHealth = e.Message[4];
float ratio = 1.0f;
if (rawHealth is float) ratio = (float)rawHealth;
else if (rawHealth is double) ratio = (float)(double)rawHealth;
else if (rawHealth is Single) ratio = (Single)rawHealth;
_healthRatioTracker[targetId] = ratio;
}
else if (eventType == 0xC9)
{
TryExtractVitals(e.Message);
}
}
}
catch { }
}
private void TryExtractVitals(Decal.Adapter.Message msg)
{
try
{
Decal.Adapter.MessageStruct eventStruct = msg.Struct("event");
if (eventStruct != null)
{
int health = 0, healthMax = 0;
try { health = eventStruct.Value<int>("health"); } catch { }
try { healthMax = eventStruct.Value<int>("healthMax"); } catch { }
if (healthMax > 0)
{
int objectId = 0;
try { objectId = eventStruct.Value<int>("object"); } catch { }
if (objectId == 0) objectId = Core.Actions.CurrentSelection;
if (objectId != 0)
{
_maxHealthTracker[objectId] = healthMax;
if (healthMax > 0) _healthRatioTracker[objectId] = (float)health / (float)healthMax;
return;
}
}
}
}
catch { }
try
{
int health = 0, healthMax = 0;
try { health = msg.Value<int>("health"); } catch { }
try { healthMax = msg.Value<int>("healthMax"); } catch { }
if (healthMax > 0)
{
int objectId = Core.Actions.CurrentSelection;
if (objectId != 0)
{
_maxHealthTracker[objectId] = healthMax;
_healthRatioTracker[objectId] = (float)health / (float)healthMax;
return;
}
}
}
catch { }
}
// ── Drawing Math & Custom Shapes ──────────────────────────────────────
private void DrawIcon(string type, Vector2 pos, Vector4 color, float s)
{
var dl = ImGui.GetWindowDrawList();
uint col = ImGui.ColorConvertFloat4ToU32(color);
switch (type)
{
case "gear":
dl.AddCircle(pos + new Vector2(s / 2, s / 2), s / 3.5f, col, 12, 1.5f);
for (int i = 0; i < 8; i++)
{
float a = i * ((float)Math.PI * 2f / 8f);
dl.AddLine(pos + new Vector2(s / 2 + (float)Math.Cos(a) * s / 3, s / 2 + (float)Math.Sin(a) * s / 3),
pos + new Vector2(s / 2 + (float)Math.Cos(a) * s / 2, s / 2 + (float)Math.Sin(a) * s / 2), col, 2f);
}
break;
case "target":
dl.AddCircle(pos + new Vector2(s / 2, s / 2), s / 2.5f, col, 12, 1.5f);
dl.AddLine(pos + new Vector2(s / 2, 0), pos + new Vector2(s / 2, s), col, 1.5f);
dl.AddLine(pos + new Vector2(0, s / 2), pos + new Vector2(s, s / 2), col, 1.5f);
break;
case "wrench":
dl.AddCircle(pos + new Vector2(s * 0.3f, s * 0.3f), s * 0.25f, col, 8, 1.5f);
dl.AddLine(pos + new Vector2(s * 0.4f, s * 0.4f), pos + new Vector2(s * 0.9f, s * 0.9f), col, 2f);
break;
case "map":
dl.AddRect(pos, pos + new Vector2(s, s), col, 1.5f);
dl.AddLine(pos + new Vector2(s / 2, 2), pos + new Vector2(s / 2, s - 2), col, 1.5f);
dl.AddLine(pos + new Vector2(2, s / 2), pos + new Vector2(s - 2, s / 2), col, 1.5f);
break;
case "bag":
dl.AddRectFilled(pos + new Vector2(2, s / 3), pos + new Vector2(s - 2, s), col, 2f);
dl.AddCircle(pos + new Vector2(s / 2, s / 4), s / 5, col, 8, 1.5f);
break;
case "shield":
dl.AddLine(pos + new Vector2(s * 0.2f, 0), pos + new Vector2(s * 0.8f, 0), col, 1.5f);
dl.AddLine(pos + new Vector2(s * 0.8f, 0), pos + new Vector2(s * 0.8f, s * 0.6f), col, 1.5f);
dl.AddLine(pos + new Vector2(s * 0.8f, s * 0.6f), pos + new Vector2(s * 0.5f, s), col, 1.5f);
dl.AddLine(pos + new Vector2(s * 0.5f, s), pos + new Vector2(s * 0.2f, s * 0.6f), col, 1.5f);
dl.AddLine(pos + new Vector2(s * 0.2f, s * 0.6f), pos + new Vector2(s * 0.2f, 0), col, 1.5f);
break;
case "code":
dl.AddLine(pos + new Vector2(s * 0.3f, 2), pos + new Vector2(0, s / 2), col, 1.5f);
dl.AddLine(pos + new Vector2(0, s / 2), pos + new Vector2(s * 0.3f, s - 2), col, 1.5f);
dl.AddLine(pos + new Vector2(s * 0.7f, 2), pos + new Vector2(s, s / 2), col, 1.5f);
dl.AddLine(pos + new Vector2(s, s / 2), pos + new Vector2(s * 0.7f, s - 2), col, 1.5f);
break;
case "heart":
dl.AddCircleFilled(pos + new Vector2(s * 0.3f, s * 0.3f), s * 0.25f, col);
dl.AddCircleFilled(pos + new Vector2(s * 0.7f, s * 0.3f), s * 0.25f, col);
dl.AddTriangleFilled(pos + new Vector2(s * 0.05f, s * 0.4f), pos + new Vector2(s * 0.95f, s * 0.4f), pos + new Vector2(s * 0.5f, s * 0.9f), col);
break;
case "run":
dl.AddCircle(pos + new Vector2(s * 0.5f, s * 0.2f), s * 0.15f, col, 8, 1.5f);
dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.35f), pos + new Vector2(s * 0.5f, s * 0.65f), col, 1.5f);
dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.65f), pos + new Vector2(s * 0.2f, s * 0.9f), col, 1.5f);
dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.65f), pos + new Vector2(s * 0.8f, s * 0.9f), col, 1.5f);
dl.AddLine(pos + new Vector2(s * 0.2f, s * 0.4f), pos + new Vector2(s * 0.8f, s * 0.4f), col, 1.5f);
break;
case "drop":
dl.AddCircleFilled(pos + new Vector2(s * 0.5f, s * 0.7f), s * 0.25f, col);
dl.AddTriangleFilled(pos + new Vector2(s * 0.25f, s * 0.65f), pos + new Vector2(s * 0.75f, s * 0.65f), pos + new Vector2(s * 0.5f, s * 0.1f), col);
break;
case "sword":
dl.AddLine(pos + new Vector2(s * 0.3f, s * 0.7f), pos + new Vector2(s * 0.9f, s * 0.1f), col, 2f);
dl.AddLine(pos + new Vector2(s * 0.2f, s * 0.6f), pos + new Vector2(s * 0.4f, s * 0.8f), col, 2f);
dl.AddLine(pos + new Vector2(s * 0.1f, s * 0.9f), pos + new Vector2(s * 0.3f, s * 0.7f), col, 2f);
break;
case "shoe":
dl.AddLine(pos + new Vector2(s * 0.3f, s * 0.2f), pos + new Vector2(s * 0.3f, s * 0.8f), col, 2f);
dl.AddLine(pos + new Vector2(s * 0.3f, s * 0.8f), pos + new Vector2(s * 0.8f, s * 0.8f), col, 2f);
dl.AddLine(pos + new Vector2(s * 0.8f, s * 0.8f), pos + new Vector2(s * 0.8f, s * 0.6f), col, 2f);
dl.AddLine(pos + new Vector2(s * 0.8f, s * 0.6f), pos + new Vector2(s * 0.5f, s * 0.5f), col, 2f);
dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.5f), pos + new Vector2(s * 0.5f, s * 0.2f), col, 2f);
dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.2f), pos + new Vector2(s * 0.3f, s * 0.2f), col, 2f);
break;
case "buff":
dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.2f), pos + new Vector2(s * 0.5f, s * 0.8f), col, 2f);
dl.AddLine(pos + new Vector2(s * 0.2f, s * 0.5f), pos + new Vector2(s * 0.8f, s * 0.5f), col, 2f);
dl.AddLine(pos + new Vector2(s * 0.3f, s * 0.3f), pos + new Vector2(s * 0.5f, s * 0.1f), col, 1.5f);
dl.AddLine(pos + new Vector2(s * 0.5f, s * 0.1f), pos + new Vector2(s * 0.7f, s * 0.3f), col, 1.5f);
break;
}
}
private void DrawSquareToggle(string icon, ref bool state, Vector2 pos, string id)
{
var dl = ImGui.GetWindowDrawList();
float s = 30f;
Vector4 bgColor = state ? ColBtnOn : ColBarBg;
Vector4 iconColor = state ? ColTeal : ColTextMute;
dl.AddRectFilled(pos, pos + new Vector2(s, s), ImGui.ColorConvertFloat4ToU32(bgColor), 4f);
if (state) dl.AddRect(pos, pos + new Vector2(s, s), ImGui.ColorConvertFloat4ToU32(ColTeal), 4f, ImDrawFlags.None, 1f);
DrawIcon(icon, pos + new Vector2(6, 6), iconColor, 18f);
ImGui.SetCursorScreenPos(pos);
if (ImGui.InvisibleButton($"##{id}", new Vector2(s, s)))
{
state = !state;
OnSettingsChanged?.Invoke();
}
}
private void DrawWideToggle(string label, string icon, ref bool state, Vector2 pos, string id, float width, float height)
{
var dl = ImGui.GetWindowDrawList();
Vector4 bgColor = state ? ColBtnOn : ColBarBg;
Vector4 iconColor = state ? ColTeal : ColTextMute;
dl.AddRectFilled(pos, pos + new Vector2(width, height), ImGui.ColorConvertFloat4ToU32(bgColor), 4f);
if (state) dl.AddRect(pos, pos + new Vector2(width, height), ImGui.ColorConvertFloat4ToU32(ColTeal), 4f, ImDrawFlags.None, 1f);
DrawIcon(icon, pos + new Vector2(4, (height - 12) / 2), iconColor, 12f);
var textSize = ImGui.CalcTextSize(label);
dl.AddText(pos + new Vector2(18, (height - textSize.Y) / 2), ImGui.ColorConvertFloat4ToU32(state ? ColTeal : ColTextDim), label);
ImGui.SetCursorScreenPos(pos);
if (ImGui.InvisibleButton($"##{id}", new Vector2(width, height)))
{
state = !state;
OnSettingsChanged?.Invoke();
}
}
private Vector4 GetGradientCol(float t)
{
if (t < 0.33f) { float f = t / 0.33f; return new Vector4(1f, f, 0f, 1f); }
else if (t < 0.66f) { float f = (t - 0.33f) / 0.33f; return new Vector4(1f - f, 1f, 0f, 1f); }
else { float f = (t - 0.66f) / 0.34f; return new Vector4(0f, 1f, f, 1f); }
}
private void DrawSegmentedBar(float pct, float width)
{
var pos = ImGui.GetCursorScreenPos();
var dl = ImGui.GetWindowDrawList();
float h = 10f; int segments = 15; float gap = 2f;
float segW = (width - (segments - 1) * gap) / segments;
for (int i = 0; i < segments; i++)
{
float t = (float)i / (segments - 1);
Vector4 drawCol = (i / (float)segments <= pct) ? GetGradientCol(t) : ColBarBg;
dl.AddRectFilled(pos + new Vector2(i * (segW + gap), 0), pos + new Vector2(i * (segW + gap) + segW, h), ImGui.ColorConvertFloat4ToU32(drawCol), 1f);
}
ImGui.Dummy(new Vector2(width, h + 2));
}
private void DrawVitalRow(string icon, string label, float pct, Vector4 color, string valText)
{
float width = ImGui.GetContentRegionAvail().X - 4f;
var pos = ImGui.GetCursorScreenPos();
var dl = ImGui.GetWindowDrawList();
float h = 16f;
dl.AddRectFilled(pos, pos + new Vector2(width, h), ImGui.ColorConvertFloat4ToU32(ColBarBg), 4f);
float safePct = Math.Max(0, Math.Min(1, pct));
dl.AddRectFilled(pos, pos + new Vector2(width * safePct, h), ImGui.ColorConvertFloat4ToU32(color), 4f);
DrawIcon(icon, pos + new Vector2(4, 1), ColTextDim, 14f);
string display = $"{label}: {(int)(safePct * 100)}% ({valText})";
dl.AddText(pos + new Vector2(24, 0), ImGui.ColorConvertFloat4ToU32(new Vector4(1, 1, 1, 1)), display);
ImGui.Dummy(new Vector2(width, h));
ImGui.Spacing();
}
private static string TruncateName(string s, int max) => s != null && s.Length > max ? s.Substring(0, max - 1) + "..." : (s ?? "");
// ── Backend Helpers ───────────────────────────────────────
public void LoadSelectedNav()
{
if (_selectedNavIdx < 0 || _selectedNavIdx >= NavFiles.Count) return;
string sel = NavFiles[_selectedNavIdx];
if (sel == "None") { Settings.CurrentNavPath = ""; Settings.CurrentRoute.Points.Clear(); Settings.ActiveNavIndex = 0; }
else
{
string fp = Path.Combine(_navFolder, sel + ".nav");
Settings.CurrentNavPath = fp; Settings.CurrentRoute = VTankNavParser.Load(fp);
Settings.ActiveNavIndex = (Settings.CurrentRoute.RouteType == NavRouteType.Once || Settings.CurrentRoute.RouteType == NavRouteType.Follow) ? 0 : FindNearestWaypoint(Settings.CurrentRoute);
}
if (RouteTab != null) RouteTab.NeedsRouteGraphicsRefresh = true; OnSettingsChanged?.Invoke();
}
private int FindNearestWaypoint(VTankNavParser route)
{
if (route?.Points == null || route.Points.Count == 0) return 0;
try
{
var me = Core.WorldFilter[Core.CharacterFilter.Id]; if (me == null) return 0;
var pos = me.Coordinates(); int best = 0; double bestD = double.MaxValue;
for (int i = 0; i < route.Points.Count; i++)
{
var pt = route.Points[i]; if (pt.Type != NavPointType.Point) continue;
double d = Math.Sqrt(Math.Pow(pt.NS - pos.NorthSouth, 2) + Math.Pow(pt.EW - pos.EastWest, 2));
if (d < bestD) { bestD = d; best = i; }
}
return best;
}
catch { return 0; }
}
private bool IsValidEquipment(WorldObject item)
{
if (item.ObjectClass == ObjectClass.MeleeWeapon ||
item.ObjectClass == ObjectClass.MissileWeapon ||
item.ObjectClass == ObjectClass.WandStaffOrb) return true;
if (item.ObjectClass == ObjectClass.Armor &&
(item.Name.IndexOf("Shield", StringComparison.OrdinalIgnoreCase) >= 0 ||
item.Name.IndexOf("Defender", StringComparison.OrdinalIgnoreCase) >= 0)) return true;
return false;
}
private string GetElement(WorldObject item)
{
switch (item.Values(LongValueKey.DamageType, 0))
{
case 1: return "Slash";
case 2: return "Pierce";
case 4: return "Bludgeon";
case 8: return "Cold";
case 16: return "Fire";
case 32: return "Acid";
case 64: return "Lightning";
default: return "Slash";
}
}
public void RefreshNavFiles()
{
NavFiles.Clear(); NavFiles.Add("None"); _selectedNavIdx = 0;
if (!Directory.Exists(_navFolder)) return;
foreach (var f in Directory.GetFiles(_navFolder, "*.nav"))
{
NavFiles.Add(Path.GetFileNameWithoutExtension(f));
if (f.Equals(Settings.CurrentNavPath, StringComparison.OrdinalIgnoreCase)) _selectedNavIdx = NavFiles.Count - 1;
}
}
public void RefreshLootFiles()
{
LootFiles.Clear(); LootFiles.Add("None");
if (!Directory.Exists(_lootFolder)) return;
foreach (var f in Directory.GetFiles(_lootFolder, "*.utl"))
{
LootFiles.Add(Path.GetFileNameWithoutExtension(f));
if (f.Equals(Settings.CurrentLootPath, StringComparison.OrdinalIgnoreCase)) Settings.LootProfileIdx = LootFiles.Count - 1;
}
}
public void RefreshMetaFiles()
{
try
{
MetaFiles.Clear(); MetaFiles.Add("None");
if (!Directory.Exists(_metaFolder)) Directory.CreateDirectory(_metaFolder);
foreach (var f in Directory.GetFiles(_metaFolder, "*.met")) MetaFiles.Add(Path.GetFileNameWithoutExtension(f));
}
catch { }
}
private void RefreshProfilesList()
{
try
{
Profiles.Clear();
string srv = Core.CharacterFilter.Server ?? "UnknownServer";
string chr = Core.CharacterFilter.Name ?? "UnknownCharacter";
string path = Path.Combine(@"C:\Games\DecalPlugins\NexSuite\RynthAi\SettingsProfiles", srv, chr);
Directory.CreateDirectory(path);
foreach (string f in Directory.GetFiles(path, "*.json"))
{
string n = Path.GetFileNameWithoutExtension(f);
if (n.ToLower() != "settings") Profiles.Add(n);
}
if (Profiles.Count == 0) Profiles.Add("Default");
}
catch { Profiles.Add("Default"); }
}
}
}

View file

@ -0,0 +1,314 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Newtonsoft.Json;
namespace NexSuite.Plugins.RynthAi
{
public class UISettings
{
// Core macro state
public bool IsMacroRunning = false;
public string CurrentState = "Default";
public bool IsRecordingNav = false;
// Subsystem Toggles
public bool EnableBuffing = true;
public bool EnableCombat = false;
public bool EnableNavigation = false;
public bool EnableLooting = false;
public bool EnableMeta = false;
public bool EnableRaycasting = true;
// Movement Mode: 0 = Legacy (SetAutorun/SetClientMotion),
// 1 = Tier1 (CM_Movement direct calls),
// 2 = Tier2 (CPhysicsObj::MoveToPosition — planned),
// 3 = Tier3 (MoveToManager queue — planned)
public int MovementMode = 0;
// ── Navigation Steering (all modes) ───────────────────────────────
public float NavStopTurnAngle = 20f; // Stop and turn in place when error > X°
public float NavResumeTurnAngle = 10f; // Resume running when error < X° (must be < StopTurn)
public float NavDeadZone = 4f; // Ignore corrections smaller than X°
public float NavSweepMult = 2.5f; // Closest-approach detect radius = ArrivalYards * this
// ── Tier 2 Tuning ─────────────────────────────────────────────────
public float T2Speed = 1.0f; // Movement speed multiplier
public float T2DistanceTo = 0.5f; // Stop this far from target (yards)
public float T2ReissueMs = 2000f; // Re-issue MoveToPosition if no progress (ms)
public float T2MaxRangeYd = 500f; // Clamp waypoint distance to this (yards)
public int T2MaxLandblocks = 3; // Skip if target is more than N landblocks away
public float T2WalkWithinYd = 5f; // Walk (not run) when within X yards of waypoint
// Persistence
public string CurrentNavPath = "";
public string CurrentLootPath = "";
public string CurrentMetaPath = "";
// Profile Selection Indices
public int MacroSettingsIdx = 1;
public int NavProfileIdx = 1;
public int LootProfileIdx = 0;
public int MetaProfileIdx = 1;
// Automation Toggles
public bool EnableAutostack = true;
public bool EnableAutocram = true;
public bool EnableCombineSalvage = true; // If true, combine salvage bags of same material
// --- Missile Crafting ---
public bool EnableMissileCrafting = false; // Master toggle for auto-crafting ammo from bundles
public int MissileCraftAmmoThreshold = 1000; // Craft when ammo count drops below this
// --- Loot Timing (ms) — tunable in Advanced Settings → Looting ---
public int LootInterItemDelayMs = 100; // Delay between picking up items
public int LootContentSettleMs = 100; // Wait for corpse contents to populate
public int LootEmptyCorpseMs = 400; // Wait before declaring corpse empty
public int LootClosingDelayMs = 200; // Delay before closing corpse
public int LootAssessWindowMs = 800; // Max time to wait for item ID data
public int LootRetryTimeoutMs = 800; // Retry pickup after this long
public int LootOpenRetryMs = 3000; // Retry opening corpse if no response
// --- Salvage Timing (ms) — first item / subsequent item ---
public int SalvageOpenDelayFirstMs = 400; // Panel open delay (first item)
public int SalvageOpenDelayFastMs = 50; // Panel open delay (subsequent)
public int SalvageAddDelayFirstMs = 600; // Add item delay (first)
public int SalvageAddDelayFastMs = 50; // Add item delay (subsequent)
public int SalvageSalvageDelayMs = 50; // Click salvage button delay
public int SalvageResultDelayFirstMs = 1000; // Wait for result (first)
public int SalvageResultDelayFastMs = 250; // Wait for result (subsequent)
public bool UseDispelItems = false;
public bool CastDispelSelf = false;
public bool AutoFellowMgmt = false;
public bool MChargesWhenOff = false;
// Vitals (0-100)
public int HealAt = 60;
public int RestamAt = 30;
public int GetManaAt = 40;
public int TopOffHP = 95;
public int TopOffStam = 95;
public int TopOffMana = 95;
public int HealOthersAt = 50;
public int RestamOthersAt = 10;
public int InfuseOthersAt = 10;
// Ranges & Misc
public int MonsterRange = 50;
public int RingRange = 5;
public int ApproachRange = 4;
public int MinRingTargets = 4; // Minimum monsters in ring range to use ring spells
public float FollowNavMin = 1.5f;
public double MaxMonRange = 12.0;
public bool SummonPets = false;
public int CustomPetRange = 5;
public int PetMinMonsters = 1;
public bool AdvancedOptions = false;
public bool MineOnly = true;
public bool ShowEditor = false;
public double CorpseApproachRangeMax = 0.04166667; // ~10 yards (10 / 240)
public double CorpseApproachRangeMin = 0.00833333; // ~2 yards (2 / 240)
// Advanced Toggles
public bool BoostNavPriority = false;
public bool BoostLootPriority = false;
// Loot Ownership: 0=MyKillsOnly (default), 1=FellowshipKills, 2=AllCorpses
public int LootOwnership = 0;
public bool LootOnlyRareCorpses = false;
public bool PeaceModeWhenIdle = true;
public bool RebuffWhenIdle = false;
// Blacklist Settings (Combat)
public int BlacklistAttempts = 3; // How many failed attacks before blacklisting
public int BlacklistTimeoutSec = 30; // How long a mob stays blacklisted (seconds)
// Attack Power (0-100 percent, or -1 for auto)
// Auto: 100% power, or 80% if UseRecklessness is enabled and Recklessness is trained
public int MeleeAttackPower = -1; // -1 = auto, 0-100 = manual percent
public int MissileAttackPower = -1; // -1 = auto, 0-100 = manual percent
public bool UseRecklessness = false; // When true + Recklessness trained, auto power = 80%
// Attack Height: 0=Low (Delete), 1=Medium (End), 2=High (Page Down)
public int MeleeAttackHeight = 1; // Default: Medium
public int MissileAttackHeight = 1; // Default: Medium
//FPS Limits
public bool EnableFPSLimit = true;
public int TargetFPSFocused = 60;
public int TargetFPSBackground = 30;
// Data Lists
public List<MonsterRule> MonsterRules = new List<MonsterRule>();
public List<ItemRule> ItemRules = new List<ItemRule>();
public List<BuffRule> BuffRules = new List<BuffRule>();
public List<MetaRule> MetaRules = new List<MetaRule>(); // <--- NEW META LIST
public string LuaScript = "-- Enter your Lua script here\nprint('RynthAi Lua Loaded')";
public string LuaConsoleOutput = "--- RynthAi Lua Console ---";
public string SelectedProfile = "Default";
public VTankNavParser CurrentRoute = new VTankNavParser(); // Uncomment if you still use this
public int ActiveNavIndex = 0;
// Advanced Settings Popup
// Inside UISettings.cs
public bool ShowAdvancedWindow = false; // Toggle this with your button
public int SelectedAdvancedTab = 0; // Tracks the left-hand selection
// Define your tabs in an array for easy rendering
[JsonIgnore]
public readonly string[] AdvancedTabs = {
"Misc", "Recharge", "Melee Combat", "Spell Combat",
"Ranges", "Navigation", "Buffing", "Crafting", "Looting"
};
//Refresh state when selected
[JsonIgnore]
public bool ForceStateReset { get; set; } = false;
public UISettings()
{
// REMOVED EnsureDefaultRule() from here to stop JSON deserialization from duplicating it.
}
public void EnsureDefaultRule()
{
// Find any existing Default rules
var existingDefaults = MonsterRules.Where(m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)).ToList();
MonsterRule trueDefault;
if (existingDefaults.Count > 0)
{
// Keep the first one (it contains your saved weapon settings)
trueDefault = existingDefaults.First();
// Erase all of them from the list to clean up any duplicates
MonsterRules.RemoveAll(m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
}
else
{
// If it truly doesn't exist, make a brand new one
trueDefault = new MonsterRule { Name = "Default", Priority = 1, DamageType = "Auto", WeaponId = 0 };
}
// Insert the one true Default safely at the very top
MonsterRules.Insert(0, trueDefault);
}
}
public class MonsterRule
{
public string Name { get; set; } = "New Monster";
public int Priority { get; set; } = 1;
public string DamageType { get; set; } = "Auto";
public int WeaponId { get; set; } = 0;
// Debuff Lights (cast on target before attacking)
public bool Fester { get; set; } = false; // F - Festering Curse
public bool Broadside { get; set; } = false; // B - Broadside of a Barn
public bool GravityWell { get; set; } = false; // G - Gravity Well
public bool Imperil { get; set; } = false; // I - Imperil
public bool Yield { get; set; } = false; // Y - Yield
public bool Vuln { get; set; } = false; // V - Vulnerability (element-matched)
// Spell Type Lights (how to attack)
public bool UseArc { get; set; } = false; // A - Arc spells (war/void)
public bool UseRing { get; set; } = false; // R - Ring spells (uses RingRange)
public bool UseStreak { get; set; } = false; // S - Streak spells (war/void)
public bool UseBolt { get; set; } = true; // B - Bolt spells (default on)
// If none of A/R/S/B are set in magic mode = don't attack (buff bot)
// Extra Vulnerability element (cast in addition to the V light)
public string ExVuln { get; set; } = "None";
// Offhand weapon/shield ID (from ItemRules, for dual wield or shield)
public int OffhandId { get; set; } = 0;
// Pet damage element
public string PetDamage { get; set; } = "PAuto";
}
public class BuffRule { public string SpellName { get; set; } public int SpellId { get; set; } public bool Enabled { get; set; } = true; }
public class ItemRule
{
public int Id { get; set; }
public string Name { get; set; }
public string Action { get; set; } = "Loot";
public string Element { get; set; } = "Slash";
public bool KeepBuffed { get; set; } = true;
}
// ====================================================================
// NEW META SYSTEM MODELS
// ====================================================================
public enum MetaConditionType
{
Never,
Always,
All,
Any,
ChatMessage,
PackSlots_LE,
SecondsInState_GE,
CharacterDeath,
AnyVendorOpen,
VendorClosed,
InventoryItemCount_LE,
InventoryItemCount_GE,
MonsterNameCountWithinDistance,
MonsterPriorityCountWithinDistance,
NeedToBuff,
NoMonstersWithinDistance,
Landblock_EQ,
Landcell_EQ,
PortalspaceEntered,
PortalspaceExited,
Not,
SecondsInStateP_GE,
TimeLeftOnSpell_GE,
TimeLeftOnSpell_LE,
BurdenPercentage_GE,
DistAnyRoutePT_GE,
Expression,
ChatMessageCapture,
NavrouteEmpty,
MainHealthLE,
MainHealthPHE,
MainManaLE,
MainManaPHE,
MainStamLE
}
public enum MetaActionType
{
None,
ChatCommand,
SetMetaState,
EmbeddedNavRoute,
All,
CallMetaState, // New
ReturnFromCall, // New
ExpressionAction, // New
ChatExpression, // New
SetWatchdog, // New
ClearWatchdog, // New
GetNTOption, // New
SetNTOption, // New
CreateView, // New
DestroyView, // New
DestroyAllViews // New
}
public class MetaRule
{
public string State { get; set; } = "Default";
public MetaConditionType Condition { get; set; }
public string ConditionData { get; set; } = "";
public MetaActionType Action { get; set; }
public string ActionData { get; set; } = "";
public List<MetaRule> Children { get; set; } = new List<MetaRule>();
// NEW: Temporary flag for the UI. JsonIgnore prevents it from saving to the file.
[JsonIgnore]
public bool HasFired { get; set; } = false;
}
}

View file

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Decal.Adapter" publicKeyToken="bd1c8ce002ce221e" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.9.8.3" newVersion="2.9.8.3" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Decal.FileService" publicKeyToken="bd1c8ce002ce221e" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.9.8.3" newVersion="2.9.8.3" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="KeraLua" version="1.4.9" targetFramework="net48" />
<package id="Newtonsoft.Json" version="13.0.4" targetFramework="net48" />
<package id="NLua" version="1.7.8" targetFramework="net48" />
</packages>

View file

@ -0,0 +1,16 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("RynthAi")]
[assembly: AssemblyDescription("Combat bot plugin for NexSuite")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NexSuite")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("33333333-3333-3333-3333-333333333333")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View file

@ -0,0 +1,150 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace RynthCore.Plugin.RynthAi.Nav;
public enum NavRouteType
{
Once = 4,
Circular = 1,
Linear = 2,
Follow = 3
}
public enum NavPointType
{
Point = 0,
Recall = 2,
Pause = 3,
Chat = 4,
PortalNPC = 6
}
public class NavPoint
{
public NavPointType Type { get; set; }
public double NS { get; set; }
public double EW { get; set; }
public double Z { get; set; }
public int SpellId { get; set; }
public int PauseTimeMs { get; set; }
public string ChatCommand { get; set; } = "";
public string TargetName { get; set; } = "";
public int ObjectClass { get; set; }
public bool IsTie { get; set; }
public double PortalExitNS { get; set; }
public double PortalExitEW { get; set; }
public double PortalExitZ { get; set; }
public double PortalLandNS { get; set; }
public double PortalLandEW { get; set; }
public double PortalLandZ { get; set; }
public override string ToString()
{
return Type switch
{
NavPointType.Point => $"[Point] {NS:F3}, {EW:F3}",
NavPointType.Recall => $"[Recall] spell {SpellId}",
NavPointType.Pause => $"[Pause] {PauseTimeMs / 1000.0}s",
NavPointType.Chat => $"[Chat] {ChatCommand}",
NavPointType.PortalNPC => $"[Portal] {TargetName}",
_ => $"[Unknown] {Type}"
};
}
}
public class VTankNavParser
{
public NavRouteType RouteType { get; set; }
public List<NavPoint> Points { get; set; } = new();
public static VTankNavParser Load(string filePath)
{
var route = new VTankNavParser();
string[] lines = File.ReadAllLines(filePath);
if (lines.Length < 3) return route;
if (!lines[0].Contains("uTank2 NAV 1.2"))
return route;
route.RouteType = (NavRouteType)int.Parse(lines[1]);
int pointCount = int.Parse(lines[2]);
int idx = 3;
for (int i = 0; i < pointCount && idx < lines.Length; i++)
{
var pt = new NavPoint();
pt.Type = (NavPointType)int.Parse(lines[idx++]);
pt.EW = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.NS = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.Z = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
idx++; // spacer
switch (pt.Type)
{
case NavPointType.Point: break;
case NavPointType.Recall: pt.SpellId = int.Parse(lines[idx++]); break;
case NavPointType.Pause: pt.PauseTimeMs = int.Parse(lines[idx++]); break;
case NavPointType.Chat: pt.ChatCommand = lines[idx++]; break;
case NavPointType.PortalNPC:
pt.TargetName = lines[idx++];
pt.ObjectClass = int.Parse(lines[idx++]);
pt.IsTie = bool.Parse(lines[idx++]);
pt.PortalExitEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.PortalExitNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.PortalExitZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
idx++; // spacer
pt.PortalLandEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.PortalLandNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.PortalLandZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
idx++; // spacer
break;
}
route.Points.Add(pt);
}
return route;
}
public void Save(string filePath)
{
using var writer = new StreamWriter(filePath, false);
writer.WriteLine("uTank2 NAV 1.2");
writer.WriteLine((int)RouteType);
writer.WriteLine(Points.Count);
foreach (var pt in Points)
{
writer.WriteLine((int)pt.Type);
writer.WriteLine(pt.EW.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(pt.NS.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(pt.Z.ToString(CultureInfo.InvariantCulture));
writer.WriteLine("0");
switch (pt.Type)
{
case NavPointType.Recall: writer.WriteLine(pt.SpellId); break;
case NavPointType.Pause: writer.WriteLine(pt.PauseTimeMs); break;
case NavPointType.Chat: writer.WriteLine(pt.ChatCommand); break;
case NavPointType.PortalNPC:
writer.WriteLine(pt.TargetName);
writer.WriteLine(pt.ObjectClass);
writer.WriteLine(pt.IsTie.ToString());
writer.WriteLine(pt.PortalExitEW.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(pt.PortalExitNS.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(pt.PortalExitZ.ToString(CultureInfo.InvariantCulture));
writer.WriteLine("0");
writer.WriteLine(pt.PortalLandEW.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(pt.PortalLandNS.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(pt.PortalLandZ.ToString(CultureInfo.InvariantCulture));
writer.WriteLine("0");
break;
}
}
}
}

View file

@ -0,0 +1,95 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthAiPlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr Name() => RynthAiPlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr Version() => RynthAiPlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUIInitialized", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUIInitialized() => Runtime.OnUIInitialized();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBusyCountIncremented", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnBusyCountIncremented() => Runtime.OnBusyCountIncremented();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBusyCountDecremented", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnBusyCountDecremented() => Runtime.OnBusyCountDecremented();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBarAction", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnBarAction() => Runtime.OnBarAction();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Render() => Runtime.OnRender();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) =>
Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) =>
Runtime.OnChatBarEnter(textUtf16, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnSelectedTargetChange", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnSelectedTargetChange(uint currentTargetId, uint previousTargetId) =>
Runtime.OnSelectedTargetChange(currentTargetId, previousTargetId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCombatModeChange", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCombatModeChange(int currentCombatMode, int previousCombatMode) =>
Runtime.OnCombatModeChange(currentCombatMode, previousCombatMode);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnSmartBoxEvent", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnSmartBoxEvent(uint opcode, uint blobSize, uint status) =>
Runtime.OnSmartBoxEvent(opcode, blobSize, status);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateObject(uint objectId) => Runtime.OnUpdateObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObjectInventory", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateObjectInventory(uint objectId) => Runtime.OnUpdateObjectInventory(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnViewObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnViewObjectContents(uint objectId) => Runtime.OnViewObjectContents(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnStopViewingObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnStopViewingObjectContents(uint objectId) => Runtime.OnStopViewingObjectContents(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) =>
Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentAdded", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnEnchantmentAdded(uint spellId, double durationSeconds) =>
Runtime.OnEnchantmentAdded(spellId, durationSeconds);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentRemoved", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnEnchantmentRemoved(uint enchantmentId) =>
Runtime.OnEnchantmentRemoved(enchantmentId);
}

View file

@ -0,0 +1,429 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthAi.Nav;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
public sealed unsafe class RynthAiPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthAi");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.0");
private const float NavPointElevationOffset = 0.5f;
private const float UnitsPerCoord = 240.0f;
private const int RingSegments = 32;
private const float RingRadius = 3.0f; // game units (~1.25 yards)
// ImGui colors (ABGR format for ImGui native)
private const uint ColorCyan = 0xFFFFFF00; // nav point rings
private const uint ColorRed = 0xFF2222FF; // active waypoint ring
private const uint ColorBlueLine = 0xFFFF8800; // lines between points
private static RynthCoreApiNative _api;
private static RynthCoreHost _host;
private static bool _initialized;
private static bool _loginComplete;
private static bool _windowVisible;
private static bool _showRoute = true;
// Route state
private static VTankNavParser? _currentRoute;
private static string _currentNavPath = "";
private static int _activeNavIndex;
private static readonly string _navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
// Nav file browser state
private static string[] _navFiles = Array.Empty<string>();
// Cached cimgui function pointers
private static delegate* unmanaged[Cdecl]<IntPtr, void> _igSetCurrentContext;
private static delegate* unmanaged[Cdecl]<ImVec2, int, ImVec2, void> _igSetNextWindowPos;
private static delegate* unmanaged[Cdecl]<ImVec2, int, void> _igSetNextWindowSize;
private static delegate* unmanaged[Cdecl]<IntPtr, IntPtr, int, byte> _igBegin;
private static delegate* unmanaged[Cdecl]<void> _igEnd;
private static delegate* unmanaged[Cdecl]<IntPtr, ImVec2, byte> _igButton;
private static delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void> _igTextUnformatted;
private static delegate* unmanaged[Cdecl]<void> _igSeparator;
private static delegate* unmanaged[Cdecl]<IntPtr, byte*, byte> _igCheckbox;
private static delegate* unmanaged[Cdecl]<IntPtr> _igGetForegroundDrawList;
// ImDrawList_AddCircle(self, center, radius, col, num_segments, thickness)
private static delegate* unmanaged[Cdecl]<IntPtr, ImVec2, float, uint, int, float, void> _igDrawListAddCircle;
// ImDrawList_AddLine(self, p1, p2, col, thickness)
private static delegate* unmanaged[Cdecl]<IntPtr, ImVec2, ImVec2, uint, float, void> _igDrawListAddLine;
// ImDrawList_AddCircleFilled(self, center, radius, col, num_segments)
private static delegate* unmanaged[Cdecl]<IntPtr, ImVec2, float, uint, int, void> _igDrawListAddCircleFilled;
private static bool _imguiBound;
public override int Initialize()
{
_api = Api;
_host = Host;
if (_api.ImGuiContext == IntPtr.Zero)
return 11;
if (!TryBindImGui(out string error))
{
Log($"RynthAi: failed to bind cimgui ({error})");
return 12;
}
_initialized = true;
_loginComplete = false;
_windowVisible = false;
_showRoute = true;
_currentRoute = null;
_currentNavPath = "";
_activeNavIndex = 0;
RefreshNavFiles();
Log("RynthAi: initialized.");
return 0;
}
public override void Shutdown()
{
Log("RynthAi: shutting down.");
_initialized = false;
_loginComplete = false;
_currentRoute = null;
}
public override void OnLoginComplete()
{
if (!_initialized) return;
_loginComplete = true;
}
public override void OnBarAction()
{
if (!_initialized || !_loginComplete) return;
_windowVisible = !_windowVisible;
}
public override void OnRender()
{
if (!_initialized || !_loginComplete || !_imguiBound || _api.ImGuiContext == IntPtr.Zero)
return;
_igSetCurrentContext(_api.ImGuiContext);
// Draw the 3D nav route overlay (always, even if UI window is hidden)
if (_showRoute && _currentRoute != null && _currentRoute.Points.Count > 0)
RenderNavRoute();
// Draw the UI panel
if (_windowVisible)
RenderNavPanel();
}
// ─── Precomputed ring geometry (unit circle on ground plane) ────────
private static readonly float[] _cosTable = new float[RingSegments];
private static readonly float[] _sinTable = new float[RingSegments];
private static bool _trigReady;
private static void EnsureTrigTables()
{
if (_trigReady) return;
for (int i = 0; i < RingSegments; i++)
{
double angle = 2.0 * Math.PI * i / RingSegments;
_cosTable[i] = (float)Math.Cos(angle);
_sinTable[i] = (float)Math.Sin(angle);
}
_trigReady = true;
}
// ─── 3D Nav Route Rendering ──────────────────────────────────────────
private static void RenderNavRoute()
{
if (!_host.HasWorldToScreen || !_host.HasGetPlayerPose || !_host.HasGetCurCoords)
return;
if (!_host.TryGetPlayerPose(out uint cell, out float px, out float py, out float pz,
out float _, out float _, out float _, out float _))
return;
if (!_host.TryGetCurCoords(out double playerNS, out double playerEW))
return;
IntPtr drawList = _igGetForegroundDrawList();
if (drawList == IntPtr.Zero)
return;
EnsureTrigTables();
var route = _currentRoute!;
int count = route.Points.Count;
// Project center of each nav point for line drawing
Span<float> centerSx = stackalloc float[count];
Span<float> centerSy = stackalloc float[count];
Span<bool> centerOnScreen = stackalloc bool[count];
for (int i = 0; i < count; i++)
{
var pt = route.Points[i];
float wx = px + (float)((pt.EW - playerEW) * UnitsPerCoord);
float wy = py + (float)((pt.NS - playerNS) * UnitsPerCoord);
float wz = (float)pt.Z + NavPointElevationOffset;
centerOnScreen[i] = _host.WorldToScreen(wx, wy, wz, out centerSx[i], out centerSy[i]);
}
// Draw lines between consecutive waypoints
for (int i = 0; i < count; i++)
{
int nextIdx = i + 1;
if (nextIdx >= count)
{
if (route.RouteType == NavRouteType.Circular)
nextIdx = 0;
else
continue;
}
if (!centerOnScreen[i] && !centerOnScreen[nextIdx])
continue;
_igDrawListAddLine(
drawList,
new ImVec2(centerSx[i], centerSy[i]),
new ImVec2(centerSx[nextIdx], centerSy[nextIdx]),
ColorBlueLine,
2.0f);
}
// Draw 3D rings on the ground at each waypoint
// Each ring is a circle of world-space points projected to screen space
Span<float> ringSx = stackalloc float[RingSegments];
Span<float> ringSy = stackalloc float[RingSegments];
Span<bool> ringVis = stackalloc bool[RingSegments];
for (int i = 0; i < count; i++)
{
var pt = route.Points[i];
float cx = px + (float)((pt.EW - playerEW) * UnitsPerCoord);
float cy = py + (float)((pt.NS - playerNS) * UnitsPerCoord);
float cz = (float)pt.Z + NavPointElevationOffset;
// Project each vertex of the ring (lying flat on the ground plane)
int visCount = 0;
for (int s = 0; s < RingSegments; s++)
{
float wx = cx + _cosTable[s] * RingRadius;
float wy = cy + _sinTable[s] * RingRadius;
ringVis[s] = _host.WorldToScreen(wx, wy, cz, out ringSx[s], out ringSy[s]);
if (ringVis[s]) visCount++;
}
// Skip if no part of the ring is visible
if (visCount == 0)
continue;
uint color = (i == _activeNavIndex) ? ColorRed : ColorCyan;
float thickness = (i == _activeNavIndex) ? 3.0f : 2.0f;
// Draw the ring as connected line segments
for (int s = 0; s < RingSegments; s++)
{
int next = (s + 1) % RingSegments;
// Draw segment if at least one end projected successfully
if (ringVis[s] || ringVis[next])
{
_igDrawListAddLine(
drawList,
new ImVec2(ringSx[s], ringSy[s]),
new ImVec2(ringSx[next], ringSy[next]),
color,
thickness);
}
}
}
}
// ─── Nav Control Panel ───────────────────────────────────────────────
private static void RenderNavPanel()
{
_igSetNextWindowPos(new ImVec2(48f, 140f), 1 << 2 /* ImGuiCond_FirstUseEver */, default);
_igSetNextWindowSize(new ImVec2(380f, 320f), 1 << 2);
bool open = _igBegin(
Marshal.StringToHGlobalAnsi("RynthAi Nav##RynthAiNav"),
IntPtr.Zero,
0) != 0;
if (open)
{
// Show route toggle
byte showByte = _showRoute ? (byte)1 : (byte)0;
if (_igCheckbox(Marshal.StringToHGlobalAnsi("Show Route"), &showByte) != 0)
_showRoute = showByte != 0;
_igSeparator();
// Current route info
string info = _currentRoute != null
? $"Route: {Path.GetFileName(_currentNavPath)} ({_currentRoute.Points.Count} pts, {_currentRoute.RouteType})"
: "No route loaded";
TextTemp(info);
if (_currentRoute != null)
TextTemp($"Active waypoint: {_activeNavIndex}");
_igSeparator();
// Nav file list
TextTemp("Nav Files:");
for (int i = 0; i < _navFiles.Length; i++)
{
string fileName = Path.GetFileName(_navFiles[i]);
bool isCurrent = string.Equals(_navFiles[i], _currentNavPath, StringComparison.OrdinalIgnoreCase);
string label = isCurrent ? $">> {fileName}" : $" {fileName}";
IntPtr labelPtr = Marshal.StringToHGlobalAnsi($"{label}##{i}");
try
{
if (_igButton(labelPtr, new ImVec2(340f, 0f)) != 0)
{
LoadNavFile(_navFiles[i]);
}
}
finally
{
Marshal.FreeHGlobal(labelPtr);
}
}
_igSeparator();
if (_igButton(Marshal.StringToHGlobalAnsi("Refresh Files"), default) != 0)
RefreshNavFiles();
}
_igEnd();
}
// ─── Nav File Management ─────────────────────────────────────────────
private static void RefreshNavFiles()
{
try
{
if (Directory.Exists(_navFolder))
_navFiles = Directory.GetFiles(_navFolder, "*.nav");
else
_navFiles = Array.Empty<string>();
}
catch
{
_navFiles = Array.Empty<string>();
}
}
private static void LoadNavFile(string path)
{
try
{
_currentRoute = VTankNavParser.Load(path);
_currentNavPath = path;
_activeNavIndex = 0;
_host.Log($"RynthAi: Loaded route '{Path.GetFileName(path)}' with {_currentRoute.Points.Count} points");
}
catch (Exception ex)
{
_host.Log($"RynthAi: Failed to load nav file: {ex.Message}");
}
}
// ─── ImGui Helpers ───────────────────────────────────────────────────
private static void TextTemp(string text)
{
IntPtr ptr = Marshal.StringToHGlobalAnsi(text);
try { _igTextUnformatted(ptr, IntPtr.Zero); }
finally { Marshal.FreeHGlobal(ptr); }
}
private static bool TryBindImGui(out string error)
{
if (_imguiBound) { error = ""; return true; }
IntPtr mod = GetModuleHandleA("RynthCore.cimgui.dll");
if (mod == IntPtr.Zero) mod = GetModuleHandleA("cimgui.dll");
if (mod == IntPtr.Zero) { error = "no cimgui module"; return false; }
if (!TryGetProc(mod, "igSetCurrentContext", out IntPtr p)) { error = "missing igSetCurrentContext"; return false; }
_igSetCurrentContext = (delegate* unmanaged[Cdecl]<IntPtr, void>)p;
if (!TryGetProc(mod, "igSetNextWindowPos", out p)) { error = "missing igSetNextWindowPos"; return false; }
_igSetNextWindowPos = (delegate* unmanaged[Cdecl]<ImVec2, int, ImVec2, void>)p;
if (!TryGetProc(mod, "igSetNextWindowSize", out p)) { error = "missing igSetNextWindowSize"; return false; }
_igSetNextWindowSize = (delegate* unmanaged[Cdecl]<ImVec2, int, void>)p;
if (!TryGetProc(mod, "igBegin", out p)) { error = "missing igBegin"; return false; }
_igBegin = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, int, byte>)p;
if (!TryGetProc(mod, "igEnd", out p)) { error = "missing igEnd"; return false; }
_igEnd = (delegate* unmanaged[Cdecl]<void>)p;
if (!TryGetProc(mod, "igButton", out p)) { error = "missing igButton"; return false; }
_igButton = (delegate* unmanaged[Cdecl]<IntPtr, ImVec2, byte>)p;
if (!TryGetProc(mod, "igTextUnformatted", out p)) { error = "missing igTextUnformatted"; return false; }
_igTextUnformatted = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void>)p;
if (!TryGetProc(mod, "igSeparator", out p)) { error = "missing igSeparator"; return false; }
_igSeparator = (delegate* unmanaged[Cdecl]<void>)p;
if (!TryGetProc(mod, "igCheckbox", out p)) { error = "missing igCheckbox"; return false; }
_igCheckbox = (delegate* unmanaged[Cdecl]<IntPtr, byte*, byte>)p;
if (!TryGetProc(mod, "igGetForegroundDrawList_Nil", out p)) { error = "missing igGetForegroundDrawList"; return false; }
_igGetForegroundDrawList = (delegate* unmanaged[Cdecl]<IntPtr>)p;
if (!TryGetProc(mod, "ImDrawList_AddCircle", out p)) { error = "missing ImDrawList_AddCircle"; return false; }
_igDrawListAddCircle = (delegate* unmanaged[Cdecl]<IntPtr, ImVec2, float, uint, int, float, void>)p;
if (!TryGetProc(mod, "ImDrawList_AddLine", out p)) { error = "missing ImDrawList_AddLine"; return false; }
_igDrawListAddLine = (delegate* unmanaged[Cdecl]<IntPtr, ImVec2, ImVec2, uint, float, void>)p;
if (!TryGetProc(mod, "ImDrawList_AddCircleFilled", out p)) { error = "missing ImDrawList_AddCircleFilled"; return false; }
_igDrawListAddCircleFilled = (delegate* unmanaged[Cdecl]<IntPtr, ImVec2, float, uint, int, void>)p;
_imguiBound = true;
error = "";
return true;
}
private static bool TryGetProc(IntPtr module, string exportName, out IntPtr address)
{
address = GetProcAddress(module, exportName);
return address != IntPtr.Zero;
}
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern IntPtr GetModuleHandleA(string lpModuleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[StructLayout(LayoutKind.Sequential)]
private readonly struct ImVec2
{
public readonly float X;
public readonly float Y;
public ImVec2(float x, float y) { X = x; Y = y; }
}
}

View file

@ -0,0 +1,57 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthAi</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthAi</AssemblyName>
<Platforms>x86</Platforms>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
<Target Name="CopyPublishedPluginToEngineOutputs" AfterTargets="Publish" Condition="'$(PublishDir)' != ''">
<ItemGroup>
<_EnginePluginDir Include="$(MSBuildThisFileDirectory)..\..\src\RynthCore.Engine\bin\$(Configuration)\net10.0-windows\win-x86\Plugins\" />
<_EnginePluginDir Include="$(MSBuildThisFileDirectory)..\..\src\RynthCore.Engine\bin\$(PlatformTarget)\$(Configuration)\net10.0-windows\win-x86\Plugins\" />
<_EnginePluginPublishDir Include="$(MSBuildThisFileDirectory)..\..\src\RynthCore.Engine\bin\$(Configuration)\net10.0-windows\win-x86\publish\Plugins\" />
<_EnginePluginPublishDir Include="$(MSBuildThisFileDirectory)..\..\src\RynthCore.Engine\bin\$(PlatformTarget)\$(Configuration)\net10.0-windows\win-x86\publish\Plugins\" />
</ItemGroup>
<MakeDir Directories="@(_EnginePluginDir)" />
<MakeDir Directories="@(_EnginePluginPublishDir)" />
<Copy
SourceFiles="$(PublishDir)$(AssemblyName).dll"
DestinationFolder="%(_EnginePluginDir.Identity)"
SkipUnchangedFiles="true"
Condition="Exists('$(PublishDir)$(AssemblyName).dll')" />
<Copy
SourceFiles="$(PublishDir)$(AssemblyName).pdb"
DestinationFolder="%(_EnginePluginDir.Identity)"
SkipUnchangedFiles="true"
Condition="Exists('$(PublishDir)$(AssemblyName).pdb')" />
<Copy
SourceFiles="$(PublishDir)$(AssemblyName).dll"
DestinationFolder="%(_EnginePluginPublishDir.Identity)"
SkipUnchangedFiles="true"
Condition="Exists('$(PublishDir)$(AssemblyName).dll')" />
<Copy
SourceFiles="$(PublishDir)$(AssemblyName).pdb"
DestinationFolder="%(_EnginePluginPublishDir.Identity)"
SkipUnchangedFiles="true"
Condition="Exists('$(PublishDir)$(AssemblyName).pdb')" />
</Target>
</Project>