RynthSuite as of 2026-10-04 (internal c94715f): RynthOracle (based on Oracle of Dereth by Advis Eveldan) and RynthInventory, RynthAi patrol doorways and rooms, healing priority, strict monster priority, finish the wounded target, slayer weapons, arcs when clear, blasts like rings, learn unknown spells, looting fixes, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:29 -04:00
commit 12ca25f911
426 changed files with 108239 additions and 7521 deletions

View file

@ -0,0 +1,14 @@
<Project>
<!--
NativeAOT GC segment size for every plugin (hex, 8 MB). Each NativeAOT DLL
runs its own GC, which reserves SOH + LOH + POH segments up front: 16 MB
each by default on x86, 48 MB of acclient's 4 GB address space per plugin
even when nearly empty, and never returned because a NativeAOT DLL can't be
unloaded (every engine hot-reload loads fresh copies). 8 MB segments
reserve 16 MB. Measured 2026-09-29 with a win-x86 NativeAOT probe; the
runtime ignores a 0x prefix, so the value is bare hex.
-->
<ItemGroup>
<IlcArg Include="--runtimeopt:GCSegmentSize=800000" />
</ItemGroup>
</Project>

View file

@ -61,11 +61,18 @@ internal readonly struct ArbiterInputs
/// but never changes who wins the tick.
/// </summary>
public readonly bool FollowActive;
/// <summary>
/// A lootable corpse in range has waited LootStarveMs while combat kept the tick, and no
/// monster is close (the caller checks both). Looting gets the tick: on a busy spawn there
/// is always a monster inside MonsterRange, so "combat first" meant corpses were never
/// looted until the area emptied (2026-10-03).
/// </summary>
public readonly bool LootStarved;
public ArbiterInputs(bool macroRunning, bool wantBuffing, bool wantCombat,
bool wantLooting, bool wantSalvaging, bool wantNav,
bool combatEngaged = false, bool boostNav = false, bool boostLoot = false,
bool followActive = false)
bool followActive = false, bool lootStarved = false)
{
MacroRunning = macroRunning;
WantBuffing = wantBuffing;
@ -77,6 +84,7 @@ internal readonly struct ArbiterInputs
BoostNav = boostNav;
BoostLoot = boostLoot;
FollowActive = followActive;
LootStarved = lootStarved;
}
}
@ -115,6 +123,9 @@ internal sealed class ActivityArbiter
// clause instead.
if (s.BoostLoot && s.WantLooting && !s.CombatEngaged) return BotActivity.Looting;
// Loot starvation: a corpse waited too long behind combat and nothing is close.
if (s.LootStarved && s.WantLooting) return BotActivity.Looting;
// ── Default order ─────────────────────────────────────────────────
if (s.WantCombat) return BotActivity.Combat;
if (s.WantLooting) return BotActivity.Looting;
@ -203,7 +214,8 @@ internal sealed class ActivityArbiter
private void LogDecisionIfChanged(BotActivity decision, in ArbiterInputs s, string botAction, bool wrote)
{
string key = $"{decision} wrote={wrote} ba={botAction} want[buff={s.WantBuffing} cbt={s.WantCombat} loot={s.WantLooting} salv={s.WantSalvaging} nav={s.WantNav}]"
+ $" eng={s.CombatEngaged} boost[nav={s.BoostNav} loot={s.BoostLoot}]";
+ $" eng={s.CombatEngaged} boost[nav={s.BoostNav} loot={s.BoostLoot}]"
+ (s.LootStarved ? " lootStarved" : "");
if (key == _lastDecisionKey) return;
_lastDecisionKey = key;
_log($"Arbiter[step5]: {key}");

View file

@ -132,11 +132,18 @@ public class WorldObject
if (o != null)
{
if (o.Strings.TryGetValue((uint)key, out string? v)) return v;
if (!o.LiveFallback) return defaultValue;
if (!o.LiveFallback) return NameOr(key, defaultValue);
}
return Cache?.GetStringProperty(Id, (uint)key, defaultValue) ?? defaultValue;
string s = Cache?.GetStringProperty(Id, (uint)key, defaultValue) ?? defaultValue;
return string.IsNullOrEmpty(s) ? NameOr(key, defaultValue) : s;
}
// The server doesn't put the name in the appraisal's string properties, so a
// StringValue(Name) loot condition compared against "" and every name rule failed
// (healing-kit Keep # rules never looted; 2026-09-28). Fall back to the object's name.
private string NameOr(StringValueKey key, string defaultValue)
=> key == StringValueKey.Name && !string.IsNullOrEmpty(Name) ? Name : defaultValue;
public double Values(DoubleValueKey key, double defaultValue)
{
var o = Overlay;
@ -236,7 +243,9 @@ public class SpellInfo
{ "Jibril's Blessing", "Armor Tinkering Expertise" },
{ "Yoshi's Blessing", "Item Tinkering Expertise" },
{ "Koga's Blessing", "Weapon Tinkering Expertise" },
{ "Nuhmidira's Blessing", "Mana Conversion Mastery" },
{ "Nuhmudira's Blessing", "Mana Conversion Mastery" },
{ "Blessing of T'ing", "Two Handed Combat Mastery" },
{ "Celdiseth's Blessing", "Magic Item Tinkering Expertise" },
{ "Saladur's Blessing", "Sprint" },
{ "Jahannan's Blessing", "Jumping Mastery" },
{ "Odif's Blessing", "Fealty" }, { "Odif's Boon", "Fealty" },
@ -323,6 +332,11 @@ public class SpellInfo
{ n = n[8..].Trim(); changed = true; }
}
// 3b. The spell data spells tiers 1-6 and 8 of the bludgeon bane "Bludgeon Bane";
// tier 7 (Tusker's Bane) maps to "Bludgeoning Bane". One family for all.
if (n.Equals("Bludgeon Bane", StringComparison.OrdinalIgnoreCase))
n = "Bludgeoning Bane";
// 4. Strip " Self" / " Other" target suffixes, then lowercase
n = n.Replace(" Self", "").Replace(" Other", "").Trim().ToLowerInvariant();
@ -471,6 +485,7 @@ public class CharacterSkills
AcSkillType.HeavyWeapons => 44,
AcSkillType.LightWeapons => 45,
AcSkillType.FinesseWeapons => 46,
AcSkillType.MissileWeapons => 47,
AcSkillType.TwoHandedCombat => 41,
AcSkillType.Shield => 48,
AcSkillType.DualWield => 49,

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,303 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.CreatureData;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Missile swaps between launchers that shoot different ammo (bow / crossbow / atlatl), rules in
/// <see cref="MissileAmmo"/>. Melee, magic and thrown weapons never come here.
///
/// 1. The plan: a launcher with no fitting ammo in the pack is not a candidate (logged once),
/// unless it is the one in hand (running out is ammo crafting's job, as before) or no
/// launcher at all has ammo (then nothing changes). A launcher's element is the element it
/// does with the ammo it would shoot: the stack wielded when it fits, else the stack
/// <see cref="MissileAmmo.Choose"/> picks.
/// 2. Before wielding a launcher, ammo of another type in the ammunition slot goes into the
/// pack (the server refuses the launcher otherwise). One move in flight, 3 tries, then a rest.
/// 3. Once the launcher is in hand, the chosen stack is wielded: one in flight, confirmed in
/// the ammunition slot, retry cap and no flip-flop (<see cref="AmmoTracker"/>, the same
/// tracker as weapons). Ammo crafting holds off while this runs (<see cref="AmmoSwapInProgress"/>).
/// </summary>
public partial class CombatManager
{
/// <summary>Combat's ammo wields after a launcher swap: one in flight, confirmed, capped.</summary>
internal WeaponSwapTracker AmmoTracker { get; } = new();
/// <summary>Tests: the pack an ammo stack is put into (default: an open pack with room).</summary>
internal Func<int>? OpenPackOverride { get; set; }
// The launcher whose ammo combat wields once it lands, and until when that holds crafting off.
private int _ammoFollowUpFor;
private DateTime _ammoFollowUpUntil = DateTime.MinValue;
private const double AmmoFollowUpMs = 30_000;
// Putting ammo of the wrong type away before the launcher wield.
private int _ammoDequipPendingId, _ammoDequipTries;
private DateTime _ammoDequipAt = DateTime.MinValue, _ammoDequipRestUntil = DateTime.MinValue;
private const double AmmoDequipResolveMs = 2500;
private const int AmmoDequipMaxTries = 3;
private readonly HashSet<int> _noAmmoNoted = new();
/// <summary>
/// A launcher swap's ammo step is under way (the old stack going into the pack, or the new
/// one being wielded). Ammo crafting waits: it would otherwise equip ammo for the launcher
/// being swapped away from, or start a craft in the middle of the swap.
/// </summary>
public bool AmmoSwapInProgress => _ammoFollowUpFor != 0 && DateTime.Now < _ammoFollowUpUntil;
private void ResetAmmoState()
{
AmmoTracker.Reset();
_ammoFollowUpFor = 0;
_ammoFollowUpUntil = DateTime.MinValue;
_ammoDequipPendingId = _ammoDequipTries = 0;
_ammoDequipRestUntil = DateTime.MinValue;
_noAmmoNoted.Clear();
}
/// <summary>Arrows, quarrels, darts: ValidLocations has the ammunition slot; by name when that isn't known.</summary>
internal static bool IsAmmoItem(WorldObject wo)
{
int valid = wo.Values(LongValueKey.Locations, 0);
if (valid != 0) return (valid & MissileAmmo.AmmoSlot) != 0;
return WorldObjectCache.IsAmmo(wo);
}
/// <summary>The ammo type a weapon needs; 0 for anything but a launcher whose type is known (thrown, melee, wand).</summary>
private static int LauncherTypeOf(WorldObject? wo)
{
if (wo == null || wo.ObjectClass != AcObjectClass.MissileWeapon || IsAmmoItem(wo)) return 0;
bool stackable = wo.Values(LongValueKey.MaxStackSize, 0) > 1;
return MissileAmmo.LauncherAmmoType(wo.Values((int)MissileAmmo.PropAmmoType, 0), wo.Name, stackable);
}
private static int AmmoTypeOfItem(WorldObject wo) => MissileAmmo.AmmoTypeOf(wo.Values((int)MissileAmmo.PropAmmoType, 0), wo.Name);
/// <summary>Every ammo stack the character carries (wielded one included), in pack order.</summary>
internal List<AmmoCandidate> PackAmmo()
{
var list = new List<AmmoCandidate>();
var rules = _settings.ItemRules;
foreach (var wo in _worldFilter.GetDirectInventory(forceRefresh: true))
{
if (!IsAmmoItem(wo)) continue;
int type = AmmoTypeOfItem(wo);
if (type == 0) continue;
uint uid = unchecked((uint)wo.Id);
int? dt = _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(uid, WeaponElements.PropDamageType, out int d) ? d : null;
int? fx = _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(uid, WeaponElements.PropUiEffects, out int f) ? f : null;
bool prismatic = MissileAmmo.IsPrismatic(dt, wo.Name);
string elem = prismatic ? "" : WeaponElements.Detect(dt, null, fx, wo.Name).Element;
int listIdx = rules.FindIndex(r => r.Id == wo.Id);
int quality = AmmoRecipes.OutputRank(wo.Name, MissileAmmo.CategoryOf(type));
bool wielded = WorldObjectCache.IsWieldedByPlayer(_host, wo);
list.Add(new AmmoCandidate(wo.Id, wo.Name, type, elem, prismatic, quality, listIdx, wielded));
}
return list;
}
private static string RuleElementOf(MonsterRule? rule) =>
rule != null && !string.IsNullOrEmpty(rule.DamageType) && !rule.DamageType.Equals("Auto", StringComparison.OrdinalIgnoreCase)
? WeaponElements.Normalize(rule.DamageType) : "";
private static Func<string, int> AmmoRank(string ruleElement, CreatureWeakness.Ranking? weak) =>
MissileAmmo.RankBy(WeaponElements.Normalize(ruleElement), weak != null && weak.Order.Count > 0 ? WeaponPlanner.TieGroups(weak) : null);
/// <summary>A launcher's own element: the Items list's, else what its properties say.</summary>
private string LauncherElement(int id, WorldObject wo)
{
var r = _settings.ItemRules.FirstOrDefault(x => x.Id == id);
string e = WeaponElements.Normalize(r?.Element);
return e.Length > 0 ? e : ElementTracker.Read(id, wo.Name).Element;
}
/// <summary>
/// The plan's view of the launchers (step 1 in the class note). Lists without a launcher come
/// back as they are, so melee and magic plans don't change.
/// </summary>
internal List<WeaponCandidate> ApplyAmmo(List<WeaponCandidate> listed, string ruleElement, CreatureWeakness.Ranking? weak)
{
if (listed.Count == 0 || !listed.Any(c => c.Kind == CombatMode.Missile)) return listed;
List<AmmoCandidate>? pack = null;
var rank = AmmoRank(ruleElement, weak);
var result = new List<WeaponCandidate>(listed.Count);
var dropped = new List<(WeaponCandidate C, int Type)>();
foreach (var c in listed)
{
if (c.Kind != CombatMode.Missile) { result.Add(c); continue; }
int lt = LauncherTypeOf(_worldFilter[c.Id]);
if (lt == 0) { result.Add(c); continue; } // thrown, or a type not known: as before
pack ??= PackAmmo();
var wielded = pack.FirstOrDefault(a => a.Wielded);
var use = wielded != null && MissileAmmo.Fits(lt, wielded.AmmoType)
? wielded
: MissileAmmo.Choose(lt, c.Element, pack, rank);
if (use == null)
{
if (c.InHand) { result.Add(c); continue; } // ran out in hand: crafting's job, as before
dropped.Add((c, lt));
continue;
}
_noAmmoNoted.Remove(c.Id);
// An element the user picked in the Items panel wins over the ammo's (owner's call,
// 2026-10-01), although the server uses the ammo's element for the damage.
if (_settings.ItemRules.FirstOrDefault(x => x.Id == c.Id)?.ElementSource == WeaponList.SourceSet)
{
result.Add(c);
continue;
}
string e = MissileAmmo.EffectiveElement(use, c.Element);
result.Add(e.Length > 0 && e != c.Element ? c with { Element = e } : c);
}
if (dropped.Count == 0) return result;
// No launcher of the character's main kind is left: change nothing (the first launcher is
// still wielded and ammo crafting makes ammo for it), rather than turning an archer into a
// swordsman or a mage because the pack ran dry.
if (listed[0].Kind == CombatMode.Missile && !result.Any(c => c.Kind == CombatMode.Missile))
return listed;
foreach (var (c, lt) in dropped)
if (_noAmmoNoted.Add(c.Id))
_host.Log($"[EquipDiag] 0x{(uint)c.Id:X8} '{c.Name}' has no {MissileAmmo.Label(lt)} in the pack — not swapping to it");
return result;
}
private enum AmmoPrep { Ready, Busy, Blocked }
/// <summary>
/// Step 2: called right before a launcher wield is sent. Ready: send it. Busy: ammo of the
/// wrong type is on its way into the pack (wait). Blocked: it can't be put away now (no pack
/// room, or resting after failed tries); don't send the launcher, the server would refuse it.
/// Also arms step 3 when a fitting stack is in the pack.
/// </summary>
private AmmoPrep PrepareAmmoFor(int launcherId)
{
int lt = LauncherTypeOf(_worldFilter[launcherId]);
if (lt == 0) return AmmoPrep.Ready;
DateTime now = DateTime.Now;
var pack = PackAmmo();
var wielded = pack.FirstOrDefault(a => a.Wielded);
if (wielded != null && MissileAmmo.Fits(lt, wielded.AmmoType))
{
_ammoDequipPendingId = 0; _ammoDequipTries = 0;
return AmmoPrep.Ready; // same ammo type: it stays
}
if (pack.Any(a => !a.Wielded && MissileAmmo.Fits(lt, a.AmmoType)))
ArmAmmoFollowUp(launcherId, now);
if (wielded == null)
{
_ammoDequipPendingId = 0; _ammoDequipTries = 0;
return AmmoPrep.Ready;
}
// Ammo of another type is wielded: into the pack first.
if (_ammoDequipPendingId == wielded.Id && (now - _ammoDequipAt).TotalMilliseconds < AmmoDequipResolveMs)
return AmmoPrep.Busy;
if (now < _ammoDequipRestUntil) return AmmoPrep.Blocked;
if (_ammoDequipTries >= AmmoDequipMaxTries)
{
_ammoDequipTries = 0;
_ammoDequipPendingId = 0;
_ammoDequipRestUntil = now.AddMinutes(2);
_host.Log($"[EquipDiag] {MissileAmmo.Label(wielded.AmmoType)} 0x{(uint)wielded.Id:X8} '{wielded.Name}' didn't come off after {AmmoDequipMaxTries} tries — not swapping to 0x{(uint)launcherId:X8} '{WeaponName(launcherId)}' for 2 min");
return AmmoPrep.Blocked;
}
int packId = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1);
if (packId == 0 || !_host.HasMoveItemInternal)
{
if (packId == 0) WorldObjectCache.WarnPackFull(_host, $"can't put the {MissileAmmo.Label(wielded.AmmoType)} away to switch launchers");
return AmmoPrep.Blocked;
}
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-ammo-dequip")) return AmmoPrep.Busy;
var wo = _worldFilter[wielded.Id];
int amount = Math.Max(1, wo?.Values(LongValueKey.StackCount, 1) ?? 1); // the whole stack, not one arrow
_host.MoveItemInternal(unchecked((uint)wielded.Id), unchecked((uint)packId), 0, amount);
_ammoDequipPendingId = wielded.Id;
_ammoDequipAt = now;
_ammoDequipTries++;
_lastEquipTime = now;
_host.Log($"[EquipDiag] {MissileAmmo.Label(wielded.AmmoType)} 0x{(uint)wielded.Id:X8} '{wielded.Name}' x{amount} -> pack 0x{(uint)packId:X8} before wielding 0x{(uint)launcherId:X8} '{WeaponName(launcherId)}' (try {_ammoDequipTries}/{AmmoDequipMaxTries})");
return AmmoPrep.Busy;
}
private void ArmAmmoFollowUp(int launcherId, DateTime now)
{
if (_ammoFollowUpFor == launcherId && now < _ammoFollowUpUntil) return;
_ammoFollowUpFor = launcherId;
_ammoFollowUpUntil = now.AddMilliseconds(AmmoFollowUpMs);
}
private void EndAmmoFollowUp() { _ammoFollowUpFor = 0; _ammoFollowUpUntil = DateTime.MinValue; }
/// <summary>
/// Step 3, with <paramref name="launcherId"/> confirmed in hand. True while the attack should
/// wait for the ammo wield. Only after combat's own launcher swap: an empty quiver otherwise is
/// left to ammo crafting (which may craft better ammo first), as before.
/// </summary>
private bool AmmoFollowUp(int launcherId, WorldObject target, MonsterRule? rule)
{
if (_ammoFollowUpFor == 0) return false;
DateTime now = DateTime.Now;
if (_ammoFollowUpFor != launcherId || now >= _ammoFollowUpUntil) { EndAmmoFollowUp(); return false; }
var wo = _worldFilter[launcherId];
int lt = LauncherTypeOf(wo);
if (wo == null || lt == 0) { EndAmmoFollowUp(); return false; }
SwapTracker.Confirmed(launcherId, now); // the launcher landed
if (AmmoTracker.PendingId != 0 && ServerRefusedSinceSend()) AmmoTracker.Refused(now, WeaponName);
var pack = PackAmmo();
var wielded = pack.FirstOrDefault(a => a.Wielded);
if (wielded != null && MissileAmmo.Fits(lt, wielded.AmmoType))
{
AmmoTracker.Confirmed(wielded.Id, now);
_host.Log($"[EquipDiag] ammo in: 0x{(uint)wielded.Id:X8} '{wielded.Name}' for 0x{(uint)launcherId:X8} '{wo.Name}'");
EndAmmoFollowUp();
return false;
}
var pick = MissileAmmo.Choose(lt, LauncherElement(launcherId, wo), pack, AmmoRank(RuleElementOf(rule), WeaknessFor(target)));
if (pick == null)
{
_host.Log($"[EquipDiag] no {MissileAmmo.Label(lt)} left for 0x{(uint)launcherId:X8} '{wo.Name}' — leaving it to ammo crafting");
EndAmmoFollowUp();
return false;
}
var step = AmmoTracker.Next(pick.Id, wielded?.Id ?? 0, now, WeaponName);
if (AmmoTracker.Notice != null)
{
_host.Log($"[EquipDiag] {AmmoTracker.Notice}");
AmmoTracker.Notice = null;
}
switch (step)
{
case WeaponSwapTracker.Step.Wait:
return true;
case WeaponSwapTracker.Step.Swap:
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-ammo")) return true;
_host.UseFor(unchecked((uint)pick.Id), "Combat", "ammo for the missile weapon");
if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out _)) _swapUseDoneSeq = uSeq;
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out _, out _, out _)) _swapWeenieSeq = wSeq;
AmmoTracker.Sent(pick.Id, wielded?.Id ?? 0, now);
_lastEquipTime = now;
_host.Log($"[EquipDiag] ammo: wielding 0x{(uint)pick.Id:X8} '{pick.Name}' for 0x{(uint)launcherId:X8} '{wo.Name}' (try {AmmoTracker.TriesFor(pick.Id)}/{AmmoTracker.MaxTries})");
return true;
case WeaponSwapTracker.Step.Hold:
_host.Log($"[EquipDiag] ammo: not wielding 0x{(uint)pick.Id:X8} '{pick.Name}' ({AmmoTracker.HoldReason}) — leaving it to ammo crafting");
EndAmmoFollowUp();
return false;
default:
EndAmmoFollowUp();
return false;
}
}
}

View file

@ -0,0 +1,388 @@
using System;
using System.Collections.Generic;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The off hand (the Shield slot): a shield, or a second weapon (dual wield). Rules in
/// <see cref="OffhandRules"/>, the choice in <see cref="OffhandPlanner"/>.
///
/// 1. The choice for a target: the Monsters rule's OffhandId (Auto / Shield / Offhand weapon /
/// None, or an item), else the global LegacyUiSettings.OffhandDefault. The Damage tab's
/// per-monster offhand item wins over the mode (not over None). Listed items only.
/// 2. Before a main weapon that can't share the hands (a two-hander, a launcher, a caster, or a
/// thrown weapon with an off-hand weapon) is wielded, the off hand goes into an open pack:
/// the server refuses the main weapon otherwise. One move in flight, 3 tries, then a rest.
/// With None the off hand is never touched: that main weapon isn't wielded (combat keeps
/// what's in hand) rather than sending a wield the server would refuse.
/// 3. Once the main weapon is confirmed in hand (and the stance reached), the planned off hand
/// is wielded into the Shield slot: one in flight, confirmed in the slot, server refusals
/// counted, 3 tries then a rest, no flip-flop (<see cref="OffhandTracker"/>, the same tracker
/// as weapons and ammo). Something else in the off hand comes off first.
/// 4. What RynthAi itself took off (for a two-hander, or buffing's wand) goes back on once the
/// hands allow it, when nothing listed is planned there.
/// </summary>
public partial class CombatManager
{
/// <summary>Combat's off-hand wields: one in flight, confirmed, capped, no flip-flop.</summary>
internal WeaponSwapTracker OffhandTracker { get; } = new();
/// <summary>How long a read of the off hand is reused (it walks the inventory). Tests set 0.</summary>
internal double OffhandReadMs { get; set; } = 1000;
// Taking the off hand off (into a pack): one move in flight, 3 tries, then a rest.
private int _offDequipPendingId, _offDequipTries;
private DateTime _offDequipAt = DateTime.MinValue, _offDequipRestUntil = DateTime.MinValue;
private const double OffDequipResolveMs = 2500;
private const int OffDequipMaxTries = 3;
// The off hand that was in the slot when the current swap was decided (for no flip-flop).
private int _offSwapFrom;
// An off hand RynthAi took off itself (for a main weapon, or buffing's wand): put back later.
private int _stowedOffhandId;
// The off-hand mode for the target combat is equipping for (the wand path reads it).
private OffhandMode _curOffhandMode = OffhandMode.Auto;
private int _offSlotId;
private DateTime _offSlotReadAt = DateTime.MinValue;
private (int Id, string Source) _lastOffPlan = (-1, "");
private DateTime _lastOffHoldLogAt = DateTime.MinValue;
private readonly HashSet<string> _offNoted = new();
private void ResetOffhandState()
{
OffhandTracker.Reset();
_offDequipPendingId = _offDequipTries = 0;
_offDequipAt = _offDequipRestUntil = DateTime.MinValue;
_offSwapFrom = _stowedOffhandId = 0;
_offSlotId = 0;
_offSlotReadAt = DateTime.MinValue;
_lastOffPlan = (-1, "");
_offNoted.Clear();
}
/// <summary>Buffing took <paramref name="id"/> out of the off hand for its wand: combat puts it back.</summary>
public void NoteOffhandStowed(int id)
{
if (id != 0) _stowedOffhandId = id;
}
// ── What things are ──────────────────────────────────────────────────────
private static int WieldedSlot(WorldObject wo) => wo.Values(LongValueKey.CurrentWieldedLocation, 0);
private static bool IsTwoHandedItem(WorldObject wo) =>
OffhandRules.IsTwoHanded(wo.Values((int)OffhandRules.PropCombatUse, 0), wo.Values(LongValueKey.Locations, 0),
wo.Values((int)OffhandRules.PropWeaponSkill, 0));
/// <summary>A shield (CombatUse Shield, or a non-weapon that goes in the Shield slot).</summary>
internal static bool IsShieldItem(WorldObject wo)
{
bool weaponClass = wo.ObjectClass == AcObjectClass.MeleeWeapon || wo.ObjectClass == AcObjectClass.MissileWeapon
|| wo.ObjectClass == AcObjectClass.WandStaffOrb;
return OffhandRules.IsShield(wo.Values((int)OffhandRules.PropCombatUse, 0), wo.Values(LongValueKey.Locations, 0), weaponClass);
}
/// <summary>A melee weapon the server lets into the Shield slot (dual wield).</summary>
internal static bool IsOffhandWeaponItem(WorldObject wo) =>
wo.ObjectClass == AcObjectClass.MeleeWeapon
&& OffhandRules.CanBeOffhandWeapon(wo.Values(LongValueKey.Locations, 0), IsTwoHandedItem(wo));
/// <summary>What a main weapon is, by ACE's wield rules.</summary>
internal static MainHandKind MainKindOf(WorldObject? wo)
{
if (wo == null) return MainHandKind.None;
if (WeaponList.IsWand(wo)) return MainHandKind.Caster;
if (wo.ObjectClass == AcObjectClass.MissileWeapon)
{
if (IsAmmoItem(wo)) return MainHandKind.None;
return wo.Values(LongValueKey.MaxStackSize, 0) > 1 ? MainHandKind.Thrown : MainHandKind.Launcher;
}
if (wo.ObjectClass == AcObjectClass.MeleeWeapon)
return IsTwoHandedItem(wo) ? MainHandKind.TwoHanded : MainHandKind.OneHandedMelee;
return MainHandKind.None;
}
/// <summary>The item in the off hand (the Shield slot), 0 = empty. Read live at most every
/// <see cref="OffhandReadMs"/>, always live while an off-hand action is in flight.</summary>
internal int OffhandInSlot(bool fresh = false)
{
DateTime now = DateTime.Now;
if (!fresh && OffhandTracker.PendingId == 0 && _offDequipPendingId == 0
&& (now - _offSlotReadAt).TotalMilliseconds < OffhandReadMs)
return _offSlotId;
_offSlotReadAt = now;
int found = 0;
try
{
foreach (var wo in _worldFilter.GetDirectInventory(forceRefresh: true))
if ((WieldedSlot(wo) & OffhandRules.ShieldSlot) != 0) { found = wo.Id; break; }
// CurrentWieldedLocation can read 0 (always under the Decal bridge): ask the weenie
// itself who wields the listed off-hand items and where.
if (found == 0 && _host.HasGetObjectWielderInfo)
{
uint pid = _host.GetPlayerId();
foreach (var r in _settings.ItemRules)
{
if (r.Id == 0 || pid == 0) continue;
if (_host.TryGetObjectWielderInfo(unchecked((uint)r.Id), out uint wielder, out uint loc)
&& wielder == pid && (loc & OffhandRules.ShieldSlot) != 0) { found = r.Id; break; }
}
}
}
catch { }
_offSlotId = found;
return found;
}
private bool DualWieldTrained => _charSkills != null && _charSkills[AcSkillType.DualWield].Training >= 2;
// ── The choice ───────────────────────────────────────────────────────────
/// <summary>
/// The off-hand mode for <paramref name="target"/> (the rule's OffhandId, else the global
/// setting) and an explicit item: the Damage tab's per-monster offhand, else the rule's old
/// item pick; listed only.
/// </summary>
internal (OffhandMode Mode, int ExplicitId, string Source) OffhandChoiceFor(WorldObject? target, MonsterRule? rule)
{
var global = OffhandRules.Parse(_settings.OffhandDefault, OffhandMode.Auto);
int ruleVal = rule?.OffhandId ?? 0;
// A rule left on Default follows the Default row; the Default row left unset is the global setting (Auto).
var defaultRow = _settings.MonsterRules.Find(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
var mode = OffhandRules.RuleMode(ruleVal) ?? OffhandRules.RuleMode(defaultRow?.OffhandId ?? 0) ?? global;
if (mode == OffhandMode.None || target == null) return (mode, 0, "");
int pick = 0;
string source = "";
if (_damageStore != null && _host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)target.Id), out uint wcid) && wcid != 0)
{
uint off = _damageStore.GetManualOffhand(wcid);
if (off != 0) { pick = unchecked((int)off); source = "Damage tab offhand"; }
}
if (pick == 0 && OffhandRules.IsRuleItem(ruleVal)) { pick = ruleVal; source = $"Monsters rule '{rule!.Name}' offhand"; }
if (pick == 0 && ruleVal == 0 && defaultRow != null && OffhandRules.IsRuleItem(defaultRow.OffhandId))
{ pick = defaultRow.OffhandId; source = "Default offhand"; }
if (pick != 0 && !_settings.ItemRules.Exists(r => r.Id == pick))
{
NoteUnlisted(pick, source);
pick = 0;
source = "";
}
return (mode, pick, source);
}
/// <summary>The Items list's shields and off-hand-capable one-handed melee weapons, in list order.</summary>
internal List<OffhandCandidate> ListedOffhand(int offInSlot)
{
var list = new List<OffhandCandidate>();
var seen = new HashSet<int>();
foreach (var r in _settings.ItemRules)
{
if (r.Id == 0 || !seen.Add(r.Id)) continue;
var wo = _worldFilter[r.Id];
if (wo == null) continue;
if (IsShieldItem(wo)) list.Add(new OffhandCandidate(r.Id, wo.Name, true, r.Id == offInSlot));
else if (IsOffhandWeaponItem(wo)) list.Add(new OffhandCandidate(r.Id, wo.Name, false, r.Id == offInSlot));
}
return list;
}
/// <summary>The off hand to go with <paramref name="mainId"/> against <paramref name="target"/>.</summary>
internal OffhandPlan OffhandPlanFor(WorldObject target, MonsterRule? rule, int mainId)
{
var (mode, pick, source) = OffhandChoiceFor(target, rule);
int off = OffhandInSlot();
var kind = MainKindOf(_worldFilter[mainId]);
var plan = OffhandPlanner.Choose(mode, kind, mainId, ListedOffhand(off), DualWieldTrained, _settings.PreferDualWield,
_host.HasWieldItem, pick, source);
// Nothing listed planned: put back what RynthAi took off itself, when the hands allow it.
if (plan.Id == 0 && mode != OffhandMode.None && _stowedOffhandId != 0 && _stowedOffhandId != mainId)
{
var stowed = _worldFilter[_stowedOffhandId];
if (stowed == null || _stowedOffhandId == off) _stowedOffhandId = 0;
else if ((kind == MainHandKind.OneHandedMelee
&& (IsShieldItem(stowed) || (IsOffhandWeaponItem(stowed) && _host.HasWieldItem)))
|| (kind == MainHandKind.Thrown && IsShieldItem(stowed))) // a thrown weapon keeps a shield
plan = new OffhandPlan(_stowedOffhandId, "putting back what was taken off");
}
return plan;
}
// ── Before a main wield ──────────────────────────────────────────────────
private enum OffPrep { Ready, Busy, Blocked }
/// <summary>
/// Would what is in the off hand stop <paramref name="mainId"/> being wielded, with RynthAi
/// not allowed to take it off (Offhand None) or resting after failed tries? Combat then keeps
/// what's in hand instead of sending a wield the server would refuse.
/// </summary>
private bool OffhandBlocksMain(int mainId, OffhandMode mode)
{
int off = OffhandInSlot();
if (off == 0) return false;
var offWo = _worldFilter[off];
var kind = MainKindOf(_worldFilter[mainId]);
if (OffhandRules.OffhandAllowed(kind, offWo != null && IsShieldItem(offWo))) return false;
string why;
if (mode == OffhandMode.None) why = "Offhand is None, so it stays";
else if (DateTime.Now < _offDequipRestUntil) why = "it didn't come off; resting";
else return false;
if ((DateTime.Now - _lastOffHoldLogAt).TotalSeconds > 10)
{
_lastOffHoldLogAt = DateTime.Now;
_host.Log($"[EquipDiag] not wielding 0x{(uint)mainId:X8} '{WeaponName(mainId)}' ({OffhandRules.KindLabel(kind)}): 0x{(uint)off:X8} '{offWo?.Name ?? "?"}' is in the off hand and {why} — the server refuses it otherwise");
}
return true;
}
/// <summary>
/// Right before a main wield of <paramref name="mainId"/>: Ready when the off hand may stay
/// (or is empty); Busy while it goes into a pack (wait); Blocked when it can't come off now
/// (Offhand None, no pack room, resting): don't send the main wield. <paramref name="gateHeld"/>:
/// the caller already holds the shared swap gate for this step (the wand paths).
/// </summary>
private OffPrep ClearOffhandFor(int mainId, OffhandMode mode, bool gateHeld = false)
{
int off = OffhandInSlot(fresh: true);
if (off == 0) { _offDequipPendingId = 0; _offDequipTries = 0; return OffPrep.Ready; }
var offWo = _worldFilter[off];
var kind = MainKindOf(_worldFilter[mainId]);
if (OffhandRules.OffhandAllowed(kind, offWo != null && IsShieldItem(offWo))) return OffPrep.Ready;
if (mode == OffhandMode.None) return OffPrep.Blocked;
var prep = DequipOffhand(off, $"before wielding 0x{(uint)mainId:X8} '{WeaponName(mainId)}' ({OffhandRules.KindLabel(kind)})", gateHeld);
if (prep == OffPrep.Busy && _stowedOffhandId == 0) _stowedOffhandId = off;
return prep;
}
/// <summary>Put <paramref name="offId"/> (in the off hand) into an open pack: one move in flight, capped.</summary>
private OffPrep DequipOffhand(int offId, string why, bool gateHeld = false)
{
DateTime now = DateTime.Now;
if (_offDequipPendingId != offId) _offDequipTries = 0;
if (_offDequipPendingId == offId && (now - _offDequipAt).TotalMilliseconds < OffDequipResolveMs)
return OffPrep.Busy;
if (now < _offDequipRestUntil) return OffPrep.Blocked;
string name = _worldFilter[offId]?.Name ?? "";
if (_offDequipTries >= OffDequipMaxTries)
{
_offDequipTries = 0;
_offDequipPendingId = 0;
_offDequipRestUntil = now.AddMinutes(2);
_host.Log($"[EquipDiag] off hand 0x{(uint)offId:X8} '{name}' didn't come off after {OffDequipMaxTries} tries — leaving the hands as they are for 2 min");
return OffPrep.Blocked;
}
int packId = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1);
if (packId == 0 || !_host.HasMoveItemInternal)
{
if (packId == 0) WorldObjectCache.WarnPackFull(_host, "can't put the shield away to change weapons");
return OffPrep.Blocked;
}
if (!gateHeld && _weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-offhand-dequip")) return OffPrep.Busy;
_host.MoveItemInternal(unchecked((uint)offId), unchecked((uint)packId), 0, 1);
_offDequipPendingId = offId;
_offDequipAt = now;
_offDequipTries++;
_lastEquipTime = now;
_host.Log($"[EquipDiag] off hand 0x{(uint)offId:X8} '{name}' -> pack 0x{(uint)packId:X8} {why} (try {_offDequipTries}/{OffDequipMaxTries})");
return OffPrep.Busy;
}
// ── After the main weapon is in hand ─────────────────────────────────────
/// <summary>
/// <paramref name="mainId"/> is confirmed in hand and the stance reached: wield the planned
/// off hand. True while the attack should wait (a wield or a move in flight).
/// </summary>
private bool OffhandFollowUp(WorldObject target, MonsterRule? rule, int mainId)
{
DateTime now = DateTime.Now;
if (OffhandTracker.PendingId != 0 && ServerRefusedSinceSend()) OffhandTracker.Refused(now, WeaponName);
var plan = OffhandPlanFor(target, rule, mainId);
int off = OffhandInSlot();
if (plan.Id != _lastOffPlan.Id || plan.Source != _lastOffPlan.Source)
{
_lastOffPlan = (plan.Id, plan.Source);
if (plan.Id != 0 || off != 0)
_host.Log(plan.Id != 0
? $"[EquipDiag] off hand for '{target.Name}': 0x{(uint)plan.Id:X8} '{WeaponName(plan.Id)}' ({plan.Source})"
: $"[EquipDiag] off hand for '{target.Name}': leaving 0x{(uint)off:X8} '{WeaponName(off)}' as it is ({plan.Source})");
}
if (plan.Id == 0 || plan.Id == off)
{
if (plan.Id != 0)
{
OffhandTracker.Confirmed(plan.Id, now);
if (plan.Id == _stowedOffhandId) _stowedOffhandId = 0;
}
if (off == 0 || off == plan.Id) { _offDequipPendingId = 0; _offDequipTries = 0; }
return false;
}
var step = OffhandTracker.Next(plan.Id, off, now, WeaponName);
if (OffhandTracker.Notice != null)
{
_host.Log($"[EquipDiag] off hand: {OffhandTracker.Notice}");
OffhandTracker.Notice = null;
}
switch (step)
{
case WeaponSwapTracker.Step.Wait:
return true;
case WeaponSwapTracker.Step.Hold:
if ((now - _lastOffHoldLogAt).TotalSeconds > 10)
{
_lastOffHoldLogAt = now;
_host.Log($"[EquipDiag] off hand: keeping 0x{(uint)off:X8} '{WeaponName(off)}' instead of 0x{(uint)plan.Id:X8} '{WeaponName(plan.Id)}' ({OffhandTracker.HoldReason})");
}
return false;
case WeaponSwapTracker.Step.Swap:
break;
default:
return false;
}
// Something else in the off hand: into the pack first (the server refuses an occupied slot).
if (off != 0)
{
var prep = DequipOffhand(off, $"to wield 0x{(uint)plan.Id:X8} '{WeaponName(plan.Id)}' there");
if (prep == OffPrep.Busy) { _offSwapFrom = off; return true; }
return false;
}
var wo = _worldFilter[plan.Id];
if (wo == null) return false;
bool shield = IsShieldItem(wo);
if (!_host.HasWieldItem && !shield)
{
if (_offNoted.Add("noslotwield")) _host.Log("[EquipDiag] off hand: this engine can't wield into the off hand — no dual wield");
return false;
}
// Another swap just went out (the main weapon, say): fight on and try again after the gate.
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-offhand")) return false;
bool sent = _host.HasWieldItem
? _host.WieldItem(unchecked((uint)plan.Id), OffhandRules.ShieldSlot)
: _host.UseFor(unchecked((uint)plan.Id), "Combat", "offhand: wield the shield or offhand weapon");
if (!sent)
{
if (_offNoted.Add("send:" + plan.Id)) _host.Log($"[EquipDiag] off hand: the wield of 0x{(uint)plan.Id:X8} '{wo.Name}' couldn't be sent");
return false;
}
if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out _)) _swapUseDoneSeq = uSeq;
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out _, out _, out _)) _swapWeenieSeq = wSeq;
OffhandTracker.Sent(plan.Id, _offSwapFrom, now);
_offSwapFrom = 0;
_lastEquipTime = now;
if (plan.Id != _stowedOffhandId) _stowedOffhandId = 0; // a listed one replaces what was taken off
_host.Log($"[EquipDiag] off hand: wielding 0x{(uint)plan.Id:X8} '{wo.Name}' for '{target.Name}' ({plan.Source}) (try {OffhandTracker.TriesFor(plan.Id)}/{OffhandTracker.MaxTries})");
return true;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,141 @@
using System;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Safety net for the melee/missile "stands there in combat mode, not attacking" stall
/// (2026-09-29, Lucy in the Olthoi swarm). The root cause is fixed in CombatManager
/// (the server's attack loop stayed bound to an old, unreachable target and ACE drops every
/// new attack request while that target lives); this catches anything else that leaves
/// the bot issuing attacks that never become swings.
///
/// Pure timing/ladder state. CombatManager decides whether the situation is eligible
/// (action Combat, live target locked and in range, Melee or Missile mode), feeds the time
/// of the last swing evidence (a hit, a miss or a kill), and carries out the step returned.
/// Pump thread only; no timers — it only advances when Tick is called.
///
/// Escalation, one step per call that returns it:
/// 1 Reissue — CancelAttack, the attack goes out again on the next cycle
/// 2 Reselect — CancelAttack, drop the lock so targeting picks again
/// 3 ToggleMode — peace and back (what the wand heal does: the mode change ends the
/// server's attack)
/// 4 Rewield — put the weapon away and wield it again
/// After step 4 with still no swings the ladder rests for <see cref="CooldownMs"/>.
/// </summary>
internal sealed class CombatStallWatchdog
{
/// <summary>No swing evidence for this long while eligible = stalled. Normal melee in
/// the 2026-09-29 log swings every 1-2 s (busy pulses, hits, "evaded your attack"); the
/// real stalls ran 12-49 s.</summary>
public const double StallMs = 6000;
/// <summary>Time allowed for each step to show a swing before the next one.</summary>
public const double StepMs = 3000;
/// <summary>Rest after a full ladder that didn't help, so the watchdog can't churn.</summary>
public const double CooldownMs = 30000;
/// <summary>Tick gap that means combat wasn't running (buffing, looting, nav took the
/// arbiter, or combat went ineligible): start the episode over instead of counting the
/// gap as stalled time.</summary>
public const double TickGapResetMs = 1500;
public enum StallAction { None, Reissue, Reselect, ToggleMode, Rewield, Recovered, GaveUp }
private DateTime _eligibleSince = DateTime.MinValue;
private DateTime _lastTick = DateTime.MinValue;
private DateTime _lastStepAt = DateTime.MinValue;
private DateTime _cooldownUntil = DateTime.MinValue;
private int _step; // steps fired in the current episode (0 = none)
private DateTime _stallRef = DateTime.MinValue; // last swing (or episode start) before the stall
/// <summary>Episodes where the watchdog acted (diagnostics / status).</summary>
public int Episodes { get; private set; }
/// <summary>Episodes that ended with swings resuming after a step.</summary>
public int Recoveries { get; private set; }
/// <summary>The last step fired in the current episode (0 = none).</summary>
public int CurrentStep => _step;
public static int StepCount => 4;
/// <summary>
/// Advance the watchdog. <paramref name="eligible"/> is the full precondition set;
/// <paramref name="lastEvidenceAt"/> the last hit, miss or kill. Returns the step to
/// carry out now (or Recovered / GaveUp for logging), with the stalled time.
/// </summary>
public StallAction Tick(DateTime now, bool eligible, DateTime lastEvidenceAt, out double stalledMs)
{
stalledMs = 0;
bool gap = _lastTick != DateTime.MinValue
&& (now - _lastTick).TotalMilliseconds > TickGapResetMs;
_lastTick = now;
if (!eligible || gap)
{
ResetEpisode();
if (!eligible) return StallAction.None;
}
if (_eligibleSince == DateTime.MinValue)
_eligibleSince = now;
DateTime refAt = lastEvidenceAt > _eligibleSince ? lastEvidenceAt : _eligibleSince;
stalledMs = (now - refAt).TotalMilliseconds;
// Swings came back after a step: the episode is over.
if (_step > 0 && lastEvidenceAt > _lastStepAt)
{
stalledMs = (lastEvidenceAt - _stallRef).TotalMilliseconds;
Recoveries++;
ResetEpisode();
_eligibleSince = now;
return StallAction.Recovered;
}
if (now < _cooldownUntil)
return StallAction.None;
if (_step == 0)
{
if (stalledMs < StallMs) return StallAction.None;
Episodes++;
_stallRef = refAt;
return Fire(now);
}
if ((now - _lastStepAt).TotalMilliseconds < StepMs)
return StallAction.None;
if (_step >= StepCount)
{
_cooldownUntil = now.AddMilliseconds(CooldownMs);
ResetEpisode();
_eligibleSince = now;
return StallAction.GaveUp;
}
return Fire(now);
}
/// <summary>Keep the episode alive through ticks where combat holds on purpose for a
/// step still settling (the step-4 re-wield), so the hold isn't read as a tick gap.</summary>
public void Hold(DateTime now) => _lastTick = now;
private StallAction Fire(DateTime now)
{
_step++;
_lastStepAt = now;
return _step switch
{
1 => StallAction.Reissue,
2 => StallAction.Reselect,
3 => StallAction.ToggleMode,
_ => StallAction.Rewield,
};
}
private void ResetEpisode()
{
_eligibleSince = DateTime.MinValue;
_lastStepAt = DateTime.MinValue;
_step = 0;
}
}

View file

@ -77,6 +77,26 @@ internal static class ComponentDatabase
private static readonly Dictionary<int, uint[]> _spellComps = new();
private static bool _spellCompsLoaded;
// spellId → (MagicSchool, Power) from the same SpellTable pass. The server's own
// values (ACE's Spell.School / Spell.Power read the dat's SpellBase), so learning a
// scroll is judged with the numbers the server uses. Tests set entries directly.
private static readonly Dictionary<int, (int School, int Power)> _spellMeta = new();
internal static readonly Dictionary<int, (int School, int Power)> SpellMetaOverride = new();
/// <summary>
/// A spell's magic school (ACE MagicSchool: War 1, Life 2, Item 3, Creature 4, Void 5)
/// and power (difficulty) from the portal.dat SpellTable. False when the dat couldn't be
/// read or the spell isn't in it.
/// </summary>
public static bool TryGetSpellSchoolAndPower(int spellId, out int school, out int power)
{
if (SpellMetaOverride.TryGetValue(spellId, out var o)) { school = o.School; power = o.Power; return true; }
if (SpellMetaOverride.Count == 0) EnsureLoaded();
if (_spellMeta.TryGetValue(spellId, out var m)) { school = m.School; power = m.Power; return true; }
school = 0; power = 0;
return false;
}
private static bool _loaded;
private static readonly object _lock = new();
private static Action<string>? _log;
@ -319,26 +339,27 @@ internal static class ComponentDatabase
{
if (r.BaseStream.Position + 4 > raw.Length) break;
uint spellId = r.ReadUInt32();
uint[] comps = ReadSpellBaseFormula(r);
uint[] comps = ReadSpellBaseFormula(r, out uint school, out uint power);
_spellComps[(int)spellId] = comps;
_spellMeta[(int)spellId] = ((int)school, (int)power);
n++;
}
return n;
}
private static uint[] ReadSpellBaseFormula(BinaryReader r)
private static uint[] ReadSpellBaseFormula(BinaryReader r, out uint school, out uint power)
{
byte[] nameB = ReadObf(r); Align(r);
byte[] descB = ReadObf(r); Align(r);
r.ReadUInt32(); // School
school = r.ReadUInt32(); // School (MagicSchool: War 1, Life 2, Item 3, Creature 4, Void 5)
r.ReadUInt32(); // Icon
r.ReadUInt32(); // Category
r.ReadUInt32(); // Bitfield
r.ReadUInt32(); // BaseMana
r.ReadSingle(); // BaseRangeConstant
r.ReadSingle(); // BaseRangeMod
r.ReadUInt32(); // Power
power = r.ReadUInt32(); // Power (the spell's difficulty; ACE's scroll rule reads it)
r.ReadSingle(); // SpellEconomyMod
r.ReadUInt32(); // FormulaVersion
r.ReadSingle(); // ComponentLoss

View file

@ -102,7 +102,9 @@ public class FellowshipTracker : IDisposable
private const int OFF_ENTRY_LEVEL = 0x0C;
private const int OFF_ENTRY_NEXT = 0x34;
private Dictionary<int, string> _memberCache = new();
// Replaced whole on each refresh, never changed in place: the radar snapshot (engine pump
// thread) reads it while RynthAi's own thread may be refreshing it.
private volatile Dictionary<int, string> _memberCache = new();
private DateTime _lastRefresh = DateTime.MinValue;
private const double REFRESH_INTERVAL_MS = 2000;
@ -278,7 +280,7 @@ public class FellowshipTracker : IDisposable
{
if ((DateTime.Now - _lastRefresh).TotalMilliseconds < REFRESH_INTERVAL_MS) return;
_lastRefresh = DateTime.Now;
_memberCache.Clear();
var members = new Dictionary<int, string>();
try
{
IntPtr fel = GetFellowshipPtr();
@ -329,12 +331,13 @@ public class FellowshipTracker : IDisposable
int memberId = Marshal.ReadInt32(keyAddr);
string name = ReadPString(nameFieldAddr);
if (memberId != 0 && !string.IsNullOrEmpty(name))
{ _memberCache[memberId] = name; found++; }
{ members[memberId] = name; found++; }
entryPtr = Marshal.ReadInt32(nextAddr);
}
}
}
catch { }
finally { _memberCache = members; } // also on the early returns (no fellowship: empty)
}
private string ReadPString(IntPtr addr)

View file

@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
/// <summary>One stack of arrows, quarrels or darts the character carries.</summary>
/// <param name="AmmoType">AC AmmoType (int 50): 1 arrow, 2 quarrel, 4 dart; 0 = not known.</param>
/// <param name="Element">Normalized element ("" = none known).</param>
/// <param name="Prismatic">Takes the launcher's element (DamageType Base, or named Prismatic).</param>
/// <param name="Quality">AmmoRecipes rank: Deadly beats Greater beats plain; 1 for ammo no recipe makes.</param>
/// <param name="ListIndex">Position in the Items list; -1 = not listed.</param>
/// <param name="Wielded">In the ammunition slot now.</param>
internal sealed record AmmoCandidate(int Id, string Name, int AmmoType, string Element, bool Prismatic,
int Quality, int ListIndex, bool Wielded)
{
public bool Listed => ListIndex >= 0;
}
/// <summary>
/// Which ammo a missile launcher shoots, and which stack to put in the ammunition slot. Pure: no
/// host. The rules are ACE's (Player_Inventory.CheckWeaponCollision, DamageEvent.GetBaseDamage):
/// * A launcher and its ammo carry AmmoType (int 50, in CreateObject): Arrow 1, Bolt 2, Atlatl 4,
/// and crystal / chorizite variants. The server refuses to wield a launcher while ammo of
/// another type is in the ammunition slot (0x00800000), and refuses ammo that doesn't match
/// the launcher in hand. So a bow-to-crossbow swap must take the arrows off first.
/// * Thrown weapons (stackable, in the missile-weapon slot) are their own ammo: no AmmoType rule.
/// * A launcher's missile damage takes the AMMO's element. Prismatic ammo (DamageType Base)
/// takes the launcher's element instead (Pierce when the launcher has none).
/// </summary>
internal static class MissileAmmo
{
public const uint PropValidLocations = 9, PropMaxStackSize = 11, PropStackSize = 12, PropAmmoType = 50;
public const int AmmoSlot = 0x00800000, MissileWeaponSlot = 0x00400000;
public const int Arrow = 0x1, Bolt = 0x2, Atlatl = 0x4;
/// <summary>DamageType Base: prismatic ammo, the launcher decides the element.</summary>
public const int DamageTypeBase = 0x10000000;
/// <summary>
/// The ammo type a launcher needs: AmmoType when known, else the name (crossbow, atlatl,
/// bow). 0 = needs none (a thrown weapon) or not known: ammo is then left alone, as before.
/// </summary>
public static int LauncherAmmoType(int ammoTypeProp, string? name, bool stackable)
{
if (stackable) return 0; // thrown: its own ammo
if (ammoTypeProp > 0) return ammoTypeProp;
string n = name ?? "";
if (n.IndexOf("crossbow", StringComparison.OrdinalIgnoreCase) >= 0) return Bolt;
if (n.IndexOf("atlatl", StringComparison.OrdinalIgnoreCase) >= 0) return Atlatl;
if (n.IndexOf("bow", StringComparison.OrdinalIgnoreCase) >= 0) return Arrow;
return 0;
}
/// <summary>A stack's ammo type: AmmoType when known, else the name (arrow, quarrel/bolt, dart). 0 = not ammo we know.</summary>
public static int AmmoTypeOf(int ammoTypeProp, string? name)
{
if (ammoTypeProp > 0) return ammoTypeProp;
string n = name ?? "";
if (AmmoRecipes.IsLooseAmmoName(n, WeaponCategory.Crossbow)) return Bolt; // before "arrow": no clash, but quarrels first
if (AmmoRecipes.IsLooseAmmoName(n, WeaponCategory.Atlatl)) return Atlatl;
if (AmmoRecipes.IsLooseAmmoName(n, WeaponCategory.Bow)) return Arrow;
return 0;
}
/// <summary>The fletching category of an ammo type (for the quality rank and labels).</summary>
public static WeaponCategory CategoryOf(int ammoType)
{
if ((ammoType & (0x2 | 0x10 | 0x80)) != 0) return WeaponCategory.Crossbow;
if ((ammoType & (0x4 | 0x20 | 0x100)) != 0) return WeaponCategory.Atlatl;
return WeaponCategory.Bow;
}
/// <summary>"arrows", "quarrels", "darts".</summary>
public static string Label(int ammoType) => CategoryOf(ammoType) switch
{
WeaponCategory.Crossbow => "quarrels",
WeaponCategory.Atlatl => "darts",
_ => "arrows",
};
/// <summary>The server's rule: the types must be equal (a crystal arrow is not an arrow).</summary>
public static bool Fits(int launcherType, int ammoType) => launcherType != 0 && ammoType == launcherType;
/// <summary>Prismatic: DamageType has the Base bit, or the name says so.</summary>
public static bool IsPrismatic(int? damageType, string? name) =>
(damageType is int dt && (dt & DamageTypeBase) != 0)
|| (name ?? "").IndexOf("Prismatic", StringComparison.OrdinalIgnoreCase) >= 0;
/// <summary>
/// The element the launcher does with this ammo: prismatic takes the launcher's (Pierce
/// when it has none); other ammo its own ("" when not known).
/// </summary>
public static string EffectiveElement(AmmoCandidate ammo, string launcherElement)
{
if (ammo.Prismatic) return launcherElement.Length > 0 ? launcherElement : "Pierce";
return ammo.Element;
}
/// <summary>
/// The stack to wield in <paramref name="launcherType"/>'s launcher, null when the pack has
/// none that fits. Order:
/// 1. listed ammo (the Items list) before anything else;
/// 2. the element: <paramref name="elementRank"/> (lower = better) of the element the
/// launcher would do with it; ammo of no known element counts as Pierce;
/// 3. quality (Deadly > Greater > plain), then the stack already wielded, then list / pack order.
/// </summary>
public static AmmoCandidate? Choose(int launcherType, string launcherElement, IReadOnlyList<AmmoCandidate> pack,
Func<string, int> elementRank)
{
AmmoCandidate? best = null;
(int, int, int, int, int) bestKey = default;
for (int i = 0; i < pack.Count; i++)
{
var a = pack[i];
if (!Fits(launcherType, a.AmmoType)) continue;
string e = EffectiveElement(a, launcherElement);
var key = (a.Listed ? 0 : 1,
elementRank(e.Length > 0 ? e : "Pierce"),
-a.Quality,
a.Wielded ? 0 : 1,
a.Listed ? a.ListIndex : 100000 + i);
if (best == null || key.CompareTo(bestKey) < 0) { best = a; bestKey = key; }
}
return best;
}
/// <summary>
/// An element ranking for <see cref="Choose"/>: the Monsters rule's damage type first (when
/// set), then the weakness tie groups from weakest; anything else after. With neither, all equal.
/// </summary>
public static Func<string, int> RankBy(string ruleElement, IReadOnlyList<List<string>>? weakGroups)
{
return e =>
{
if (ruleElement.Length > 0 && e == ruleElement) return 0;
if (weakGroups != null)
for (int g = 0; g < weakGroups.Count; g++)
if (weakGroups[g].Contains(e)) return 1 + g;
return 1000;
};
}
}

View file

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using RynthCore.PluginSdk;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
@ -30,6 +31,12 @@ public class MissileCraftingManager
_host.HasGetCurrentCombatMode ? _host.GetCurrentCombatMode() : CombatMode.NonCombat;
public void SetObjectCache(WorldObjectCache cache) => _objectCache = cache;
/// <summary>
/// While this says true, no new ammo check starts: combat is swapping launchers and wields
/// the new launcher's ammo itself (CombatManager.AmmoSwapInProgress). Without it, crafting
/// could equip ammo for the launcher being swapped away from, or start a craft mid-swap.
/// </summary>
public Func<bool>? HoldWhile { get; set; }
public void SetCharacterSkills(CharacterSkills skills) => _charSkills = skills;
public enum CraftState { Idle, Evaluating, Combining, EquippingAmmo }
@ -134,6 +141,7 @@ public class MissileCraftingManager
private void ProcessIdle()
{
if ((DateTime.Now - _lastAmmoCheck).TotalMilliseconds < AMMO_CHECK_INTERVAL_MS) return;
if (HoldWhile?.Invoke() == true) return;
_lastAmmoCheck = DateTime.Now;
var inv = GetInventory(forceRefresh: true);
@ -279,7 +287,7 @@ public class MissileCraftingManager
{
try
{
if (!_host.UseObjectOn((uint)_headBundleId, (uint)_shaftBundleId))
if (!_host.UseOnFor((uint)_headBundleId, (uint)_shaftBundleId, "Crafting", "missile crafting: heads on shafts"))
{
ChatLog($"UseObjectOn returned false for 0x{_headBundleId:X8} -> 0x{_shaftBundleId:X8}");
_lastApplyAttempt = DateTime.Now;
@ -318,7 +326,7 @@ public class MissileCraftingManager
if (targetId != 0)
{
_host.UseObject((uint)targetId);
_host.UseFor((uint)targetId, "Crafting", "missile crafting: wield the new ammo");
ChatLog($"Equipped ammo (id=0x{targetId:X8})");
Reset($"Done: {_currentRecipe?.OutputName ?? "ammo"}");
}

View file

@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Bounded per-object diagnostics for <see cref="WorldObjectCache"/> ([ClassifyTrace] and
/// [ReclassifyDiag]). Each kind of event keeps a few full detail lines per session; after that
/// it is only counted, and <see cref="Flush"/> writes one summary line per prefix (counts, the
/// sub-flags the old detail lines carried, a few sample ids) on the cache's 2 s cadence.
///
/// Why (2026-10-02, Matron Hive South copy): the old lines were one per object per attempt
/// with caps of 200-5000 each, and every engine log line is a synchronous open-append-close of
/// the log file on the plugin thread (~350 us). A flood of 1000 creates and 585 deletes wrote
/// ~950 lines, a third of a second of the plugin tick, exactly when the tick was busiest.
///
/// Not thread-safe: the cache calls it under its own _gate.
/// </summary>
internal sealed class ObjectDiagLog
{
private const int MaxSamples = 6;
private sealed class Kind
{
public required string Name;
public required string Prefix;
public required string[] FlagNames;
public int DetailLeft;
public int Count;
public readonly int[] Flags = new int[4];
public readonly uint[] Samples = new uint[MaxSamples];
public int SampleCount;
public long Total;
}
private readonly Action<string> _log;
private readonly Dictionary<string, Kind> _kinds = new(StringComparer.Ordinal);
private readonly List<Kind> _order = new();
public ObjectDiagLog(Action<string> log) => _log = log;
/// <summary>Lines written by <see cref="Flush"/> so far (tests).</summary>
public int SummaryLines { get; private set; }
/// <summary>Declares a kind: its log prefix, how many full detail lines a session may write,
/// and up to four sub-flags counted per event (e.g. "seenCreate").</summary>
public void Define(string name, string prefix, int detailLines, params string[] flagNames)
{
var k = new Kind { Name = name, Prefix = prefix, FlagNames = flagNames, DetailLeft = detailLines };
_kinds[name] = k;
_order.Add(k);
}
/// <summary>
/// Counts one event of <paramref name="kind"/> for <paramref name="id"/>; bit i of
/// <paramref name="flags"/> counts the kind's i-th sub-flag. True while the kind still has
/// detail lines left: the caller then writes its full line (the summary counts it too).
/// </summary>
public bool Note(string kind, uint id, int flags = 0)
{
if (!_kinds.TryGetValue(kind, out Kind? k))
return false;
k.Count++;
k.Total++;
for (int i = 0; i < k.FlagNames.Length && i < k.Flags.Length; i++)
if ((flags & (1 << i)) != 0) k.Flags[i]++;
if (k.SampleCount < MaxSamples)
k.Samples[k.SampleCount++] = id;
if (k.DetailLeft > 0)
{
k.DetailLeft--;
return true;
}
return false;
}
/// <summary>Events of <paramref name="kind"/> since the session started.</summary>
public long Total(string kind) => _kinds.TryGetValue(kind, out Kind? k) ? k.Total : 0;
/// <summary>
/// Writes one line per prefix covering every kind counted since the last flush, e.g.
/// "[ReclassifyDiag] last 2 s: DELETE-BEFORE-CLASSIFY 585 (seenCreate 12) e.g. 0x8000CC23 ...".
/// Writes nothing when nothing happened.
/// </summary>
public void Flush(string window)
{
StringBuilder? sb = null;
string? prefix = null;
foreach (Kind k in _order)
{
if (k.Count == 0) continue;
if (prefix != k.Prefix)
{
if (sb != null) Emit(sb);
prefix = k.Prefix;
sb = new StringBuilder(160).Append(k.Prefix).Append(" last ").Append(window).Append(':');
}
else
{
sb!.Append(';');
}
sb!.Append(' ').Append(k.Name).Append(' ').Append(k.Count);
bool any = false;
for (int i = 0; i < k.FlagNames.Length && i < k.Flags.Length; i++)
{
sb.Append(any ? ", " : " (").Append(k.FlagNames[i]).Append(' ').Append(k.Flags[i]);
any = true;
}
if (any) sb.Append(')');
sb.Append(" e.g.");
for (int i = 0; i < k.SampleCount; i++)
sb.Append(" 0x").Append(k.Samples[i].ToString("X8"));
if (k.Count > k.SampleCount) sb.Append(" ...");
k.Count = 0;
k.SampleCount = 0;
Array.Clear(k.Flags);
}
if (sb != null) Emit(sb);
}
private void Emit(StringBuilder sb)
{
SummaryLines++;
_log(sb.ToString());
}
}

View file

@ -0,0 +1,210 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
/// <summary>What combat puts in the off hand (the Shield slot).</summary>
internal enum OffhandMode
{
/// <summary>A listed shield with a one-handed melee or thrown weapon; dual wield instead only
/// when "Prefer dual wield" is on and the character has the skill.</summary>
Auto,
/// <summary>A listed shield, or nothing.</summary>
Shield,
/// <summary>A second listed one-handed melee weapon (dual wield), else a listed shield.</summary>
Weapon,
/// <summary>Hands off: never wield, never take off, whatever is there.</summary>
None,
}
/// <summary>What the main hand holds, by ACE's wield rules.</summary>
internal enum MainHandKind { None, OneHandedMelee, TwoHanded, Launcher, Thrown, Caster }
/// <summary>A listed item that can go in the off hand: a shield, or a one-handed melee weapon.</summary>
internal sealed record OffhandCandidate(int Id, string Name, bool IsShield, bool InOffhand);
/// <summary>The off hand to wield (0 = add nothing; what is there stays) and why.</summary>
internal readonly record struct OffhandPlan(int Id, string Source);
/// <summary>
/// ACE's off-hand rules (ACE.Server WorldObjects/Player_Inventory.cs: CheckWeaponCollision and
/// DoHandleActionGetAndWieldItem; Creature_Equipment.cs), pure:
/// * The off hand is the Shield slot, 0x00200000. A shield (CombatUse 4) goes there; so does
/// an off-hand weapon (dual wield) whose ValidLocations is exactly MeleeWeapon (0x00100000).
/// * The Shield slot is refused while it is occupied, and while the main hand holds a
/// two-handed weapon (WeaponSkill TwoHandedCombat), a caster or an ammo launcher.
/// * A weapon in the Shield slot (dual wield) also needs a one-handed melee main weapon: a
/// thrown weapon, a launcher, a wand or a two-hander there is refused (ConflictingInventoryLocation).
/// * Two-handed weapons (TwoHanded slot), launchers and casters (Held slot) are refused while
/// anything is in the off hand. A thrown weapon is refused with an off-hand weapon, but a
/// shield may stay ("Thrown weapons (ie. phials) can have a shield").
/// * The server does not ask for the Dual Wield skill; off-hand swings use the lower of Dual
/// Wield and the weapon skill (Player_Combat.GetCurrentWeaponSkill), so RynthAi only dual
/// wields with the skill trained.
/// </summary>
internal static class OffhandRules
{
public const int ShieldSlot = 0x00200000, MeleeSlot = 0x00100000, MissileSlot = 0x00400000,
HeldSlot = 0x01000000, TwoHandedSlot = 0x02000000;
public const uint PropValidLocations = 9, PropCurrentWieldedLocation = 10, PropWeaponSkill = 48, PropCombatUse = 51;
public const int CombatUseShield = 4, CombatUseTwoHanded = 5;
public const int SkillTwoHandedCombat = 41;
// MonsterRule.OffhandId: 0 = the Default row's choice (on the Default row: the global setting), 1-4 a mode, anything else an item id (no AC
// object has an id of 1-4). The engine and the external editor carry the int as it is.
public const int RuleDefault = 0, RuleAuto = 1, RuleShield = 2, RuleWeapon = 3, RuleNone = 4;
/// <summary>A shield: CombatUse Shield, or a non-weapon whose ValidLocations has the Shield slot.</summary>
public static bool IsShield(int combatUse, int validLocations, bool weaponClass) =>
combatUse == CombatUseShield || (!weaponClass && (validLocations & ShieldSlot) != 0);
/// <summary>Two-handed: CombatUse TwoHanded, the TwoHanded slot, or WeaponSkill Two Handed Combat.</summary>
public static bool IsTwoHanded(int combatUse, int validLocations, int weaponSkill) =>
combatUse == CombatUseTwoHanded || (validLocations & TwoHandedSlot) != 0 || weaponSkill == SkillTwoHandedCombat;
/// <summary>A melee weapon the server lets into the Shield slot: ValidLocations exactly MeleeWeapon, not two-handed.</summary>
public static bool CanBeOffhandWeapon(int validLocations, bool twoHanded) =>
validLocations == MeleeSlot && !twoHanded;
/// <summary>May the off hand (a shield, else a weapon) stay with this main hand?</summary>
public static bool OffhandAllowed(MainHandKind main, bool offIsShield) => main switch
{
MainHandKind.None => true,
MainHandKind.OneHandedMelee => true,
MainHandKind.Thrown => offIsShield,
_ => false,
};
/// <summary>The mode a MonsterRule.OffhandId encodes; null for 0 (the global setting) or an item id.</summary>
public static OffhandMode? RuleMode(int offhandId) => offhandId switch
{
RuleAuto => OffhandMode.Auto,
RuleShield => OffhandMode.Shield,
RuleWeapon => OffhandMode.Weapon,
RuleNone => OffhandMode.None,
_ => null,
};
/// <summary>MonsterRule.OffhandId names an item (the old per-rule picker).</summary>
public static bool IsRuleItem(int offhandId) => offhandId != RuleDefault && RuleMode(offhandId) == null;
public static int RuleValue(OffhandMode m) => m switch
{
OffhandMode.Shield => RuleShield,
OffhandMode.Weapon => RuleWeapon,
OffhandMode.None => RuleNone,
_ => RuleAuto,
};
/// <summary>"Auto", "Shield", "Weapon" ("Offhand weapon", "Dual", "DualWield"), "None"; or 0-3. Else <paramref name="fallback"/>.</summary>
public static OffhandMode Parse(string? s, OffhandMode fallback)
{
if (string.IsNullOrWhiteSpace(s)) return fallback;
string t = s.Trim().Replace(" ", "").Replace("-", "");
if (t.Equals("auto", StringComparison.OrdinalIgnoreCase) || t == "0") return OffhandMode.Auto;
if (t.Equals("shield", StringComparison.OrdinalIgnoreCase) || t == "1") return OffhandMode.Shield;
if (t.Equals("weapon", StringComparison.OrdinalIgnoreCase) || t.Equals("offhandweapon", StringComparison.OrdinalIgnoreCase)
|| t.Equals("offhand", StringComparison.OrdinalIgnoreCase) || t.Equals("dual", StringComparison.OrdinalIgnoreCase)
|| t.Equals("dualwield", StringComparison.OrdinalIgnoreCase) || t == "2") return OffhandMode.Weapon;
if (t.Equals("none", StringComparison.OrdinalIgnoreCase) || t.Equals("off", StringComparison.OrdinalIgnoreCase) || t == "3") return OffhandMode.None;
return fallback;
}
public static bool TryParse(string? s, out OffhandMode mode)
{
mode = Parse(s, (OffhandMode)(-1));
return (int)mode >= 0;
}
/// <summary>The spelling saved in LegacyUiSettings.OffhandDefault.</summary>
public static string SettingValue(OffhandMode m) => m switch
{
OffhandMode.Shield => "Shield",
OffhandMode.Weapon => "Weapon",
OffhandMode.None => "None",
_ => "Auto",
};
public static string Label(OffhandMode m) => m switch
{
OffhandMode.Shield => "Shield",
OffhandMode.Weapon => "Offhand weapon",
OffhandMode.None => "None",
_ => "Auto",
};
public static string KindLabel(MainHandKind k) => k switch
{
MainHandKind.OneHandedMelee => "one-handed",
MainHandKind.TwoHanded => "two-handed",
MainHandKind.Launcher => "launcher",
MainHandKind.Thrown => "thrown weapon",
MainHandKind.Caster => "caster",
_ => "empty hand",
};
}
/// <summary>
/// The off hand for a main weapon, pure. After the main weapon is chosen:
/// * None: nothing (what is in the off hand stays).
/// * Anything but a one-handed melee weapon in the main hand: nothing to add (a two-hander,
/// launcher or caster can't have one; for a thrown weapon ACE allows a shield, but RynthAi
/// adds none).
/// * An explicit item (the Damage tab's per-monster offhand, else the rule's old item pick):
/// used when it is listed and allowed (a weapon needs the Dual Wield skill and the
/// slot-wield call), else the mode decides.
/// * Shield: the best listed shield. Weapon: a second listed one-handed melee weapon when
/// the Dual Wield skill is trained, else the best shield. Auto: the best shield; a second
/// listed one-handed weapon instead only when <paramref name="preferDualWield"/> is on and
/// dual wield is possible. A thrown weapon gets a shield too (never a second weapon).
/// "Best": the listed one already in the off hand, else list order. Only listed items count.
/// </summary>
internal static class OffhandPlanner
{
public static OffhandPlan Choose(OffhandMode mode, MainHandKind main, int mainId,
IReadOnlyList<OffhandCandidate> listed, bool dualWieldTrained, bool preferDualWield, bool canWieldOffhandWeapon,
int explicitId = 0, string explicitSource = "")
{
if (mode == OffhandMode.None) return new OffhandPlan(0, "Offhand None");
// A shield goes with a one-handed melee weapon, and with a thrown weapon too (ACE
// allows it; owner, 2026-10-01). Dual wield only with a one-handed melee weapon.
if (main != MainHandKind.OneHandedMelee && main != MainHandKind.Thrown)
return new OffhandPlan(0, $"nothing with a {OffhandRules.KindLabel(main)}");
bool dualOk = dualWieldTrained && canWieldOffhandWeapon && main == MainHandKind.OneHandedMelee;
OffhandCandidate? shield = null, weapon = null;
foreach (var c in listed)
{
if (c.Id == 0 || c.Id == mainId) continue;
if (c.IsShield) { if (shield == null || (c.InOffhand && !shield.InOffhand)) shield = c; }
else if (weapon == null || (c.InOffhand && !weapon.InOffhand)) weapon = c;
}
if (explicitId != 0 && explicitId != mainId)
{
foreach (var c in listed)
{
if (c.Id != explicitId) continue;
if (c.IsShield || dualOk) return new OffhandPlan(c.Id, explicitSource);
break;
}
}
string why = dualWieldTrained ? "can't wield into the off hand on this engine" : "Dual Wield not trained";
switch (mode)
{
case OffhandMode.Shield:
return shield != null ? new OffhandPlan(shield.Id, "Shield") : new OffhandPlan(0, "Shield: none listed");
case OffhandMode.Weapon:
if (dualOk && weapon != null) return new OffhandPlan(weapon.Id, "Offhand weapon");
if (shield != null) return new OffhandPlan(shield.Id, weapon == null ? "Offhand weapon: no second one-handed weapon listed; shield" : $"Offhand weapon: {why}; shield");
return new OffhandPlan(0, weapon == null ? "Offhand weapon: no second one-handed weapon listed" : $"Offhand weapon: {why}");
default:
// Auto is the shield; dual wield only with "Prefer dual wield" on (owner,
// 2026-10-01), so two swords listed for element switching don't start dual wielding.
if (dualOk && weapon != null && preferDualWield)
return new OffhandPlan(weapon.Id, "Auto (dual wield preferred)");
return shield != null ? new OffhandPlan(shield.Id, "Auto") : new OffhandPlan(0, "Auto: no shield listed");
}
}
}

View file

@ -0,0 +1,136 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.CreatureData;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Which combat pet to summon for a monster. The Damage panel stores a choice per
/// monster (wcid): Auto (""), an element ("E:Cold"), or a specific essence
/// ("I:&lt;id&gt;"). Auto picks an element from, in order: the Monsters-tab rule
/// (Pet damage, else damage type), the monster's learned resists, then the
/// element that has done best on it in the Damage tab; with none of those the
/// Items-panel order is kept. Combat pets can't be swapped while one is out
/// (ACE: "already active"), so the choice is made at each summon.
/// </summary>
internal static class PetChoice
{
/// <summary>Elements a pet can deal, in the order the Damage panel lists them.</summary>
public static readonly string[] Elements =
{ "Fire", "Cold", "Lightning", "Acid", "Nether", "Slash", "Pierce", "Bludgeon" };
/// <summary>
/// A summoning essence's element. From UiEffects (int 18), which essences carry
/// in their public data (Fire K'nath 32, Frost 128, Acid 256 ...), else from
/// words in the name. "" if unknown.
/// </summary>
public static string ElementOf(RynthCoreHost host, uint deviceId, string name)
{
if (host.HasGetObjectIntProperty && host.TryGetObjectIntProperty(deviceId, 18, out int fx) && fx != 0)
{
if ((fx & 0x0020) != 0) return "Fire";
if ((fx & 0x0040) != 0) return "Lightning";
if ((fx & 0x0080) != 0) return "Cold";
if ((fx & 0x0100) != 0) return "Acid";
if ((fx & 0x1000) != 0) return "Nether";
if ((fx & 0x0200) != 0) return "Bludgeon";
if ((fx & 0x0400) != 0) return "Slash";
if ((fx & 0x0800) != 0) return "Pierce";
}
return ElementFromName(name);
}
public static string ElementFromName(string name)
{
if (string.IsNullOrEmpty(name)) return "";
static bool Has(string n, params string[] words)
=> words.Any(w => n.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0);
if (Has(name, "Fire", "Flame", "Blaz", "Burn", "Scorch", "Charred", "Inferno", "Magma", "Incendiary")) return "Fire";
if (Has(name, "Frost", "Blizzard", "Arctic", "Ice", "Frozen", "Glacial", "Cold")) return "Cold";
if (Has(name, "Lightning", "Electric", "Storm", "Spark", "Shock", "Thunder", "Voltaic")) return "Lightning";
if (Has(name, "Acid", "Caustic", "Corros", "Blister", "Toxic")) return "Acid";
if (Has(name, "Nether", "Void", "Shadow")) return "Nether";
if (Has(name, "Golem")) return "Bludgeon"; // golem essences carry no UiEffects; all bludgeon
return "";
}
/// <summary>Normalises element names from rules and the Damage tab ("Electric" → "Lightning").</summary>
public static string NormalizeElement(string? e)
{
if (string.IsNullOrWhiteSpace(e)) return "";
string t = e.Trim();
if (t.StartsWith("P", StringComparison.Ordinal) && t.Equals("PAuto", StringComparison.OrdinalIgnoreCase)) return "";
if (t.Equals("Auto", StringComparison.OrdinalIgnoreCase)) return "";
if (t.Equals("Electric", StringComparison.OrdinalIgnoreCase)) return "Lightning";
foreach (string x in Elements)
if (x.Equals(t, StringComparison.OrdinalIgnoreCase)) return x;
return "";
}
/// <summary>
/// Orders <paramref name="devices"/> (id, name) for summoning against a monster:
/// the chosen essence first, or the chosen element's essences first, or (Auto) the
/// element the monster takes most damage from. Stable, so ties keep the Items-panel order.
/// </summary>
public static List<(int Id, string Name, string Element)> Order(
RynthCoreHost host, IEnumerable<(int Id, string Name)> devices, string choice,
CreatureData.CreatureWeakness.Ranking? weakness, out string reason, string ruleElement = "")
{
var list = devices.Select(d => (d.Id, d.Name, Element: ElementOf(host, unchecked((uint)d.Id), d.Name))).ToList();
choice ??= "";
if (choice.StartsWith("I:", StringComparison.Ordinal)
&& int.TryParse(choice.AsSpan(2), out int wantId))
{
// Same essence by id, or (after it was replaced) by the name it had.
int idx = list.FindIndex(d => d.Id == wantId);
reason = idx >= 0 ? $"picked {list[idx].Name}" : "picked essence not in pack, using Auto";
if (idx >= 0)
{
var pick = list[idx];
list.RemoveAt(idx);
list.Insert(0, pick);
return list;
}
choice = "";
}
if (choice.StartsWith("E:", StringComparison.Ordinal))
{
string want = choice.Substring(2);
var ordered = list.OrderBy(d => d.Element.Equals(want, StringComparison.OrdinalIgnoreCase) ? 0 : 1).ToList();
reason = ordered.Count > 0 && ordered[0].Element.Equals(want, StringComparison.OrdinalIgnoreCase)
? $"{want} chosen" : $"{want} chosen, but no {want} essence; using the first";
return ordered;
}
// Auto. 1) the Monsters-tab rule's pet damage / damage type for this monster;
// 2) the owned element the monster takes most damage from: server data, else
// what the Damage tab learned, else its creature type (CreatureWeakness). The
// old step read resists ACE never sends and took the lowest, the element the
// monster resists most (2026-09-29). Without any of these the Items order stands.
var have = new HashSet<string>(list.Where(d => d.Element.Length > 0).Select(d => d.Element), StringComparer.OrdinalIgnoreCase);
string autoElem = "";
string why = "";
string re = NormalizeElement(ruleElement);
if (re.Length > 0 && have.Contains(re)) { autoElem = re; why = "Monsters rule"; }
if (autoElem.Length == 0 && weakness != null)
foreach (var (elem, mult) in weakness.Order)
{
if (!have.Contains(elem)) continue;
autoElem = elem;
why = double.IsNaN(mult) ? weakness.Source : $"{weakness.Source}, takes {mult:0.0#}x";
break;
}
if (autoElem.Length == 0)
{
reason = "Auto: no element data for this monster, using Items order";
return list;
}
reason = $"Auto: {autoElem} ({why})";
return list.OrderBy(d => d.Element.Equals(autoElem, StringComparison.OrdinalIgnoreCase) ? 0 : 1).ToList();
}
}

View file

@ -3,6 +3,7 @@ using System.Collections.Generic;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
@ -42,6 +43,9 @@ internal sealed class PetManager
private PetState _state = PetState.Idle;
private int _activeDeviceId;
private string _summonElement = ""; // element of the essence last summoned from
private long _petOutCheckedAt; // CurrentSummon's landscape scan, at most once a second
private bool _petOutCached;
private int _activeSpiritId;
private int _preActionCharges = -1; // device charges read just before issuing a summon (-1 = unreadable)
private long _actionIssuedAt;
@ -98,6 +102,8 @@ internal sealed class PetManager
// or the summoned creature is now visible in the cache.
if (SummonLanded() || IsPetActive())
{
_summonElement = PetChoice.ElementOf(_host, unchecked((uint)_activeDeviceId),
_objectCache[_activeDeviceId]?.Name ?? "");
_assumePetActiveUntil = now + AssumeActiveAfterSummonMs;
GoIdle();
}
@ -187,8 +193,10 @@ internal sealed class PetManager
if (!_host.HasUseObject) return;
// Use the first usable configured essence (panel order).
foreach (int deviceId in EnumeratePetDevices())
// Best essence for the monster being fought first (Damage panel pet choice:
// a specific essence, an element, or Auto = lowest learned resist), then the
// rest in Items-panel order as fallbacks.
foreach (int deviceId in OrderDevicesForTarget(EnumeratePetDevices()))
{
if (_deviceCooldownUntil.TryGetValue(deviceId, out long until) && now < until)
continue;
@ -232,7 +240,7 @@ internal sealed class PetManager
_preActionCharges = charges;
_actionIssuedAt = NowMs;
_host.Log($"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}).");
_host.UseObject(unchecked((uint)deviceId));
_host.UseFor(unchecked((uint)deviceId), "Pet", "summon a pet from the essence");
}
private void IssueRefill(int deviceId, int spiritId)
@ -244,7 +252,7 @@ internal sealed class PetManager
_activeSpiritId = spiritId;
_actionIssuedAt = NowMs;
_host.Log($"[RynthAi] Pet: refilling essence 0x{(uint)deviceId:X8} with spirit 0x{(uint)spiritId:X8}.");
_host.UseObjectOn(unchecked((uint)spiritId), unchecked((uint)deviceId));
_host.UseOnFor(unchecked((uint)spiritId), unchecked((uint)deviceId), "Pet", "refill the essence with a spirit");
}
private void GoIdle()
@ -310,6 +318,21 @@ internal sealed class PetManager
/// A combat pet is up if a live creature named "&lt;PlayerName&gt;'s …" exists in
/// the cache — the server names summoned pets exactly that (Pet.Init).
/// </summary>
/// <summary>
/// The summon out now, for the Damage tab's summon stats: null = none, else the element of
/// the essence it came from ("" when that isn't known, e.g. summoned by hand).
/// </summary>
internal string? CurrentSummon()
{
long now = NowMs;
if (now - _petOutCheckedAt > 1000)
{
_petOutCheckedAt = now;
_petOutCached = IsPetActive();
}
return _petOutCached ? _summonElement : null;
}
private bool IsPetActive()
{
string me = PlayerName();
@ -369,6 +392,53 @@ internal sealed class PetManager
}
}
private int _lastChoiceTarget;
private string _lastChoiceReason = "";
private List<int> OrderDevicesForTarget(IEnumerable<int> ids)
{
var raw = new List<(int Id, string Name)>();
var seen = new HashSet<int>();
foreach (int id in ids)
if (seen.Add(id)) raw.Add((id, _objectCache[id]?.Name ?? ""));
if (raw.Count <= 1 || _combat == null) return raw.ConvertAll(r => r.Id);
int target = _combat.activeTargetId;
if (target == 0)
{
double best = double.MaxValue;
foreach (var t in _combat.ScannedTargets)
if (t.Distance < best) { best = t.Distance; target = t.Id; }
}
if (target == 0) return raw.ConvertAll(r => r.Id);
uint wcid = 0;
if (_host.HasGetObjectWcid) _host.TryGetObjectWcid(unchecked((uint)target), out wcid);
string tname = _objectCache[target]?.Name ?? "";
string choice = wcid != 0 ? _combat.DamageStore?.GetManualPet(wcid) ?? "" : "";
// Monsters-tab rule for this monster: its pet damage (PetDamage) wins over its
// weapon damage type. Same name match combat uses.
var rule = _settings.MonsterRules.Find(r => r.Name.Length > 0 && !r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)
&& tname.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0);
// No rule of its own, or one left on Auto: the Default row's pet damage, when it names one.
var defaultRow = _settings.MonsterRules.Find(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
if ((rule == null || (PetChoice.NormalizeElement(rule.PetDamage).Length == 0 && PetChoice.NormalizeElement(rule.DamageType).Length == 0))
&& defaultRow != null && PetChoice.NormalizeElement(defaultRow.PetDamage).Length > 0)
rule = defaultRow;
string ruleElem = rule == null ? "" :
(PetChoice.NormalizeElement(rule.PetDamage).Length > 0 ? rule.PetDamage : rule.DamageType);
var weak = _combat.WeaknessFor(wcid, tname, target);
var ordered = PetChoice.Order(_host, raw, choice, weak, out string why, ruleElem);
if (target != _lastChoiceTarget || why != _lastChoiceReason)
{
_lastChoiceTarget = target;
_lastChoiceReason = why;
_host.Log($"[RynthAi] Pet: for {tname}: {why} -> {(ordered.Count > 0 ? ordered[0].Name : "none")}");
}
return ordered.ConvertAll(d => d.Id);
}
private int FindEncapsulatedSpirit()
{
int playerId = unchecked((int)_host.GetPlayerId());

View file

@ -104,6 +104,22 @@ public static class SpellDatabase
return map;
}
/// <summary>
/// Every id per name. Some names have several ids (Missile Weapon Mastery Self VI is
/// 472/496/544, Light Weapon Mastery has five per tier), and BuildNameToIdMap keeps
/// only the last, which a character may not know.
/// </summary>
public static Dictionary<string, List<int>> BuildNameToIdsMap()
{
var map = new Dictionary<string, List<int>>(StringComparer.OrdinalIgnoreCase);
foreach (var kvp in _spellNames)
{
if (!map.TryGetValue(kvp.Value, out var ids)) map[kvp.Value] = ids = new List<int>();
ids.Add(kvp.Key);
}
return map;
}
/// <summary>Looks up a spell ID by exact name (case-insensitive).</summary>
public static int GetIdByName(string name)
{

View file

@ -33,6 +33,10 @@ public class SpellManager
public Dictionary<string, int> SpellDictionary { get; private set; } =
new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
// All ids per name (SpellDictionary keeps one). Lets TryGetId find the id this
// character actually knows when a name has several (weapon masteries, Item Tinkering).
private Dictionary<string, List<int>> _nameToIds = new(StringComparer.OrdinalIgnoreCase);
// Map base spell names to their exact Level 7 Lore counterparts
private readonly Dictionary<string, string[]> LoreNames = new(StringComparer.OrdinalIgnoreCase)
{
@ -66,7 +70,9 @@ public class SpellManager
{ "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" } },
{ "Mana Conversion Mastery", new[] { "Nuhmudira's Blessing" } },
{ "Two Handed Combat Mastery", new[] { "Blessing of T'ing" } },
{ "Magic Item Tinkering Expertise", new[] { "Celdiseth's Blessing" } },
{ "Sprint", new[] { "Saladur's Blessing" } },
{ "Jumping Mastery", new[] { "Jahannan's Blessing" } },
{ "Fealty", new[] { "Odif's Blessing", "Odif's Boon" } },
@ -113,6 +119,7 @@ public class SpellManager
if (!SpellDatabase.IsLoaded)
SpellDatabase.Load(msg => _host.WriteToChat(msg, 2));
SpellDictionary = SpellDatabase.BuildNameToIdMap();
_nameToIds = SpellDatabase.BuildNameToIdsMap();
_host.WriteToChat($"[RynthAi] Magic System Online: {SpellDictionary.Count} spells loaded.", 1);
}
catch (Exception ex)
@ -176,38 +183,56 @@ public class SpellManager
int maxTier = GetHighestBuffSpellTier(magicSkill);
string cleanBase = baseSpellName.Replace(" Self", "").Trim();
BaseNameAliases.TryGetValue(cleanBase, out string? alias);
for (int tier = maxTier; tier >= 1; tier--)
{
if (tier == 8)
{
if (TryGetId($"Incantation of {cleanBase} Self", out int id1)) return id1;
if (TryGetId($"Incantation of {cleanBase}", out int id2)) return id2;
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)
{
if (LoreNames.TryGetValue(cleanBase, out string[]? lores))
foreach (string lore in lores)
if (TryGetId(lore, out int idL)) return idL;
if (TryGetId($"{cleanBase} Self VII", out int id7a)) return id7a;
if (TryGetId($"{cleanBase} VII", out int id7b)) return id7b;
if (TryGetId($"Aura of {cleanBase} Self VII", out int id7c)) return id7c;
if (TryGetId($"Aura of {cleanBase} VII", out int id7d)) return id7d;
}
else
{
string numeral = GetRomanNumeral(tier);
if (TryGetId($"{cleanBase} Self {numeral}", out int idNum1)) return idNum1;
if (TryGetId($"{cleanBase} {numeral}", out int idNum2)) return idNum2;
if (TryGetId($"Aura of {cleanBase} Self {numeral}", out int idNum3)) return idNum3;
if (TryGetId($"Aura of {cleanBase} {numeral}", out int idNum4)) return idNum4;
}
if (TryGetTierId(cleanBase, tier, out int id)) return id;
if (alias != null && TryGetTierId(alias, tier, out int idAlias)) return idAlias;
}
return 0;
}
// The spell data spells some families differently from the buff list: the
// bludgeon bane is "Bludgeon Bane I-VI" / "Incantation of Bludgeon Bane", so
// "Bludgeoning Bane" only resolved at tier 7 (Tusker's Bane).
private static readonly Dictionary<string, string> BaseNameAliases = new(StringComparer.OrdinalIgnoreCase)
{
{ "Bludgeoning Bane", "Bludgeon Bane" },
};
private bool TryGetTierId(string cleanBase, int tier, out int id)
{
if (tier == 8)
{
if (TryGetId($"Incantation of {cleanBase} Self", out id)) return true;
if (TryGetId($"Incantation of {cleanBase}", out id)) return true;
if (TryGetId($"Aura of Incantation of {cleanBase} Self", out id)) return true;
if (TryGetId($"Aura of Incantation of {cleanBase}", out id)) return true;
}
else if (tier == 7)
{
if (LoreNames.TryGetValue(cleanBase, out string[]? lores))
foreach (string lore in lores)
if (TryGetId(lore, out id)) return true;
if (TryGetId($"{cleanBase} Self VII", out id)) return true;
if (TryGetId($"{cleanBase} VII", out id)) return true;
if (TryGetId($"Aura of {cleanBase} Self VII", out id)) return true;
if (TryGetId($"Aura of {cleanBase} VII", out id)) return true;
}
else
{
string numeral = GetRomanNumeral(tier);
if (TryGetId($"{cleanBase} Self {numeral}", out id)) return true;
if (TryGetId($"{cleanBase} {numeral}", out id)) return true;
if (TryGetId($"Aura of {cleanBase} Self {numeral}", out id)) return true;
if (TryGetId($"Aura of {cleanBase} {numeral}", out id)) return true;
}
id = 0;
return false;
}
/// <summary>
/// Record that a spell id is not actually castable by this character
/// (empirically: a cast of it got zero chat back). Resolution will skip
@ -249,7 +274,17 @@ public class SpellManager
spellId = 0;
if (!SpellDictionary.TryGetValue(exactName, out int id)) return false;
if (_knownSpellIds.Count == 0) return false; // cold — don't guess
if (!_knownSpellIds.Contains(id)) return false; // char doesn't know it
if (!_knownSpellIds.Contains(id))
{
// Same name, another id (as TryGetId): the map keeps the LAST id of a name, and
// war names have duplicates, e.g. "Acid Blast III" is 99 (the one players learn)
// and 3653, "Flame Bolt I" is 27 and four others. A char who knew 99 never cast it.
if (!_nameToIds.TryGetValue(exactName, out List<int>? ids)) return false;
id = 0;
foreach (int alt in ids)
if (_knownSpellIds.Contains(alt)) { id = alt; break; }
if (id == 0) return false; // char doesn't know it
}
spellId = id;
return true;
}
@ -335,6 +370,12 @@ public class SpellManager
if (_knownSpellIds.Count > 0)
{
if (_knownSpellIds.Contains(spellId)) return true;
// Same name, another id: an archer who knows the bow line of Missile
// Weapon Mastery (472) failed every tier because the map held the
// thrown line (544).
if (_nameToIds.TryGetValue(exactName, out List<int>? ids))
foreach (int alt in ids)
if (_knownSpellIds.Contains(alt)) { spellId = alt; return true; }
spellId = 0;
return false;
}

View file

@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Reads each listed weapon's element from its properties (<see cref="WeaponElements"/>) and
/// identifies the ones whose DamageType isn't known yet: one identify at a time, at most one
/// every <see cref="RequestGapMs"/>, at most <see cref="MaxRequestsPerItem"/> per weapon. The
/// engine (2026.9.30.5+) keeps every identified property, so a weapon is identified once.
/// Before the identify, CreateObject gives the icon's element glow (UiEffects) and the name.
/// </summary>
internal sealed class WeaponElementTracker
{
private readonly RynthCoreHost _host;
private readonly Func<DateTime> _now;
private readonly Dictionary<int, int> _requests = new();
private int _inFlightId;
private DateTime _inFlightAt = DateTime.MinValue;
private DateTime _lastRequestAt = DateTime.MinValue;
public double RequestGapMs { get; set; } = 2000;
public double RequestTimeoutMs { get; set; } = 5000;
public int MaxRequestsPerItem { get; set; } = 2;
/// <summary>Identify requests sent (diagnostics and tests).</summary>
public int RequestsSent { get; private set; }
public WeaponElementTracker(RynthCoreHost host, Func<DateTime>? now = null)
{
_host = host;
_now = now ?? (() => DateTime.Now);
}
/// <summary>What is known about <paramref name="id"/>'s element right now.</summary>
public WeaponElements.Info Read(int id, string? name) => ReadFrom(_host, id, name);
/// <summary>The same, for callers without a tracker (the Items panel's Add buttons).</summary>
public static WeaponElements.Info ReadFrom(RynthCoreHost host, int id, string? name)
{
uint uid = unchecked((uint)id);
int? ReadInt(uint stype) => host.HasGetObjectIntProperty && host.TryGetObjectIntProperty(uid, stype, out int v) ? v : null;
double? mod = null;
if (host.HasGetObjectDoubleProperty && host.TryGetObjectDoubleProperty(uid, WeaponElements.PropElementalDamageMod, out double m))
mod = m;
return WeaponElements.Detect(ReadInt(WeaponElements.PropDamageType), ReadInt(WeaponElements.PropImbuedEffect),
ReadInt(WeaponElements.PropUiEffects), name, mod);
}
/// <summary>True once the weapon has been identified (its DamageType, if it has one, is in).</summary>
public bool IsIdentified(int id)
{
uint uid = unchecked((uint)id);
if (_host.HasHasAppraisalData) return _host.HasAppraisalData(uid);
return ReadInt(uid, WeaponElements.PropDamageType) is int dt && dt != 0;
}
/// <summary>
/// Sends at most one identify, for the first of <paramref name="ids"/> that isn't identified
/// yet. Call it every few hundred milliseconds; it paces itself. Returns the id asked for (0 = none).
/// </summary>
public int Pump(IEnumerable<int> ids)
{
if (!_host.HasRequestId) return 0;
DateTime now = _now();
if (_inFlightId != 0)
{
if (!IsIdentified(_inFlightId) && (now - _inFlightAt).TotalMilliseconds < RequestTimeoutMs) return 0;
_inFlightId = 0;
}
if ((now - _lastRequestAt).TotalMilliseconds < RequestGapMs) return 0;
foreach (int id in ids)
{
if (id == 0 || IsIdentified(id)) continue;
int n = _requests.TryGetValue(id, out int c) ? c : 0;
if (n >= MaxRequestsPerItem) continue;
_requests[id] = n + 1;
_inFlightId = id;
_inFlightAt = now;
_lastRequestAt = now;
RequestsSent++;
try { _host.RequestId(unchecked((uint)id)); } catch { }
return id;
}
return 0;
}
/// <summary>Forget the request counts (a relog: the ids are new).</summary>
public void Reset()
{
_requests.Clear();
_inFlightId = 0;
}
private int? ReadInt(uint id, uint stype)
{
if (!_host.HasGetObjectIntProperty) return null;
return _host.TryGetObjectIntProperty(id, stype, out int v) ? v : (int?)null;
}
}

View file

@ -0,0 +1,149 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.CreatureData;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// A weapon's damage element, from its properties. Pure: no host, no cache.
///
/// Sources, best first:
/// 1. DamageType (int 45): the caster's element, or the melee/missile weapon profile's
/// damage type. Only arrives with an identify.
/// 2. The icon's element glow (UiEffects, int 18). In CreateObject, so known before
/// any identify; the engine serves it from the object's PublicWeenieDesc.
/// 3. A rending imbue (ImbuedEffect, int 179): "Fire Rending" etc. Identify-only. Used
/// when the weapon has no other element; it also marks the weapon as the best pick
/// against that element, since rending ignores the target's resistance to it.
/// 4. The name: Fire/Flame/Flaming, Frost/Ice, Acid, Lightning/Electric, Blade, ...
/// Element names are CreatureWeakness's: Slash, Pierce, Bludgeon, Fire, Cold, Acid,
/// Lightning, Nether. "" = no element known.
/// </summary>
internal static class WeaponElements
{
public const uint PropUiEffects = 18, PropDamageType = 45, PropImbuedEffect = 179;
/// <summary>Float 152: the caster's bonus to war spells of its own element (1.0 = none).</summary>
public const uint PropElementalDamageMod = 152;
/// <summary>
/// AC DAMAGE_TYPE flags → element. A single elemental bit wins; several physical bits
/// (a Slash/Pierce sword, 0x3) give the first of Slash, Pierce, Bludgeon. 0 → "".
/// </summary>
public static string FromDamageType(int dt)
{
if (dt == 0) return "";
if ((dt & 0x400) != 0) return "Nether";
if ((dt & 0x10) != 0) return "Fire";
if ((dt & 0x08) != 0) return "Cold";
if ((dt & 0x40) != 0) return "Lightning";
if ((dt & 0x20) != 0) return "Acid";
if ((dt & 0x01) != 0) return "Slash";
if ((dt & 0x02) != 0) return "Pierce";
if ((dt & 0x04) != 0) return "Bludgeon";
return "";
}
/// <summary>ACE UiEffects (the icon's glow) → element; "" when it has none.</summary>
public static string FromUiEffects(int fx)
{
if (fx == 0) return "";
if ((fx & 0x1000) != 0) return "Nether";
if ((fx & 0x0020) != 0) return "Fire";
if ((fx & 0x0080) != 0) return "Cold";
if ((fx & 0x0040) != 0) return "Lightning";
if ((fx & 0x0100) != 0) return "Acid";
if ((fx & 0x0400) != 0) return "Slash";
if ((fx & 0x0800) != 0) return "Pierce";
if ((fx & 0x0200) != 0) return "Bludgeon";
return "";
}
/// <summary>ACE ImbuedEffectType rending flags → element; "" when there is none.</summary>
public static string FromImbuedEffect(int imbue)
{
if (imbue == 0) return "";
if ((imbue & 0x4000) != 0) return "Nether";
if ((imbue & 0x0200) != 0) return "Fire";
if ((imbue & 0x0080) != 0) return "Cold";
if ((imbue & 0x0100) != 0) return "Lightning";
if ((imbue & 0x0040) != 0) return "Acid";
if ((imbue & 0x0008) != 0) return "Slash";
if ((imbue & 0x0010) != 0) return "Pierce";
if ((imbue & 0x0020) != 0) return "Bludgeon";
return "";
}
// Whole words in a weapon's name, first match wins. "Staff of the Blade" is Slash;
// "Iceberg" isn't "Ice" (whole words only).
private static readonly (string Word, string Element)[] NameWords =
{
("Fire", "Fire"), ("Flame", "Fire"), ("Flaming", "Fire"), ("Fiery", "Fire"), ("Burning", "Fire"), ("Inferno", "Fire"),
("Frost", "Cold"), ("Ice", "Cold"), ("Icy", "Cold"), ("Cold", "Cold"), ("Freezing", "Cold"), ("Frozen", "Cold"), ("Glacial", "Cold"),
("Acid", "Acid"), ("Acidic", "Acid"), ("Corrosive", "Acid"), ("Caustic", "Acid"),
("Lightning", "Lightning"), ("Electric", "Lightning"), ("Electrical", "Lightning"), ("Shock", "Lightning"), ("Thunder", "Lightning"),
("Nether", "Nether"), ("Void", "Nether"),
("Blade", "Slash"), ("Blades", "Slash"), ("Slashing", "Slash"), ("Slash", "Slash"),
("Pierce", "Pierce"), ("Piercing", "Pierce"), ("Force", "Pierce"),
("Bludgeon", "Bludgeon"), ("Bludgeoning", "Bludgeon"),
};
/// <summary>The element a weapon's name says, "" when it names none.</summary>
public static string FromName(string? name)
{
if (string.IsNullOrWhiteSpace(name)) return "";
foreach (var (word, element) in NameWords)
if (ContainsWord(name, word)) return element;
return "";
}
/// <summary>What <see cref="Detect"/> worked out for one weapon.</summary>
public readonly record struct Info(string Element, string Source, string Rending, double Bonus)
{
/// <summary>No element known from anything.</summary>
public bool Unknown => Element.Length == 0;
}
/// <summary>
/// A weapon's element from what is known about it. Pass null for a property that isn't
/// known (not sent yet); 0 for one that is known to be empty. <paramref name="elementalMod"/>
/// is the caster's float 152 (null = unknown; it only counts for the caster's own element).
/// Source: "properties", "icon", "rending", "name" or "".
/// </summary>
public static Info Detect(int? damageType, int? imbuedEffect, int? uiEffects, string? name, double? elementalMod = null)
{
string rending = imbuedEffect is int ie ? FromImbuedEffect(ie) : "";
double bonus = elementalMod is double m && m > 1.0 && m < 5.0 ? m : 1.0;
string e = damageType is int dt ? FromDamageType(dt) : "";
if (e.Length > 0) return new Info(e, "properties", rending, bonus);
e = uiEffects is int fx ? FromUiEffects(fx) : "";
if (e.Length > 0) return new Info(e, "icon", rending, bonus);
if (rending.Length > 0) return new Info(rending, "rending", rending, bonus);
e = FromName(name);
if (e.Length > 0) return new Info(e, "name", rending, bonus);
return new Info("", "", rending, bonus);
}
/// <summary>Element spelling as the rest of RynthAi uses it (Blade → Slash, Electric → Lightning, Frost → Cold).</summary>
public static string Normalize(string? element)
{
if (string.IsNullOrWhiteSpace(element)) return "";
string t = element.Trim();
if (t.Equals("Frost", StringComparison.OrdinalIgnoreCase) || t.Equals("Ice", StringComparison.OrdinalIgnoreCase)) return "Cold";
return CreatureWeakness.Normalize(t);
}
private static bool ContainsWord(string text, string word)
{
int i = 0;
while ((i = text.IndexOf(word, i, StringComparison.OrdinalIgnoreCase)) >= 0)
{
bool startOk = i == 0 || !char.IsLetter(text[i - 1]);
int end = i + word.Length;
bool endOk = end >= text.Length || !char.IsLetter(text[end]);
if (startOk && endOk) return true;
i = end;
}
return false;
}
}

View file

@ -0,0 +1,240 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// A weapon's full retail name: the material (MaterialType, int 131, in CreateObject) in
/// front of the base name the client reports ("Wand" -> "Silver Wand"), and optionally the
/// element after it ("Silver Wand (Fire)"). Display only: rules are matched and saved by id.
/// Spellings are ACE's MaterialType names split into words ("Black Garnet", "Imperial Topaz").
/// </summary>
internal static class WeaponNames
{
public const uint PropMaterialType = 131;
private static readonly Dictionary<int, string> Materials = new()
{
[1] = "Ceramic", [2] = "Porcelain", [3] = "Cloth", [4] = "Linen", [5] = "Satin", [6] = "Silk",
[7] = "Velvet", [8] = "Wool", [9] = "Gem", [10] = "Agate", [11] = "Amber", [12] = "Amethyst",
[13] = "Aquamarine", [14] = "Azurite", [15] = "Black Garnet", [16] = "Black Opal", [17] = "Bloodstone",
[18] = "Carnelian", [19] = "Citrine", [20] = "Diamond", [21] = "Emerald", [22] = "Fire Opal",
[23] = "Green Garnet", [24] = "Green Jade", [25] = "Hematite", [26] = "Imperial Topaz", [27] = "Jet",
[28] = "Lapis Lazuli", [29] = "Lavender Jade", [30] = "Malachite", [31] = "Moonstone", [32] = "Onyx",
[33] = "Opal", [34] = "Peridot", [35] = "Red Garnet", [36] = "Red Jade", [37] = "Rose Quartz",
[38] = "Ruby", [39] = "Sapphire", [40] = "Smokey Quartz", [41] = "Sunstone", [42] = "Tiger Eye",
[43] = "Tourmaline", [44] = "Turquoise", [45] = "White Jade", [46] = "White Quartz",
[47] = "White Sapphire", [48] = "Yellow Garnet", [49] = "Yellow Topaz", [50] = "Zircon",
[51] = "Ivory", [52] = "Leather", [53] = "Armoredillo Hide", [54] = "Gromnie Hide",
[55] = "Reed Shark Hide", [56] = "Metal", [57] = "Brass", [58] = "Bronze", [59] = "Copper",
[60] = "Gold", [61] = "Iron", [62] = "Pyreal", [63] = "Silver", [64] = "Steel", [65] = "Stone",
[66] = "Alabaster", [67] = "Granite", [68] = "Marble", [69] = "Obsidian", [70] = "Sandstone",
[71] = "Serpentine", [72] = "Wood", [73] = "Ebony", [74] = "Mahogany", [75] = "Oak", [76] = "Pine",
[77] = "Teak",
};
/// <summary>The material's display name, "" when unknown.</summary>
public static string Material(int materialType) => Materials.TryGetValue(materialType, out string? n) ? n : "";
/// <summary>"Silver Wand": the material in front, unless the name already starts with it.</summary>
public static string Full(string? baseName, int materialType)
{
string name = (baseName ?? "").Trim();
string mat = Material(materialType);
if (mat.Length == 0 || name.Length == 0) return name;
if (name.StartsWith(mat + " ", StringComparison.OrdinalIgnoreCase) || name.Equals(mat, StringComparison.OrdinalIgnoreCase))
return name;
return mat + " " + name;
}
/// <summary>"Silver Wand (Fire)"; the bare name when the element is unknown.</summary>
public static string WithElement(string name, string? element)
=> string.IsNullOrWhiteSpace(element) ? name : $"{name} ({element})";
/// <summary>
/// An object's full name from the client (name and material read live through the host,
/// which is safe from the panels' threads; the object cache is not), else <paramref name="fallback"/>.
/// </summary>
public static string For(RynthCoreHost host, WorldObjectCache? cache, int id, string? fallback)
{
_ = cache; // kept for callers; the cache's lazy lookup isn't thread-safe
string baseName = "";
if (host.HasGetObjectName)
{
try { host.TryGetObjectName(unchecked((uint)id), out baseName); } catch { baseName = ""; }
}
if (string.IsNullOrEmpty(baseName)) baseName = fallback ?? "";
int mat = 0;
if (host.HasGetObjectIntProperty && host.TryGetObjectIntProperty(unchecked((uint)id), PropMaterialType, out int m)) mat = m;
return Full(baseName, mat);
}
}
/// <summary>The Items list's weapons: their elements and the wand lookups shared by combat and buffing.</summary>
internal static class WeaponList
{
/// <summary>ItemRule.ElementSource when the user picked the element in the Items panel.</summary>
public const string SourceSet = "set";
/// <summary>ItemRule.Action of a listed shield (the off hand); weapons are "Weapon".</summary>
public const string ShieldAction = "Shield";
public static bool IsShieldRule(ItemRule r) => string.Equals(r.Action, ShieldAction, StringComparison.OrdinalIgnoreCase);
private static int Rank(string source) => source switch
{
SourceSet => 9,
"properties" => 4,
"icon" => 3,
"rending" => 2,
"name" => 1,
_ => 0,
};
/// <summary>
/// Brings each listed weapon's element up to date from what's known about it. An element
/// the user set is kept. A better source replaces a worse one (properties beat the icon,
/// the icon beats a rending, a rending beats the name). An entry from before this (no
/// source) keeps a non-Slash element as the user's; its old "Slash" default is replaced as
/// soon as anything is known. Returns the entries that changed.
/// </summary>
public static int RefreshElements(List<ItemRule> rules, Func<int, string?, WeaponElements.Info> read, Func<int, string?>? nameOf = null)
{
int changed = 0;
foreach (var r in rules)
{
if (r.ElementSource == SourceSet || IsShieldRule(r)) continue; // a shield has no element
if (r.ElementSource.Length == 0 && r.Element.Length > 0
&& !r.Element.Equals("Slash", StringComparison.OrdinalIgnoreCase))
{
r.ElementSource = SourceSet;
changed++;
continue;
}
var info = read(r.Id, nameOf?.Invoke(r.Id) ?? r.Name);
if (info.Unknown) continue;
bool better = Rank(info.Source) > Rank(r.ElementSource);
bool same = Rank(info.Source) == Rank(r.ElementSource);
if (better || (same && !info.Element.Equals(r.Element, StringComparison.OrdinalIgnoreCase)))
{
r.Element = info.Element;
r.ElementSource = info.Source;
changed++;
}
}
return changed;
}
/// <summary>What the Items panel shows for an element nobody knows yet.</summary>
public const string UnknownLabel = "Unknown";
/// <summary>
/// Copies of the weapons for the Items panel: the full name (material in front) and
/// "Unknown" for an element not known yet. The panel sends the copies back on an edit;
/// <see cref="MergeEdited"/> maps them onto the saved entries by id.
/// </summary>
public static List<ItemRule> ForDisplay(IEnumerable<ItemRule> rules, Func<ItemRule, string> fullName)
{
var list = new List<ItemRule>();
foreach (var r in rules)
list.Add(new ItemRule
{
Id = r.Id, Name = fullName(r), Action = r.Action, KeepBuffed = r.KeepBuffed,
// A shield shows "Shield" in the element column (it has no element).
Element = IsShieldRule(r) ? ShieldAction : r.Element.Length > 0 ? r.Element : UnknownLabel,
ElementSource = r.ElementSource,
});
return list;
}
/// <summary>
/// The Items panel's edited list, mapped onto the saved one by id: the saved name stays
/// (the panel shows the full name; entries are matched and saved by id), an element the
/// user changed becomes theirs ("set"), and "Unknown" stays unknown. Order and deletions
/// follow the panel.
/// </summary>
public static List<ItemRule> MergeEdited(IReadOnlyList<ItemRule> saved, IEnumerable<ItemRule> edited)
{
var byId = new Dictionary<int, ItemRule>();
foreach (var r in saved) byId.TryAdd(r.Id, r);
var list = new List<ItemRule>();
foreach (var e in edited)
{
string elem = e.Element.Equals(UnknownLabel, StringComparison.OrdinalIgnoreCase) ? "" : e.Element;
if (byId.TryGetValue(e.Id, out var old))
{
if (IsShieldRule(old)) elem = old.Element; // a shield keeps no element; the column only says "Shield"
bool changed = !elem.Equals(old.Element, StringComparison.OrdinalIgnoreCase);
list.Add(new ItemRule
{
// The panel carries only id, name and element: the rest stays as saved.
Id = old.Id, Name = old.Name, Action = old.Action, KeepBuffed = old.KeepBuffed,
Element = changed ? elem : old.Element,
ElementSource = changed ? (elem.Length > 0 ? SourceSet : "") : old.ElementSource,
});
}
else
{
e.Element = elem;
list.Add(e);
}
}
return list;
}
/// <summary>
/// The wand to wield for buffing or casting: a listed wand (the one already in hand first,
/// then list order). When the list has no wand at all and <paramref name="allowUnlisted"/> is
/// on (LegacyUiSettings.WieldUnlistedWandWhenNoneListed), a caster from the pack (by object
/// class; never by name). 0 = none.
/// </summary>
public static int FindWand(IEnumerable<ItemRule> rules, Func<int, WorldObject?> lookup, Func<WorldObject, bool> isWielded,
IEnumerable<WorldObject> inventory, bool allowUnlisted, out bool unlisted)
{
unlisted = false;
int first = 0;
bool anyListedWand = false;
foreach (var r in rules)
{
var wo = lookup(r.Id);
if (wo == null) continue;
if (!IsWand(wo)) continue;
anyListedWand = true;
if (isWielded(wo)) return r.Id;
if (first == 0) first = r.Id;
}
if (first != 0) return first;
if (anyListedWand || !allowUnlisted) return 0;
foreach (var wo in inventory)
if (wo.ObjectClass == AcObjectClass.WandStaffOrb)
{
unlisted = true;
return wo.Id;
}
return 0;
}
/// <summary>
/// A caster: object class WandStaffOrb, or an unclassified item named like one. A melee
/// weapon named "Quarter Staff" is not a wand (it used to be, and put the character in Magic mode).
/// </summary>
public static bool IsWand(WorldObject wo)
{
if (wo.ObjectClass == AcObjectClass.WandStaffOrb) return true;
if (wo.ObjectClass == AcObjectClass.MeleeWeapon || wo.ObjectClass == AcObjectClass.MissileWeapon) return false;
return IsWandName(wo.Name);
}
public static bool IsWandName(string? name)
{
if (string.IsNullOrEmpty(name)) return false;
return name.IndexOf("Orb", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Staff", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Wand", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Scepter", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Sceptre", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Baton", StringComparison.OrdinalIgnoreCase) >= 0
|| name.IndexOf("Crozier", StringComparison.OrdinalIgnoreCase) >= 0;
}
}

View file

@ -0,0 +1,315 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.CreatureData;
namespace RynthCore.Plugin.RynthAi;
/// <summary>One weapon from the user's Items list that combat may wield.</summary>
/// <param name="Kind">CombatMode.Melee / Missile / Magic.</param>
/// <param name="Element">Normalized element ("" = unknown).</param>
/// <param name="Rending">Element of a rending imbue ("" = none).</param>
/// <param name="SlayerType">The creature type it slays (PropertyInt 166 SlayerCreatureType, 0 = none).</param>
/// <param name="SlayerBonus">Its damage multiplier against that type (PropertyFloat 138 SlayerDamageBonus, 0 = none).</param>
internal sealed record WeaponCandidate(int Id, string Name, int Kind, string Element, string Rending, bool InHand,
int SlayerType = 0, double SlayerBonus = 0);
/// <summary>What to fight a monster with: the weapon (0 = none), the element to cast or
/// debuff with, and why.</summary>
internal readonly record struct WeaponPlan(int WeaponId, string Element, string Source);
/// <summary>
/// The element-and-weapon rule, pure (no host). The weakness decides the weapon, never the
/// other way round, except for a slayer:
/// 1. A Damage tab weapon (this monster's, else the DEFAULT row's) is used as set; it must be in the Items list.
/// Its element is the rule's, else its own, else the weakest the character can cast.
/// 2. A slayer: a listed weapon of the character's main kind whose SlayerCreatureType is
/// the monster's CreatureType and whose SlayerDamageBonus is above 1 (ACE multiplies the
/// whole hit by it, so it beats any element choice). Several: the biggest bonus, then
/// the element order (the rule's element, else the weakest group), then a matching
/// rending, then the one in hand, then list order. Its element is the wand's own, else a
/// melee/missile weapon's own, else the rule's, else the weakest the character can cast.
/// Creature type unknown (not appraised yet): no slayer step.
/// 3. (The Damage tab DEFAULT row's weapon is a player pick too: it is step 1.)
/// 4. A Monsters rule damage type (not Auto) is the element; wield the listed weapon of that
/// element (a matching rending first, then the one in hand, then list order).
/// Whatever is chosen, a wand casts its own element when it has one (owner's rule,
/// 2026-09-30: "the wand should always cast its element, especially when rended").
/// 5. Auto with a known weakness: walk the monster's elements from weakest (highest
/// multiplier) down; the first element a listed weapon of the character's main kind has
/// wins, and that weapon is wielded. Elements tied on the multiplier count as one step,
/// and within a step the weapon in hand wins, then a rending, then the weakness order.
/// A caster only counts for elements the character can cast.
/// No listed weapon has any of them: keep the one in hand (else the learned best, else
/// the first), and cast the weakest element the character can.
/// 6. Weakness unknown: keep the weapon in hand (else the learned best, else the first) and
/// use its element; nothing known at all: Slash (or the first element the character can cast).
/// "Main kind" = the kind of the first usable weapon in the list, so a bow character with a
/// buff wand listed isn't switched to magic, and a melee character isn't swapped to a wand.
/// </summary>
internal static class WeaponPlanner
{
/// <summary>Two multipliers this close are a tie.</summary>
public const double TieEpsilon = 0.005;
/// <summary>Fallback element order when nothing is known ("Slash" first).</summary>
public static readonly string[] FallbackOrder = { "Slash", "Fire", "Cold", "Lightning", "Acid", "Pierce", "Bludgeon", "Nether" };
public static WeaponPlan Choose(
IReadOnlyList<WeaponCandidate> listed,
string? ruleElement,
CreatureWeakness.Ranking? weak,
Func<string, bool> canCast,
int fixedWeaponId = 0,
string fixedSource = "Damage tab",
int learnedBestId = 0,
int creatureType = 0,
bool fixedIsDefault = false)
{
string rule = WeaponElements.Normalize(ruleElement);
bool ruleSet = rule.Length > 0;
WeaponCandidate? fixedPick = fixedWeaponId != 0 ? Find(listed, fixedWeaponId) : null;
// 1. A weapon the player picked on the Damage tab: for this monster, or the DEFAULT row's
// (listed only). A player's pick is honoured, slayer or not (owner, 2026-10-04: "if
// it's set to auto slayer wins, if the player picks a weapon we honour that").
// fixedIsDefault only changes the source label.
if (fixedPick != null)
return FixedPlan(fixedPick, fixedSource, rule, weak, canCast);
if (listed.Count == 0)
{
// Nothing listed: no weapon; the element still follows the rule / weakness.
string elem = ruleSet ? rule : WeakestCastable(weak, canCast, null) ?? Fallback(canCast);
return new WeaponPlan(0, elem, "none");
}
int mainKind = listed[0].Kind;
var pool = new List<WeaponCandidate>();
foreach (var c in listed) if (c.Kind == mainKind) pool.Add(c);
// 2. A slayer of this monster's creature type.
if (creatureType > 0)
{
var s = BestSlayer(pool, creatureType, rule, weak, canCast);
if (s != null)
{
string elem = WandElement(s, canCast)
?? (s.Kind != CombatMode.Magic && s.Element.Length > 0 ? s.Element
: ruleSet ? rule
: WeakestCastable(weak, canCast, s) ?? ElementOrFallback(s, canCast));
return new WeaponPlan(s.Id, elem, SlayerSource(creatureType, s.SlayerBonus));
}
}
// 3. The Damage tab default weapon (listed only).
if (fixedPick != null)
return FixedPlan(fixedPick, fixedSource, rule, weak, canCast);
// 4. An explicit damage type: the listed weapon of that element (main kind first).
if (ruleSet)
{
var w = BestOf(pool, rule, null) ?? BestOf(listed, rule, null);
if (w != null) return new WeaponPlan(w.Id, rule, "Monsters rule " + rule);
var keep = InHand(pool) ?? pool[0];
// A wand casts its own element: the rule's element only when the weapon has none.
string keepElem = WandElement(keep, canCast) ?? rule;
return new WeaponPlan(keep.Id, keepElem, keep.InHand ? "Monsters rule " + rule + " (none listed; in hand)" : "Monsters rule " + rule + " (none listed)");
}
// 5. Auto, weakness known: weakest element a listed weapon has.
if (weak != null && weak.Order.Count > 0)
{
string handElem = InHand(pool)?.Element ?? "";
foreach (var group in TieGroups(weak))
{
// Within a tie: the element of the weapon in hand (no needless swap), else
// the weakness order; for one element: a matching rending, then the weapon
// in hand, then list order.
bool handInGroup = handElem.Length > 0 && group.Contains(handElem);
WeaponCandidate? best = null;
int bestRank = int.MaxValue;
for (int i = 0; i < pool.Count; i++)
{
var c = pool[i];
int idx = group.IndexOf(c.Element);
if (idx < 0) continue;
if (c.Kind == CombatMode.Magic && !canCast(c.Element)) continue;
int elemRank = handInGroup && c.Element == handElem ? 0 : 1 + idx;
int rank = elemRank * 100000
+ (c.Rending.Length > 0 && c.Rending == c.Element ? 0 : 10000)
+ (c.InHand ? 0 : 1000)
+ i;
if (rank < bestRank) { bestRank = rank; best = c; }
}
if (best != null)
return new WeaponPlan(best.Id, best.Element, $"weak to {best.Element} ({weak.Source})");
}
// No listed weapon has any element of the ranking: keep what we have.
var keep = InHand(pool) ?? Find(pool, learnedBestId) ?? pool[0];
// A wand whose element the character can't cast (no Void Magic for a Nether
// wand, no spells of it) casts the weakest element the character can, like a
// wand with no element; only a melee/missile weapon keeps its own element here.
string elem = WandElement(keep, canCast)
?? (keep.Element.Length == 0 || keep.Kind == CombatMode.Magic
? WeakestCastable(weak, canCast, keep) ?? Fallback(canCast)
: keep.Element);
return new WeaponPlan(keep.Id, elem, $"weak to {elem} ({weak.Source}); no listed weapon of it");
}
// 6. Weakness unknown: the weapon in hand and its element.
var hand = InHand(pool);
if (hand != null)
return new WeaponPlan(hand.Id, ElementOrFallback(hand, canCast), "in hand (weakness unknown)");
var learned = Find(pool, learnedBestId);
if (learned != null)
return new WeaponPlan(learned.Id, ElementOrFallback(learned, canCast), "Damage tab learned");
return new WeaponPlan(pool[0].Id, ElementOrFallback(pool[0], canCast), "ItemRules");
}
/// <summary>
/// The ranking's elements grouped by equal multiplier, weakest group first. A learned
/// ranking (NaN multipliers) is one element per group.
/// </summary>
public static List<List<string>> TieGroups(CreatureWeakness.Ranking weak)
{
var groups = new List<List<string>>();
double last = double.NaN;
foreach (var (e, m) in weak.Order)
{
if (groups.Count > 0 && !double.IsNaN(m) && !double.IsNaN(last) && Math.Abs(m - last) <= TieEpsilon)
groups[^1].Add(e);
else
groups.Add(new List<string> { e });
last = m;
}
return groups;
}
/// <summary>The weakest element the character can cast; ties go to <paramref name="wand"/>'s element.</summary>
public static string? WeakestCastable(CreatureWeakness.Ranking? weak, Func<string, bool> canCast, WeaponCandidate? wand)
{
if (weak == null) return null;
foreach (var group in TieGroups(weak))
{
if (wand != null && wand.Element.Length > 0 && group.Contains(wand.Element) && canCast(wand.Element))
return wand.Element;
foreach (string e in group)
if (canCast(e)) return e;
}
return null;
}
/// <summary>True when <paramref name="c"/> slays <paramref name="creatureType"/> (ACE: SlayerCreatureType == CreatureType, with a bonus).</summary>
public static bool Slays(WeaponCandidate c, int creatureType) =>
creatureType > 0 && c.SlayerType == creatureType && c.SlayerBonus > 1.0 + TieEpsilon;
/// <summary>The plan's source for a slayer: "slayer (Olthoi x2)".</summary>
public static string SlayerSource(int creatureType, double bonus) =>
$"slayer ({CreatureTypeNames.Name(creatureType)} x{bonus.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)})";
/// <summary>
/// The matching slayer to wield: the biggest bonus (ties within <see cref="TieEpsilon"/>),
/// then the element order (the rule's element, else the weakest group), then a matching
/// rending, then the one in hand, then list order. Null when none matches.
/// </summary>
private static WeaponCandidate? BestSlayer(List<WeaponCandidate> pool, int creatureType, string rule,
CreatureWeakness.Ranking? weak, Func<string, bool> canCast)
{
double top = 0;
foreach (var c in pool) if (Slays(c, creatureType) && c.SlayerBonus > top) top = c.SlayerBonus;
if (top <= 0) return null;
List<List<string>>? groups = rule.Length == 0 && weak != null && weak.Order.Count > 0 ? TieGroups(weak) : null;
WeaponCandidate? best = null;
int bestRank = int.MaxValue;
for (int i = 0; i < pool.Count; i++)
{
var c = pool[i];
if (!Slays(c, creatureType) || c.SlayerBonus < top - TieEpsilon) continue;
int elemRank = 0;
if (rule.Length > 0) elemRank = c.Element == rule ? 0 : 1;
else if (groups != null)
{
elemRank = groups.Count;
if (c.Element.Length > 0 && (c.Kind != CombatMode.Magic || canCast(c.Element)))
for (int g = 0; g < groups.Count; g++)
if (groups[g].Contains(c.Element)) { elemRank = g; break; }
}
int rank = elemRank * 100000
+ (c.Rending.Length > 0 && c.Rending == c.Element ? 0 : 10000)
+ (c.InHand ? 0 : 1000)
+ i;
if (rank < bestRank) { bestRank = rank; best = c; }
}
return best;
}
/// <summary>A Damage tab weapon: the wand's own element, else the rule's, else its own / the weakest castable.</summary>
private static WeaponPlan FixedPlan(WeaponCandidate f, string source, string rule, CreatureWeakness.Ranking? weak, Func<string, bool> canCast)
{
string elem = WandElement(f, canCast) ?? (rule.Length > 0 ? rule : ElementFor(f, weak, canCast));
return new WeaponPlan(f.Id, elem, source);
}
/// <summary>
/// The element for a weapon the user fixed (the Damage tab): its own element when known
/// (the walk down the weakness list stops at the only candidate's element), else the
/// weakest element the character can cast.
/// </summary>
private static string ElementFor(WeaponCandidate w, CreatureWeakness.Ranking? weak, Func<string, bool> canCast)
{
if (w.Element.Length > 0 && (w.Kind != CombatMode.Magic || canCast(w.Element))) return w.Element;
return WeakestCastable(weak, canCast, w) ?? ElementOrFallback(w, canCast);
}
/// <summary>
/// A wand (caster) always casts its own element when it has one (damage type, icon element
/// or rending) and the character can cast it: its elemental bonus (and a rending) only
/// works for spells of its element. Null for other weapons or an element not known.
/// </summary>
private static string? WandElement(WeaponCandidate w, Func<string, bool> canCast) =>
w.Kind == CombatMode.Magic && w.Element.Length > 0 && canCast(w.Element) ? w.Element : null;
private static string ElementOrFallback(WeaponCandidate w, Func<string, bool> canCast)
{
if (w.Element.Length > 0 && (w.Kind != CombatMode.Magic || canCast(w.Element))) return w.Element;
return Fallback(canCast);
}
private static string Fallback(Func<string, bool> canCast)
{
foreach (string e in FallbackOrder)
if (canCast(e)) return e;
return "Slash";
}
/// <summary>The weapon of <paramref name="element"/> to wield: matching rending first, then in hand, then list order.</summary>
private static WeaponCandidate? BestOf(IReadOnlyList<WeaponCandidate> list, string element, Func<string, bool>? canCast)
{
WeaponCandidate? best = null;
int bestRank = int.MaxValue;
for (int i = 0; i < list.Count; i++)
{
var c = list[i];
if (c.Element != element) continue;
if (canCast != null && c.Kind == CombatMode.Magic && !canCast(element)) continue;
int rank = (c.Rending == element ? 0 : 10000) + (c.InHand ? 0 : 1000) + i;
if (rank < bestRank) { bestRank = rank; best = c; }
}
return best;
}
private static WeaponCandidate? InHand(IReadOnlyList<WeaponCandidate> list)
{
foreach (var c in list) if (c.InHand) return c;
return null;
}
private static WeaponCandidate? Find(IReadOnlyList<WeaponCandidate> list, int id)
{
if (id == 0) return null;
foreach (var c in list) if (c.Id == id) return c;
return null;
}
}

View file

@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Combat's weapon swaps, one at a time, confirmed, bounded, and never back and forth. Pure:
/// the caller reads what's in hand and the server's replies and passes them in with the time.
///
/// * One swap in flight: after <see cref="Sent"/> nothing else is sent until the weapon is
/// seen in hand (confirmed), the server refuses (UseDone with an error, or a WeenieError:
/// <see cref="Refused"/>), or <see cref="ResolveMs"/> passes.
/// * Retry cap: a weapon that doesn't reach the hand after <see cref="MaxTries"/> sends is
/// rested for <see cref="GiveUpMs"/>; combat carries on with what's in hand (logged once).
/// * No flip-flop: having swapped A → B, swapping back to A within <see cref="MinDwellMs"/>
/// is held, and so is any swap once <see cref="MaxSwapsPerWindow"/> landed inside
/// <see cref="SwapWindowMs"/>. Combat keeps fighting with B.
/// </summary>
internal sealed class WeaponSwapTracker
{
public enum Step
{
/// <summary>The chosen weapon is in hand (or none is wanted): fight.</summary>
InHand,
/// <summary>A swap is in flight: hold the attack.</summary>
Wait,
/// <summary>Send the wield now (then call <see cref="Sent"/>).</summary>
Swap,
/// <summary>Don't swap: fight with what's in hand.</summary>
Hold,
}
public int MaxTries { get; set; } = 3;
public double ResolveMs { get; set; } = 2500;
public double GiveUpMs { get; set; } = 120_000;
public double MinDwellMs { get; set; } = 20_000;
public int MaxSwapsPerWindow { get; set; } = 4;
public double SwapWindowMs { get; set; } = 60_000;
private int _pendingId, _pendingFrom;
private DateTime _pendingAt;
private readonly Dictionary<int, int> _tries = new();
private readonly Dictionary<int, DateTime> _restUntil = new();
private readonly List<DateTime> _landed = new();
private int _lastFrom, _lastTo;
private DateTime _lastLandedAt = DateTime.MinValue;
/// <summary>The weapon a swap is in flight for (0 = none).</summary>
public int PendingId => _pendingId;
/// <summary>Wields sent for <paramref name="id"/> since it was last in hand.</summary>
public int TriesFor(int id) => _tries.TryGetValue(id, out int t) ? t : 0;
/// <summary>Why the last Hold happened, for the log ("" = none).</summary>
public string HoldReason { get; private set; } = "";
/// <summary>A line to log once (a give-up), then cleared by the caller reading it.</summary>
public string? Notice { get; set; }
/// <summary>
/// What to do about <paramref name="chosenId"/> with <paramref name="inHandId"/> in hand
/// (0 = nothing readable in hand).
/// </summary>
public Step Next(int chosenId, int inHandId, DateTime now, Func<int, string>? nameOf = null)
{
HoldReason = "";
if (chosenId == 0) return Step.InHand;
if (inHandId == chosenId)
{
if (_pendingId == chosenId) Land(now);
_tries.Remove(chosenId);
return Step.InHand;
}
if (_pendingId != 0)
{
if ((now - _pendingAt).TotalMilliseconds < ResolveMs) return Step.Wait;
Fail(now, "not seen in hand", nameOf);
}
if (_restUntil.TryGetValue(chosenId, out DateTime rest) && now < rest)
{
HoldReason = "resting after failed tries";
return Step.Hold;
}
if (inHandId != 0)
{
if (chosenId == _lastFrom && inHandId == _lastTo && (now - _lastLandedAt).TotalMilliseconds < MinDwellMs)
{
HoldReason = "just swapped away from it";
return Step.Hold;
}
_landed.RemoveAll(t => (now - t).TotalMilliseconds > SwapWindowMs);
if (_landed.Count >= MaxSwapsPerWindow)
{
HoldReason = $"{_landed.Count} swaps in {SwapWindowMs / 1000:0}s";
return Step.Hold;
}
}
return Step.Swap;
}
/// <summary>A wield of <paramref name="id"/> was sent with <paramref name="fromId"/> in hand.</summary>
public void Sent(int id, int fromId, DateTime now)
{
_pendingId = id;
_pendingFrom = fromId;
_pendingAt = now;
_tries[id] = (_tries.TryGetValue(id, out int t) ? t : 0) + 1;
}
/// <summary>The server refused the action in flight (UseDone error / WeenieError).</summary>
public void Refused(DateTime now, Func<int, string>? nameOf = null)
{
if (_pendingId != 0) Fail(now, "refused by the server", nameOf);
}
/// <summary>The chosen weapon was seen in hand some other way (the wield-location read).</summary>
public void Confirmed(int id, DateTime now)
{
if (_pendingId == id) Land(now);
_tries.Remove(id);
}
public void Reset()
{
_pendingId = _pendingFrom = 0;
_tries.Clear();
_restUntil.Clear();
_landed.Clear();
_lastFrom = _lastTo = 0;
_lastLandedAt = DateTime.MinValue;
HoldReason = "";
Notice = null;
}
private void Land(DateTime now)
{
if (_pendingFrom != 0 && _pendingFrom != _pendingId)
{
_lastFrom = _pendingFrom;
_lastTo = _pendingId;
_lastLandedAt = now;
_landed.Add(now);
}
_pendingId = _pendingFrom = 0;
}
private void Fail(DateTime now, string why, Func<int, string>? nameOf)
{
int id = _pendingId;
_pendingId = _pendingFrom = 0;
if (!_tries.TryGetValue(id, out int tries) || tries < MaxTries) return;
_tries.Remove(id);
_restUntil[id] = now.AddMilliseconds(GiveUpMs);
string name = nameOf?.Invoke(id) ?? "";
Notice = $"0x{(uint)id:X8} '{name}' didn't wield after {MaxTries} tries ({why}) — fighting with what's in hand for {GiveUpMs / 60000:0.#} min";
}
}

View file

@ -46,14 +46,23 @@ public class WorldObjectCache
// OnCreateObject IDs pending classification
private readonly Queue<uint> _pending = new();
private const int MaxClassifyPerTick = 30;
// Classification work per tick: up to MaxClassifyPerTick ids, and no more than
// ClassifyBudgetMs of the plugin tick once at least MinClassifyPerTick are done. Was a flat
// 30, so a 1000-create flood (2026-10-02) took 34+ ticks, longer when the tick slowed.
private const int MaxClassifyPerTick = 250;
private const int MinClassifyPerTick = 30;
private const double ClassifyBudgetMs = 3.0;
// Fast retries wait for the next tick: the engine's name/position snapshots only change
// between ticks, so the old same-tick re-queue spent all 8 retries in ~10 ms on the same
// answer (and logged each one) before parking the id in the 2 s slow-retry.
private readonly Queue<uint> _retryNext = new();
// Retry tracking for 0x8000xxxx objects that have no weenie yet (e.g. spawning corpses)
private readonly Dictionary<uint, int> _classifyRetry = new();
private const int MaxClassifyRetries = 8;
// Slow-retry rescue. When the 8-tick fast-retry burst exhausts (all attempts
// within ~10 ms because Tick processes 30 pending entries per pass), the uid
// Slow-retry rescue. When the 8-tick fast-retry burst exhausts (one attempt per
// tick since 2026-10-02, ~250 ms; before that all 8 ran within ~10 ms), the uid
// moves here instead of being abandoned. Every ReclassifyIntervalSec the
// entries are flushed back into _pending so the engine has fresh chances to
// populate name+position. Successful classification evicts the uid at the
@ -76,7 +85,7 @@ public class WorldObjectCache
private readonly Dictionary<uint, string> _reclassifySkipState = new();
private int _reclassifyDiagCount;
private int _reclassifyDiagSummaryCount;
private const int MaxReclassifyDiagLines = 500;
private const int MaxReclassifyDiagLines = 40;
private const int MaxReclassifyDiagSummaries = 60;
// Diagnostic — track every uid OnCreateObject ever saw. Lets HEALTHADD-RESCUE
@ -85,16 +94,21 @@ public class WorldObjectCache
// hook never fired for this respawn — the suspected bug). No eviction: a delete +
// recreate of the same id MUST keep showing seenCreate=1 to be diagnostic-correct.
private readonly HashSet<uint> _seenCreateObject = new();
private int _healthAddLogCount;
private int _indexerRescueLogCount;
private int _classifyGiveupLogCount;
private int _deleteWhilePendingSkipLogCount;
private int _deleteBeforeClassifyLogCount;
private const int MaxHealthAddDiagLines = 200;
private const int MaxIndexerRescueDiagLines = 200;
private const int MaxClassifyGiveupLogLines = 200;
private const int MaxDeleteWhilePendingSkipLogLines = 200;
private const int MaxDeleteBeforeClassifyLogLines = 200;
// [ClassifyTrace] / [ReclassifyDiag]: a few full lines per kind per session, then counts
// and sample ids in one summary line every ReclassifyIntervalSec (see ObjectDiagLog). Was
// one line per object per attempt (caps 200-5000), ~950 lines for the 2026-10-02 flood.
private readonly ObjectDiagLog _diag;
private const string DeleteBeforeClassify = "DELETE-BEFORE-CLASSIFY";
private const string HealthAddRescue = "HEALTHADD-RESCUE";
private const string DeleteWhilePendingSkip = "DELETE-WHILE-PENDING-SKIP";
private const string ClassifyGiveup = "CLASSIFY-GIVEUP";
private const string IndexerRescue = "INDEXER-RESCUE";
private static readonly string[] TraceNotes =
{
"noNamePos", "nopos-creature", "nopos-item", "nopos-retry", "nopos-giveup",
"pos", "attackable->creature", "healthAdd->creature",
};
// ItemType flag constants (AC ITEM_TYPE bitmask)
private const uint ItemTypeMeleeWeapon = 0x00000001;
@ -131,8 +145,19 @@ public class WorldObjectCache
public WorldObjectCache(RynthCoreHost host)
{
_host = host;
_diag = new ObjectDiagLog(line => _host.Log(line));
_diag.Define(DeleteBeforeClassify, "[ReclassifyDiag]", 10, "seenCreate");
_diag.Define(HealthAddRescue, "[ReclassifyDiag]", 10, "seenCreate", "inLandscape", "inById", "wasSkipped");
_diag.Define(DeleteWhilePendingSkip, "[ReclassifyDiag]", 10);
_diag.Define(ClassifyGiveup, "[ReclassifyDiag]", 10);
_diag.Define(IndexerRescue, "[ReclassifyDiag]", 20, "seenCreate");
foreach (string note in TraceNotes)
_diag.Define(note, "[ClassifyTrace]", 0); // detail lines: TraceClassify's own per-uid rule
}
/// <summary>Summary lines the bounded diagnostics wrote (tests).</summary>
internal int DiagSummaryLines => _diag.SummaryLines;
public void SetPlayerId(uint playerId)
{
lock (_gate)
@ -190,11 +215,11 @@ public class WorldObjectCache
// the object. If a respawn never re-fires OnCreateObject (which would
// clear this mark), the plugin loses awareness of the uid until the
// indexer's lazy lookup is forced (typically by a user click).
if (id >= 0x80000000u && _deleteBeforeClassifyLogCount < MaxDeleteBeforeClassifyLogLines)
if (id >= 0x80000000u)
{
_deleteBeforeClassifyLogCount++;
bool seenCreate = _seenCreateObject.Contains(id);
_host.Log($"[ReclassifyDiag] 0x{id:X8} DELETE-BEFORE-CLASSIFY seenCreate={(seenCreate ? 1 : 0)}");
if (_diag.Note(DeleteBeforeClassify, id, seenCreate ? 1 : 0))
_host.Log($"[ReclassifyDiag] 0x{id:X8} DELETE-BEFORE-CLASSIFY seenCreate={(seenCreate ? 1 : 0)}");
}
}
if (wasInventory)
@ -227,26 +252,22 @@ public class WorldObjectCache
// engine's CreateObject hook never fired for this respawn, yet the server is
// sending vitals for it, meaning the mob exists for AC but was invisible to the
// plugin until something poked it (typically a user click → QueryHealth response).
if (id >= 0x80000000u && _healthAddLogCount < MaxHealthAddDiagLines)
bool wasSkipped = _reclassifySkipState.Remove(id); // skip state cleared either way
if (id >= 0x80000000u)
{
_healthAddLogCount++;
bool wasSkipped = _reclassifySkipState.Remove(id);
bool seenCreate = _seenCreateObject.Contains(id);
bool inLandscape = _landscape.Contains(sid);
bool inById = _byId.ContainsKey(sid);
_host.Log($"[ReclassifyDiag] 0x{id:X8} HEALTHADD-RESCUE ratio={healthRatio:0.00} seenCreate={(seenCreate ? 1 : 0)} inLandscape={(inLandscape ? 1 : 0)} inById={(inById ? 1 : 0)} wasSkipped={(wasSkipped ? 1 : 0)}");
}
else if (_reclassifySkipState.ContainsKey(id))
{
// Past the log cap — still clean up skip state so the dict doesn't grow unbounded.
_reclassifySkipState.Remove(id);
int flags = (seenCreate ? 1 : 0) | (inLandscape ? 2 : 0) | (inById ? 4 : 0) | (wasSkipped ? 8 : 0);
if (_diag.Note(HealthAddRescue, id, flags))
_host.Log($"[ReclassifyDiag] 0x{id:X8} HEALTHADD-RESCUE ratio={healthRatio:0.00} seenCreate={(seenCreate ? 1 : 0)} inLandscape={(inLandscape ? 1 : 0)} inById={(inById ? 1 : 0)} wasSkipped={(wasSkipped ? 1 : 0)}");
}
// DIAG: a creature first learned via server health update (the
// "aggressive mob self-rescues" path) — NOT via TryClassify. Lets us
// correlate a manually-selected mob's id to how/when it entered
// _creatures vs. why classification missed it earlier.
TraceClassify(id, true, true, false, 0u, $"healthAdd->creature hr={healthRatio:0.00}");
TraceClassify(id, true, true, false, 0u, "healthAdd->creature", healthRatio: healthRatio);
// If the object was already classified as a Corpse, don't promote it back to Monster.
// AC fires health=0 events during the creature→corpse transition; if TryClassify already
@ -295,11 +316,22 @@ public class WorldObjectCache
public void Tick()
{
int pending0;
lock (_gate) pending0 = _pending.Count;
lock (_gate)
{
// Last tick's fast retries get their next attempt now.
while (_retryNext.Count > 0)
_pending.Enqueue(_retryNext.Dequeue());
pending0 = _pending.Count;
}
int processed = 0;
long start = System.Diagnostics.Stopwatch.GetTimestamp();
long budget = (long)(System.Diagnostics.Stopwatch.Frequency * ClassifyBudgetMs / 1000.0);
while (processed < MaxClassifyPerTick)
{
if (processed >= MinClassifyPerTick
&& System.Diagnostics.Stopwatch.GetTimestamp() - start > budget)
break;
uint uid;
lock (_gate)
{
@ -327,6 +359,7 @@ public class WorldObjectCache
_lastReclassifyTime = DateTime.Now;
FlushSlowRetry();
ReclassifyUnknownDynamics();
lock (_gate) _diag.Flush("2 s");
}
// Full container scan disabled — causes delayed crash when 160+ items in cache
@ -362,18 +395,33 @@ public class WorldObjectCache
// already-computed hasName/hasPos/TryGetItemType). Bounded so one login is
// conclusive without flooding. Dynamic (0x8000+) only — that's the
// creature/NPC/equipped range the login-mob bug lives in.
private int _classifyTrace;
// Bumped from 500 while the missing-respawn investigation needs coverage of late
// OnCreateObject events (login-burst alone blows the 500 cap in <2s, leaving the
// session blind to anything that spawned later).
private void TraceClassify(uint uid, bool hasName, bool hasPos, bool gotType, uint flags, string note)
// Full trace lines for the first TraceDetailUids dynamic ids of the session, at most
// TraceLinesPerUid each (their first attempt and the next distinct step), so a login still
// shows how individual objects classified. Every attempt is counted by note in the 2 s
// [ClassifyTrace] summary. Was every attempt of every object up to 5000 lines: a create
// flood logged each object up to 10 times (8 same-tick retries), 600 lines in seconds.
private const int TraceDetailUids = 25;
private const int TraceLinesPerUid = 2;
private readonly Dictionary<uint, (int Lines, string LastNote)> _traceDetail = new();
private void TraceClassify(uint uid, bool hasName, bool hasPos, bool gotType, uint flags, string note,
int retry = -1, float healthRatio = -1f)
{
if (_classifyTrace >= 5000 || uid < 0x80000000u) return;
_classifyTrace++;
if (uid < 0x80000000u) return;
_diag.Note(note, uid);
if (_traceDetail.TryGetValue(uid, out var seen))
{
if (seen.Lines >= TraceLinesPerUid || seen.LastNote == note) return;
}
else if (_traceDetail.Count >= TraceDetailUids)
return;
_traceDetail[uid] = (seen.Lines + 1, note);
int atk = -1;
try { if (_host.HasObjectIsAttackable) atk = _host.ObjectIsAttackable(uid) ? 1 : 0; }
catch { atk = -2; }
_host.Log($"[ClassifyTrace] 0x{uid:X8} name={(hasName ? 1 : 0)} pos={(hasPos ? 1 : 0)} gotType={(gotType ? 1 : 0)} flags=0x{flags:X8} creature={((flags & ItemTypeCreature) != 0 ? 1 : 0)} atk={atk} {note}");
string extra = retry >= 0 ? $" r={retry}" : healthRatio >= 0f ? $" hr={healthRatio:0.00}" : "";
_host.Log($"[ClassifyTrace] 0x{uid:X8} name={(hasName ? 1 : 0)} pos={(hasPos ? 1 : 0)} gotType={(gotType ? 1 : 0)} flags=0x{flags:X8} creature={((flags & ItemTypeCreature) != 0 ? 1 : 0)} atk={atk} {note}{extra}");
}
private void TryClassify(uint uid)
@ -396,11 +444,8 @@ public class WorldObjectCache
// the entity, the delete fired spuriously, or the create-delete-recreate
// sequence dropped one create), it sits invisible to the plugin until
// an indexer access rescues it. Pairs with DELETE-BEFORE-CLASSIFY.
if (uid >= 0x80000000u && _deleteWhilePendingSkipLogCount < MaxDeleteWhilePendingSkipLogLines)
{
_deleteWhilePendingSkipLogCount++;
if (uid >= 0x80000000u && _diag.Note(DeleteWhilePendingSkip, uid))
_host.Log($"[ReclassifyDiag] 0x{uid:X8} DELETE-WHILE-PENDING-SKIP");
}
return;
}
@ -421,35 +466,50 @@ public class WorldObjectCache
bool hasName = _host.TryGetObjectName(uid, out string name);
bool hasPos = _host.TryGetObjectPosition(uid, out _, out _, out _, out _);
bool looksLikeCorpse = hasPos && IsCorpseName(name);
// Object not accessible yet — retry for any dynamic object (weenie may not be ready)
// A corpse is a corpse whether or not its position is readable yet. This used to
// need hasPos, and a fresh corpse whose name and type (Container) were in the
// engine's identity snapshot before its position was fell to the "nopos-item"
// branch below: filed as an inventory Container, off the landscape, and never
// looked at again (ReclassifyUnknownDynamics only walks the landscape). Your own
// fresh kills hit that most (created next to you, classified at once), so looting
// never saw them while older corpses of other players' kills were found
// (2026-10-03, Dargoth Hera: "Loot All" didn't loot either). Nothing carried
// in a pack is named "Corpse of X", and the weenie's corpse flag says so too.
bool looksLikeCorpse = IsCorpseName(name) || HasCorpseFlag(uid);
if (looksLikeCorpse)
{
FileAsCorpse(id, uid, name);
return;
}
// Object not accessible yet — retry (weenie may not be ready). Names and
// positions come from the engine's snapshots, so an object created between two
// snapshots reads as neither. That includes static world objects: a portal
// (0x7xxxxxxx) used to be dropped here for good, so it was missing from the
// radar and "/ub usel <portal>" until a click looked it up (2026-09-29).
if (!hasName && !hasPos)
{
TraceClassify(uid, hasName, hasPos, false, 0u, "noNamePos");
if (uid >= 0x80000000u)
{
int retries = _classifyRetry.TryGetValue(uid, out int r) ? r : 0;
if (retries < MaxClassifyRetries)
{
_classifyRetry[uid] = retries + 1;
_pending.Enqueue(uid);
_retryNext.Enqueue(uid); // retry next tick
}
else
{
// Fast-retry burst exhausted (8 ticks ≈ 10 ms because Tick drains
// 30 pending per pass). Hand off to slow-retry: reset the fast
// Fast-retry burst exhausted (8 ticks, one attempt each). Hand off
// to slow-retry: reset the fast
// counter so the next attempt gets a fresh 8 ticks, and park the
// uid in _slowRetry. FlushSlowRetry re-enqueues it every
// ReclassifyIntervalSec until the engine populates name/position.
_classifyRetry.Remove(uid);
_slowRetry.Add(uid);
if (_classifyGiveupLogCount < MaxClassifyGiveupLogLines)
{
_classifyGiveupLogCount++;
if (_diag.Note(ClassifyGiveup, uid))
_host.Log($"[ReclassifyDiag] 0x{uid:X8} CLASSIFY-GIVEUP retries={retries} (name+pos unreadable across {MaxClassifyRetries} ticks; parked in slow-retry)");
}
}
}
return;
@ -465,13 +525,9 @@ public class WorldObjectCache
AcObjectClass cls;
if (isPackItemGuid || !hasPos)
{
if (looksLikeCorpse)
{
cls = AcObjectClass.Corpse;
}
// Could be pack item, equipped item on 0x8000 range, or spawning dynamic object
// Check item type flags first
else if (_host.TryGetItemType(uid, out uint typeFlags))
if (_host.TryGetItemType(uid, out uint typeFlags))
{
if ((typeFlags & ItemTypeCreature) != 0)
{
@ -485,17 +541,17 @@ public class WorldObjectCache
}
TraceClassify(uid, hasName, hasPos, true, typeFlags, "nopos-item");
cls = ClassifyByItemType(typeFlags);
cls = ClassifyItem(uid, typeFlags);
}
else
{
// No weenie/item-type accessible yet — retry for a few ticks
int retries = _classifyRetry.TryGetValue(uid, out int r) ? r : 0;
TraceClassify(uid, hasName, hasPos, false, 0u, retries < MaxClassifyRetries ? $"nopos-retry r={retries}" : "nopos-giveup");
TraceClassify(uid, hasName, hasPos, false, 0u, retries < MaxClassifyRetries ? "nopos-retry" : "nopos-giveup", retry: retries);
if (retries < MaxClassifyRetries)
{
_classifyRetry[uid] = retries + 1;
_pending.Enqueue(uid); // re-queue
_retryNext.Enqueue(uid); // retry next tick
return;
}
// Gave up retrying — fall through to name heuristics
@ -503,7 +559,10 @@ public class WorldObjectCache
cls = ClassifyInventoryItem(name);
}
if (cls == AcObjectClass.Corpse)
// Portals are world objects: one created before its position is known
// was filed as inventory here, so nothing searching the landscape (e.g.
// /ub closestportal) could find it (2026-09-28).
if (cls == AcObjectClass.Corpse || cls == AcObjectClass.Portal)
{
_creatures.Remove(id);
_inventory.Remove(id);
@ -517,16 +576,6 @@ public class WorldObjectCache
}
else
{
if (looksLikeCorpse)
{
_classifyRetry.Remove(uid);
_creatures.Remove(id);
_inventory.Remove(id);
_landscape.Add(id);
_byId[id] = Make(id, name, AcObjectClass.Corpse);
return;
}
// Has a position — check if it's actually a creature type (equipped items have 0x8000 GUIDs with positions)
bool gotType = _host.TryGetItemType(uid, out uint typeFlags);
TraceClassify(uid, hasName, hasPos, gotType, gotType ? typeFlags : 0u, "pos");
@ -540,12 +589,24 @@ public class WorldObjectCache
return;
}
// Portals were left as Unknown landscape below, so nothing looking
// for ObjectClass.Portal (/ub closestportal, Lua UsePortal) ever
// found one standing in front of it (2026-09-28).
if ((typeFlags & ItemTypePortal) != 0)
{
_classifyRetry.Remove(uid);
_inventory.Remove(id);
_landscape.Add(id);
_byId[id] = Make(id, name, AcObjectClass.Portal);
return;
}
// Non-creature with a position — could be equipped item on 0x8000 range
// or static world object; classify by type flags
if ((typeFlags & (ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer)) != 0)
{
// Item with a world position = equipped or ground-dropped
cls = ClassifyByItemType(typeFlags);
cls = ClassifyItem(uid, typeFlags);
_inventory.Add(id);
_landscape.Remove(id);
_byId[id] = Make(id, name, cls);
@ -560,7 +621,7 @@ public class WorldObjectCache
if (retries < MaxClassifyRetries)
{
_classifyRetry[uid] = retries + 1;
_pending.Enqueue(uid);
_retryNext.Enqueue(uid); // retry next tick
return;
}
_classifyRetry.Remove(uid);
@ -599,6 +660,38 @@ public class WorldObjectCache
}
}
// PublicWeenieDesc._bitfield BF_CORPSE (ObjectDescriptionFlag.Corpse).
private const uint BfCorpse = 0x2000;
/// <summary>The weenie's corpse flag (dynamic objects only; false when the engine can't say).</summary>
private bool HasCorpseFlag(uint uid)
=> uid >= 0x80000000u
&& _host.HasGetObjectBitfield
&& _host.TryGetObjectBitfield(uid, out uint bf)
&& (bf & BfCorpse) != 0;
/// <summary>Files <paramref name="id"/> as a landscape Corpse (caller holds _gate).</summary>
private void FileAsCorpse(int id, uint uid, string? name)
{
_classifyRetry.Remove(uid);
_creatures.Remove(id);
if (_inventory.Remove(id)) _inventoryDirty = true;
_landscape.Add(id);
_byId[id] = Make(id, name ?? string.Empty, AcObjectClass.Corpse);
}
// Bounded log for corpses found filed as something else and moved to Corpse.
private int _corpseRescueLogLines;
private const int MaxCorpseRescueLogLines = 20;
private void LogCorpseRescue(uint uid, string name, AcObjectClass was, string where)
{
if (_corpseRescueLogLines >= MaxCorpseRescueLogLines) return;
_corpseRescueLogLines++;
_host.Log($"[RynthAi] Corpse 0x{uid:X8} '{name}' was filed as {was} ({where}); now a Corpse"
+ (_corpseRescueLogLines == MaxCorpseRescueLogLines ? " (further rescues counted only)" : ""));
}
/// <summary>
/// Re-enqueue every uid that's currently parked in <see cref="_slowRetry"/>. Pairs
/// with the give-up branch of <see cref="TryClassify"/>: when an OnCreateObject-then-
@ -622,16 +715,33 @@ public class WorldObjectCache
/// any that are now recognised as TYPE_CREATURE. Runs every ~2 seconds from Tick().
/// This rescues creatures whose weenie data wasn't available when they were first classified.
/// </summary>
// PublicWeenieDesc._bitfield flags (as ExpressionEngine's BF_PLAYER / BF_ATTACKABLE).
private const uint BfPlayer = 0x8, BfAttackable = 0x10;
private void ReclassifyUnknownDynamics()
{
lock (_gate)
{
List<int>? toPromote = null;
List<int>? toCorpse = null;
List<(int id, string name, AcObjectClass cls)>? statics = null;
foreach (int id in _landscape)
{
uint uid = unchecked((uint)id);
if (uid < 0x80000000u) continue; // static objects never become creatures/corpses
if (uid < 0x80000000u)
{
// Static objects never become creatures/corpses, but one classified before
// its name or type was readable is fixed up here: the name filled in, and
// a portal that read as Unknown becomes a Portal (radar, /ub closestportal).
if (!_byId.TryGetValue(id, out var so) || so.ObjectClass != AcObjectClass.Unknown) continue;
string sName = so.Name;
if (sName.Length == 0 && _host.TryGetObjectName(uid, out string n2) && n2.Length > 0) sName = n2;
AcObjectClass sCls = _host.TryGetItemType(uid, out uint sType) && (sType & ItemTypePortal) != 0
? AcObjectClass.Portal : AcObjectClass.Unknown;
if (sName != so.Name || sCls != so.ObjectClass)
(statics ??= new()).Add((id, sName, sCls));
continue;
}
if (!_byId.TryGetValue(id, out var wo)) continue;
if (wo.ObjectClass == AcObjectClass.Corpse) continue; // already correct
@ -645,8 +755,8 @@ public class WorldObjectCache
// item each pass; IsCorpseName is specific ("X corpse"/"Corpse of X")
// so a live mob cannot be misread as a corpse.
if ((wo.ObjectClass == AcObjectClass.Monster || wo.ObjectClass == AcObjectClass.Unknown)
&& _host.TryGetObjectName(uid, out string maybeCorpse)
&& IsCorpseName(maybeCorpse))
&& ((_host.TryGetObjectName(uid, out string maybeCorpse) && IsCorpseName(maybeCorpse))
|| HasCorpseFlag(uid)))
{
toCorpse ??= new List<int>();
toCorpse.Add(id);
@ -677,6 +787,38 @@ public class WorldObjectCache
toPromote.Add(id);
}
// Corpses filed as inventory. Before 2026-10-03 a corpse classified while its
// position wasn't readable went to the inventory as a Container (its ItemType) and
// stayed there: invisible to looting for good. TryClassify no longer does that, but
// an object filed before its name or flag was readable still can, so the bags in the
// inventory list (a handful) are re-checked here. Packs we carry aren't corpses.
List<(int id, AcObjectClass was)>? invCorpses = null;
foreach (int id in _inventory)
{
uint uid = unchecked((uint)id);
if (uid < 0x80000000u) continue;
if (!_byId.TryGetValue(id, out var wo)) continue;
if (wo.ObjectClass != AcObjectClass.Container && wo.ObjectClass != AcObjectClass.Unknown) continue;
if (IsCorpseName(wo.Name)
|| (_host.TryGetObjectName(uid, out string invName) && IsCorpseName(invName))
|| HasCorpseFlag(uid))
(invCorpses ??= new()).Add((id, wo.ObjectClass));
}
if (invCorpses != null)
{
foreach (var (id, was) in invCorpses)
{
uint uid = unchecked((uint)id);
string n = _host.TryGetObjectName(uid, out string nn) && nn.Length > 0 ? nn : _byId[id].Name;
FileAsCorpse(id, uid, n);
LogCorpseRescue(uid, n, was, "inventory, no position when classified");
}
}
if (statics != null)
foreach (var (id, name, cls) in statics)
_byId[id] = Make(id, name, cls);
if (toCorpse != null)
{
foreach (int id in toCorpse)
@ -703,12 +845,25 @@ public class WorldObjectCache
if (toPromote == null) return;
uint selfId = _host.GetPlayerId();
foreach (int id in toPromote)
{
uint uid = unchecked((uint)id);
_host.TryGetObjectName(uid, out string name);
_creatures.Add(id);
_byId[id] = Make(id, name ?? string.Empty, AcObjectClass.Monster);
// Players are creatures too: under the Decal bridge more objects arrive before their
// type is readable and come through here, and the character and other players were
// promoted to Monster (Lucy listed herself in the Monsters tab, 2026-10-01). The
// weenie bitfield says player (0x8) or not attackable (0x10 clear = NPC).
AcObjectClass cls = AcObjectClass.Monster;
if (uid == selfId)
cls = AcObjectClass.Player;
else if (_host.HasGetObjectBitfield && _host.TryGetObjectBitfield(uid, out uint bf))
{
if ((bf & BfPlayer) != 0) cls = AcObjectClass.Player;
else if ((bf & BfAttackable) == 0) cls = AcObjectClass.Npc;
}
if (cls == AcObjectClass.Monster) _creatures.Add(id);
_byId[id] = Make(id, name ?? string.Empty, cls);
_reclassifySkipState.Remove(uid); // diagnostic state cleared on success
}
@ -754,6 +909,14 @@ public class WorldObjectCache
// Patch empty name on access
if (wo.Name.Length == 0 && _host.TryGetObjectName(unchecked((uint)id), out string n) && n.Length > 0)
{
// A corpse stored before its name was readable becomes a Corpse here.
if (wo.ObjectClass != AcObjectClass.Corpse && IsCorpseName(n))
{
AcObjectClass was = wo.ObjectClass;
FileAsCorpse(id, unchecked((uint)id), n);
LogCorpseRescue(unchecked((uint)id), n, was, "named late");
return _byId[id];
}
wo = Make(id, n, wo.ObjectClass);
_byId[id] = wo;
}
@ -768,7 +931,7 @@ public class WorldObjectCache
return null;
bool isPackItemGuid = uid >= 0xC0000000u;
bool looksLikeCorpse = hasPos && IsCorpseName(name);
bool looksLikeCorpse = IsCorpseName(name) || HasCorpseFlag(uid); // position not needed (see TryClassify)
AcObjectClass cls;
if (looksLikeCorpse)
{
@ -788,15 +951,15 @@ public class WorldObjectCache
// queries qualities → TYPE_CREATURE finally readable → bot sees the
// mob" path. seenCreate=0 here is the strongest signal that the
// engine's CreateObject hook missed this respawn entirely.
if (uid >= 0x80000000u && _indexerRescueLogCount < MaxIndexerRescueDiagLines)
if (uid >= 0x80000000u)
{
_indexerRescueLogCount++;
bool seenCreate = _seenCreateObject.Contains(uid);
_host.Log($"[ReclassifyDiag] 0x{uid:X8} INDEXER-RESCUE name='{name}' flags=0x{typeFlags:X8} seenCreate={(seenCreate ? 1 : 0)}");
if (_diag.Note(IndexerRescue, uid, seenCreate ? 1 : 0))
_host.Log($"[ReclassifyDiag] 0x{uid:X8} INDEXER-RESCUE name='{name}' flags=0x{typeFlags:X8} seenCreate={(seenCreate ? 1 : 0)}");
}
}
else
cls = ClassifyByItemType(typeFlags);
cls = ClassifyItem(uid, typeFlags);
}
else if (isPackItemGuid || !hasPos)
cls = ClassifyInventoryItem(name);
@ -832,6 +995,16 @@ public class WorldObjectCache
return _host.TryGetObjectIntProperty(uid, stype, out int v) ? v : defaultValue;
}
/// <summary>
/// Read an STypeDID property (e.g. a scroll's Spell 28 from its CreateObject header).
/// 0 if the API is unavailable or the property is not set.
/// </summary>
public uint GetDataIdProperty(int id, uint stype)
{
try { return _host.TryGetObjectDataIdProperty(unchecked((uint)id), stype, out uint v) ? v : 0; }
catch { return 0; }
}
/// <summary>
/// Read an STypeFloat property from an object via CBaseQualities::InqFloat.
/// Returns defaultValue if the API is unavailable or the property is not set.
@ -910,6 +1083,31 @@ public class WorldObjectCache
return double.IsFinite(d) ? d : double.MaxValue;
}
/// <summary>
/// <see cref="Distance"/> from a position the caller already read (cell + landblock-local
/// x/y/z, e.g. the player's, once per scan) to object <paramref name="id2"/>, with the same
/// math and the same MaxValue for an unreadable or non-finite position.
/// <paramref name="hasPos"/>/<paramref name="x2"/>/<paramref name="y2"/> return the object's
/// position as read (landblock-local) so the caller needn't read it again.
/// </summary>
public double DistanceFrom(uint cell1, float x1, float y1, float z1, int id2, out bool hasPos, out float x2, out float y2)
{
hasPos = _host.TryGetObjectPosition(unchecked((uint)id2), out uint cell2, out x2, out y2, out float z2);
if (!hasPos)
return double.MaxValue;
float gx1 = ((cell1 >> 24) & 0xFF) * 192f + x1;
float gy1 = ((cell1 >> 16) & 0xFF) * 192f + y1;
float gx2 = ((cell2 >> 24) & 0xFF) * 192f + x2;
float gy2 = ((cell2 >> 16) & 0xFF) * 192f + y2;
float dx = gx1 - gx2;
float dy = gy1 - gy2;
float dz = z1 - z2;
double d = Math.Sqrt(dx * dx + dy * dy + dz * dz);
return double.IsFinite(d) ? d : double.MaxValue;
}
/// <summary>Enumerate objects in player's inventory (no physics position).</summary>
public IEnumerable<WorldObject> GetInventory()
{
@ -1060,13 +1258,100 @@ public class WorldObjectCache
// forceRefresh — the dequip paths gate an AV-risky move, so must not read a
// stale cache before the move.
var inv = cache.GetDirectInventory(forceRefresh: true);
return FindPackFor(inv, playerId, includeMainPack, requireFree);
return FindPackFor(inv, playerId, includeMainPack, requireFree, host);
}
/// <summary>
/// The player is wielding <paramref name="wo"/>. The cached CurrentWieldedLocation /
/// EquippedSlots can read 0 for a wielded weapon (2026-09-28: a Longbow in hand read
/// 0, so the wand swap never stowed it and retried forever with a full pack), so a
/// 0 falls back to the live wielder info.
/// </summary>
public static bool IsWieldedByPlayer(RynthCoreHost host, WorldObject wo)
{
if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0) return true;
if (wo.Values(LongValueKey.EquippedSlots, 0) != 0) return true;
if (!host.HasGetObjectWielderInfo) return false;
uint pid = host.GetPlayerId();
return pid != 0
&& host.TryGetObjectWielderInfo(unchecked((uint)wo.Id), out uint wielder, out _)
&& wielder == pid;
}
/// <summary>
/// Arrows, quarrels and darts. AC files ammo as a missile weapon, so the "put the bow
/// away before the wand" lookups picked the wielded arrows when they came first and
/// took them off instead of the bow (2026-09-29). Slot bits when known, else the name.
/// </summary>
public static bool IsAmmo(WorldObject wo)
{
const int MissileAmmoSlot = 0x00800000;
if ((wo.Values(LongValueKey.Locations, 0) & MissileAmmoSlot) != 0) return true;
if ((wo.Values(LongValueKey.CurrentWieldedLocation, 0) & MissileAmmoSlot) != 0) return true;
// Never a launcher: a weapon whose name happens to say "bolt" must still be put away.
string n = wo.Name ?? "";
if (n.IndexOf("crossbow", StringComparison.OrdinalIgnoreCase) >= 0
|| n.TrimEnd().EndsWith("bow", StringComparison.OrdinalIgnoreCase)) return false;
return AmmoRecipes.IsLooseAmmoName(n, WeaponCategory.Bow)
|| AmmoRecipes.IsLooseAmmoName(n, WeaponCategory.Crossbow)
|| AmmoRecipes.IsLooseAmmoName(n, WeaponCategory.Atlatl);
}
private static bool IsWieldable(WorldObject wo) =>
wo.ObjectClass == AcObjectClass.MeleeWeapon
|| wo.ObjectClass == AcObjectClass.MissileWeapon
|| wo.ObjectClass == AcObjectClass.WandStaffOrb;
/// <summary>
/// Free item slots the player has: the main pack (102) plus every side pack. -1 when a
/// side pack's capacity isn't known yet (callers then don't act on a guess).
/// </summary>
public static int CountFreeItemSlots(RynthCoreHost host, WorldObjectCache? cache)
{
if (cache == null) return -1;
int playerId = unchecked((int)host.GetPlayerId());
if (playerId == 0) return -1;
var inv = cache.GetDirectInventory(forceRefresh: false);
int mainUsed = 0, sideFree = 0;
foreach (var p in inv)
{
if (p.Container != playerId) continue;
if (p.ObjectClass == AcObjectClass.Foci) continue;
if (p.ObjectClass != AcObjectClass.Container)
{
if (p.Values(LongValueKey.EquippedSlots, 0) != 0) continue;
if (IsWieldable(p) && IsWieldedByPlayer(host, p)) continue;
mainUsed++;
continue;
}
if (!string.IsNullOrEmpty(p.Name) && p.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0) continue;
int capacity = p.Values(LongValueKey.ItemsCapacity, 0);
if (capacity <= 0) return -1;
int used = 0;
foreach (var it in inv)
if (it.Container == p.Id && it.ObjectClass != AcObjectClass.Container) used++;
sideFree += Math.Max(0, capacity - used);
}
return Math.Max(0, 102 - mainUsed) + sideFree;
}
private static DateTime _packFullWarnedAt = DateTime.MinValue;
/// <summary>A chat warning that a full pack blocks something, at most once every 5 minutes.</summary>
public static void WarnPackFull(RynthCoreHost host, string what)
{
if ((DateTime.Now - _packFullWarnedAt).TotalMinutes < 5) return;
_packFullWarnedAt = DateTime.Now;
host.WriteToChat($"[RynthAi] Pack full: {what}. Free a slot (salvage, sell or drop); looting keeps {LootReserveFreeSlots} slots free.", 2);
}
/// <summary>The looter stops picking items up below this many free slots, so weapon swaps always have room.</summary>
public const int LootReserveFreeSlots = 2;
// Snapshot overload — caller supplies an already-built inventory list (AutoCram
// reuses its single per-tick GetDirectInventory snapshot here; do NOT re-refresh).
public static int FindPackFor(IReadOnlyList<WorldObject> inv, int playerId,
bool includeMainPack, int requireFree)
bool includeMainPack, int requireFree, RynthCoreHost? host = null)
{
if (inv == null || playerId == 0) return 0;
if (requireFree < 1) requireFree = 1;
@ -1080,7 +1365,8 @@ public class WorldObjectCache
// NOT the 102 item slots, so they're excluded from this count.
if (p.ObjectClass != AcObjectClass.Container
&& p.ObjectClass != AcObjectClass.Foci
&& p.Values(LongValueKey.EquippedSlots, 0) == 0)
&& p.Values(LongValueKey.EquippedSlots, 0) == 0
&& !(host.HasValue && IsWieldable(p) && IsWieldedByPlayer(host.Value, p)))
mainUsed++;
if (p.ObjectClass != AcObjectClass.Container) continue;
// Skip foci — technically containers but reserved for spell components.
@ -1108,6 +1394,30 @@ public class WorldObjectCache
return mainFree > 0 ? playerId : 0;
}
/// <summary>
/// Where a looted item goes: the main pack while it has a free slot, else the side pack
/// with the most room, 0 when nothing has room. The pickup used to be a UseObject, which
/// let the client pick the spot, but a use on a wearable item lying in a corpse is a
/// get-and-wield: jewellery for an empty slot went straight onto the character
/// (2026-10-02). A move needs an explicit target, and the engine refuses a move into a
/// full pack of ours, so this finds one with room.
/// </summary>
public static int FindLootDestination(IReadOnlyList<WorldObject> inv, int playerId, RynthCoreHost? host = null)
{
if (inv == null || playerId == 0) return 0;
int mainUsed = 0; // same tally as FindPackFor
foreach (var p in inv)
{
if (p.Container != playerId) continue;
if (p.ObjectClass == AcObjectClass.Container || p.ObjectClass == AcObjectClass.Foci) continue;
if (p.Values(LongValueKey.EquippedSlots, 0) != 0) continue;
if (host.HasValue && IsWieldable(p) && IsWieldedByPlayer(host.Value, p)) continue;
mainUsed++;
}
if (102 - mainUsed > 0) return playerId;
return FindPackFor(inv, playerId, includeMainPack: false, requireFree: 1, host);
}
/// <summary>
/// Re-reads the name and item type of an object stored with a blank name or an Unknown
/// class, and replaces its entry when either improved. Corpse items are usually created
@ -1131,7 +1441,7 @@ public class WorldObjectCache
if (needClass)
{
if (_host.TryGetItemType(uid, out uint flags) && (flags & ItemTypeCreature) == 0)
cls = ClassifyByItemType(flags);
cls = ClassifyItem(uid, flags);
if (cls == AcObjectClass.Unknown && name.Length > 0)
cls = ClassifyInventoryItem(name);
}
@ -1150,6 +1460,93 @@ public class WorldObjectCache
}
}
/// <summary>
/// Re-reads the item type of <paramref name="id"/> and replaces its entry when the type
/// gives a different class. An object first seen before its type was known is classed by
/// its name, and RefreshIdentity only revisits Unknown ones, so a guess stuck: a quest
/// axe without "Axe" in its name (Silifi, Tungi, Ono...) was "not a weapon" when added to
/// the Items list (2026-10-03). Returns the entry to use (null when not cached).
/// </summary>
public WorldObject? ReclassifyFromItemType(int id)
{
WorldObject? wo;
lock (_gate) _byId.TryGetValue(id, out wo);
if (wo == null) return null;
bool typed = _host.TryGetItemType(unchecked((uint)id), out uint flags);
if (typed && (flags & ItemTypeCreature) != 0)
return wo;
AcObjectClass cls = typed ? ClassifyByItemType(flags) : AcObjectClass.Unknown;
// Custom content can carry a non-weapon item type on something wielded as a weapon
// (a Driftwarden Greataxe, 2026-10-03): its weapon slot or weapon skill decides.
if (cls != AcObjectClass.MeleeWeapon && cls != AcObjectClass.MissileWeapon && cls != AcObjectClass.WandStaffOrb)
{
AcObjectClass bySlot = WeaponClassFromSlot(unchecked((uint)id));
if (bySlot != AcObjectClass.Unknown) cls = bySlot;
}
if (cls == AcObjectClass.Unknown || cls == wo.ObjectClass)
return wo;
lock (_gate)
{
if (!_byId.TryGetValue(id, out var current) || !ReferenceEquals(current, wo))
return current ?? wo;
var fresh = Make(id, wo.Name, cls);
fresh._wieldedLocationDirect = wo._wieldedLocationDirect;
fresh._directContainerId = wo._directContainerId;
fresh._directSlot = wo._directSlot;
fresh.Overlay = wo.Overlay;
_byId[id] = fresh;
return fresh;
}
}
// ValidLocations (STypeInt 9) weapon slots and WeaponSkill (STypeInt 48).
private const int ValidLocationsInt = 9, WeaponSkillInt = 48;
private const uint SlotMeleeWeapon = 0x00100000, SlotMissileWeapon = 0x00400000, SlotTwoHanded = 0x02000000;
/// <summary>ClassifyByItemType, except that an item typed Misc (or nothing) which fits a
/// weapon slot is a weapon: custom content does this (see ReclassifyFromItemType).</summary>
private AcObjectClass ClassifyItem(uint uid, uint flags)
{
AcObjectClass cls = ClassifyByItemType(flags);
// A writable that carries a spell (data id 28) or is named "Scroll ..." is a Scroll, as in
// Decal/VTank, so metas, AutoVendor and loot rules all see "Scroll" (owner, 2026-10-04).
// Other writables (books, notes, journals) stay Book.
if (cls == AcObjectClass.Book && IsSpellScroll(uid)) return AcObjectClass.Scroll;
if (cls == AcObjectClass.Misc || cls == AcObjectClass.Unknown)
{
AcObjectClass bySlot = WeaponClassFromSlot(uid);
if (bySlot != AcObjectClass.Unknown) return bySlot;
}
return cls;
}
private const uint DataIdSpell = 28;
private bool IsSpellScroll(uint uid)
{
if (_host.TryGetObjectDataIdProperty(uid, DataIdSpell, out uint spell) && spell != 0) return true;
return _host.TryGetObjectName(uid, out string name)
&& name.StartsWith("Scroll", StringComparison.OrdinalIgnoreCase);
}
/// <summary>The weapon class an item's equip slot implies (Unknown when it has no weapon slot).
/// A weapon skill with no slot known reads as melee.</summary>
private AcObjectClass WeaponClassFromSlot(uint id)
{
if (!_host.HasGetObjectIntProperty) return AcObjectClass.Unknown;
if (_host.TryGetObjectIntProperty(id, ValidLocationsInt, out int slots) && slots != 0)
{
uint s = unchecked((uint)slots);
if ((s & SlotMissileWeapon) != 0) return AcObjectClass.MissileWeapon;
if ((s & (SlotMeleeWeapon | SlotTwoHanded)) != 0) return AcObjectClass.MeleeWeapon;
return AcObjectClass.Unknown;
}
if (_host.TryGetObjectIntProperty(id, WeaponSkillInt, out int skill) && skill > 0)
return AcObjectClass.MeleeWeapon;
return AcObjectClass.Unknown;
}
public IEnumerable<WorldObject> GetContainedItems(int containerId)
{
if (containerId == 0)
@ -1523,7 +1920,7 @@ public class WorldObjectCache
if (_host.TryGetItemType(uid, out uint flags))
{
isContainer = (flags & ItemTypeContainer) != 0;
cls = ClassifyByItemType(flags);
cls = ClassifyItem(uid, flags);
}
if (cls == AcObjectClass.Unknown)
@ -1579,7 +1976,7 @@ public class WorldObjectCache
public (int Total, int Creatures, int Inventory, int Landscape, int Pending) GetStats()
{
lock (_gate)
return (_byId.Count, _creatures.Count, _inventory.Count, _landscape.Count, _pending.Count);
return (_byId.Count, _creatures.Count, _inventory.Count, _landscape.Count, _pending.Count + _retryNext.Count);
}
// ── Factory ───────────────────────────────────────────────────────────
@ -1654,7 +2051,13 @@ public class WorldObjectCache
ContainsAny(name, "Sword", "Falchion", "Axe", "Mace", "Spear",
"Dagger", "Katar", "Claw", "Club", "Hammer", "Blade",
"Knife", "Lance", "Rapier", "Scimitar", "Estoc", "Cleaver",
"Flail", "Maul", "Glaive", "Halberd", "Pike", "Trident");
"Flail", "Maul", "Glaive", "Halberd", "Pike", "Trident",
// retail names without one of the words above (quest weapons often use these)
"Hatchet", "Silifi", "Tungi", "Shou-ono", "Dolabra", "Lugian Hammer", "Kasrullah",
"Nabut", "Jitte", "Yaoji", "Tachi", "Takuba", "Shamshir", "Kaskara",
"Flamberge", "Jambiya", "Khanjar", "Kukri", "Poniard", "Stiletto", "Cestus",
"Nekode", "Bastone", "Tofun", "Morning Star", "Partizan", "Spadone", "Yari",
"Budiaq", "Naginata", "Quarterstaff", "Bardiche", "Assagai");
private static bool IsClothing(string name) =>
ContainsAny(name, "Coat", "Shirt", "Smock", "Pants", "Pantaloons", "Trousers",

View file

@ -5,6 +5,7 @@ using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
@ -42,6 +43,8 @@ public sealed partial class RynthAiPlugin
private long _busyCountBecamePositiveAt; // when count first went 0→positive
private const long BUSY_TIMEOUT_MS = 10_000; // safety: force-clear if stuck >10s
private const long NameWaitMs = 3_000; // extra wait past the assess window for a corpse item's name
private const long AppraisalWaitMs = 3_000; // extra wait past the assess window for an item's appraisal
private const long AppraisalHoldTimeoutMarginMs = 1_000; // stop holding this long before the corpse timeout
// Wedge detection: when AC's item-action state locks up (server-side, e.g.
// after a corpse pile is opened too fast), EVERY corpse open times out.
@ -66,9 +69,17 @@ public sealed partial class RynthAiPlugin
// re-evaluation pass.
private readonly HashSet<int> _pendingManaStoneIds = new();
// Keep # (KeepUpTo) rules: items approved on this corpse per rule, with their
// stack size, not yet counted in the pack. Same idea as _pendingManaStoneIds.
private readonly Dictionary<string, Dictionary<int, int>> _pendingKeepUpTo = new();
// Same idea for ManaTap candidates: tracks items approved this corpse
// session so we don't approve more than the available empty-stone slots.
private readonly HashSet<int> _pendingManaTapIds = new();
// Action label of an item looted only so ManaStoneManager can drain it. A pickup
// with this label is recorded in ManaStoneManager, whose drain touches nothing else.
private const string ManaTapActionLabel = "ManaTap";
private int _targetCorpseId;
private int _currentLootItemId;
private long _corpseTargetSince;
@ -246,6 +257,15 @@ public sealed partial class RynthAiPlugin
}
if (_corpseIdRequested.Count > 200)
_corpseIdRequested.Clear();
if (_corpseSkipLogged.Count > 200)
_corpseSkipLogged.Clear();
if (_corpseWaitingSince.Count > 200)
{
var old = new List<int>();
foreach (var kvp in _corpseWaitingSince)
if (now - kvp.Value > 10 * 60_000 || _completedCorpses.ContainsKey(kvp.Key)) old.Add(kvp.Key);
foreach (int id in old) _corpseWaitingSince.Remove(id);
}
// _corpseCooldownUntil — remove expired entries
var expiredCooldowns = new List<int>();
@ -294,7 +314,7 @@ public sealed partial class RynthAiPlugin
{
_processedCorpseItems.Clear();
_corpseItemAttempts.Clear();
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear();
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
}
LootDiag($"[RynthAi] Corpse loot: opened container 0x{objectId:X8}.");
_consecutiveLootTimeouts = 0; // a successful open proves AC is responsive again
@ -437,11 +457,15 @@ public sealed partial class RynthAiPlugin
// ── Combat takes priority over claiming NEW corpses ───────────────
// But if we already have an opened container, finish looting it
// (no movement, no conflict with combat).
// Exception: loot starvation (see LootStarveMs) - the arbiter gave this tick to
// Looting because a corpse waited too long and no monster is close.
if (settings.EnableCombat
&& _combatManager?.HasTargets == true
&& !settings.BoostLootPriority
&& !_lootStarveTurn
&& _openedContainerId == 0)
{
LogCorpsesHeldByCombat();
FreezeCorpseTimeout(CorpseNowMs);
return; // Keep our target, just wait — don't ResetCorpseTarget
}
@ -468,6 +492,11 @@ public sealed partial class RynthAiPlugin
long now = CorpseNowMs;
if (_targetCorpseId == 0)
{
// Same gate as HasLootWork: this claim runs every tick whatever the arbiter
// decided, so without it a full pack still claimed the next corpse.
if (IsLootingBlockedByPack(settings))
return;
if (!TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out _))
{
// No corpses in range. STEP 4: nothing to release. The "Looting"
@ -484,10 +513,27 @@ public sealed partial class RynthAiPlugin
_targetCorpseId = corpse.Id;
_corpseTargetSince = now;
_lastCorpseOpenAttemptAt = 0;
_lastOpenAttemptCorpseId = 0; // a new claim: no open sent for it yet
LootDiag($"[RynthAi] Corpse loot: claimed corpse target 0x{(uint)corpse.Id:X8}.");
PauseNavigationForCorpse();
}
// A claim can be tentative: the killer is unknown until the corpse's ID lands.
// Once it says the corpse isn't ours to loot, drop the claim instead of walking
// over and firing opens the server refuses until the 12 s timeout (which also
// fed the loot-wedge counter). TryFindNearestCorpse then skips it as usual.
WorldObject? claimedCorpse = _objectCache[_targetCorpseId];
if (claimedCorpse != null && claimedCorpse.ObjectClass == AcObjectClass.Corpse)
{
CorpseLootDecision claimDecision = EvaluateCorpseLootDecision(claimedCorpse);
if (!claimDecision.ShouldLoot)
{
LootDiag($"[RynthAi] Corpse loot: dropping claim on 0x{(uint)_targetCorpseId:X8} — killer='{claimDecision.KillerName}' mode='{claimDecision.ModeName}' reason='{claimDecision.Reason}'");
ResetCorpseTarget();
return;
}
}
if (HasCorpseTimedOut(settings, now))
{
AbandonCurrentCorpse(now, "timeout");
@ -518,9 +564,21 @@ public sealed partial class RynthAiPlugin
return;
}
// Farther than reach: just use the corpse. The server walks the character to it and turns
// it (as a player's double-click does); steering there ourselves looked awkward and
// turned slowly (owner, 2026-10-04). Our own movement stays off so it can't cancel that
// walk, and the use is re-sent only after about the walk's time, not every 500 ms
// (each re-send restarts the server's walk).
if (distanceMeters > minMeters)
{
ApproachCorpse(_targetCorpseId);
StopCorpseMovement();
long walkMs = (long)(distanceMeters / FarOpenWalkMetersPerSec * 1000.0) + FarOpenSlackMs;
if (_lastCorpseOpenAttemptAt == 0 || now - _lastCorpseOpenAttemptAt >= walkMs)
{
if (_busyCount > 0 && now - _lastCorpseOpenAttemptAt < OpenBusyWaitMaxMs) return;
AttemptOpenCorpse(_targetCorpseId);
_lastCorpseOpenAttemptAt = now;
}
return;
}
@ -557,6 +615,9 @@ public sealed partial class RynthAiPlugin
// already zeroed the phantom count and the open proceeds cleanly. Was 8000ms, which
// cost ~8s of dead time per corpse whenever a cast had leaked the busy count.
private const long OpenBusyWaitMaxMs = 2500;
// Far corpse: the server walks us there (running ~4 m/s; slack for the turn and the open).
private const double FarOpenWalkMetersPerSec = 3.0;
private const long FarOpenSlackMs = 1500;
private bool ShouldDriveCorpseOpening(LegacyUiSettings settings)
{
@ -573,7 +634,8 @@ public sealed partial class RynthAiPlugin
// since that involves no movement and doesn't conflict with combat.
if (settings.EnableCombat
&& _combatManager?.HasTargets == true
&& !settings.BoostLootPriority)
&& !settings.BoostLootPriority
&& !_lootStarveTurn)
{
if (_openedContainerId == 0)
return false;
@ -1035,7 +1097,17 @@ public sealed partial class RynthAiPlugin
pendingDataCount++;
continue;
}
// Timed out but we have a name — fall through and classify best-effort.
// The ID often lands after the assess window (about 350 ms in the live
// logs against a 200 ms window). Judged before it, every stat reads 0, a
// stat rule fails and the item was marked processed and left for good.
// Keep holding it for AppraisalWaitMs, but never into the corpse timeout.
if (now - _corpseIdsRequestedAt < Math.Max(100, settings.LootAssessWindowMs) + AppraisalWaitMs
&& now - _corpseTargetSince < GetCorpseTimeoutMs(settings) - AppraisalHoldTimeoutMarginMs)
{
pendingDataCount++;
continue;
}
// Still no appraisal — fall through and classify best-effort.
}
// Evaluate against loot profile — pure classification, no UseObject.
@ -1100,31 +1172,41 @@ public sealed partial class RynthAiPlugin
if (_busyCount > 0 && !assessTimedOut)
return;
// Keep room for weapon swaps: with a full pack the bow can't be put away to
// switch to the wand, so buffs and spell heals stop (2026-09-28 death). Leave
// the corpse rather than filling the last slots; -1 = side-pack capacity unknown.
int freeSlots = WorldObjectCache.CountFreeItemSlots(Host, _objectCache);
if (freeSlots >= 0 && freeSlots < WorldObjectCache.LootReserveFreeSlots)
{
LootDiag($"[RynthAi] Corpse loot: skipping '{matchItemName}' on 0x{(uint)corpseId:X8} — {freeSlots} free slot(s), keeping {WorldObjectCache.LootReserveFreeSlots} for weapon swaps.");
WorldObjectCache.WarnPackFull(Host, $"looting paused with {freeSlots} free slot(s) so weapon swaps still work");
MarkCorpseCompleted(corpseId);
return;
}
ChatLine($"[RynthAi] Loot rule: {matchItemName} -> [{matchActionLabel}] {matchRuleLabel}");
_currentLootItemId = firstMatchId;
Host.SelectItem(unchecked((uint)firstMatchId));
LootDiag($"[RynthAi] Corpse loot: using 0x{(uint)firstMatchId:X8} '{matchItemName}' from corpse 0x{(uint)corpseId:X8}.");
LootDiag($"[RynthAi] Corpse loot: picking up 0x{(uint)firstMatchId:X8} '{matchItemName}' from corpse 0x{(uint)corpseId:X8}.");
// Jump-loot: jump before MoveItemExternal to cancel the pickup animation.
// Jump-loot: jump before the move to cancel the pickup animation.
// Only jump when multiple items remain (single-item: no animation worth cancelling).
// Guards: needs both hooks, stamina > 5 to cover the cost.
bool moved;
int remainingItems = visibleItemCount - _processedCorpseItems.Count;
bool useJumpLoot = settings.LootJumpEnabled
&& Host.HasJumpNonAutonomous
&& Host.HasMoveItemExternal
&& _vitals.CurrentStamina > 5;
if (useJumpLoot)
{
if (remainingItems > 1)
Host.JumpNonAutonomous(Math.Clamp(settings.LootJumpHeight / 100f, 0.01f, 1f));
moved = Host.MoveItemExternal(unchecked((uint)firstMatchId), _playerId, 0);
}
else
{
moved = Host.UseObject(unchecked((uint)firstMatchId));
}
if (useJumpLoot && remainingItems > 1)
Host.JumpNonAutonomous(Math.Clamp(settings.LootJumpHeight / 100f, 0.01f, 1f));
// Always a move into a pack, never a use: a use on a wearable corpse item is
// get-and-wield, which put salvage jewellery on the character (2026-10-02).
LootPickupResult pickup = SendLootPickup(firstMatchId, matchItemName, corpseId);
if (pickup == LootPickupResult.NoRoom || pickup == LootPickupResult.Refused)
return;
bool moved = pickup == LootPickupResult.Moved || pickup == LootPickupResult.Used;
if (!moved)
{
@ -1140,6 +1222,21 @@ public sealed partial class RynthAiPlugin
_lastLootActionAt = now;
return;
}
// Record a loot-for-tap pickup as soon as it is sent: several resets (busy
// force-clear, corpse closed or reopened) drop the pending pickup without
// confirming it, and the item may still land in the pack. If it never
// does, ManaStoneManager prunes the id.
if (matchActionLabel == ManaTapActionLabel)
_manaStoneManager?.MarkLootedForTap(firstMatchId);
// Same for salvage: the confirm below can be lost the same ways, and an
// unconfirmed salvage item used to sit in the pack for good. The salvage
// manager's sweep queues it once it shows up in the pack.
if (matchIsSalvage)
_salvageManager?.NoteLootedForSalvage(unchecked((uint)firstMatchId), matchItemName);
// Read (the built-in learn rule, or a loot profile's Read action): read it once it
// is in the pack. Noted on send for the same reason as salvage above.
if (matchActionLabel == ScrollLearner.ReadAction)
_scrollLearner?.NoteLooted(firstMatchId, matchItemName, fromProfile: matchRuleLabel != ScrollLearner.RuleLabel);
_currentLootItemMovePending = true;
_currentLootItemMoveRequestedAt = now;
_currentLootItemMoveAttempts = 1;
@ -1203,7 +1300,10 @@ public sealed partial class RynthAiPlugin
return; // Client is busy — don't queue retry
Host.SelectItem(unchecked((uint)_currentLootItemId));
bool retried = Host.UseObject(unchecked((uint)_currentLootItemId));
LootPickupResult retry = SendLootPickup(_currentLootItemId, _currentLootItemName, _openedContainerId);
if (retry == LootPickupResult.NoRoom || retry == LootPickupResult.Refused)
return; // SendLootPickup finished the item / corpse
bool retried = retry == LootPickupResult.Moved || retry == LootPickupResult.Used;
_currentLootItemMoveAttempts++;
_currentLootItemMoveRequestedAt = now;
_lastLootActionAt = now;
@ -1248,6 +1348,34 @@ public sealed partial class RynthAiPlugin
return false;
}
/// <summary>
/// Sends the pickup for a corpse item (<see cref="LootPickup"/>: a move into a pack,
/// never a use). NoRoom finishes the corpse like the free-slot check does; Refused
/// leaves the item. Both reset the current item, so the caller just returns.
/// </summary>
private LootPickupResult SendLootPickup(int itemId, string itemName, int corpseId)
{
LootPickupResult r = LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out uint dest);
switch (r)
{
case LootPickupResult.Moved:
LootDiag($"[RynthAi] Corpse loot: moving 0x{(uint)itemId:X8} '{itemName}' into {(dest == _playerId ? "the main pack" : $"pack 0x{dest:X8}")}.");
break;
case LootPickupResult.NoRoom:
LootDiag($"[RynthAi] Corpse loot: no pack has a free slot for '{itemName}' on 0x{(uint)corpseId:X8}; leaving the corpse.");
WorldObjectCache.WarnPackFull(Host, "looting stopped, no pack has a free slot");
ResetCurrentLootItem();
MarkCorpseCompleted(corpseId);
break;
case LootPickupResult.Refused:
LootDiag($"[RynthAi] Corpse loot: leaving '{itemName}' 0x{(uint)itemId:X8} — the engine has no move call and a use would put it on.");
_processedCorpseItems.Add(itemId);
ResetCurrentLootItem();
break;
}
return r;
}
private void ConfirmCurrentLootItemMoved(long now, string reason)
{
if (_currentLootItemId == 0)
@ -1261,6 +1389,10 @@ public sealed partial class RynthAiPlugin
if (_currentLootItemIsSalvage)
_salvageManager?.EnqueueItem(unchecked((uint)_currentLootItemId));
// Refresh the loot-for-tap record so its arrival grace counts from now.
if (_currentLootItemActionLabel == ManaTapActionLabel)
_manaStoneManager?.MarkLootedForTap(_currentLootItemId);
ResetCurrentLootItem();
_lastLootActionAt = now;
}
@ -1286,12 +1418,23 @@ public sealed partial class RynthAiPlugin
/// </summary>
private bool HasLootWork(LegacyUiSettings settings, long nowMs)
{
_lootStarved = false;
if (!settings.IsMacroRunning || !settings.EnableLooting)
return false;
// Already committed to a body, or mid-loot with the container open.
if (_openedContainerId != 0 || _targetCorpseId != 0 || _corpseAutorunActive)
{
int current = _targetCorpseId != 0 ? _targetCorpseId : _openedContainerId;
_lootStarved = current != 0
&& _corpseWaitingSince.TryGetValue(current, out long since)
&& CorpseNowMs - since >= LootStarveMs;
return true;
}
// No room anywhere: don't start on another corpse (IsPackFull says so once in chat).
if (IsLootingBlockedByPack(settings))
return false;
// Loot grace: combat just ended and the corpse CreateObject has not
// arrived yet. Hold Looting across that gap so nav doesn't walk away
@ -1306,6 +1449,14 @@ public sealed partial class RynthAiPlugin
return HasUnlootedCorpsesInRange(maxMeters);
}
/// <summary>
/// Stop Looting When Pack Full: no free slot anywhere, or fewer than the weapon-swap
/// reserve. Below the reserve the pickup gate refuses every item, so a new corpse was
/// only walked to, opened and given up on (its loot skipped for good).
/// </summary>
private bool IsLootingBlockedByPack(LegacyUiSettings settings)
=> settings.StopLootingWhenPackFull && (IsPackFull() || IsBelowLootReserve());
// STEP 4/5: IsCorpseNavigationClaimActive is gone. It answered "should loot
// block nav?", which was only ever a question because nav and loot each
// decided for themselves whether to run. The arbiter answers it once now,
@ -1315,9 +1466,27 @@ public sealed partial class RynthAiPlugin
// BotAction=="Looting" gap check became unnecessary once the string stopped
// being a lock that someone had to remember to release.
/// <summary>Returns true if at least one lootable, non-completed corpse is within range.</summary>
// -- Loot starvation (2026-10-03) ---------------------------------------
// Combat outranks looting, and on a busy spawn there is always a monster inside
// MonsterRange, so a corpse could wait behind combat until the area emptied (by which
// time nav had often moved on). A lootable corpse in range that has waited
// LootStarveMs gets a turn as soon as no monster is within LootStarveCloseYards.
internal const long LootStarveMs = 8000;
internal const double LootStarveCloseYards = 5.0;
private readonly Dictionary<int, long> _corpseWaitingSince = new(); // lootable corpse first seen in range
private readonly List<int> _lootableInRange = new(); // last scan's lootable corpses in range
private readonly HashSet<int> _corpseSkipLogged = new(); // once-per-corpse "why not looted" lines
private bool _lootStarved; // HasLootWork: the current/in-range corpse has waited LootStarveMs
private bool _lootStarveTurn; // the arbiter gave Looting this tick because of starvation
/// <summary>
/// Returns true if at least one lootable, non-completed corpse is within range. Also
/// records when each lootable corpse was first seen in range (loot starvation), and
/// logs once per corpse when one of your own kills is lootable but out of range.
/// </summary>
private bool HasUnlootedCorpsesInRange(double maxMeters)
{
_lootableInRange.Clear();
if (_objectCache == null || _playerId == 0)
return false;
@ -1331,15 +1500,53 @@ public sealed partial class RynthAiPlugin
continue;
if (_corpseCooldownUntil.TryGetValue(candidate.Id, out long blockedUntil) && blockedUntil > now)
continue;
if (!ShouldLootCorpse(candidate))
CorpseLootDecision decision = EvaluateCorpseLootDecision(candidate);
if (!decision.ShouldLoot)
continue;
double dist = _objectCache.Distance(playerId, candidate.Id);
if (dist <= maxMeters)
return true;
{
_lootableInRange.Add(candidate.Id);
if (!_corpseWaitingSince.ContainsKey(candidate.Id))
_corpseWaitingSince[candidate.Id] = now;
if (now - _corpseWaitingSince[candidate.Id] >= LootStarveMs)
_lootStarved = true;
}
else if (dist != double.MaxValue && IsOwnKill(decision) && _corpseSkipLogged.Add(candidate.Id))
{
LootDiag($"[RynthAi] Corpse loot: own corpse 0x{(uint)candidate.Id:X8} '{candidate.Name}' is out of loot range (d={dist:0.0}m > {maxMeters:0.0}m); not walking back for it.");
}
}
return false;
return _lootableInRange.Count > 0;
}
/// <summary>
/// The arbiter's LootStarved input: looting wants the tick, combat wants it too, a corpse
/// has waited LootStarveMs (HasLootWork set _lootStarved this tick), and no monster is
/// within LootStarveCloseYards. Melee fights keep combat in charge (the mob is on you).
/// </summary>
private bool IsLootStarvedTurn(bool wantLoot, bool wantCombat)
=> wantLoot && wantCombat && _lootStarved
&& _combatManager?.HasCloseThreat(LootStarveCloseYards) != true;
private static bool IsOwnKill(CorpseLootDecision d)
=> !string.IsNullOrWhiteSpace(d.KillerName) && !string.IsNullOrWhiteSpace(d.PlayerName)
&& NormalizeCharName(d.KillerName).Equals(NormalizeCharName(d.PlayerName), StringComparison.OrdinalIgnoreCase);
/// <summary>Once per corpse: a lootable corpse in range is waiting because combat holds the tick.</summary>
private void LogCorpsesHeldByCombat()
{
if (_lootableInRange.Count == 0) return;
long now = CorpseNowMs;
foreach (int id in _lootableInRange)
{
if (!_corpseSkipLogged.Add(id)) continue;
long waited = _corpseWaitingSince.TryGetValue(id, out long since) ? now - since : 0;
LootDiag($"[RynthAi] Corpse loot: corpse 0x{(uint)id:X8} waits for combat (targets in range, waited {waited / 1000.0:0.0}s); "
+ $"it gets a turn after {LootStarveMs / 1000}s with no monster within {LootStarveCloseYards:0} yd, or when the fight ends.");
}
}
private void PauseNavigationForCorpse()
@ -1350,6 +1557,14 @@ public sealed partial class RynthAiPlugin
// the corpse claim through them.
if (_navStopIssued && _navStoppedFor == BotActivity.Looting)
return;
// Only while Looting owns the tick (then OnTick's StopNavFor(_activity) already did
// this). While Combat owned the tick and an opened corpse was being finished, OnTick
// stopped nav "for Combat" and this stopped it "for Looting": the owner flipped every
// tick, so Stop + StopCompletely went out twice a tick, 60 times a second, flooding
// AC's main-thread queue (thousands of dropped actions, mid-attack stops, and a
// launcher killed the client for it, 2026-10-01).
if (_activity != BotActivity.Looting)
return;
StopNavFor(BotActivity.Looting);
@ -1369,6 +1584,15 @@ public sealed partial class RynthAiPlugin
isSalvage = false;
ruleLabel = string.Empty;
// Learn unknown spells (VTank ReadUnknownScrolls): a built-in rule ahead of the loot
// profile, as in VTank. A scroll of a spell we don't know and can learn is looted to read.
if (_scrollLearner != null && _scrollLearner.ShouldLootFromCorpse(item, out string learnRule))
{
actionLabel = ScrollLearner.ReadAction;
ruleLabel = learnRule;
return true;
}
// Consumable override — checked before loot profile. Stone detection is
// centralized in ManaStoneManager.IsManaStone so this loot gate and the
// KeepCount tally below use one predicate: named-rule match if the user
@ -1448,10 +1672,19 @@ public sealed partial class RynthAiPlugin
}
return false;
}
ruleLabel = string.IsNullOrWhiteSpace(nativeRule.Name) ? "rule" : nativeRule.Name.Trim();
if (nativeAction == LootAction.Read && IsReadOfNonScroll(item, ruleLabel))
return false;
if (nativeAction == LootAction.KeepUpTo)
{
var rule = nativeRule;
if (!UnderKeepCap("n:" + ruleLabel, ruleLabel, item, rule.KeepCount,
inv => LootEvaluator.Matches(rule, inv, _charSkills)))
return false;
}
_corpseItemsMatched++;
actionLabel = nativeAction.ToString();
isSalvage = nativeAction == LootAction.Salvage;
ruleLabel = string.IsNullOrWhiteSpace(nativeRule.Name) ? "rule" : nativeRule.Name.Trim();
return true;
}
@ -1461,17 +1694,7 @@ public sealed partial class RynthAiPlugin
_corpseItemsEvaluated++;
VTankLootContext lootCtx = new(Host, _playerId) { Cache = _objectCache };
VTankLootRule? matchedRule = null;
int matchedRuleIndex = -1;
for (int ri = 0; ri < vtankProfile.Rules.Count; ri++)
{
if (VTankLootEvaluator.Match(vtankProfile.Rules[ri], item, lootCtx))
{
matchedRule = vtankProfile.Rules[ri];
matchedRuleIndex = ri;
break;
}
}
VTankLootRule? matchedRule = VTankLootEvaluator.FirstMatch(vtankProfile, item, lootCtx, out int matchedRuleIndex);
if (matchedRule == null)
{
@ -1483,20 +1706,129 @@ public sealed partial class RynthAiPlugin
return false;
}
_corpseItemsMatched++;
ruleLabel = string.IsNullOrWhiteSpace(matchedRule.Name)
? $"#{matchedRuleIndex}"
: matchedRule.Name.Trim();
if (matchedRule.Action == VTankLootAction.Read && IsReadOfNonScroll(item, ruleLabel))
return false;
if (matchedRule.Action == VTankLootAction.KeepUpTo)
{
var rule = matchedRule;
if (!UnderKeepCap("v:" + matchedRuleIndex + ":" + ruleLabel, ruleLabel, item, rule.KeepCount ?? 0,
inv => VTankLootEvaluator.Match(rule, inv, lootCtx)))
return false;
}
_corpseItemsMatched++;
actionLabel = matchedRule.Action.ToString();
isSalvage = matchedRule.Action == VTankLootAction.Salvage;
return true;
}
private readonly HashSet<int> _readNonScrollLogged = new();
/// <summary>
/// A loot profile's Read action on something that isn't a scroll. VTank: "Lootplugin
/// attempted to classify item ... for reading, but that item does not appear to be a
/// scroll. Ignoring it." The item is left, with one log line.
/// </summary>
private bool IsReadOfNonScroll(WorldObject item, string ruleLabel)
{
if (ScrollLearner.LooksLikeScroll(item)) return false;
if (_readNonScrollLogged.Count > 1000) _readNonScrollLogged.Clear();
if (_readNonScrollLogged.Add(item.Id))
Host.Log($"[Learn] loot rule '{ruleLabel}' says Read, but '{item.Name}' isn't a scroll - leaving it");
return true;
}
/// <summary>
/// Keep # (KeepUpTo): loot only while the pack holds fewer than
/// <paramref name="cap"/> of what the rule matches, counting whole stacks, plus
/// items already approved on this corpse that haven't reached the pack yet.
/// A matching Keep # rule used to loot everything, like a plain Keep.
/// </summary>
private bool UnderKeepCap(string key, string ruleLabel, WorldObject item, int cap, Func<WorldObject, bool> matches)
{
if (!_pendingKeepUpTo.TryGetValue(key, out var pending))
_pendingKeepUpTo[key] = pending = new Dictionary<int, int>();
if (pending.ContainsKey(item.Id)) return true; // approved on an earlier pass
// Whole stacks in the pack that the rule matches, plus approved-but-not-in-the-pack-yet
// items. Approved ones that no longer exist are skipped: a looted stack merges into a
// pack stack and is deleted, and is already counted. (LootKeepCap holds the arithmetic.)
int have = LootKeepCap.CountHave(
_objectCache?.GetDirectInventory(forceRefresh: true),
matches,
pending,
id => _objectCache?[id] != null);
int stack = LootKeepCap.StackOf(item);
if (!LootKeepCap.UnderCap(have, cap))
{
ChatLine($"[RynthAi] Keep # '{ruleLabel}': have {have}/{cap} — leaving {item.Name}.");
return false;
}
pending[item.Id] = stack;
ChatLine($"[RynthAi] Keep # '{ruleLabel}': have {have}/{cap} — looting {item.Name}{(stack > 1 ? " x" + stack : "")}.");
return true;
}
// ManaStoneManager asks before draining an inventory item (the drain destroys it).
// Cached per item: a big VTank profile is costly to run on every think tick.
private readonly Dictionary<int, (bool Kept, long At)> _lootKeptCache = new();
private const long LootKeptCacheMs = 60_000;
/// <summary>
/// True when a Keep or Keep # rule in the active loot profile matches the item.
/// Pure: no pending sets, counters or chat (unlike ClassifyItemAgainstProfile).
/// </summary>
private bool IsKeptByLootProfile(WorldObject item)
{
long now = CorpseNowMs;
if (_lootKeptCache.TryGetValue(item.Id, out var c) && now - c.At < LootKeptCacheMs)
return c.Kept;
bool kept;
string path = (_dashboard?.Settings?.CurrentLootPath ?? string.Empty).Trim().Trim('"');
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
kept = false; // no profile: the loaders would print a chat line on every call
else
{
try
{
if (TryLoadNativeLootProfile(out LootProfile nativeProfile, out _))
{
var (action, rule) = LootEvaluator.Classify(nativeProfile, item, _charSkills);
kept = rule != null && (action == LootAction.Keep || action == LootAction.KeepUpTo);
}
else if (TryLoadLootProfile(string.Empty, out VTankLootProfile vtankProfile, out _))
{
kept = false;
VTankLootContext ctx = new(Host, _playerId) { Cache = _objectCache };
foreach (var rule in vtankProfile.Rules)
{
if (!VTankLootEvaluator.Match(rule, item, ctx)) continue;
kept = rule.Action == VTankLootAction.Keep || rule.Action == VTankLootAction.KeepUpTo;
break;
}
}
else
kept = false;
}
catch { kept = true; } // can't tell: don't destroy it
}
if (_lootKeptCache.Count > 1000) _lootKeptCache.Clear();
_lootKeptCache[item.Id] = (kept, now);
return kept;
}
/// <summary>
/// Loot-for-tap fallback: when an item doesn't match any loot rule but it
/// holds at least the configured mana threshold AND the player has an
/// uncharged mana stone in inventory, loot the item so ManaStoneManager
/// can drain it (which destroys the item and charges the stone).
/// can drain it (which destroys the item and charges the stone). This is the
/// only way an item becomes a tap target: the pickup (label ManaTap) is
/// recorded via ManaStoneManager.MarkLootedForTap.
/// </summary>
private bool TryClassifyAsManaTap(WorldObject item, LegacyUiSettings settings,
out string actionLabel, out string ruleLabel)
@ -1519,7 +1851,7 @@ public sealed partial class RynthAiPlugin
// or re-counting against the quota.
if (_pendingManaTapIds.Contains(item.Id))
{
actionLabel = "ManaTap";
actionLabel = ManaTapActionLabel;
ruleLabel = $"ManaTap (mana={curMana} ≥ {threshold})";
return true;
}
@ -1530,7 +1862,7 @@ public sealed partial class RynthAiPlugin
int freeSlots = _manaStoneManager.FreeEmptyStoneSlots() - _pendingManaTapIds.Count;
if (freeSlots <= 0) return false;
actionLabel = "ManaTap";
actionLabel = ManaTapActionLabel;
ruleLabel = $"ManaTap (mana={curMana} ≥ {threshold})";
ChatLine($"[RynthAi] Mana tap candidate: '{item.Name}' (mana {curMana}, slot {_pendingManaTapIds.Count + 1}) — looting to drain.");
_pendingManaTapIds.Add(item.Id);
@ -1547,11 +1879,17 @@ public sealed partial class RynthAiPlugin
/// </summary>
private bool ItemNeedsAppraisalForLoot(WorldObject item)
{
// The ManaTap fallback (run when no rule matches) reads CurrentMana, which only
// the appraisal carries, so with tapping on every item waits for its ID.
var tapSettings = _dashboard?.Settings;
bool manaTapNeedsId = tapSettings != null && tapSettings.EnableManaTapping
&& tapSettings.ManaTapMinMana > 0 && _manaStoneManager != null;
if (TryLoadNativeLootProfile(out LootProfile nativeProfile, out _))
return NativeProfileNeedsAppraisalForClass(nativeProfile, item.ObjectClass);
return manaTapNeedsId || NativeProfileNeedsAppraisalForClass(nativeProfile, item.ObjectClass);
if (TryLoadLootProfile(string.Empty, out VTankLootProfile vtankProfile, out _))
return VTankProfileNeedsAppraisalForClass(vtankProfile, item.ObjectClass);
return manaTapNeedsId || VTankProfileNeedsAppraisalForClass(vtankProfile, item.ObjectClass);
return false; // No active profile — no ID request needed
}
@ -1570,7 +1908,9 @@ public sealed partial class RynthAiPlugin
if (cond is ObjectClassCondition occ)
{
hasClassFilter = true;
if ((AcObjectClass)(int)occ.ObjectClass == cls)
if ((AcObjectClass)(int)occ.ObjectClass == cls
|| ((AcObjectClass)(int)occ.ObjectClass == AcObjectClass.Scroll && cls == AcObjectClass.Book) // a scroll not yet known as one
|| ((AcObjectClass)(int)occ.ObjectClass == AcObjectClass.Book && cls == AcObjectClass.Scroll)) // Book rules from when scrolls filed as Book
classMatches = true;
}
}
@ -1598,8 +1938,10 @@ public sealed partial class RynthAiPlugin
private static bool VTankProfileNeedsAppraisalForClass(VTankLootProfile profile, AcObjectClass cls)
{
// Requirement types that need appraisal data from the server.
// 0 = SpellNameMatch: the item's spell list comes from the appraisal, so a
// cantrip rule ("Legendary") never matched a pre-classified item.
static bool TypeNeedsAppraisal(int t) => t is
2 or 3 or 4 or 5 or 6 or 8 or 9 or 10 or 11 or 12 or 13 or
0 or 2 or 3 or 4 or 5 or 6 or 8 or 9 or 10 or 11 or 12 or 13 or
14 or 15 or 16 or 17 or 2000 or 2001 or 2003 or 2005 or 2006 or 2007 or 2008;
int targetClass = (int)cls;
@ -1621,7 +1963,8 @@ public sealed partial class RynthAiPlugin
&& int.TryParse(cond.DataLines[0].Trim(),
System.Globalization.NumberStyles.Integer,
System.Globalization.CultureInfo.InvariantCulture, out int cls2)
&& cls2 == targetClass)
&& (cls2 == targetClass || (cls2 == (int)AcObjectClass.Scroll && cls == AcObjectClass.Book)
|| (cls2 == (int)AcObjectClass.Book && cls == AcObjectClass.Scroll))) // scrolls once filed as Book
classMatches = true;
}
else if (TypeNeedsAppraisal(cond.NodeType))
@ -1647,7 +1990,7 @@ public sealed partial class RynthAiPlugin
_processedCorpseItems.Clear();
_corpseItemAttempts.Clear();
_corpseIdsRequested = false;
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear();
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
ResetCurrentLootItem();
// Clear container state immediately. Do NOT send UseObject(corpse) to close it —
@ -1709,6 +2052,26 @@ public sealed partial class RynthAiPlugin
if (!TryGetHeadingToObject(corpseId, out double desiredDeg, out double absError, out double signedError))
return;
// Turn the way nav does (fast servo, turn in place on a big turn, steer while running).
if (_navigationEngine != null && Host.HasTurnToHeading)
{
ClearCorpseTurnMotions();
if (!_navigationEngine.ServoToward(desiredDeg))
{
if (_corpseAutorunActive) { Host.SetAutoRun(false); _corpseAutorunActive = false; }
return;
}
long nowMs = CorpseNowMs;
if (!_corpseAutorunActive || nowMs - _lastCorpseApproachHeartbeatAt >= 500)
{
Host.SetAutoRun(true);
_corpseAutorunActive = true;
_lastCorpseApproachHeartbeatAt = nowMs;
}
return;
}
// Fallback (no TurnToHeading on this host): the old motion-key turn.
if (absError > 18.0)
{
StopCorpseMovement();
@ -1761,11 +2124,16 @@ public sealed partial class RynthAiPlugin
_corpseAutorunActive = false;
}
// Last corpse an open was sent for (AbandonCurrentCorpse: was this a failed open,
// or a corpse the bot never reached?).
private int _lastOpenAttemptCorpseId;
private void AttemptOpenCorpse(int corpseId)
{
_lastOpenAttemptCorpseId = corpseId;
StopCorpseMovement();
Host.SelectItem(unchecked((uint)corpseId));
Host.UseObject(unchecked((uint)corpseId));
Host.UseFor(unchecked((uint)corpseId), "Loot", "open the claimed corpse");
LootDiag($"[RynthAi] Corpse loot: attempting open for 0x{(uint)corpseId:X8}.");
}
@ -1820,7 +2188,7 @@ public sealed partial class RynthAiPlugin
{
_processedCorpseItems.Clear();
_corpseItemAttempts.Clear();
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear();
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
}
_targetCorpseId = rawOpen;
@ -1853,7 +2221,7 @@ public sealed partial class RynthAiPlugin
ResetCurrentLootItem();
_processedCorpseItems.Clear();
_corpseItemAttempts.Clear();
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear();
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
}
private void HandleCorpseObjectDeleted(uint objectId)
@ -1868,6 +2236,8 @@ public sealed partial class RynthAiPlugin
_corpseCooldownUntil.Remove(sid);
_ownershipSkipLogged.Remove(sid);
_corpseIdRequested.Remove(sid);
_corpseSkipLogged.Remove(sid);
_corpseWaitingSince.Remove(sid);
// If this is the corpse we were actively looting (container was open and we received
// at least one inventory update), mark it completed before resetting. Without this,
@ -2009,7 +2379,8 @@ public sealed partial class RynthAiPlugin
// instead; after a few never-opened abandons, give up for real so an
// unreachable corpse can't cycle forever.
bool wasOpened = _openedContainerId == corpseId;
int abandons = _corpseAbandonCounts.TryGetValue(corpseId, out int n) ? n + 1 : 1;
bool openWasSent = wasOpened || _lastOpenAttemptCorpseId == corpseId;
int abandons =_corpseAbandonCounts.TryGetValue(corpseId, out int n) ? n + 1 : 1;
_corpseAbandonCounts[corpseId] = abandons;
if (wasOpened || abandons >= 3)
{
@ -2037,7 +2408,10 @@ public sealed partial class RynthAiPlugin
// Track open timeouts to detect a wedged item-action state. A successful
// open resets this counter; a run of timeouts means AC stopped accepting
// item actions (the "you can only move or use one item at a time" lock).
if (reason.IndexOf("timeout", StringComparison.OrdinalIgnoreCase) >= 0)
// Only when an open was actually sent: a corpse the bot never reached (autorun
// into a wall, a body on a ledge) says nothing about AC's item-action state,
// and three of those in a row fired the full wedge reset.
if (openWasSent && reason.IndexOf("timeout", StringComparison.OrdinalIgnoreCase) >= 0)
{
_consecutiveLootTimeouts++;
if (_consecutiveLootTimeouts >= LootWedgeThreshold)
@ -2060,13 +2434,16 @@ public sealed partial class RynthAiPlugin
if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat);
if (Host.HasStopCompletely) Host.StopCompletely();
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
// The lock is client-side: AC's pending-item-request slot or attacking
// flag (see the engine's ClientActionGates). Open both now.
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc unlockactions");
_busyCount = 0;
_busyCountLastIncrementAt = 0;
_busyCountBecamePositiveAt = 0;
if (_combatManager != null) _combatManager.BusyCount = 0;
if (_buffManager != null) _buffManager.BusyCount = 0;
ChatLine($"[RynthAi] WEDGE: {LootWedgeThreshold} corpse opens timed out — AC item-actions are locked. Halting looting {LootWedgeHaltMs / 1000}s and resetting. If equip/loot stays stuck, RELOG (server-side lock — /ra panic can't clear it).");
ChatLine($"[RynthAi] WEDGE: {LootWedgeThreshold} corpse opens timed out — AC item-actions are locked. Halting looting {LootWedgeHaltMs / 1000}s and unlocking. If equip/loot stays stuck, /rc actionstate shows what the client is waiting on.");
Log($"[RynthAi] LOOT WEDGE detected ({LootWedgeThreshold} consecutive open timeouts) — halt {LootWedgeHaltMs}ms + reset fired.");
}

View file

@ -0,0 +1,120 @@
using System;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.CreatureData;
/// <summary>
/// Aelrynth's difficulty tier where the player stands, and which server this is (2026-10-03).
///
/// Aelrynth's awakened worlds and scaled dungeon copies hold the same monsters as real Dereth -
/// same names, same wcids - with health, skills and damage scaled 5% a tier (resistances and
/// weaknesses are not). Every monster in one copy or world shares one tier. The server tells
/// the player's own client that tier as PropertyInt 9051 on the player (Aeshnidae.AwakenedRewards
/// TierFeed.cs): a private update on login, teleport and every change; 0 = real Dereth.
///
/// The rule: on any server other than Aelrynth this is inert - <see cref="Current"/> is 0 and
/// <see cref="Active"/> false - so every store keyed by tier behaves exactly as before. On
/// Aelrynth it also stays inert until the property has been seen this login (an older server
/// build that does not send it changes nothing either).
///
/// Server detection matches RynthOracle's (Data/ServerIdentity.cs) older-engine path: the world
/// name the server announced (Aelrynth's live world is still named "Aeshnidae"; both names, and
/// the staging world, count), else the Bank mod's player properties 9101-9103, which only
/// Aelrynth sends. Engine API v75 adds GetServerInfo (the engine's own verdict); when the SDK
/// this builds against has it, it should be asked first, as RynthOracle does.
/// </summary>
internal sealed class AwakenedTier
{
/// <summary>PropertyInt 9051 on the player: the difficulty tier where they stand.</summary>
public const uint TierProperty = 9051;
/// <summary>The server's scaling per tier (InstancesNoDat DifficultyPercentPerEnlightenment, 5.0).</summary>
public const double PercentPerTier = 5.0;
private const uint QuadRadianceEarned = 9101, QuadLuminanceBanked = 9102, QuadLuminanceDrawn = 9103;
private volatile bool _aelrynth;
private volatile bool _seen;
private volatile int _tier;
private string _serverKey = "";
private long _nextRefreshMs;
/// <summary>On Aelrynth (live or staging), by the world name or the Bank properties.</summary>
public bool OnAelrynth => _aelrynth;
/// <summary>The tier property has been seen this login.</summary>
public bool Seen => _seen;
/// <summary>The tier feature is in force: on Aelrynth and the property seen. Off everywhere else.</summary>
public bool Active => _aelrynth && _seen;
/// <summary>The tier where the player stands; 0 whenever <see cref="Active"/> is false.</summary>
public int Current => Active ? _tier : 0;
/// <summary>
/// The server's key for per-server data (creatures.json): "Aelrynth" for every Aelrynth
/// world name (live "Aeshnidae", "Aelrynth", "Aeshnidae Staging"), else the world name made
/// safe for a folder name; "" while unknown.
/// </summary>
public string ServerKey => _serverKey;
/// <summary>The multiplier a tier puts on a monster's health: 1 + 5% per tier.</summary>
public static double HealthScale(int tier) => tier <= 0 ? 1.0 : 1.0 + PercentPerTier / 100.0 * tier;
/// <summary>Logout: nothing carries to the next login (it may be another server).</summary>
public void Reset()
{
_aelrynth = false;
_seen = false;
_tier = 0;
_serverKey = "";
_nextRefreshMs = 0;
}
/// <summary>Re-reads the server and the tier, at most once a second. Pump thread.</summary>
public void Refresh(RynthCoreHost host, uint playerId, bool force = false)
{
long now = Environment.TickCount64;
if (!force && now < _nextRefreshMs) return;
_nextRefreshMs = now + 1000;
try
{
string world = host.HasGetWorldName && host.TryGetWorldName(out string w) ? (w ?? "").Trim() : "";
bool aelrynth = IsAelrynthWorld(world)
|| (playerId != 0 && host.HasGetObjectQuadProperty
&& (host.TryGetObjectQuadProperty(playerId, QuadRadianceEarned, out _)
|| host.TryGetObjectQuadProperty(playerId, QuadLuminanceBanked, out _)
|| host.TryGetObjectQuadProperty(playerId, QuadLuminanceDrawn, out _)));
_aelrynth = aelrynth;
_serverKey = aelrynth ? "Aelrynth" : SafeKey(world);
if (aelrynth && playerId != 0 && host.HasGetObjectIntProperty
&& host.TryGetObjectIntProperty(playerId, TierProperty, out int tier))
{
_tier = Math.Max(0, tier);
_seen = true;
}
}
catch { }
}
/// <summary>Aelrynth's world names: "Aelrynth...", or "Aeshnidae..." (its earlier name, still the live config's).</summary>
public static bool IsAelrynthWorld(string? world)
{
if (string.IsNullOrWhiteSpace(world)) return false;
string w = world.Trim();
return w.StartsWith("Aelrynth", StringComparison.OrdinalIgnoreCase)
|| w.StartsWith("Aeshnidae", StringComparison.OrdinalIgnoreCase);
}
/// <summary>A world name as a folder name (the SettingsProfiles rule); "" for none.</summary>
public static string SafeKey(string? world)
{
if (string.IsNullOrWhiteSpace(world)) return "";
var sb = new System.Text.StringBuilder(world.Length);
foreach (char c in world.Trim())
sb.Append(char.IsLetterOrDigit(c) || c == '\'' || c == '-' ? c : '_');
return sb.ToString();
}
}

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace RynthCore.Plugin.RynthAi.CreatureData;
@ -16,7 +17,16 @@ public sealed class CreatureProfile
public int CreatureType { get; set; }
/// <summary>Max health at Aelrynth difficulty tier 0 (real Dereth; every tier on other servers).</summary>
public uint MaxHealth { get; set; }
/// <summary>
/// Max health at Aelrynth difficulty tiers above 0 (awakened worlds, scaled copies: +5% a
/// tier), tier -> highest seen. Null until one is seen, and then left out of the file
/// on every other server. Resists, armour, spells and type are the same at every tier.
/// </summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public Dictionary<int, uint>? TierMaxHealth { get; set; }
public uint MaxStamina { get; set; }
public uint MaxMana { get; set; }

View file

@ -7,13 +7,28 @@ namespace RynthCore.Plugin.RynthAi.CreatureData;
/// <summary>
/// Thread-safe disk-backed store of CreatureProfile records.
/// File: C:\Games\RynthSuite\RynthAi\CreatureData\creatures.json
/// Shared across all characters; engine writes, optional external editor reads.
/// Keyed by composite "name|wcid" so tier variants don't collide.
///
/// Per server (2026-10-03): wcids are only unique within one server's world database, and
/// custom content (Aelrynth's 3000001+, ConquestAC's own) reuses numbers, so each server keeps
/// its own file:
/// C:\Games\RynthSuite\RynthAi\CreatureData\&lt;server&gt;\creatures.json
/// &lt;server&gt; is <see cref="AwakenedTier.ServerKey"/>: "Aelrynth" for every Aelrynth world name,
/// else the world name the server announced, made safe for a folder (the SettingsProfiles rule).
/// The shared file from before, CreatureData\creatures.json, is the legacy store: COPIED (not
/// moved) into a server's folder the first time that server is played, so every server starts
/// from exactly what it had - the same precedent as the per-server SettingsProfiles
/// (MigrateToServerFolder). It is only read and written while no server is known (before the
/// first tick of a login, or a server that announces no name), as before.
///
/// Aelrynth difficulty tiers: appraised max health above tier 0 goes to
/// <see cref="CreatureProfile.TierMaxHealth"/>; MaxHealth stays the tier-0 value. Everything
/// else in a profile is the same at every tier.
/// </summary>
internal sealed class CreatureProfileStore
{
private const string Folder = @"C:\Games\RynthSuite\RynthAi\CreatureData";
internal const string Folder = @"C:\Games\RynthSuite\RynthAi\CreatureData";
private const string FileName = "creatures.json";
private readonly object _lock = new();
@ -21,14 +36,58 @@ internal sealed class CreatureProfileStore
= new(StringComparer.OrdinalIgnoreCase);
private string _lastSavedJson = string.Empty;
private bool _dirty;
private string _serverKey = string.Empty; // "" = the legacy shared file
private string FilePath => Path.Combine(Folder, FileName);
private string FilePath => FileFor(_serverKey);
private static string FileFor(string serverKey) =>
string.IsNullOrEmpty(serverKey) ? Path.Combine(Folder, FileName) : Path.Combine(Folder, serverKey, FileName);
/// <summary>The server whose file is loaded ("" = the legacy shared file).</summary>
public string ServerKey { get { lock (_lock) return _serverKey; } }
/// <summary>
/// Switch to <paramref name="serverKey"/>'s file (saving the current one first). The first
/// time a server is seen its file is a copy of the legacy shared file. "" or the same server
/// is a no-op. Returns a line for the log when a copy was made, else null.
/// </summary>
public string? SetServer(string serverKey)
{
serverKey = serverKey?.Trim() ?? string.Empty;
string? note = null;
lock (_lock)
{
if (serverKey.Length == 0 || string.Equals(serverKey, _serverKey, StringComparison.OrdinalIgnoreCase))
return null;
}
SaveIfDirty();
try
{
string legacy = FileFor("");
string target = FileFor(serverKey);
if (!File.Exists(target) && File.Exists(legacy))
{
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
File.Copy(legacy, target);
note = $"creature data is now kept per server: copied the shared creatures.json into {serverKey}";
}
}
catch (Exception ex)
{
note = $"copying creatures.json into {serverKey} failed ({ex.Message}); starting {serverKey} empty";
}
lock (_lock) _serverKey = serverKey;
Load();
return note;
}
public void Load()
{
lock (_lock)
{
_byKey.Clear();
_lastSavedJson = string.Empty;
_dirty = false;
string path = FilePath;
if (!File.Exists(path)) return;
@ -64,15 +123,16 @@ internal sealed class CreatureProfileStore
try
{
Directory.CreateDirectory(Folder);
string path = FilePath;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string json = JsonSerializer.Serialize(
_byKey, RynthAiJsonContext.Default.CreatureProfileDict);
if (json == _lastSavedJson) return;
string tmp = FilePath + ".tmp";
string tmp = path + ".tmp";
File.WriteAllText(tmp, json);
File.Copy(tmp, FilePath, overwrite: true);
File.Copy(tmp, path, overwrite: true);
try { File.Delete(tmp); } catch { }
_lastSavedJson = json;
}
@ -132,10 +192,24 @@ internal sealed class CreatureProfileStore
}
/// <summary>
/// Merge a new observation into the store. Fields with value 0 / empty are
/// ignored so partial samples don't clobber better data.
/// A profile's appraised max health at an Aelrynth difficulty tier (0 = real Dereth, and
/// every tier on other servers); 0 when that tier hasn't been seen.
/// </summary>
public void Upsert(CreatureProfile sample)
public uint MaxHealthAt(CreatureProfile? profile, int difficulty)
{
if (profile == null) return 0;
if (difficulty <= 0) return profile.MaxHealth;
lock (_lock)
return profile.TierMaxHealth != null && profile.TierMaxHealth.TryGetValue(difficulty, out uint hp) ? hp : 0;
}
/// <summary>
/// Merge a new observation into the store. Fields with value 0 / empty are
/// ignored so partial samples don't clobber better data. <paramref name="difficulty"/>
/// above 0 (an Aelrynth awakened world or scaled copy) files the max health under that tier
/// and leaves the tier-0 vitals alone; the rest merges as always.
/// </summary>
public void Upsert(CreatureProfile sample, int difficulty = 0)
{
if (string.IsNullOrEmpty(sample.Name)) return;
@ -154,10 +228,23 @@ internal sealed class CreatureProfileStore
if (sample.CreatureType != 0) existing.CreatureType = sample.CreatureType;
// Vitals: take the max observed (handles partial samples + minor variation).
if (sample.MaxHealth > existing.MaxHealth) existing.MaxHealth = sample.MaxHealth;
if (sample.MaxStamina > existing.MaxStamina) existing.MaxStamina = sample.MaxStamina;
if (sample.MaxMana > existing.MaxMana) existing.MaxMana = sample.MaxMana;
if (difficulty > 0)
{
// Health, skills and damage scale with the tier; only health is kept (kill prediction).
if (sample.MaxHealth > 0)
{
existing.TierMaxHealth ??= new Dictionary<int, uint>();
if (!existing.TierMaxHealth.TryGetValue(difficulty, out uint had) || sample.MaxHealth > had)
existing.TierMaxHealth[difficulty] = sample.MaxHealth;
}
}
else
{
// Vitals: take the max observed (handles partial samples + minor variation).
if (sample.MaxHealth > existing.MaxHealth) existing.MaxHealth = sample.MaxHealth;
if (sample.MaxStamina > existing.MaxStamina) existing.MaxStamina = sample.MaxStamina;
if (sample.MaxMana > existing.MaxMana) existing.MaxMana = sample.MaxMana;
}
if (sample.ArmorLevel > 0) existing.ArmorLevel = sample.ArmorLevel;
@ -187,7 +274,8 @@ internal sealed class CreatureProfileStore
}
/// <summary>
/// Returns the lowest resist (the creature's weakest damage type). 1.0 means "no data".
/// The damage type the creature takes the most damage from: resists are damage multipliers
/// (1.0 full, 0.5 half), so that's the HIGHEST value (this took the lowest until 2026-09-29).
/// </summary>
public static (string Type, double Resist) GetWeakest(CreatureProfile p)
{
@ -202,10 +290,10 @@ internal sealed class CreatureProfileStore
("electric", p.ResistElectric),
};
string bestType = "slash";
double best = double.MaxValue;
double best = double.MinValue;
foreach (var pair in pairs)
{
if (pair.Item2 < best)
if (pair.Item2 > best)
{
best = pair.Item2;
bestType = pair.Item1;

View file

@ -0,0 +1,30 @@
namespace RynthCore.Plugin.RynthAi.CreatureData;
/// <summary>
/// Names of the creature types (PropertyInt 2 CreatureType on a monster, PropertyInt 166
/// SlayerCreatureType on a weapon), in ACE's ACE.Entity.Enum.CreatureType order.
/// </summary>
internal static class CreatureTypeNames
{
private static readonly string[] Names =
{
"Invalid", "Olthoi", "Banderling", "Drudge", "Mosswart", "Lugian", "Tumerok", "Mite", "Tusker",
"Phyntos Wasp", "Rat", "Auroch", "Cow", "Golem", "Undead", "Gromnie", "Reedshark", "Armoredillo",
"Fae", "Virindi", "Wisp", "Knathtead", "Shadow", "Mattekar", "Mumiyah", "Rabbit", "Sclavus",
"Shallows Shark", "Monouga", "Zefir", "Skeleton", "Human", "Shreth", "Chittick", "Moarsman",
"Olthoi Larvae", "Slithis", "Deru", "Fire Elemental", "Snowman", "Unknown", "Bunny",
"Lightning Elemental", "Rockslide", "Grievver", "Niffis", "Ursuin", "Crystal", "Hollow Minion",
"Scarecrow", "Idol", "Empyrean", "Hopeslayer", "Doll", "Marionette", "Carenzi", "Siraluun",
"Aun Tumerok", "Hea Tumerok", "Simulacrum", "Acid Elemental", "Frost Elemental", "Elemental",
"Statue", "Wall", "Altered Human", "Device", "Harbinger", "Dark Sarcophagus", "Chicken",
"Gotrok Lugian", "Margul", "Bleached Rabbit", "Nasty Rabbit", "Grimacing Rabbit", "Burun",
"Target", "Ghost", "Fiun", "Eater", "Penguin", "Ruschk", "Thrungus", "Viamontian Knight",
"Remoran", "Swarm", "Moar", "Enchanted Arms", "Sleech", "Mukkir", "Merwart", "Food",
"Paradox Olthoi", "Harvest", "Energy", "Apparition", "Aerbax", "Touched", "Blighted Moarsman",
"Gear Knight", "Gurog", "Anekshay",
};
/// <summary>The type's name ("type N" for one this table doesn't know).</summary>
public static string Name(int type) =>
type > 0 && type < Names.Length ? Names[type] : "type " + type;
}

View file

@ -0,0 +1,325 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace RynthCore.Plugin.RynthAi.CreatureData;
/// <summary>
/// Which damage elements hurt a monster most. ACE never sends a creature's resists on
/// appraisal (ResistSlash 64 … ResistNether 166 aren't assessment properties), so RynthAi
/// ships them from the Aelrynth world database, keyed on the wcid (in CreateObject):
/// Data\creature_weakness.json — ops/overnight/creature-weakness.json; loaded once, lazily.
/// A copy in C:\Games\RynthSuite\RynthAi\Data wins over the built-in one.
/// creature_resists.tsv — the same rows from ops/rynth-creature-resists.py; every creature with resist data, by wcid (name must match, so a
/// custom monster that reuses a wcid on another server isn't mistaken)
/// creature_types.txt — per creature type, elements ranked by the type's average resists,
/// plus name keywords: the fallback for custom monsters.
/// A copy of creature_types.txt in C:\Games\RynthSuite\RynthAi\CreatureData overrides lines
/// by type id. Multipliers are damage taken: 1.0 = full, 0.5 = half, so higher = weaker.
/// </summary>
internal static class CreatureWeakness
{
public static readonly string[] Elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Acid", "Lightning", "Nether" };
public sealed class Ranking
{
/// <summary>Most damage first. Mult is NaN when only the order is known (learned).</summary>
public List<(string Element, double Mult)> Order = new();
/// <summary>"server data", "learned", "Olthoi type", …</summary>
public string Source = "";
/// <summary>"Bludgeon 1.0, Pierce 1.0, Fire 0.75" (first <paramref name="n"/>).</summary>
public string Describe(int n = 3)
{
var parts = new List<string>();
for (int i = 0; i < Order.Count && parts.Count < n; i++)
parts.Add(double.IsNaN(Order[i].Mult) ? Order[i].Element
: Order[i].Element + " " + Order[i].Mult.ToString("0.0#", CultureInfo.InvariantCulture));
return string.Join(", ", parts);
}
}
private sealed class TypeInfo
{
public int Id;
public string Name = "";
public List<(string Element, double Mult)> Order = new();
}
private static readonly object Sync = new();
private static bool _loaded;
private static readonly Dictionary<uint, (string Name, int Type, double[] Mult)> ByWcid = new();
private static readonly Dictionary<string, uint> ByName = new(StringComparer.OrdinalIgnoreCase); // first wcid per name
private static readonly Dictionary<int, TypeInfo> Types = new();
private static readonly List<(string Keyword, int Type)> Keywords = new(); // longest first
/// <summary>
/// The elements that hurt this monster most, or null when nothing is known. Order of
/// sources: the server table (wcid + name), then what the Damage tab learned
/// (<paramref name="learnedBest"/>) ahead of the creature-type ranking, then the type
/// ranking alone. <paramref name="creatureType"/> 0 = unknown (the name keywords decide).
/// </summary>
public static Ranking? Rank(uint wcid, string? name, int creatureType, string? learnedBest)
{
EnsureLoaded();
name ??= "";
// No wcid (a meta asking by name): the first creature of that name in the table.
if (wcid == 0 && name.Length > 0 && ByName.TryGetValue(name, out uint byName)) wcid = byName;
if (wcid != 0 && ByWcid.TryGetValue(wcid, out var row)
&& (name.Length == 0 || row.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
{
var r = new Ranking { Source = "server data" };
r.Order = Ordered(row.Mult);
return r;
}
TypeInfo? type = FindType(creatureType, name);
string learned = Normalize(learnedBest);
if (learned.Length > 0)
{
var r = new Ranking { Source = type != null ? $"learned, then {Pretty(type.Name)} type" : "learned" };
r.Order.Add((learned, double.NaN));
if (type != null)
foreach (var e in type.Order)
if (!e.Element.Equals(learned, StringComparison.OrdinalIgnoreCase)) r.Order.Add(e);
return r;
}
if (type != null)
return new Ranking { Source = Pretty(type.Name) + " type", Order = new(type.Order) };
return null;
}
/// <summary>Damage multiplier for one element from the server table or the type average; false when unknown.</summary>
public static bool TryGetMultiplier(uint wcid, string? name, int creatureType, string element, out double mult)
{
mult = 1.0;
Ranking? r = Rank(wcid, name, creatureType, null);
if (r == null) return false;
string e = Normalize(element);
foreach (var x in r.Order)
if (x.Element.Equals(e, StringComparison.OrdinalIgnoreCase) && !double.IsNaN(x.Mult))
{
mult = x.Mult;
return true;
}
return false;
}
/// <summary>Element names as the rest of RynthAi spells them ("Electric" → "Lightning"); "" when not an element.</summary>
public static string Normalize(string? element)
{
if (string.IsNullOrWhiteSpace(element)) return "";
string t = element.Trim();
if (t.Equals("Electric", StringComparison.OrdinalIgnoreCase)) return "Lightning";
if (t.Equals("Blade", StringComparison.OrdinalIgnoreCase)) return "Slash";
foreach (string e in Elements)
if (e.Equals(t, StringComparison.OrdinalIgnoreCase)) return e;
return "";
}
private static string Pretty(string typeName)
{
var sb = new System.Text.StringBuilder();
foreach (char c in typeName)
{
if (char.IsUpper(c) && sb.Length > 0) sb.Append(' ');
sb.Append(c);
}
return sb.ToString();
}
private static List<(string, double)> Ordered(double[] mult)
{
var idx = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7 };
idx.Sort((a, b) =>
{
int c = Math.Round(mult[b], 3).CompareTo(Math.Round(mult[a], 3));
return c != 0 ? c : a.CompareTo(b);
});
var list = new List<(string, double)>(8);
foreach (int i in idx) list.Add((Elements[i], mult[i]));
return list;
}
private static TypeInfo? FindType(int creatureType, string name)
{
if (creatureType > 0 && Types.TryGetValue(creatureType, out var t)) return t;
if (name.Length == 0) return null;
foreach (var (kw, type) in Keywords)
if (ContainsWord(name, kw) && Types.TryGetValue(type, out var k)) return k;
return null;
}
private static bool ContainsWord(string text, string word)
{
int i = 0;
while ((i = text.IndexOf(word, i, StringComparison.OrdinalIgnoreCase)) >= 0)
{
bool startOk = i == 0 || !char.IsLetter(text[i - 1]);
int end = i + word.Length;
bool endOk = end >= text.Length || !char.IsLetter(text[end]);
if (startOk && endOk) return true;
i = end;
}
return false;
}
private static void EnsureLoaded()
{
if (_loaded) return;
lock (Sync)
{
if (_loaded) return;
try
{
foreach (string line in ReadResource("creature_resists.tsv"))
{
if (line.Length == 0 || line[0] == '#') continue;
string[] f = line.Split('\t');
if (f.Length < 11 || !uint.TryParse(f[0], out uint wcid)) continue;
var m = new double[8];
for (int i = 0; i < 8; i++)
m[i] = double.TryParse(f[3 + i], NumberStyles.Float, CultureInfo.InvariantCulture, out double v) ? v : 1.0;
int.TryParse(f[2], out int ct);
ByWcid[wcid] = (f[1], ct, m);
ByName.TryAdd(f[1], wcid);
}
// The weakness table (wcid -> multipliers), generated from the world database
// (ops/overnight/creature-weakness.json). A copy in the RynthAi folder wins over
// the one built into the DLL, so the table can be refreshed without a rebuild.
// Its rows replace the TSV's by wcid.
string? json = null;
try { if (File.Exists(WeaknessFile)) json = File.ReadAllText(WeaknessFile); } catch { json = null; }
json ??= ReadResourceText("Data.creature_weakness.json", rooted: true);
if (!string.IsNullOrEmpty(json)) LoadWeaknessJson(json);
foreach (string line in ReadResource("creature_types.txt")) ParseTypeLine(line);
string user = Path.Combine(CreatureProfileStore.Folder, "creature_types.txt");
if (File.Exists(user))
foreach (string line in File.ReadAllLines(user)) ParseTypeLine(line);
}
catch { }
Keywords.Sort((a, b) => b.Keyword.Length.CompareTo(a.Keyword.Length));
_loaded = true;
}
}
// id|Type|keywords|Element mult,Element mult,...
private static void ParseTypeLine(string line)
{
line = line.Trim();
if (line.Length == 0 || line[0] == '#') return;
string[] f = line.Split('|');
if (f.Length < 4 || !int.TryParse(f[0], out int id)) return;
var info = new TypeInfo { Id = id, Name = f[1].Trim() };
foreach (string part in f[3].Split(','))
{
string[] p = part.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (p.Length == 0) continue;
string e = Normalize(p[0]);
if (e.Length == 0) continue;
double m = p.Length > 1 && double.TryParse(p[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double v) ? v : double.NaN;
info.Order.Add((e, m));
}
if (info.Order.Count == 0) return;
Types[id] = info; // a later line (the user's file) replaces the shipped one
Keywords.RemoveAll(k => k.Type == id);
foreach (string kw in f[2].Split(' ', StringSplitOptions.RemoveEmptyEntries))
Keywords.Add((kw, id));
}
/// <summary>The on-disk copy of the weakness table next to RynthAi (optional; the DLL has one built in).</summary>
internal const string WeaknessFile = @"C:\Games\RynthSuite\RynthAi\Data\creature_weakness.json";
// JSON keys → Elements index (the table spells Lightning "electric").
private static readonly (string Key, int Index)[] JsonKeys =
{
("slash", 0), ("pierce", 1), ("bludgeon", 2), ("fire", 3), ("cold", 4), ("acid", 5),
("electric", 6), ("lightning", 6), ("nether", 7),
};
/// <summary>
/// {"creatures": {"&lt;wcid&gt;": {"slash": 0.75, ..., "electric": 0.25, "nether": 1.0, "name": "..."}}}.
/// A missing element is 1.0 (normal damage). Returns the rows read.
/// </summary>
internal static int LoadWeaknessJson(string json)
{
int n = 0;
try
{
using var doc = System.Text.Json.JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("creatures", out var creatures)
|| creatures.ValueKind != System.Text.Json.JsonValueKind.Object) return 0;
foreach (var c in creatures.EnumerateObject())
{
if (!uint.TryParse(c.Name, NumberStyles.Integer, CultureInfo.InvariantCulture, out uint wcid) || wcid == 0) continue;
if (c.Value.ValueKind != System.Text.Json.JsonValueKind.Object) continue;
var m = new double[8];
for (int i = 0; i < 8; i++) m[i] = 1.0;
string name = "";
int type = 0;
foreach (var p in c.Value.EnumerateObject())
{
if (p.NameEquals("name")) { name = p.Value.GetString() ?? ""; continue; }
if (p.NameEquals("type") && p.Value.TryGetInt32(out int t)) { type = t; continue; }
if (p.Value.ValueKind != System.Text.Json.JsonValueKind.Number) continue;
foreach (var (key, idx) in JsonKeys)
if (p.Name.Equals(key, StringComparison.OrdinalIgnoreCase)) { m[idx] = p.Value.GetDouble(); break; }
}
if (type == 0 && ByWcid.TryGetValue(wcid, out var old)) type = old.Type;
if (name.Length == 0 && ByWcid.TryGetValue(wcid, out var old2)) name = old2.Name;
ByWcid[wcid] = (name, type, m);
if (name.Length > 0) ByName.TryAdd(name, wcid);
n++;
}
}
catch { }
return n;
}
/// <summary>
/// A ranking from a creature's own appraisal resist floats (ResistSlash 64 … ResistElectric
/// 70, ResistNether 166), when the server sent any. Stock ACE doesn't mark them as assessment
/// properties, so this is usually null and the table decides. Missing elements count 1.0.
/// </summary>
public static Ranking? FromAppraisal(double?[] mult)
{
if (mult == null || mult.Length < 8) return null;
bool any = false;
var m = new double[8];
for (int i = 0; i < 8; i++)
{
if (mult[i] is double v && v >= 0 && v < 10) { m[i] = v; any = true; }
else m[i] = 1.0;
}
return any ? new Ranking { Source = "appraisal", Order = Ordered(m) } : null;
}
private static string? ReadResourceText(string file, bool rooted)
{
try
{
var asm = Assembly.GetExecutingAssembly();
string res = "RynthCore.Plugin.RynthAi." + (rooted ? file : "CreatureData." + file);
using Stream? s = asm.GetManifestResourceStream(res);
if (s == null) return null;
using var reader = new StreamReader(s);
return reader.ReadToEnd();
}
catch { return null; }
}
private static IEnumerable<string> ReadResource(string file)
{
var asm = Assembly.GetExecutingAssembly();
using Stream? s = asm.GetManifestResourceStream("RynthCore.Plugin.RynthAi.CreatureData." + file);
if (s == null) yield break;
using var reader = new StreamReader(s);
string? line;
while ((line = reader.ReadLine()) != null) yield return line;
}
}

View file

@ -11,7 +11,7 @@ namespace RynthCore.Plugin.RynthAi.CreatureData;
/// skill/buffs AND the weapon used AND the spell, so unlike CreatureProfileStore
/// (shared HP/resists — monster intrinsics) this is per character, stored next to
/// that character's settings:
/// ...\SettingsProfiles\ACEmulator\&lt;charName&gt;\monster_damage.txt
/// ...\SettingsProfiles\&lt;server&gt;\&lt;charName&gt;\monster_damage.txt
///
/// Learned, all as running averages:
/// • HpPool[wcid] — total damage to kill (≈ HP), weapon-independent
@ -31,6 +31,22 @@ namespace RynthCore.Plugin.RynthAi.CreatureData;
/// M|&lt;wcid&gt;|&lt;name&gt;|&lt;hp&gt; (manual HP override)
/// D|&lt;wcid&gt;|&lt;name&gt;|&lt;weaponId&gt;|&lt;element&gt;|&lt;tier&gt;|&lt;avgDamage&gt;|&lt;dmgSamples&gt;|&lt;avgCastsToKill&gt;|&lt;killSamples&gt;|&lt;critAvg&gt;|&lt;critSamples&gt;|&lt;nonCritAvg&gt;|&lt;nonCritSamples&gt;
/// (The loader also accepts the older 9/10-field name-less / crit-less D rows so existing data carries over.)
///
/// Aelrynth difficulty tiers (2026-10-03, <see cref="AwakenedTier"/>): Aelrynth's awakened worlds
/// and scaled copies hold the same monsters (same wcids) with health, skills and damage scaled 5%
/// a tier. What a tier changes is kept per (wcid, tier): the HP pool, casts-to-kill, hits and
/// misses, seconds per kill (per weapon and per summon) and the damage the monster does to us.
/// What it does not change stays shared: per-cast damage (resistances and armour don't scale)
/// and every rule (weapon, offhand, pet, manual HP). Tier 0 - real Dereth, and every other
/// server, where the tier is always 0 - is today's data in today's rows, untouched. Tiers above 0
/// are extra rows an older loader skips:
/// AH|&lt;tier&gt;|&lt;wcid&gt;|&lt;name&gt;|&lt;hpToKill&gt;|&lt;samples&gt;
/// AD|&lt;tier&gt;|&lt;wcid&gt;|&lt;name&gt;|&lt;weaponId&gt;|&lt;element&gt;|&lt;spellTier&gt;|&lt;avgCastsToKill&gt;|&lt;killSamples&gt;
/// AU|&lt;tier&gt;|&lt;wcid&gt;|&lt;name&gt;|&lt;weaponId&gt;|&lt;hits&gt;|&lt;misses&gt;|&lt;secAvg&gt;|&lt;secSamples&gt;
/// APK|&lt;tier&gt;|&lt;wcid&gt;|&lt;name&gt;|&lt;element&gt;|&lt;kills&gt;|&lt;secAvg&gt;
/// AT|&lt;tier&gt;|&lt;wcid&gt;|&lt;name&gt;|&lt;element&gt;|&lt;hits&gt;|&lt;avg&gt;|&lt;max&gt;
/// Records go to <see cref="Difficulty"/> (the tier where the player stands, set each tick);
/// readers without a tier argument read it too, and the Damage panel passes the tier it shows.
/// </summary>
internal sealed class MonsterDamageStore
{
@ -48,6 +64,30 @@ internal sealed class MonsterDamageStore
public int NonCritSamples; // non-crit observations
}
/// <summary>One weapon (or wand) against one monster: accuracy and fight length.</summary>
private sealed class WeaponUse
{
public int Hits; // landed attacks / damaging casts
public int Misses; // "X evaded your attack", "X resists your spell"
public double SecAvg; // avg seconds from engaging to the kill (fights we timed)
public int SecSamples;
}
/// <summary>Kills with a summon of one element out ("" key = no summon).</summary>
private sealed class PetUse
{
public int Kills;
public double SecAvg;
}
/// <summary>Damage the monster did to us, per element.</summary>
private sealed class TakenStat
{
public int Hits;
public double Avg;
public double Max;
}
private sealed class WcidProfile
{
public string Name = ""; // last-seen monster name (for the readable file + UI)
@ -56,16 +96,53 @@ internal sealed class MonsterDamageStore
public double HpManual; // 0 = unset; user-entered HP override (UI), authoritative when > 0
public uint WeaponManual; // 0 = unset; user-picked weapon override for this wcid (Damage panel)
public uint OffhandManual; // 0 = unset; user-picked offhand override for this wcid (Damage panel; stored only)
public string PetManual = ""; // "" = Auto; "E:<element>" or "I:<essence id>" (Damage panel)
public int LastTier = NoTier; // most-recent cast tier (negative = ring); NoTier = unset this session
// key = "weaponId|element|tier"
public readonly Dictionary<string, CastStat> Casts =
new(StringComparer.OrdinalIgnoreCase);
public readonly Dictionary<uint, WeaponUse> Weapons = new();
public readonly Dictionary<string, PetUse> Pets = new(StringComparer.OrdinalIgnoreCase);
public readonly Dictionary<string, TakenStat> Taken = new(StringComparer.OrdinalIgnoreCase);
}
private const int NoTier = int.MinValue; // sentinel: no cast observed for this wcid yet
/// <summary>Casts-to-kill for one (weapon, element, spell tier) at one difficulty tier.</summary>
private sealed class KillStat
{
public double AvgCastsToKill;
public int KillSamples;
}
/// <summary>What one Aelrynth difficulty tier above 0 changes about one monster (see the class comment).</summary>
private sealed class TierProfile
{
public double HpPool;
public int HpSamples;
// key = "weaponId|element|tier" (the spell tier), as WcidProfile.Casts
public readonly Dictionary<string, KillStat> Kills = new(StringComparer.OrdinalIgnoreCase);
public readonly Dictionary<uint, WeaponUse> Weapons = new();
public readonly Dictionary<string, PetUse> Pets = new(StringComparer.OrdinalIgnoreCase);
public readonly Dictionary<string, TakenStat> Taken = new(StringComparer.OrdinalIgnoreCase);
}
private readonly object _lock = new();
private readonly Dictionary<uint, WcidProfile> _byWcid = new();
/// <summary>Difficulty tiers above 0 only; tier 0 is <see cref="_byWcid"/>.</summary>
private readonly Dictionary<(uint Wcid, int Difficulty), TierProfile> _byTier = new();
private volatile int _difficulty;
/// <summary>
/// The Aelrynth difficulty tier new observations are recorded under, and the one the
/// tier-less readers answer for: the tier where the player stands (AwakenedTier.Current,
/// set every tick). Always 0 off Aelrynth.
/// </summary>
public int Difficulty
{
get => _difficulty;
set => _difficulty = value < 0 ? 0 : value;
}
private string _filePath = string.Empty;
private bool _dirty;
// Per-character DEFAULT weapon: the fallback every monster without its own weapon override uses,
@ -88,6 +165,7 @@ internal sealed class MonsterDamageStore
lock (_lock)
{
_byWcid.Clear();
_byTier.Clear();
_defaultWeapon = 0;
_dirty = false;
_filePath = string.IsNullOrWhiteSpace(charFolder)
@ -102,6 +180,7 @@ internal sealed class MonsterDamageStore
lock (_lock)
{
_byWcid.Clear();
_byTier.Clear();
_defaultWeapon = 0;
if (string.IsNullOrEmpty(_filePath) || !File.Exists(_filePath)) return;
@ -113,7 +192,11 @@ internal sealed class MonsterDamageStore
if (line.Length == 0 || line[0] == '#') continue;
string[] f = line.Split('|');
if (f.Length >= 2 && f[0] == "DEF")
if (f.Length >= 2 && f[0].Length >= 2 && f[0][0] == 'A' && f[0] != "A")
{
LoadTierRow(f);
}
else if (f.Length >= 2 && f[0] == "DEF")
{
// DEF|weaponId — per-character default weapon (sweeping fallback)
if (uint.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint dw))
@ -156,6 +239,16 @@ internal sealed class MonsterDamageStore
if (f[2].Length > 0) p.Name = f[2];
}
}
else if (f.Length >= 4 && f[0] == "P")
{
// P|wcid|name|choice — per-monster pet choice (Damage panel)
if (uint.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint pw))
{
var p = Get(pw);
p.PetManual = f[3];
if (f[2].Length > 0) p.Name = f[2];
}
}
else if (f.Length >= 4 && f[0] == "O")
{
// O|wcid|name|offhandId — per-monster offhand override (Damage panel; stored only)
@ -167,6 +260,49 @@ internal sealed class MonsterDamageStore
if (f[2].Length > 0) p.Name = f[2];
}
}
else if (f.Length >= 8 && f[0] == "U")
{
// U|wcid|name|weaponId|hits|misses|secAvg|secSamples
if (uint.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint uw)
&& uint.TryParse(f[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint wid))
{
var p = Get(uw);
if (f[2].Length > 0) p.Name = f[2];
var u = new WeaponUse();
int.TryParse(f[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out u.Hits);
int.TryParse(f[5], NumberStyles.Integer, CultureInfo.InvariantCulture, out u.Misses);
double.TryParse(f[6], NumberStyles.Float, CultureInfo.InvariantCulture, out u.SecAvg);
int.TryParse(f[7], NumberStyles.Integer, CultureInfo.InvariantCulture, out u.SecSamples);
p.Weapons[wid] = u;
}
}
else if (f.Length >= 6 && f[0] == "PK")
{
// PK|wcid|name|element (none = no summon)|kills|secAvg
if (uint.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint kw))
{
var p = Get(kw);
if (f[2].Length > 0) p.Name = f[2];
var k = new PetUse();
int.TryParse(f[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out k.Kills);
double.TryParse(f[5], NumberStyles.Float, CultureInfo.InvariantCulture, out k.SecAvg);
p.Pets[f[3] == "none" ? "" : f[3]] = k;
}
}
else if (f.Length >= 7 && f[0] == "T")
{
// T|wcid|name|element|hits|avg|max
if (uint.TryParse(f[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out uint tw))
{
var p = Get(tw);
if (f[2].Length > 0) p.Name = f[2];
var t = new TakenStat();
int.TryParse(f[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out t.Hits);
double.TryParse(f[5], NumberStyles.Float, CultureInfo.InvariantCulture, out t.Avg);
double.TryParse(f[6], NumberStyles.Float, CultureInfo.InvariantCulture, out t.Max);
p.Taken[f[3]] = t;
}
}
else if (f.Length >= 9 && f[0] == "D")
{
// New: D|wcid|name|weaponId|element|tier|avg|dmgS|avgCasts|killS|critAvg|critS|nonCritAvg|nonCritS (14 fields)
@ -208,6 +344,103 @@ internal sealed class MonsterDamageStore
}
}
/// <summary>One AH/AD/AU/APK/AT row (a difficulty tier above 0). Caller holds _lock.</summary>
private void LoadTierRow(string[] f)
{
var inv = CultureInfo.InvariantCulture;
// f[1] = tier, f[2] = wcid, f[3] = name, then the row's own fields.
if (f.Length < 5
|| !int.TryParse(f[1], NumberStyles.Integer, inv, out int d) || d <= 0
|| !uint.TryParse(f[2], NumberStyles.Integer, inv, out uint wcid) || wcid == 0)
return;
if (f[3].Length > 0) Get(wcid).Name = f[3]; // the name lives on the tier-0 profile
var tp = Tier(wcid, d);
switch (f[0])
{
case "AH" when f.Length >= 6:
double.TryParse(f[4], NumberStyles.Float, inv, out tp.HpPool);
int.TryParse(f[5], NumberStyles.Integer, inv, out tp.HpSamples);
break;
case "AD" when f.Length >= 9:
if (uint.TryParse(f[4], NumberStyles.Integer, inv, out uint wid)
&& int.TryParse(f[6], NumberStyles.Integer, inv, out int spellTier))
{
var k = new KillStat();
double.TryParse(f[7], NumberStyles.Float, inv, out k.AvgCastsToKill);
int.TryParse(f[8], NumberStyles.Integer, inv, out k.KillSamples);
tp.Kills[CastKey(wid, f[5], spellTier)] = k;
}
break;
case "AU" when f.Length >= 9:
if (uint.TryParse(f[4], NumberStyles.Integer, inv, out uint uw))
{
var u = new WeaponUse();
int.TryParse(f[5], NumberStyles.Integer, inv, out u.Hits);
int.TryParse(f[6], NumberStyles.Integer, inv, out u.Misses);
double.TryParse(f[7], NumberStyles.Float, inv, out u.SecAvg);
int.TryParse(f[8], NumberStyles.Integer, inv, out u.SecSamples);
tp.Weapons[uw] = u;
}
break;
case "APK" when f.Length >= 7:
{
var k = new PetUse();
int.TryParse(f[5], NumberStyles.Integer, inv, out k.Kills);
double.TryParse(f[6], NumberStyles.Float, inv, out k.SecAvg);
tp.Pets[f[4] == "none" ? "" : f[4]] = k;
break;
}
case "AT" when f.Length >= 8:
{
var t = new TakenStat();
int.TryParse(f[5], NumberStyles.Integer, inv, out t.Hits);
double.TryParse(f[6], NumberStyles.Float, inv, out t.Avg);
double.TryParse(f[7], NumberStyles.Float, inv, out t.Max);
tp.Taken[f[4]] = t;
break;
}
}
}
/// <summary>The tier rows of the file (empty when there are none). Caller holds _lock.</summary>
private void AppendTierRows(StringBuilder sb)
{
if (_byTier.Count == 0) return;
sb.Append("# Aelrynth difficulty tiers above 0 (awakened worlds, scaled copies); tier 0 is the rows above:\n");
sb.Append("# AH|tier|wcid|name|hpToKill|samples\n");
sb.Append("# AD|tier|wcid|name|weaponId|element|spellTier|avgCastsToKill|killSamples\n");
sb.Append("# AU|tier|wcid|name|weaponId|hits|misses|secToKillAvg|secSamples\n");
sb.Append("# APK|tier|wcid|name|summonElement|kills|secToKillAvg\n");
sb.Append("# AT|tier|wcid|name|element|hitsTaken|avgDamageTaken|maxDamageTaken\n");
var keys = new List<(uint Wcid, int Difficulty)>(_byTier.Keys);
keys.Sort((a, b) => a.Difficulty != b.Difficulty ? a.Difficulty.CompareTo(b.Difficulty) : a.Wcid.CompareTo(b.Wcid));
foreach (var key in keys)
{
var tp = _byTier[key];
string head = key.Difficulty.ToString(CultureInfo.InvariantCulture) + "|" + key.Wcid.ToString(CultureInfo.InvariantCulture)
+ "|" + (_byWcid.TryGetValue(key.Wcid, out var p) ? p.Name : "");
if (tp.HpSamples > 0)
sb.Append("AH|").Append(head).Append('|').Append(Num(tp.HpPool)).Append('|').Append(tp.HpSamples).Append('\n');
foreach (var k in tp.Kills)
{
string[] kp = k.Key.Split('|'); // weaponId|element|tier
if (kp.Length < 3 || k.Value.KillSamples <= 0) continue;
sb.Append("AD|").Append(head).Append('|').Append(kp[0]).Append('|').Append(kp[1]).Append('|').Append(kp[2]).Append('|')
.Append(Num(k.Value.AvgCastsToKill)).Append('|').Append(k.Value.KillSamples).Append('\n');
}
foreach (var u in tp.Weapons)
sb.Append("AU|").Append(head).Append('|').Append(u.Key).Append('|')
.Append(u.Value.Hits).Append('|').Append(u.Value.Misses).Append('|')
.Append(Num(u.Value.SecAvg)).Append('|').Append(u.Value.SecSamples).Append('\n');
foreach (var k in tp.Pets)
sb.Append("APK|").Append(head).Append('|').Append(k.Key.Length == 0 ? "none" : k.Key).Append('|')
.Append(k.Value.Kills).Append('|').Append(Num(k.Value.SecAvg)).Append('\n');
foreach (var t in tp.Taken)
sb.Append("AT|").Append(head).Append('|').Append(t.Key).Append('|')
.Append(t.Value.Hits).Append('|').Append(Num(t.Value.Avg)).Append('|').Append(Num(t.Value.Max)).Append('\n');
}
}
/// <summary>Persist if anything changed. Cheap to call from a tick.</summary>
public void SaveIfDirty()
{
@ -225,8 +458,12 @@ internal sealed class MonsterDamageStore
sb.Append("# M|wcid|name|hp (manual HP override, set in the Damage panel)\n");
sb.Append("# W|wcid|name|weaponId (per-monster weapon override, set in the Damage panel)\n");
sb.Append("# O|wcid|name|offhandId (per-monster offhand override, set in the Damage panel)\n");
sb.Append("# P|wcid|name|E:element or I:essenceId (per-monster pet choice; none = Auto)\n");
sb.Append("# D|wcid|name|weaponId|element|tier|avgDamage|dmgSamples|avgCastsToKill|killSamples|critAvg|critSamples|nonCritAvg|nonCritSamples\n");
sb.Append("# DEF|weaponId (per-character default weapon — fallback for every monster without its own override)\n");
sb.Append("# U|wcid|name|weaponId|hits|misses|secToKillAvg|secSamples (accuracy and fight length per weapon)\n");
sb.Append("# PK|wcid|name|summonElement (none = no summon)|kills|secToKillAvg\n");
sb.Append("# T|wcid|name|element|hitsTaken|avgDamageTaken|maxDamageTaken\n");
if (_defaultWeapon != 0)
sb.Append("DEF|").Append(_defaultWeapon).Append('\n');
foreach (var kv in _byWcid)
@ -245,6 +482,20 @@ internal sealed class MonsterDamageStore
if (p.OffhandManual != 0)
sb.Append("O|").Append(kv.Key).Append('|').Append(name).Append('|')
.Append(p.OffhandManual).Append('\n');
if (p.PetManual.Length > 0)
sb.Append("P|").Append(kv.Key).Append('|').Append(name).Append('|')
.Append(p.PetManual).Append('\n');
foreach (var u in p.Weapons)
sb.Append("U|").Append(kv.Key).Append('|').Append(name).Append('|').Append(u.Key).Append('|')
.Append(u.Value.Hits).Append('|').Append(u.Value.Misses).Append('|')
.Append(Num(u.Value.SecAvg)).Append('|').Append(u.Value.SecSamples).Append('\n');
foreach (var k in p.Pets)
sb.Append("PK|").Append(kv.Key).Append('|').Append(name).Append('|')
.Append(k.Key.Length == 0 ? "none" : k.Key).Append('|')
.Append(k.Value.Kills).Append('|').Append(Num(k.Value.SecAvg)).Append('\n');
foreach (var t in p.Taken)
sb.Append("T|").Append(kv.Key).Append('|').Append(name).Append('|').Append(t.Key).Append('|')
.Append(t.Value.Hits).Append('|').Append(Num(t.Value.Avg)).Append('|').Append(Num(t.Value.Max)).Append('\n');
foreach (var c in p.Casts)
{
string[] kp = c.Key.Split('|'); // weaponId|element|tier
@ -258,6 +509,7 @@ internal sealed class MonsterDamageStore
.Append(Num(v.NonCritAvg)).Append('|').Append(v.NonCritSamples).Append('\n');
}
}
AppendTierRows(sb);
string tmp = _filePath + ".tmp";
File.WriteAllText(tmp, sb.ToString());
@ -278,11 +530,13 @@ internal sealed class MonsterDamageStore
public void RecordHit(uint weaponId, uint wcid, string name, string element, int tier, double damage, bool crit)
{
if (wcid == 0 || damage <= 0) return;
int d = Difficulty;
lock (_lock)
{
SetNameLocked(wcid, name);
Get(wcid).LastTier = tier;
var s = GetCast(wcid, weaponId, element, tier);
if (weaponId != 0) Use(wcid, weaponId, d).Hits++; // hit rate: the monster's defence scales
var s = GetCast(wcid, weaponId, element, tier); // damage per cast: shared by every tier
s.Avg = s.Samples == 0 ? damage : s.Avg + Alpha * (damage - s.Avg);
s.Samples++;
if (crit)
@ -308,11 +562,33 @@ internal sealed class MonsterDamageStore
public void RecordKill(uint weaponId, uint wcid, string name, string element, int tier, int castCount, double totalDamage)
{
if (wcid == 0) return;
int d = Difficulty;
lock (_lock)
{
var p = Get(wcid);
SetNameLocked(wcid, name);
p.LastTier = tier;
if (d > 0)
{
// A scaled tier: its own HP pool and casts-to-kill. The shared cast row is made
// (empty) when missing so the Damage panel lists this weapon/spell.
var tp = Tier(wcid, d);
if (totalDamage > 0)
{
tp.HpPool = tp.HpSamples == 0 ? totalDamage : tp.HpPool + Alpha * (totalDamage - tp.HpPool);
tp.HpSamples++;
}
if (castCount > 0)
{
GetCast(wcid, weaponId, element, tier);
string key = CastKey(weaponId, element, tier);
if (!tp.Kills.TryGetValue(key, out var k)) tp.Kills[key] = k = new KillStat();
k.AvgCastsToKill = k.KillSamples == 0 ? castCount : k.AvgCastsToKill + Alpha * (castCount - k.AvgCastsToKill);
k.KillSamples++;
}
_dirty = true;
return;
}
if (totalDamage > 0)
{
p.HpPool = p.HpSamples == 0 ? totalDamage : p.HpPool + Alpha * (totalDamage - p.HpPool);
@ -328,6 +604,156 @@ internal sealed class MonsterDamageStore
}
}
/// <summary>An attack or cast that did nothing: evaded, or the spell was resisted.</summary>
public void RecordMiss(uint weaponId, uint wcid, string name)
{
if (wcid == 0 || weaponId == 0) return;
int d = Difficulty;
lock (_lock)
{
SetNameLocked(wcid, name);
Use(wcid, weaponId, d).Misses++;
_dirty = true;
}
}
/// <summary>
/// A timed fight ended in our kill: <paramref name="seconds"/> from engaging it, with
/// <paramref name="summonElement"/>: "none" = no summon out, "" = a summon of unknown element, else its element.
/// </summary>
public void RecordFightTime(uint weaponId, uint wcid, string name, double seconds, string? summonElement)
{
if (wcid == 0 || seconds <= 0 || seconds > 600) return;
int d = Difficulty;
lock (_lock)
{
SetNameLocked(wcid, name);
if (weaponId != 0)
{
var u = Use(wcid, weaponId, d);
u.SecAvg = u.SecSamples == 0 ? seconds : u.SecAvg + Alpha * (seconds - u.SecAvg);
u.SecSamples++;
}
// "none" = no summon out (kept, to compare against); "" = a summon of unknown element (skipped).
if (summonElement != null && summonElement.Length > 0)
{
string key = summonElement == "none" ? "" : summonElement;
var pets = d > 0 ? Tier(wcid, d).Pets : Get(wcid).Pets;
if (!pets.TryGetValue(key, out var k)) pets[key] = k = new PetUse();
k.SecAvg = k.Kills == 0 ? seconds : k.SecAvg + Alpha * (seconds - k.SecAvg);
k.Kills++;
}
_dirty = true;
}
}
/// <summary>The monster hit us for <paramref name="damage"/> of <paramref name="element"/>.</summary>
public void RecordTaken(uint wcid, string name, string element, double damage)
{
if (wcid == 0 || damage <= 0) return;
int d = Difficulty;
lock (_lock)
{
SetNameLocked(wcid, name);
var taken = d > 0 ? Tier(wcid, d).Taken : Get(wcid).Taken; // monster damage scales
string key = string.IsNullOrEmpty(element) ? "Physical" : element;
if (!taken.TryGetValue(key, out var t)) taken[key] = t = new TakenStat();
t.Avg = t.Hits == 0 ? damage : t.Avg + Alpha * (damage - t.Avg);
t.Hits++;
if (damage > t.Max) t.Max = damage;
_dirty = true;
}
}
/// <summary>Seconds per kill over every timed fight with this monster (kills-weighted), and hit rate
/// over every weapon (-1 when unknown). For the Damage tab's main row.</summary>
public (double SecPerKill, double HitRate) GetSummary(uint wcid) => GetSummary(wcid, Difficulty);
/// <summary><see cref="GetSummary(uint)"/> for one difficulty tier (0 = real Dereth).</summary>
public (double SecPerKill, double HitRate) GetSummary(uint wcid, int difficulty)
{
lock (_lock)
{
var weapons = WeaponsAt(wcid, difficulty);
if (weapons == null) return (-1, -1);
double secW = 0; int secN = 0, hits = 0, misses = 0;
foreach (var u in weapons.Values)
{
secW += u.SecAvg * u.SecSamples; secN += u.SecSamples;
hits += u.Hits; misses += u.Misses;
}
return (secN > 0 ? secW / secN : -1, hits + misses > 0 ? (double)hits / (hits + misses) : -1);
}
}
public readonly record struct WeaponUseRow(uint WeaponId, int Hits, int Misses, double SecAvg, int SecSamples);
public readonly record struct PetUseRow(string Element, int Kills, double SecAvg);
public readonly record struct TakenRow(string Element, int Hits, double Avg, double Max);
/// <summary>The detail panel's extra tables for one monster.</summary>
public (List<WeaponUseRow> Weapons, List<PetUseRow> Pets, List<TakenRow> Taken) GetDetail(uint wcid) => GetDetail(wcid, Difficulty);
/// <summary>The detail tables at one difficulty tier (0 = real Dereth).</summary>
public (List<WeaponUseRow> Weapons, List<PetUseRow> Pets, List<TakenRow> Taken) GetDetail(uint wcid, int difficulty)
{
var w = new List<WeaponUseRow>(); var pl = new List<PetUseRow>(); var tl = new List<TakenRow>();
lock (_lock)
{
Dictionary<uint, WeaponUse>? weapons = null;
Dictionary<string, PetUse>? pets = null;
Dictionary<string, TakenStat>? taken = null;
if (difficulty > 0)
{
if (_byTier.TryGetValue((wcid, difficulty), out var tp)) { weapons = tp.Weapons; pets = tp.Pets; taken = tp.Taken; }
}
else if (_byWcid.TryGetValue(wcid, out var p)) { weapons = p.Weapons; pets = p.Pets; taken = p.Taken; }
if (weapons != null)
foreach (var u in weapons) w.Add(new(u.Key, u.Value.Hits, u.Value.Misses, u.Value.SecAvg, u.Value.SecSamples));
if (pets != null)
foreach (var k in pets) pl.Add(new(k.Key, k.Value.Kills, k.Value.SecAvg));
if (taken != null)
foreach (var t in taken) tl.Add(new(t.Key, t.Value.Hits, t.Value.Avg, t.Value.Max));
}
return (w, pl, tl);
}
/// <summary>One weapon's accuracy/fight-length record at a difficulty tier (made when missing). Caller holds _lock.</summary>
private WeaponUse Use(uint wcid, uint weaponId, int difficulty)
{
var d = difficulty > 0 ? Tier(wcid, difficulty).Weapons : Get(wcid).Weapons;
if (!d.TryGetValue(weaponId, out var u)) d[weaponId] = u = new WeaponUse();
return u;
}
/// <summary>The per-weapon records at a difficulty tier, or null when there are none. Caller holds _lock.</summary>
private Dictionary<uint, WeaponUse>? WeaponsAt(uint wcid, int difficulty)
{
if (difficulty > 0)
return _byTier.TryGetValue((wcid, difficulty), out var tp) ? tp.Weapons : null;
return _byWcid.TryGetValue(wcid, out var p) ? p.Weapons : null;
}
/// <summary>A monster's record at a difficulty tier above 0 (made when missing). Caller holds _lock.</summary>
private TierProfile Tier(uint wcid, int difficulty)
{
if (!_byTier.TryGetValue((wcid, difficulty), out var tp))
{
tp = new TierProfile();
_byTier[(wcid, difficulty)] = tp;
Get(wcid); // the monster's name and rules live on its tier-0 profile
}
return tp;
}
/// <summary>The difficulty tiers above 0 with anything learned, ascending (empty off Aelrynth).</summary>
public List<int> KnownDifficulties()
{
var set = new SortedSet<int>();
lock (_lock)
foreach (var k in _byTier.Keys) set.Add(k.Difficulty);
return new List<int>(set);
}
/// <summary>Note the tier of the most-recent cast at a wcid (negative = ring) so the Damage tab's
/// collapsed row shows the LATEST tier used. In-memory only (not persisted) — resets per session.</summary>
public void NoteCast(uint wcid, int tier, string? name = null)
@ -385,8 +811,19 @@ internal sealed class MonsterDamageStore
{
killSamples = 0;
if (wcid == 0) return 0;
int d = Difficulty;
lock (_lock)
{
if (d > 0)
{
// Only this tier's own kills: a tier-0 one-shot can take two casts at tier 10.
if (_byTier.TryGetValue((wcid, d), out var tp) && tp.Kills.TryGetValue(CastKey(weaponId, element, tier), out var k))
{
killSamples = k.KillSamples;
return k.AvgCastsToKill;
}
return 0;
}
if (_byWcid.TryGetValue(wcid, out var p) && p.Casts.TryGetValue(CastKey(weaponId, element, tier), out var s))
{
killSamples = s.KillSamples;
@ -397,11 +834,18 @@ internal sealed class MonsterDamageStore
}
/// <summary>Learned total-damage-to-kill for this wcid, or 0 if not yet learned.</summary>
public double GetLearnedHp(uint wcid)
public double GetLearnedHp(uint wcid) => GetLearnedHp(wcid, Difficulty);
/// <summary>Learned total-damage-to-kill at one difficulty tier (0 = real Dereth), or 0.</summary>
public double GetLearnedHp(uint wcid, int difficulty)
{
if (wcid == 0) return 0;
lock (_lock)
{
if (difficulty > 0)
return _byTier.TryGetValue((wcid, difficulty), out var tp) ? tp.HpPool : 0;
return _byWcid.TryGetValue(wcid, out var p) ? p.HpPool : 0;
}
}
/// <summary>User-entered HP override for this wcid (0 = none). Authoritative when &gt; 0.</summary>
@ -446,6 +890,27 @@ internal sealed class MonsterDamageStore
}
}
/// <summary>Per-monster pet choice: "" = Auto, "E:&lt;element&gt;", or "I:&lt;essence id&gt;".</summary>
public string GetManualPet(uint wcid)
{
if (wcid == 0) return "";
lock (_lock)
return _byWcid.TryGetValue(wcid, out var p) ? p.PetManual : "";
}
/// <summary>Set ("" = Auto) the per-monster pet choice. Persists on next save.</summary>
public void SetManualPet(uint wcid, string choice, string? name = null)
{
if (wcid == 0) return;
lock (_lock)
{
var p = Get(wcid);
p.PetManual = (choice ?? "").Replace('|', ' ').Trim();
if (!string.IsNullOrEmpty(name)) SetNameLocked(wcid, name);
_dirty = true;
}
}
/// <summary>User-picked offhand override for this wcid (0 = none). Stored only — combat does not equip it.</summary>
public uint GetManualOffhand(uint wcid)
{
@ -475,6 +940,50 @@ internal sealed class MonsterDamageStore
/// Fewest-casts naturally captures element effectiveness empirically (the wand
/// that kills a fire-weak mob fastest tends to be the fire wand).
/// </summary>
/// <summary>
/// The damage element that has worked best on this monster (fewest casts to
/// kill, else highest average damage), from the Damage tab's learned rows.
/// "" when nothing is learned yet.
/// </summary>
public string GetBestElement(uint wcid)
{
if (wcid == 0) return "";
lock (_lock)
{
if (!_byWcid.TryGetValue(wcid, out var p) || p.Casts.Count == 0) return "";
var byElem = new Dictionary<string, (double castsW, int kills, double dmgW, int dmg)>(StringComparer.OrdinalIgnoreCase);
foreach (var c in p.Casts)
{
string[] kp = c.Key.Split('|'); // weaponId|element|tier
if (kp.Length < 2 || string.IsNullOrWhiteSpace(kp[1])) continue;
var v = c.Value;
byElem.TryGetValue(kp[1], out var a);
a.castsW += v.AvgCastsToKill * v.KillSamples;
a.kills += v.KillSamples;
a.dmgW += v.Avg * v.Samples;
a.dmg += v.Samples;
byElem[kp[1]] = a;
}
string bestByCasts = ""; double bestCasts = double.MaxValue;
string bestByDmg = ""; double bestDmg = 0;
foreach (var kv in byElem)
{
var a = kv.Value;
if (a.kills >= 2)
{
double avgCasts = a.castsW / a.kills;
if (avgCasts > 0 && avgCasts < bestCasts) { bestCasts = avgCasts; bestByCasts = kv.Key; }
}
if (a.dmg >= 3)
{
double avgDmg = a.dmgW / a.dmg;
if (avgDmg > bestDmg) { bestDmg = avgDmg; bestByDmg = kv.Key; }
}
}
return bestByCasts.Length > 0 ? bestByCasts : bestByDmg;
}
}
public uint GetBestWeapon(uint wcid)
{
if (wcid == 0) return 0;
@ -547,11 +1056,21 @@ internal sealed class MonsterDamageStore
lock (_lock)
{
if (!_byWcid.TryGetValue(wcid, out var p)) return false;
bool removed = p.Casts.Remove(CastKey(weaponId, element, tier));
string key = CastKey(weaponId, element, tier);
bool removed = p.Casts.Remove(key);
// The row's casts-to-kill at every difficulty tier goes with it.
bool anyTier = false;
foreach (var kv in _byTier)
{
if (kv.Key.Wcid != wcid) continue;
if (kv.Value.Kills.Remove(key)) removed = true;
anyTier = true;
}
if (removed)
{
if (p.Casts.Count == 0 && p.HpSamples == 0 && p.HpManual <= 0 && p.HpPool <= 0
&& p.WeaponManual == 0 && p.OffhandManual == 0)
if (!anyTier && p.Casts.Count == 0 && p.HpSamples == 0 && p.HpManual <= 0 && p.HpPool <= 0
&& p.WeaponManual == 0 && p.OffhandManual == 0 && p.PetManual.Length == 0
&& p.Weapons.Count == 0 && p.Pets.Count == 0 && p.Taken.Count == 0)
_byWcid.Remove(wcid);
_dirty = true;
}
@ -565,6 +1084,10 @@ internal sealed class MonsterDamageStore
lock (_lock)
{
bool removed = _byWcid.Remove(wcid);
var tierKeys = new List<(uint, int)>();
foreach (var k in _byTier.Keys) if (k.Wcid == wcid) tierKeys.Add(k);
foreach (var k in tierKeys) _byTier.Remove(k);
removed |= tierKeys.Count > 0;
if (removed) _dirty = true;
return removed;
}
@ -584,6 +1107,9 @@ internal sealed class MonsterDamageStore
{
p.HpPool = 0;
p.HpSamples = 0;
p.Weapons.Clear();
p.Pets.Clear();
p.Taken.Clear();
foreach (var c in p.Casts.Values)
{
c.Avg = 0; c.Samples = 0;
@ -592,6 +1118,7 @@ internal sealed class MonsterDamageStore
c.NonCritAvg = 0; c.NonCritSamples = 0;
}
}
_byTier.Clear(); // every difficulty tier's numbers are learned statistics too
_dirty = true;
}
}
@ -606,7 +1133,13 @@ internal sealed class MonsterDamageStore
double AvgCastsToKill, int KillSamples);
/// <summary>Snapshot all learned rows for live display. Cheap; copies under lock.</summary>
public List<DamageRow> Snapshot()
public List<DamageRow> Snapshot() => Snapshot(0);
/// <summary>
/// The rows as seen at one difficulty tier: damage per cast is shared, while the HP pool and
/// casts-to-kill are that tier's own (0 / no kills where it has none). Tier 0 = today's rows.
/// </summary>
public List<DamageRow> Snapshot(int difficulty)
{
var list = new List<DamageRow>();
lock (_lock)
@ -614,6 +1147,9 @@ internal sealed class MonsterDamageStore
foreach (var kv in _byWcid)
{
var p = kv.Value;
TierProfile? tp = null;
if (difficulty > 0) _byTier.TryGetValue((kv.Key, difficulty), out tp);
double hpPool = difficulty > 0 ? tp?.HpPool ?? 0 : p.HpPool;
foreach (var c in p.Casts)
{
string[] kp = c.Key.Split('|'); // weaponId|element|tier
@ -621,9 +1157,15 @@ internal sealed class MonsterDamageStore
string element = kp.Length >= 2 ? kp[1] : "";
int tier = kp.Length >= 3 && int.TryParse(kp[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int t) ? t : 0;
var v = c.Value;
list.Add(new DamageRow(kv.Key, p.Name, p.HpPool, p.HpManual, weaponId, element, tier,
double casts = v.AvgCastsToKill; int kills = v.KillSamples;
if (difficulty > 0)
{
if (tp != null && tp.Kills.TryGetValue(c.Key, out var k)) { casts = k.AvgCastsToKill; kills = k.KillSamples; }
else { casts = 0; kills = 0; }
}
list.Add(new DamageRow(kv.Key, p.Name, hpPool, p.HpManual, weaponId, element, tier,
v.Avg, v.Samples, v.CritAvg, v.CritSamples, v.NonCritAvg, v.NonCritSamples,
v.AvgCastsToKill, v.KillSamples));
casts, kills));
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,95 @@
# RynthAi creature-type weaknesses: the fallback for monsters that aren't in
# creature_resists.tsv (custom monsters on other servers). Generated from the average
# resists of each type's creatures in the Aelrynth world database.
# id|Type|name keywords|Element multiplier,... (most damage first)
# A multiplier is damage taken (1.0 = full, 0.5 = half). The bot uses the first element
# in the list it can attack with. To change a type, put its line (same id) in
# C:\Games\RynthSuite\RynthAi\CreatureData\creature_types.txt; lines there win.
# Keywords match whole words in a monster's name when its type isn't known yet.
1|Olthoi|Olthoi|Nether 1.00,Bludgeon 0.91,Pierce 0.86,Cold 0.72,Slash 0.67,Fire 0.65,Lightning 0.35,Acid 0.32
2|Banderling|Banderling|Lightning 1.16,Nether 1.00,Fire 0.96,Cold 0.76,Slash 0.73,Acid 0.64,Pierce 0.63,Bludgeon 0.51
3|Drudge|Drudge|Fire 1.11,Cold 1.03,Nether 1.00,Slash 0.85,Acid 0.83,Bludgeon 0.81,Lightning 0.79,Pierce 0.66
4|Mosswart|Mosswart|Nether 1.02,Fire 0.99,Lightning 0.94,Bludgeon 0.79,Pierce 0.77,Acid 0.67,Slash 0.58,Cold 0.53
5|Lugian|Lugian|Nether 1.00,Lightning 0.95,Acid 0.79,Pierce 0.68,Bludgeon 0.63,Slash 0.62,Cold 0.48,Fire 0.33
6|Tumerok|Tumerok|Nether 1.00,Slash 0.91,Fire 0.72,Cold 0.69,Pierce 0.68,Bludgeon 0.67,Lightning 0.67,Acid 0.66
7|Mite|Mite|Nether 1.00,Fire 0.93,Acid 0.93,Pierce 0.82,Bludgeon 0.80,Lightning 0.78,Cold 0.75,Slash 0.74
8|Tusker|Tusker|Nether 1.00,Fire 0.97,Pierce 0.95,Cold 0.68,Acid 0.68,Bludgeon 0.67,Slash 0.48,Lightning 0.30
9|PhyntosWasp|Phyntos Wasp|Nether 1.00,Bludgeon 0.87,Slash 0.82,Pierce 0.82,Cold 0.67,Acid 0.67,Fire 0.62,Lightning 0.54
10|Rat||Bludgeon 1.14,Fire 1.01,Nether 1.00,Pierce 0.97,Lightning 0.92,Slash 0.69,Acid 0.68,Cold 0.61
13|Golem|Golem|Bludgeon 2.70,Acid 2.66,Cold 2.57,Fire 2.56,Pierce 2.53,Slash 2.48,Nether 1.00,Lightning 0.80
14|Undead|Undead|Nether 1.00,Fire 0.84,Slash 0.74,Bludgeon 0.68,Acid 0.66,Lightning 0.62,Pierce 0.51,Cold 0.39
15|Gromnie|Gromnie|Nether 1.00,Pierce 0.82,Bludgeon 0.82,Slash 0.80,Acid 0.71,Cold 0.70,Lightning 0.68,Fire 0.60
16|Reedshark|Reedshark|Nether 1.02,Cold 0.80,Slash 0.79,Pierce 0.75,Acid 0.74,Lightning 0.72,Bludgeon 0.68,Fire 0.56
17|Armoredillo|Armoredillo|Nether 1.00,Pierce 0.92,Lightning 0.85,Cold 0.75,Acid 0.59,Slash 0.58,Bludgeon 0.52,Fire 0.49
19|Virindi|Virindi|Nether 1.00,Slash 0.86,Pierce 0.80,Bludgeon 0.80,Fire 0.80,Acid 0.79,Cold 0.48,Lightning 0.47
20|Wisp||Slash 1.04,Nether 1.00,Pierce 0.90,Bludgeon 0.86,Lightning 0.56,Acid 0.42,Fire 0.40,Cold 0.39
21|Knathtead|K'nath|Nether 1.00,Fire 0.83,Acid 0.83,Lightning 0.82,Slash 0.74,Pierce 0.73,Cold 0.67,Bludgeon 0.54
22|Shadow|Shadow|Nether 0.97,Slash 0.88,Fire 0.87,Bludgeon 0.63,Pierce 0.52,Lightning 0.49,Acid 0.27,Cold 0.15
23|Mattekar|Mattekar|Nether 1.00,Pierce 0.90,Fire 0.88,Bludgeon 0.86,Acid 0.75,Slash 0.59,Cold 0.45,Lightning 0.34
25|Rabbit||Fire 1.50,Slash 1.00,Pierce 1.00,Bludgeon 1.00,Cold 1.00,Acid 1.00,Lightning 1.00,Nether 1.00
26|Sclavus|Sclavus|Nether 1.00,Cold 0.98,Slash 0.95,Pierce 0.75,Fire 0.75,Bludgeon 0.46,Acid 0.27,Lightning 0.27
27|ShallowsShark|Shallows|Nether 1.02,Pierce 0.88,Lightning 0.87,Slash 0.67,Bludgeon 0.64,Cold 0.62,Fire 0.61,Acid 0.54
28|Monouga|Monouga|Nether 1.00,Cold 0.96,Pierce 0.91,Acid 0.82,Slash 0.70,Lightning 0.68,Fire 0.66,Bludgeon 0.60
29|Zefir|Zefir|Nether 1.00,Slash 0.95,Bludgeon 0.92,Acid 0.80,Pierce 0.75,Cold 0.74,Lightning 0.53,Fire 0.51
30|Skeleton|Skeleton|Nether 0.99,Bludgeon 0.89,Slash 0.62,Fire 0.59,Acid 0.47,Lightning 0.44,Pierce 0.37,Cold 0.35
31|Human|Human|Nether 1.00,Lightning 0.77,Pierce 0.62,Acid 0.61,Bludgeon 0.58,Slash 0.57,Cold 0.55,Fire 0.50
32|Shreth|Shreth|Cold 1.18,Bludgeon 1.00,Nether 1.00,Pierce 0.78,Slash 0.67,Acid 0.67,Lightning 0.61,Fire 0.56
33|Chittick|Chittick|Pierce 1.00,Nether 1.00,Acid 0.85,Cold 0.71,Lightning 0.67,Fire 0.63,Slash 0.58,Bludgeon 0.55
34|Moarsman||Nether 1.00,Slash 0.83,Cold 0.80,Lightning 0.78,Pierce 0.66,Fire 0.61,Acid 0.61,Bludgeon 0.55
35|OlthoiLarvae|Larvae|Nether 1.00,Pierce 0.89,Bludgeon 0.87,Slash 0.70,Cold 0.69,Fire 0.68,Lightning 0.37,Acid 0.36
36|Slithis|Slithis|Nether 1.00,Fire 0.72,Bludgeon 0.63,Slash 0.58,Acid 0.58,Pierce 0.51,Cold 0.25,Lightning 0.17
38|FireElemental||Nether 1.00,Cold 0.72,Slash 0.44,Pierce 0.44,Bludgeon 0.44,Acid 0.39,Lightning 0.30,Fire 0.04
39|Snowman|Snowman|Nether 1.00,Fire 0.99,Slash 0.91,Bludgeon 0.91,Acid 0.91,Lightning 0.91,Pierce 0.85,Cold 0.00
40|Unknown||Nether 1.00,Slash 0.81,Pierce 0.81,Bludgeon 0.79,Acid 0.57,Lightning 0.53,Fire 0.46,Cold 0.39
41|Bunny|Bunny|Fire 1.19,Nether 1.00,Pierce 0.88,Slash 0.86,Bludgeon 0.85,Acid 0.84,Lightning 0.84,Cold 0.82
42|LightningElemental||Nether 1.00,Acid 0.74,Slash 0.47,Pierce 0.47,Bludgeon 0.47,Cold 0.37,Fire 0.30,Lightning 0.00
43|Rockslide||Bludgeon 1.00,Nether 1.00,Pierce 0.90,Slash 0.53,Fire 0.40,Lightning 0.40,Acid 0.33,Cold 0.10
44|Grievver|Grievver|Nether 1.00,Slash 0.99,Pierce 0.76,Bludgeon 0.68,Fire 0.38,Lightning 0.33,Acid 0.28,Cold 0.26
45|Niffis|Niffis|Nether 0.94,Slash 0.92,Cold 0.81,Acid 0.81,Bludgeon 0.55,Pierce 0.53,Fire 0.50,Lightning 0.50
46|Ursuin|Ursuin|Pierce 1.00,Nether 1.00,Fire 0.86,Slash 0.59,Bludgeon 0.59,Cold 0.59,Acid 0.59,Lightning 0.59
47|Crystal|Crystal|Nether 1.00,Bludgeon 0.85,Slash 0.76,Pierce 0.74,Lightning 0.71,Cold 0.59,Fire 0.45,Acid 0.44
48|HollowMinion|Hollow|Nether 1.00,Cold 0.65,Slash 0.49,Pierce 0.49,Acid 0.49,Bludgeon 0.32,Fire 0.24,Lightning 0.24
49|Scarecrow|Scarecrow|Fire 1.00,Nether 1.00,Slash 0.90,Lightning 0.90,Bludgeon 0.53,Pierce 0.51,Cold 0.51,Acid 0.51
50|Idol||Nether 1.00,Slash 0.96,Fire 0.87,Bludgeon 0.67,Pierce 0.50,Lightning 0.50,Acid 0.20,Cold 0.10
51|Empyrean||Nether 1.00,Slash 0.60,Pierce 0.60,Bludgeon 0.60,Fire 0.00,Cold 0.00,Acid 0.00,Lightning 0.00
52|Hopeslayer||Fire 1.50,Slash 1.00,Pierce 1.00,Bludgeon 1.00,Cold 1.00,Acid 1.00,Lightning 1.00,Nether 1.00
53|Doll|Doll|Nether 1.00,Bludgeon 0.94,Slash 0.93,Pierce 0.84,Fire 0.84,Acid 0.84,Cold 0.59,Lightning 0.57
54|Marionette|Marionette|Nether 1.00,Slash 0.99,Fire 0.68,Pierce 0.67,Acid 0.64,Cold 0.60,Lightning 0.58,Bludgeon 0.51
55|Carenzi|Carenzi|Bludgeon 1.00,Nether 1.00,Cold 0.90,Slash 0.80,Acid 0.76,Lightning 0.74,Pierce 0.60,Fire 0.60
56|Siraluun|Siraluun|Cold 1.00,Acid 1.00,Nether 1.00,Bludgeon 0.95,Slash 0.80,Pierce 0.60,Fire 0.60,Lightning 0.50
57|AunTumerok||Nether 1.00,Slash 0.78,Pierce 0.78,Bludgeon 0.78,Fire 0.78,Cold 0.78,Acid 0.78,Lightning 0.78
58|HeaTumerok||Nether 1.00,Cold 0.87,Pierce 0.86,Fire 0.86,Acid 0.85,Lightning 0.84,Slash 0.82,Bludgeon 0.82
59|Simulacrum|Simulacrum|Nether 1.00,Bludgeon 0.88,Pierce 0.85,Slash 0.84,Fire 0.80,Lightning 0.76,Acid 0.70,Cold 0.65
60|AcidElemental||Nether 1.00,Lightning 0.60,Slash 0.39,Pierce 0.39,Bludgeon 0.39,Cold 0.36,Fire 0.24,Acid 0.00
61|FrostElemental||Nether 0.99,Fire 0.66,Slash 0.49,Pierce 0.48,Bludgeon 0.48,Lightning 0.41,Acid 0.38,Cold 0.03
62|Elemental||Nether 1.00,Slash 0.59,Bludgeon 0.59,Pierce 0.57,Acid 0.46,Fire 0.41,Lightning 0.40,Cold 0.39
63|Statue|Statue|Nether 1.00,Acid 0.69,Lightning 0.61,Fire 0.50,Cold 0.50,Bludgeon 0.26,Slash 0.15,Pierce 0.15
64|Wall|Wall|Nether 1.00,Bludgeon 0.72,Slash 0.69,Pierce 0.69,Acid 0.69,Lightning 0.69,Fire 0.68,Cold 0.64
65|AlteredHuman|Martine|Nether 1.00,Slash 0.10,Pierce 0.10,Bludgeon 0.10,Fire 0.10,Cold 0.10,Acid 0.10,Lightning 0.10
68|DarkSarcophagus||Nether 1.00,Fire 0.50,Slash 0.00,Pierce 0.00,Bludgeon 0.00,Cold 0.00,Acid 0.00,Lightning 0.00
69|Chicken|Chicken Chick|Fire 1.00,Nether 1.00,Lightning 0.90,Bludgeon 0.89,Slash 0.81,Cold 0.81,Pierce 0.77,Acid 0.77
70|GotrokLugian|Gotrok|Lightning 1.05,Nether 1.00,Acid 0.82,Pierce 0.67,Slash 0.64,Bludgeon 0.63,Cold 0.43,Fire 0.28
71|Margul|Margul|Nether 1.00,Bludgeon 0.95,Cold 0.95,Lightning 0.95,Slash 0.85,Pierce 0.85,Fire 0.74,Acid 0.74
75|Burun|Burun|Nether 1.00,Pierce 0.75,Cold 0.74,Slash 0.59,Fire 0.59,Bludgeon 0.47,Lightning 0.34,Acid 0.12
77|Ghost|Spectral|Nether 1.01,Bludgeon 0.60,Fire 0.56,Slash 0.54,Acid 0.48,Pierce 0.46,Lightning 0.44,Cold 0.39
78|Fiun|Fiun|Nether 1.00,Fire 0.94,Lightning 0.94,Slash 0.78,Pierce 0.74,Acid 0.73,Bludgeon 0.66,Cold 0.60
79|Eater|Eater|Slash 1.19,Pierce 1.17,Nether 1.00,Fire 0.99,Cold 0.99,Lightning 0.99,Bludgeon 0.61,Acid 0.61
80|Penguin|Penguin|Fire 1.30,Nether 1.00,Lightning 0.90,Slash 0.86,Pierce 0.75,Acid 0.75,Bludgeon 0.66,Cold 0.60
81|Ruschk|Ruschk|Fire 1.06,Nether 1.00,Lightning 0.97,Pierce 0.96,Bludgeon 0.89,Slash 0.88,Acid 0.81,Cold 0.79
82|Thrungus|Thrungus|Nether 1.00,Fire 0.89,Lightning 0.70,Cold 0.63,Pierce 0.62,Slash 0.61,Acid 0.50,Bludgeon 0.47
83|ViamontianKnight|Viamontian|Lightning 1.20,Fire 1.17,Nether 1.00,Bludgeon 0.90,Cold 0.90,Acid 0.90,Slash 0.80,Pierce 0.80
84|Remoran|Remoran|Nether 0.96,Bludgeon 0.52,Pierce 0.47,Fire 0.42,Lightning 0.39,Slash 0.38,Cold 0.38,Acid 0.38
85|Swarm||Nether 1.00,Slash 0.65,Bludgeon 0.65,Fire 0.65,Pierce 0.40,Cold 0.40,Acid 0.40,Lightning 0.40
86|Moar|Moar|Lightning 1.00,Nether 1.00,Slash 0.85,Cold 0.79,Acid 0.76,Pierce 0.62,Fire 0.52,Bludgeon 0.43
89|Mukkir|Mukkir|Nether 1.00,Pierce 0.88,Bludgeon 0.88,Slash 0.65,Fire 0.63,Cold 0.63,Acid 0.38,Lightning 0.23
91|Food||Nether 1.00,Cold 0.90,Pierce 0.88,Lightning 0.88,Fire 0.86,Slash 0.79,Bludgeon 0.73,Acid 0.61
92|ParadoxOlthoi|Touched Paradox|Nether 1.00,Bludgeon 0.86,Pierce 0.84,Slash 0.68,Fire 0.58,Cold 0.58,Lightning 0.39,Acid 0.32
93|Harvest|Pumpkin|Nether 1.00,Bludgeon 0.77,Pierce 0.73,Slash 0.70,Fire 0.61,Acid 0.56,Lightning 0.47,Cold 0.39
95|Apparition||Nether 1.00,Bludgeon 0.70,Pierce 0.65,Slash 0.60,Fire 0.35,Cold 0.35,Acid 0.35,Lightning 0.35
96|Aerbax|Aerbax's|Nether 0.95,Pierce 0.94,Slash 0.92,Fire 0.92,Acid 0.87,Bludgeon 0.65,Cold 0.43,Lightning 0.43
97|Touched||Nether 1.00,Slash 0.01,Pierce 0.01,Bludgeon 0.01,Fire 0.01,Cold 0.01,Acid 0.01,Lightning 0.01
98|BlightedMoarsman||Nether 1.00,Lightning 0.94,Slash 0.89,Cold 0.83,Acid 0.81,Pierce 0.56,Bludgeon 0.50,Fire 0.49
99|GearKnight|Gear Gearknight|Acid 1.29,Nether 1.00,Lightning 0.96,Bludgeon 0.51,Cold 0.51,Slash 0.50,Pierce 0.50,Fire 0.50
100|Gurog|Gurog|Nether 1.00,Pierce 0.80,Fire 0.80,Lightning 0.40,Slash 0.31,Bludgeon 0.31,Cold 0.31,Acid 0.31
101|Anekshay||Nether 1.07,Acid 0.76,Bludgeon 0.65,Cold 0.45,Lightning 0.40,Fire 0.34,Pierce 0.33,Slash 0.29
28640|Type28640||Slash 1.20,Pierce 1.20,Fire 1.00,Cold 1.00,Lightning 1.00,Nether 1.00,Bludgeon 0.60,Acid 0.60

File diff suppressed because one or more lines are too long

View file

@ -6,11 +6,17 @@
// locked (UseObject fails to open it).
//
// State machine: None → Opening → CheckingResult → Unlocking → RetryOpen → Cooldown
//
// Two ways in: the proximity scan (OpenDoors setting, nearest closed door in
// range), and a requested door (RequestDoorOpen): the nav engine's recovery
// detour asks for the closed door on its next leg. A requested door is opened
// even with OpenDoors off, since the detour was planned through that doorway.
// ============================================================================
using System;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
@ -22,11 +28,14 @@ public sealed partial class RynthAiPlugin
private bool _doorPausedNav;
private DoorState _doorState = DoorState.None;
private long _doorLastDiagAt;
private int _doorRequestedId; // asked for by the nav recovery detour; taken on the next idle tick
private bool _doorTargetRequested; // the current target came from a request
// Doors we've already opened — skip for 60s so we don't re-target them
private readonly System.Collections.Generic.Dictionary<int, long> _doorOpenedRecently = new();
private const long DoorBusyTimeoutMs = 3000;
private const long DoorResultSettleMs = 1200; // a use is not judged "didn't open" sooner (below DoorBusyTimeoutMs)
private const long DoorCooldownMs = 5000;
private const long DoorOpenedSkipMs = 60000;
private const int DoorMaxAttempts = 3;
@ -49,9 +58,11 @@ public sealed partial class RynthAiPlugin
private bool TickDoorInteraction()
{
var settings = _dashboard?.Settings;
if (settings == null || !settings.IsMacroRunning || !settings.OpenDoors)
bool requested = _doorRequestedId != 0 || _doorTargetRequested;
if (settings == null || !settings.IsMacroRunning || (!settings.OpenDoors && !requested))
{
ResetDoorState();
_doorRequestedId = 0;
return false;
}
@ -70,10 +81,23 @@ public sealed partial class RynthAiPlugin
// ── Idle: scan for a nearby closed door ─────────────────────────────
if (_doorState == DoorState.None)
{
int doorId = FindNearestClosedDoor(settings.OpenDoorRange, now);
int doorId = 0;
if (_doorRequestedId != 0)
{
int req = _doorRequestedId;
_doorRequestedId = 0;
if (!IsDoorOpen(req))
{
doorId = req;
_doorTargetRequested = true;
}
}
if (doorId == 0 && settings.OpenDoors)
doorId = FindNearestClosedDoor(settings.OpenDoorRange, now);
if (doorId == 0) return false;
Host.Log($"[RynthAi] Door: targeting 0x{(uint)doorId:X8} (state={GetDoorStateDebug(doorId)}, busy={_busyCount})");
string why = _doorTargetRequested ? " (asked for by the nav detour)" : "";
Host.Log($"[RynthAi] Door: targeting 0x{(uint)doorId:X8}{why} (state={GetDoorStateDebug(doorId)}, busy={_busyCount})");
_doorTargetId = doorId;
_doorState = DoorState.Opening;
_doorAttempts = 0;
@ -83,7 +107,8 @@ public sealed partial class RynthAiPlugin
if (Host.HasStopCompletely) Host.StopCompletely();
_doorPausedNav = true;
Host.UseObject(unchecked((uint)doorId));
Host.UseFor(unchecked((uint)doorId), "Door",
_doorTargetRequested ? "the nav detour asked to open this door" : $"Open Doors: closed door within {settings.OpenDoorRange:0} yd");
return true;
}
@ -110,7 +135,7 @@ public sealed partial class RynthAiPlugin
Host.Log($"[RynthAi] Door: timeout in {_doorState}, retry #{_doorAttempts} for 0x{(uint)_doorTargetId:X8} (busy={_busyCount})");
_doorState = DoorState.Opening;
_doorActionAt = now;
Host.UseObject(unchecked((uint)_doorTargetId));
Host.UseFor(unchecked((uint)_doorTargetId), "Door", $"retry #{_doorAttempts}: the door didn't open in {DoorBusyTimeoutMs} ms");
return true;
}
@ -124,6 +149,10 @@ public sealed partial class RynthAiPlugin
MarkDoorOpenedAndReset(now);
return false;
}
// The use is queued for AC's main thread and the server answers later: the
// busy count was still 0 when this read "not open" ~45 ms after the use
// (2026-10-02 logs), every time. Give the door time to swing first.
if (now - _doorActionAt < DoorResultSettleMs) return true;
Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} not open after use ({GetDoorStateDebug(_doorTargetId)}), checking result");
_doorState = DoorState.CheckingResult;
_doorActionAt = now;
@ -148,7 +177,7 @@ public sealed partial class RynthAiPlugin
Host.Log($"[RynthAi] Door: using lockpick {lockpick.Name} on 0x{(uint)_doorTargetId:X8}");
_doorState = DoorState.Unlocking;
_doorActionAt = now;
Host.UseObjectOn(unchecked((uint)lockpick.Id), unchecked((uint)_doorTargetId));
Host.UseOnFor(unchecked((uint)lockpick.Id), unchecked((uint)_doorTargetId), "Door", "Auto Unlock Doors: lockpick on a door that didn't open");
return true;
case DoorState.Unlocking:
@ -156,7 +185,7 @@ public sealed partial class RynthAiPlugin
Host.Log($"[RynthAi] Door: unlock done, retrying open 0x{(uint)_doorTargetId:X8}");
_doorState = DoorState.RetryOpen;
_doorActionAt = now;
Host.UseObject(unchecked((uint)_doorTargetId));
Host.UseFor(unchecked((uint)_doorTargetId), "Door", "open again after the lockpick");
return true;
case DoorState.RetryOpen:
@ -167,6 +196,7 @@ public sealed partial class RynthAiPlugin
MarkDoorOpenedAndReset(now);
return false;
}
if (now - _doorActionAt < DoorResultSettleMs) return true;
_doorAttempts++;
if (_doorAttempts >= DoorMaxAttempts)
{
@ -178,7 +208,7 @@ public sealed partial class RynthAiPlugin
{
_doorState = DoorState.Opening;
_doorActionAt = now;
Host.UseObject(unchecked((uint)_doorTargetId));
Host.UseFor(unchecked((uint)_doorTargetId), "Door", $"still closed after the lockpick, try {_doorAttempts + 1}");
}
return true;
@ -206,6 +236,58 @@ public sealed partial class RynthAiPlugin
_doorState = DoorState.None;
_doorAttempts = 0;
_doorPausedNav = false;
_doorTargetRequested = false;
}
/// <summary>
/// Nav recovery: open this door on the next tick, whether or not OpenDoors is on.
/// Ignored while another door is being handled (the detour asks again later).
/// </summary>
private void RequestDoorOpen(int doorId)
{
if (doorId != 0 && _doorState == DoorState.None) _doorRequestedId = doorId;
}
/// <summary>
/// Nav recovery: the closed door nearest the start of the leg (ax, ay) to (bx, by), in
/// world units, within <paramref name="corridor"/> of it and about the same height as
/// <paramref name="z"/>; 0 when there is none. Doors are static objects with BF_DOOR
/// (or a door-like name when the bitfield isn't available).
/// </summary>
private int FindClosedDoorOnLeg(double ax, double ay, double bx, double by, double z, double corridor)
{
if (_objectCache == null || !Host.HasGetObjectPosition) return 0;
bool hasBitfield = Host.HasGetObjectBitfield;
double dx = bx - ax, dy = by - ay;
double len2 = dx * dx + dy * dy;
int bestId = 0;
double bestT = double.MaxValue;
foreach (var wo in _objectCache.GetLandscapeObjects())
{
uint uid = unchecked((uint)wo.Id);
if (uid >= 0x80000000u) continue;
if (hasBitfield)
{
if (!Host.TryGetObjectBitfield(uid, out uint bf) || (bf & 0x1000u) == 0) continue;
}
else
{
string nl = (wo.Name ?? string.Empty).ToLowerInvariant();
if (!nl.Contains("door") && !nl.Contains("gate") && !nl.Contains("hatch") && !nl.Contains("portcullis")) continue;
}
if (IsDoorOpen(wo.Id)) continue;
if (!Host.TryGetObjectPosition(uid, out uint cell, out float x, out float y, out float oz)) continue;
if (Math.Abs(oz - z) > 4.0) continue;
double px = ((cell >> 24) & 0xFF) * 192.0 + x;
double py = ((cell >> 16) & 0xFF) * 192.0 + y;
double t = len2 < 1e-6 ? 0.0 : Math.Clamp(((px - ax) * dx + (py - ay) * dy) / len2, 0.0, 1.0);
double cx = ax + dx * t - px, cy = ay + dy * t - py;
if (cx * cx + cy * cy > corridor * corridor) continue;
if (t < bestT) { bestT = t; bestId = wo.Id; }
}
return bestId;
}
private int FindNearestClosedDoor(float rangeYards, long now)

View file

@ -0,0 +1,382 @@
// DungeonGeometry: the openings, floors and walls of a dungeon landblock, for laying routes.
//
// DungeonPathfinder walks the EnvCell portal graph. A graph edge says two cells share an
// opening; this class says where that opening is, how wide it is and which way it faces,
// from the portal polygons of the dungeon map geometry DungeonLOS already builds (render
// polygons with the portal flag, one in each of the two cells, at the same spot). With that:
//
// - a NARROW opening (a doorway, a hallway mouth, the joint between two corridor pieces)
// gets an approach point centred in front of it and an exit point centred beyond it, on
// its centre line, so the character lines up and goes through straight;
// - a WIDE opening (8 m or more: a whole 10 m cell side, or the diagonal of one) is no
// opening at all to a player: it joins two cells of one big room. DungeonPathfinder
// merges those cells into one room and crosses it directly.
//
// Floors (physics floor polygons) and walls (upright render polygons) say whether a straight
// line across a room stays on its floor and clear of its walls (an L-shaped room, a pillar).
//
// World units throughout (metres; the nav code calls them yards): x east, y north, z up.
// Pure data and maths; Build takes plain polygon lists, so tests feed it fixtures.
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.Raycasting;
namespace RynthCore.Plugin.RynthAi;
/// <summary>One opening between two cells.</summary>
internal sealed class DungeonDoorway
{
public uint CellA, CellB;
/// <summary>Centre of the opening at floor level (world units; z = its lowest vertex).</summary>
public double X, Y, Z;
/// <summary>Horizontal unit normal, pointing from CellA into CellB.</summary>
public double Nx, Ny;
/// <summary>Horizontal width of the opening.</summary>
public double Width;
public bool IsWide => Width >= DungeonGeometry.WideOpeningMeters;
/// <summary>The normal pointing out of <paramref name="fromCell"/> through the opening.</summary>
public (double Nx, double Ny) NormalFrom(uint fromCell) => fromCell == CellA ? (Nx, Ny) : (-Nx, -Ny);
}
internal sealed class DungeonGeometry
{
/// <summary>An opening at least this wide joins two cells of one room (a 10 m cell side is
/// open). Corridor and doorway openings in AC dungeons are about 5 m; 0x6346 has 5.3 m
/// (568 pairs), 7 m (2), 10 m (60) and 14 m (35).</summary>
public const double WideOpeningMeters = 8.0;
/// <summary>Portal polygons in two cells are the same opening when their centres are this close.</summary>
private const double PairTolerance = 1.5;
// A floor counts under a point when it is at most this far above / below the given height.
private const double FloorAbove = 1.0, FloorBelow = 4.0;
// Walls that matter for walking: they reach into this band above the floor. Lower lips
// and kerbs are what snags at doorways, so the band starts low.
private const double WallBandLow = 0.25, WallBandHigh = 1.8;
private readonly Dictionary<ulong, DungeonDoorway> _doorways = new();
private readonly Dictionary<uint, List<Vector3[]>> _floors = new();
private readonly Dictionary<uint, List<WallSeg>> _walls = new();
private readonly struct WallSeg
{
public readonly double X0, Y0, X1, Y1, ZMin, ZMax;
public WallSeg(double x0, double y0, double x1, double y1, double zMin, double zMax)
{ X0 = x0; Y0 = y0; X1 = x1; Y1 = y1; ZMin = zMin; ZMax = zMax; }
}
public int DoorwayCount => _doorways.Count;
public int FloorCellCount => _floors.Count;
// ── Building ────────────────────────────────────────────────────────────
/// <summary>
/// Builds the geometry for a cell graph. <paramref name="portalPolys"/> are the polygons
/// flagged as portals (render geometry), <paramref name="floorPolys"/> the upward-facing
/// physics floor polygons, <paramref name="wallPolys"/> the other render polygons (only
/// the upright ones are used). Any list may be empty: missing data just means fewer
/// doorways (the pathfinder falls back to cell-centre midpoints) or no floor/wall checks.
/// </summary>
public static DungeonGeometry Build(
IReadOnlyDictionary<uint, DungeonNavNode> graph,
IEnumerable<(uint CellId, Vector3[] Verts)> portalPolys,
IEnumerable<(uint CellId, Vector3[] Verts)> floorPolys,
IEnumerable<(uint CellId, Vector3[] Verts)> wallPolys)
{
var g = new DungeonGeometry();
foreach (var (cell, v) in floorPolys)
{
if (v == null || v.Length < 3) continue;
if (!IsUpwardFloor(v)) continue; // the "floor" list holds ceilings too
if (!g._floors.TryGetValue(cell, out var list)) g._floors[cell] = list = new List<Vector3[]>();
list.Add(v);
}
foreach (var (cell, v) in wallPolys)
{
if (v == null || v.Length < 3) continue;
if (!TryWallFootprint(v, out var seg)) continue;
if (!g._walls.TryGetValue(cell, out var list)) g._walls[cell] = list = new List<WallSeg>();
list.Add(seg);
}
// Portal polygons per cell: centre, horizontal normal, width.
var portals = new Dictionary<uint, List<PortalPoly>>();
foreach (var (cell, v) in portalPolys)
{
if (v == null || v.Length < 3) continue;
if (!TryPortalPoly(v, out var pp)) continue;
if (!portals.TryGetValue(cell, out var list)) portals[cell] = list = new List<PortalPoly>();
list.Add(pp);
}
foreach (var node in graph.Values)
{
foreach (uint nb in node.Neighbors)
{
if (nb <= node.CellId) continue; // each edge once
if (!graph.TryGetValue(nb, out var other)) continue;
if (!portals.TryGetValue(node.CellId, out var aList) || !portals.TryGetValue(nb, out var bList)) continue;
if (TryMatch(g, node, other, aList, bList, out var door))
g._doorways[EdgeKey(node.CellId, nb)] = door;
}
}
return g;
}
private readonly struct PortalPoly
{
public readonly double X, Y, Z, CentreZ, Nx, Ny, Width;
public PortalPoly(double x, double y, double z, double cz, double nx, double ny, double w)
{ X = x; Y = y; Z = z; CentreZ = cz; Nx = nx; Ny = ny; Width = w; }
}
private static bool TryPortalPoly(Vector3[] v, out PortalPoly pp)
{
pp = default;
NewellNormal(v, out double nx, out double ny, out double nz);
double len = Math.Sqrt(nx * nx + ny * ny + nz * nz);
if (len < 1e-6) return false;
double hx = nx / len, hy = ny / len;
double h = Math.Sqrt(hx * hx + hy * hy);
// A floor or ceiling portal (a shaft) has no horizontal facing: not a doorway.
if (h < 0.5) return false;
hx /= h; hy /= h;
// Width along the opening (perpendicular to the normal, horizontal); centre at the
// middle of that span, the mean along the normal, at the lowest vertex.
double px = -hy, py = hx;
double minS = double.MaxValue, maxS = double.MinValue, sumN = 0, minZ = double.MaxValue, sumZ = 0;
foreach (var p in v)
{
double s = p.X * px + p.Y * py;
if (s < minS) minS = s;
if (s > maxS) maxS = s;
sumN += p.X * hx + p.Y * hy;
if (p.Z < minZ) minZ = p.Z;
sumZ += p.Z;
}
double midS = (minS + maxS) * 0.5, meanN = sumN / v.Length;
pp = new PortalPoly(px * midS + hx * meanN, py * midS + hy * meanN, minZ, sumZ / v.Length, hx, hy, maxS - minS);
return true;
}
private static bool TryMatch(DungeonGeometry g, DungeonNavNode a, DungeonNavNode b,
List<PortalPoly> aList, List<PortalPoly> bList, out DungeonDoorway door)
{
door = null!;
double ax = NavToWorld(a.EW), ay = NavToWorld(a.NS), bx = NavToWorld(b.EW), by = NavToWorld(b.NS);
double midX = (ax + bx) * 0.5, midY = (ay + by) * 0.5;
double best = double.MaxValue;
PortalPoly hit = default;
bool found = false;
foreach (var pa in aList)
{
foreach (var pb in bList)
{
double dx = pa.X - pb.X, dy = pa.Y - pb.Y, dz = pa.CentreZ - pb.CentreZ;
if (dx * dx + dy * dy + dz * dz > PairTolerance * PairTolerance) continue;
// If two cells share more than one opening, take the one nearest the line between them.
double dm = (pa.X - midX) * (pa.X - midX) + (pa.Y - midY) * (pa.Y - midY);
if (dm < best) { best = dm; hit = pa; found = true; }
}
}
if (!found) return false;
double nx = hit.Nx, ny = hit.Ny;
// Orient A -> B. The floors decide when they can (a cell's origin isn't always its
// middle): a step back from the opening must be on A's floor, a step forward on B's.
int vote = 0;
if (g.HasFloor(a.CellId)) vote += g.OnCellFloor(a.CellId, hit.X - nx, hit.Y - ny, hit.Z) ? 1 : g.OnCellFloor(a.CellId, hit.X + nx, hit.Y + ny, hit.Z) ? -1 : 0;
if (g.HasFloor(b.CellId)) vote += g.OnCellFloor(b.CellId, hit.X + nx, hit.Y + ny, hit.Z) ? 1 : g.OnCellFloor(b.CellId, hit.X - nx, hit.Y - ny, hit.Z) ? -1 : 0;
if (vote == 0) vote = (bx - ax) * nx + (by - ay) * ny >= 0 ? 1 : -1; // cell centres
if (vote < 0) { nx = -nx; ny = -ny; }
door = new DungeonDoorway
{
CellA = a.CellId, CellB = b.CellId,
X = hit.X, Y = hit.Y, Z = hit.Z,
Nx = nx, Ny = ny,
Width = hit.Width,
};
return true;
}
private static bool TryWallFootprint(Vector3[] v, out WallSeg seg)
{
seg = default;
NewellNormal(v, out double nx, out double ny, out double nz);
double len = Math.Sqrt(nx * nx + ny * ny + nz * nz);
if (len < 1e-6) return false;
if (Math.Abs(nz) / len > 0.5) return false; // floor / ceiling / ramp, not a wall
double hx = nx, hy = ny, h = Math.Sqrt(hx * hx + hy * hy);
if (h < 1e-9) return false;
double px = -hy / h, py = hx / h; // along the wall
double minS = double.MaxValue, maxS = double.MinValue, minZ = double.MaxValue, maxZ = double.MinValue;
double sx0 = 0, sy0 = 0, sx1 = 0, sy1 = 0;
foreach (var p in v)
{
double s = p.X * px + p.Y * py;
if (s < minS) { minS = s; sx0 = p.X; sy0 = p.Y; }
if (s > maxS) { maxS = s; sx1 = p.X; sy1 = p.Y; }
if (p.Z < minZ) minZ = p.Z;
if (p.Z > maxZ) maxZ = p.Z;
}
if (maxS - minS < 0.05) return false;
seg = new WallSeg(sx0, sy0, sx1, sy1, minZ, maxZ);
return true;
}
/// <summary>
/// A polygon facing up (counter-clockwise seen from above). DungeonLOS's floor polygon list
/// keeps every near-horizontal physics polygon, ceilings included: at 0x6346 the corridor
/// ceilings 3.8 m up are in it, and some cells have only their ceiling there.
/// </summary>
internal static bool IsUpwardFloor(Vector3[] v)
{
NewellNormal(v, out double nx, out double ny, out double nz);
double len = Math.Sqrt(nx * nx + ny * ny + nz * nz);
return len > 1e-6 && nz / len >= 0.4;
}
// ── Queries ─────────────────────────────────────────────────────────────
public bool TryGetDoorway(uint a, uint b, out DungeonDoorway door) => _doorways.TryGetValue(EdgeKey(a, b), out door!);
public bool HasFloor(uint cell) => _floors.ContainsKey(cell);
/// <summary>True when (x, y) is on one of the cell's floor polygons, the floor at most 1 m
/// above and 4 m below z. False when the cell has no floor data.</summary>
public bool OnCellFloor(uint cell, double x, double y, double z)
{
if (!_floors.TryGetValue(cell, out var list)) return false;
foreach (var v in list)
{
if (!InsidePolygon2D(v, x, y)) continue;
double fz = FloorZAt(v);
double dz = z - fz;
if (dz >= -FloorAbove && dz <= FloorBelow) return true;
}
return false;
}
/// <summary>True when (x, y) is on the floor of any of <paramref name="cells"/>; also true
/// when none of them has floor data (nothing to check against).</summary>
public bool OnFloorOfAny(IEnumerable<uint> cells, double x, double y, double z)
{
bool anyFloor = false;
foreach (uint c in cells)
{
if (!_floors.ContainsKey(c)) continue;
anyFloor = true;
if (OnCellFloor(c, x, y, z)) return true;
}
return !anyFloor;
}
/// <summary>
/// Can a character walk the straight line (x0, y0) to (x1, y1) at floor height z, inside
/// <paramref name="cells"/> (one room)? The line and two lines <paramref name="clearance"/>
/// to either side must stay on the room's floor (sampled every half metre) and cross none of
/// its walls that reach into knee-to-head height.
/// </summary>
public bool SegmentClear(IReadOnlyCollection<uint> cells, double x0, double y0, double z0,
double x1, double y1, double z1, double clearance = 0.5)
{
double dx = x1 - x0, dy = y1 - y0;
double len = Math.Sqrt(dx * dx + dy * dy);
if (len < 1e-6) return true;
double ox = -dy / len * clearance, oy = dx / len * clearance;
// Floor: centre line and both sides.
bool checkFloor = false;
foreach (uint c in cells) if (_floors.ContainsKey(c)) { checkFloor = true; break; }
if (checkFloor)
{
int steps = Math.Max(1, (int)Math.Ceiling(len / 0.5));
for (int i = 0; i <= steps; i++)
{
double t = (double)i / steps;
double x = x0 + dx * t, y = y0 + dy * t, z = z0 + (z1 - z0) * t;
if (!OnFloorOfAny(cells, x, y, z)) return false;
if (!OnFloorOfAny(cells, x + ox, y + oy, z)) return false;
if (!OnFloorOfAny(cells, x - ox, y - oy, z)) return false;
}
}
// Walls.
double zLo = Math.Min(z0, z1) + WallBandLow, zHi = Math.Max(z0, z1) + WallBandHigh;
foreach (uint c in cells)
{
if (!_walls.TryGetValue(c, out var list)) continue;
foreach (var w in list)
{
if (w.ZMax < zLo || w.ZMin > zHi) continue;
if (SegmentsCross(x0, y0, x1, y1, w.X0, w.Y0, w.X1, w.Y1)) return false;
if (SegmentsCross(x0 + ox, y0 + oy, x1 + ox, y1 + oy, w.X0, w.Y0, w.X1, w.Y1)) return false;
if (SegmentsCross(x0 - ox, y0 - oy, x1 - ox, y1 - oy, w.X0, w.Y0, w.X1, w.Y1)) return false;
}
}
return true;
}
// ── Helpers ─────────────────────────────────────────────────────────────
internal static ulong EdgeKey(uint a, uint b)
=> a < b ? ((ulong)a << 32) | b : ((ulong)b << 32) | a;
internal static double NavToWorld(double navCoord) => (navCoord * 10.0 + 1019.5) * 24.0;
internal static double WorldToNav(double world) => (world / 24.0 - 1019.5) / 10.0;
private static void NewellNormal(Vector3[] v, out double nx, out double ny, out double nz)
{
nx = 0; ny = 0; nz = 0;
int n = v.Length;
for (int i = 0; i < n; i++)
{
var a = v[i]; var b = v[(i + 1) % n];
nx += (a.Y - b.Y) * (a.Z + b.Z);
ny += (a.Z - b.Z) * (a.X + b.X);
nz += (a.X - b.X) * (a.Y + b.Y);
}
}
private static double FloorZAt(Vector3[] v)
{
double z = 0;
foreach (var p in v) z += p.Z;
return z / v.Length;
}
internal static bool InsidePolygon2D(Vector3[] v, double x, double y)
{
bool inside = false;
for (int i = 0, j = v.Length - 1; i < v.Length; j = i++)
{
double xi = v[i].X, yi = v[i].Y, xj = v[j].X, yj = v[j].Y;
if ((yi > y) != (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi)
inside = !inside;
}
return inside;
}
// Proper crossing of two 2D segments (touching at an end point does not count).
private static bool SegmentsCross(double ax, double ay, double bx, double by,
double cx, double cy, double dx, double dy)
{
double d1 = Cross(cx, cy, dx, dy, ax, ay);
double d2 = Cross(cx, cy, dx, dy, bx, by);
double d3 = Cross(ax, ay, bx, by, cx, cy);
double d4 = Cross(ax, ay, bx, by, dx, dy);
return ((d1 > 1e-9 && d2 < -1e-9) || (d1 < -1e-9 && d2 > 1e-9)) &&
((d3 > 1e-9 && d4 < -1e-9) || (d3 < -1e-9 && d4 > 1e-9));
}
private static double Cross(double ax, double ay, double bx, double by, double px, double py)
=> (bx - ax) * (py - ay) - (by - ay) * (px - ax);
}

View file

@ -0,0 +1,717 @@
// DungeonPathfinder, rooms half: routes laid on real openings, rooms crossed directly.
//
// Why: the cell walk put two points (30% and 50% of the way between cell centres) on every
// cell-to-cell step. A big room is several EnvCells joined by wide openings, so the patrol
// (which walks every graph edge once) went cell to cell inside it, around and across: a
// zig-zag. And at real doorways the points were only near the opening, not centred on it,
// and the steering's lookahead and sweep pass cut the corner into the door frame.
//
// Now, when the dungeon map geometry is there (DungeonGeometry):
// - cells joined by a WIDE opening, or sharing one origin (the pieces of a junction), are
// one room (union-find; hazard cells never merge);
// - the patrol walks the ROOM graph: every doorway between rooms of the main route once
// (same coverage goal as before, see GetMainRouteNodes), crossing each room in a straight
// line from the doorway it came in by to the one it leaves by;
// - every NARROW opening gets an approach point centred in front of it and an exit point
// centred beyond it, flagged NavPoint.Doorway: the engine reaches them tightly and does
// not cut corners at them, so the character lines up and goes through straight;
// - a crossing that would leave the room's floor or hit a wall (an L-shaped room, a
// pillar) goes through the room's own cells instead, string-pulled to the fewest points;
// - a big room entered and left by the same doorway, or by two doorways close together
// (a dead end, or one the patrol would only skirt), gets one point in its middle, once
// a lap, so the patrol still looks into it.
// Without the geometry (DungeonLOS not loaded) the old cell walk is used unchanged.
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Raycasting;
namespace RynthCore.Plugin.RynthAi;
/// <summary>Cells grouped into rooms (cells joined by wide openings).</summary>
internal sealed class DungeonRooms
{
public readonly Dictionary<uint, int> RoomOf = new();
public readonly List<List<uint>> Cells = new();
}
internal static partial class DungeonPathfinder
{
// Approach / exit points: this far in front of / beyond the opening's centre, shortened
// (down to the last value) until the point is on the cell's floor.
// 4 m (was 2.5): at 2.5 the turn into the opening still began close enough to climb the
// raised sides of a hallway mouth (Tom, 2026-10-04: "plenty of room to get into the hallway").
private static readonly double[] DoorwayStandoffs = { 4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 1.0 };
// Room crossings must keep this much room either side of the walking line.
private const double CrossingClearance = 0.5;
// Emitted points closer than this to the previous one are dropped.
private const double MinPointSpacing = 0.3;
// A point within this of the straight line through its neighbours is dropped.
private const double CollinearTolerance = 0.25;
// ── Geometry cache ───────────────────────────────────────────────────────
private static uint _geoLandblock;
private static DungeonGeometry? _cachedGeometry;
/// <summary>
/// The openings, floors and walls of the landblock's dungeon (cached per landblock), from
/// the dungeon map geometry DungeonLOS builds. Null when DungeonLOS is missing.
/// </summary>
public static DungeonGeometry? GetGeometry(uint landblockKey, DatDatabase cellDat, DungeonLOS? los)
{
if (los == null) return null;
if (_cachedGeometry != null && _geoLandblock == landblockKey) return _cachedGeometry;
var graph = GetGraph(landblockKey, cellDat);
var portals = new List<(uint, Vector3[])>();
var walls = new List<(uint, Vector3[])>();
var floors = new List<(uint, Vector3[])>();
try
{
foreach (var p in los.GetDungeonMapPolygons(landblockKey))
{
if (p.Vertices == null) continue;
if (p.IsPortal) portals.Add((p.CellId, p.Vertices)); else walls.Add((p.CellId, p.Vertices));
}
foreach (var p in los.GetDungeonMapFloorPolygons(landblockKey))
if (p.Vertices != null && !p.IsPortal) floors.Add((p.CellId, p.Vertices));
}
catch
{
return null;
}
_cachedGeometry = DungeonGeometry.Build(graph, portals, floors, walls);
_geoLandblock = landblockKey;
return _cachedGeometry;
}
// ── Rooms ────────────────────────────────────────────────────────────────
// Cells whose origins are this close (metres, each axis) are pieces of one junction.
private const double SamePieceMeters = 1.0;
/// <summary>
/// Groups cells joined by wide, walkable openings (or pieces of one junction: cells with
/// the same origin) into rooms. A cell in
/// <paramref name="excluded"/> (a hazard) never merges: it stays a room of its own.
/// </summary>
internal static DungeonRooms BuildRooms(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo,
IReadOnlySet<uint>? excluded = null)
{
var parent = new Dictionary<uint, uint>(graph.Count);
foreach (uint c in graph.Keys) parent[c] = c;
uint Find(uint x)
{
while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; }
return x;
}
foreach (var node in graph.Values)
{
if (excluded != null && excluded.Contains(node.CellId)) continue;
foreach (uint nb in node.Neighbors)
{
if (nb <= node.CellId || !graph.TryGetValue(nb, out var other)) continue;
if (excluded != null && excluded.Contains(nb)) continue;
if (IsDropEdge(node, other)) continue;
bool wide = geo.TryGetDoorway(node.CellId, nb, out var d) && d.IsWide;
// Pieces of one junction: AC builds a crossing or a corner from several cells
// with the same origin (0x6544 has clusters of three). Their openings to each
// other are inside the junction; kept apart, the patrol looped round them.
bool samePiece = Math.Abs(node.NS - other.NS) * 240.0 < SamePieceMeters
&& Math.Abs(node.EW - other.EW) * 240.0 < SamePieceMeters
&& Math.Abs(node.Z - other.Z) < SamePieceMeters;
if (!wide && !samePiece) continue;
uint ra = Find(node.CellId), rb = Find(nb);
if (ra != rb) parent[Math.Max(ra, rb)] = Math.Min(ra, rb);
}
}
var rooms = new DungeonRooms();
var index = new Dictionary<uint, int>();
var ids = new List<uint>(graph.Keys);
ids.Sort();
foreach (uint c in ids)
{
uint root = Find(c);
if (!index.TryGetValue(root, out int r))
{
r = rooms.Cells.Count;
index[root] = r;
rooms.Cells.Add(new List<uint>());
}
rooms.Cells[r].Add(c);
rooms.RoomOf[c] = r;
}
return rooms;
}
// ── Patrol over rooms ────────────────────────────────────────────────────
private readonly record struct RoomEdge(int Room, ulong Key, uint From, uint To);
/// <summary>
/// The patrol over rooms: a closed walk taking every doorway between the main route's
/// rooms once (greedy, re-treading only to reach the nearest unused doorway), crossing
/// each room directly. Null when there is nothing to walk.
/// </summary>
private static NavRouteParser? BuildRoomPatrol(
Dictionary<uint, DungeonNavNode> graph, uint startCell, HashSet<uint> mainRoute,
IReadOnlySet<uint>? hazardCells, DungeonGeometry geo)
{
var rooms = BuildRooms(graph, geo, hazardCells);
var patrolRooms = new HashSet<int>();
foreach (uint c in mainRoute)
if (rooms.RoomOf.TryGetValue(c, out int r)) patrolRooms.Add(r);
var adj = new Dictionary<int, List<RoomEdge>>();
var edges = new HashSet<ulong>();
foreach (int r in patrolRooms)
{
foreach (uint c in rooms.Cells[r])
{
if (hazardCells != null && hazardCells.Contains(c)) continue;
if (!graph.TryGetValue(c, out var cn)) continue;
foreach (uint nb in cn.Neighbors)
{
if (!rooms.RoomOf.TryGetValue(nb, out int rn) || rn == r || !patrolRooms.Contains(rn)) continue;
if (hazardCells != null && hazardCells.Contains(nb)) continue;
if (!graph.TryGetValue(nb, out var nbn) || IsDropEdge(cn, nbn)) continue;
if (!adj.TryGetValue(r, out var list)) adj[r] = list = new List<RoomEdge>();
list.Add(new RoomEdge(rn, EdgeKey(c, nb), c, nb));
edges.Add(EdgeKey(c, nb));
}
}
}
if (edges.Count == 0) return null;
// Start in the player's room if it has a doorway on the patrol, else the nearest that does.
int startRoom = rooms.RoomOf.TryGetValue(startCell, out int sr) && adj.ContainsKey(sr) ? sr : -1;
if (startRoom < 0 && graph.TryGetValue(startCell, out var sNode))
{
double bestD = double.MaxValue;
foreach (int r in adj.Keys)
foreach (uint c in rooms.Cells[r])
{
if (!graph.TryGetValue(c, out var n)) continue;
double d = Sq(n.NS - sNode.NS) + Sq(n.EW - sNode.EW);
if (d < bestD) { bestD = d; startRoom = r; }
}
}
if (startRoom < 0) return null;
// Greedy edge-covering closed walk over the room multigraph.
var walk = new List<RoomEdge>();
var remaining = new HashSet<ulong>(edges);
int cur = startRoom;
int guard = edges.Count * 4 + rooms.Cells.Count + 16;
while (remaining.Count > 0 && guard-- > 0)
{
RoomEdge? next = null;
if (adj.TryGetValue(cur, out var list))
foreach (var e in list)
if (remaining.Contains(e.Key)) { next = e; break; }
if (next is RoomEdge step)
{
remaining.Remove(step.Key);
walk.Add(step);
cur = step.Room;
}
else
{
var hop = RoomBfs(adj, cur, r => r != cur && HasUnused(adj, r, remaining));
if (hop == null) break;
walk.AddRange(hop);
cur = hop[hop.Count - 1].Room;
}
}
if (cur != startRoom)
{
var back = RoomBfs(adj, cur, r => r == startRoom);
if (back != null) walk.AddRange(back);
}
if (walk.Count == 0) return null;
var steps = new List<Step>(walk.Count);
foreach (var e in walk) steps.Add(new Step(e.From, e.To, e.Key));
var route = new NavRouteParser { RouteType = NavRouteType.Circular };
route.Points.AddRange(EmitSteps(graph, geo, rooms, steps, closed: true, null, 0, null, 0, out _));
return route;
}
private static bool HasUnused(Dictionary<int, List<RoomEdge>> adj, int room, HashSet<ulong> remaining)
{
if (!adj.TryGetValue(room, out var list)) return false;
foreach (var e in list) if (remaining.Contains(e.Key)) return true;
return false;
}
// Shortest hop path (as the doorway steps taken) from src to the first room passing goal.
private static List<RoomEdge>? RoomBfs(Dictionary<int, List<RoomEdge>> adj, int src, Func<int, bool> goal)
{
var prev = new Dictionary<int, (int From, RoomEdge Step)>();
var seen = new HashSet<int> { src };
var q = new Queue<int>();
q.Enqueue(src);
while (q.Count > 0)
{
int c = q.Dequeue();
if (c != src && goal(c))
{
var path = new List<RoomEdge>();
for (int at = c; at != src; at = prev[at].From) path.Add(prev[at].Step);
path.Reverse();
return path;
}
if (!adj.TryGetValue(c, out var list)) continue;
foreach (var e in list)
{
if (!seen.Add(e.Room)) continue;
prev[e.Room] = (c, e);
q.Enqueue(e.Room);
}
}
return null;
}
// ── Paths over rooms (dunnav, recovery detours) ──────────────────────────
/// <summary>
/// Points for walking a cell path from (startNS, startEW) to (destNS, destEW), the
/// destination itself not included: straight on through every narrow opening, straight
/// across rooms. Without geometry, the old cell-centre midpoints. <paramref name="doorways"/>
/// counts the narrow openings given approach and exit points.
/// </summary>
public static List<NavPoint> BuildPathPoints(
List<uint> cellPath, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry? geo,
IReadOnlySet<uint>? hazardCells,
double startNS, double startEW, double startZ,
double destNS, double destEW, double destZ,
out int doorways)
{
doorways = 0;
var pts = new List<NavPoint>();
if (geo == null)
{
var tmp = new NavRouteParser();
for (int i = 0; i + 1 < cellPath.Count; i++)
{
if (!graph.TryGetValue(cellPath[i], out var a) || !graph.TryGetValue(cellPath[i + 1], out var b)) continue;
AddPortalWaypoints(tmp, a, b);
}
return tmp.Points;
}
var rooms = BuildRooms(graph, geo, hazardCells);
var steps = new List<Step>();
for (int i = 0; i + 1 < cellPath.Count; i++)
{
uint a = cellPath[i], b = cellPath[i + 1];
if (!rooms.RoomOf.TryGetValue(a, out int ra) || !rooms.RoomOf.TryGetValue(b, out int rb) || ra == rb) continue;
steps.Add(new Step(a, b, EdgeKey(a, b)));
}
if (cellPath.Count == 0) return pts;
var start = WorldPoint(DungeonGeometry.NavToWorld(startEW), DungeonGeometry.NavToWorld(startNS), startZ, false);
var dest = WorldPoint(DungeonGeometry.NavToWorld(destEW), DungeonGeometry.NavToWorld(destNS), destZ, false);
return EmitSteps(graph, geo, rooms, steps, closed: false, start, cellPath[0], dest, cellPath[cellPath.Count - 1], out doorways);
}
// ── Laying points along doorway steps ────────────────────────────────────
private readonly record struct Step(uint From, uint To, ulong Key);
/// <summary>
/// Points for a sequence of doorway steps (cell From in one room to cell To in the next).
/// Openings close together in a row (the Olthoi hive puts 0.7 m joint cells between its
/// corridor pieces: three openings in 1.3 m) are one run: one approach point in front of
/// the first, one exit point beyond the last, and the openings' centres in between only
/// when the run turns. Between runs, the room is crossed (<see cref="CrossRoom"/>).
/// <paramref name="closed"/>: a loop (the patrol), its last exit crossing back to its first
/// approach. Otherwise <paramref name="start"/> / <paramref name="dest"/> (in startCell /
/// destCell) begin and end it, neither included. <paramref name="doorways"/> counts the
/// runs through narrow openings.
/// </summary>
private static List<NavPoint> EmitSteps(
Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, DungeonRooms rooms, List<Step> steps, bool closed,
NavPoint? start, uint startCell, NavPoint? dest, uint destCell, out int doorways)
{
doorways = 0;
var pts = new List<NavPoint>();
if (steps.Count == 0)
{
if (start != null && dest != null && rooms.RoomOf.TryGetValue(startCell, out int r0))
CrossRoom(pts, graph, geo, rooms, r0, start, startCell, dest, destCell, revisit: false);
return pts;
}
// A loop starts where a run starts (not halfway along one).
if (closed && steps.Count > 1)
{
int k = 0;
while (k < steps.Count && Continues(geo, steps[(k - 1 + steps.Count) % steps.Count], steps[k])) k++;
if (k > 0 && k < steps.Count) steps = steps.GetRange(k, steps.Count - k).Concat(steps.GetRange(0, k)).ToList();
}
NavPoint? prev = start;
uint prevCell = startCell;
NavPoint? firstApproach = null;
var lookedInto = new HashSet<int>(); // rooms already looked into this lap
int i = 0;
while (i < steps.Count)
{
int j = i;
while (j + 1 < steps.Count && Continues(geo, steps[j], steps[j + 1])) j++;
RunPoints(graph, geo, rooms, steps, i, j, out var approach, out var middle, out var exit, out bool narrow);
if (narrow) doorways++;
if (prev != null)
{
// Only the patrol looks into rooms; a path to somewhere (dunnav, a detour) doesn't.
bool revisit = i > 0 && (closed ? LooksIn(graph, rooms, lookedInto, steps[i - 1], steps[i], prev, approach) : steps[i - 1].Key == steps[i].Key);
CrossRoom(pts, graph, geo, rooms, rooms.RoomOf[steps[i].From], prev, prevCell, approach, steps[i].From, revisit);
}
else firstApproach = approach;
Append(pts, approach);
foreach (var m in middle) Append(pts, m);
Append(pts, exit);
prev = exit;
prevCell = steps[j].To;
i = j + 1;
}
if (closed && firstApproach != null && prev != null)
{
bool revisit = LooksIn(graph, rooms, lookedInto, steps[steps.Count - 1], steps[0], prev, firstApproach);
CrossRoom(pts, graph, geo, rooms, rooms.RoomOf[steps[0].From], prev, prevCell, firstApproach, steps[0].From, revisit);
}
if (!closed && dest != null && prev != null && rooms.RoomOf.TryGetValue(destCell, out int rd))
CrossRoom(pts, graph, geo, rooms, rd, prev, prevCell, dest, destCell, revisit: false);
DropCollinear(pts, closed);
return pts;
}
// A big room (its cells spread over 10 m or more) left again close to where it was entered is looked into: a
// walk to its middle and back. A straight crossing to a nearby opening would only skirt
// it (the patrol hunts; the old cell walk went all round such rooms). Also any room left
// by the opening it was entered by.
private const double LookInMinSpreadMeters = 10.0;
private const double LookInMaxSkirtMeters = 8.0;
// Once per room per lap: a hub room with many doorways was otherwise walked to its middle
// again every time the patrol passed between two of its doorways.
private static bool LooksIn(Dictionary<uint, DungeonNavNode> graph, DungeonRooms rooms, HashSet<int> lookedInto,
Step inStep, Step outStep, NavPoint entered, NavPoint leaving)
{
if (!rooms.RoomOf.TryGetValue(outStep.From, out int r)) return false;
bool big = RoomSpreadMeters(graph, rooms.Cells[r]) >= LookInMinSpreadMeters;
bool look = (inStep.Key == outStep.Key && (big || rooms.Cells[r].Count == 1))
|| (big && NavPointYd(entered, leaving) < LookInMaxSkirtMeters);
return look && lookedInto.Add(r);
}
// The diagonal of the box round a room's cell origins: 0 for the pieces of one junction
// (several cells, one origin), 28 m for a 3x3 room of 10 m cells.
private static double RoomSpreadMeters(Dictionary<uint, DungeonNavNode> graph, List<uint> cells)
{
double minN = double.MaxValue, maxN = double.MinValue, minE = double.MaxValue, maxE = double.MinValue;
foreach (uint c in cells)
{
if (!graph.TryGetValue(c, out var n)) continue;
minN = Math.Min(minN, n.NS); maxN = Math.Max(maxN, n.NS);
minE = Math.Min(minE, n.EW); maxE = Math.Max(maxE, n.EW);
}
if (minN > maxN) return 0;
return Math.Sqrt(Sq(maxN - minN) + Sq(maxE - minE)) * 240.0;
}
// Openings this close (centre to centre) are taken as one: the room between them is too
// short for an exit point and the next approach point (DoorwayStandoffs[0] each) without
// doubling back.
private const double RunGapMeters = 8.0;
private static bool Continues(DungeonGeometry geo, Step a, Step b)
{
if (a.Key == b.Key) return false; // turning back through the same opening
if (!geo.TryGetDoorway(a.From, a.To, out var da) || !geo.TryGetDoorway(b.From, b.To, out var db)) return false;
double dx = da.X - db.X, dy = da.Y - db.Y;
if (dx * dx + dy * dy >= RunGapMeters * RunGapMeters || Math.Abs(da.Z - db.Z) >= 2.0) return false;
// A run goes on: through the next opening no more than 90 degrees off the last. Turning
// back (in at one opening, out at another beside it) is a visit to the room between.
var (ax, ay) = da.NormalFrom(a.From);
var (bx, by) = db.NormalFrom(b.From);
return ax * bx + ay * by > 0.0;
}
// The approach point before steps[i], the exit point after steps[j], and the opening centres
// between them when the run turns (more than 25 degrees between openings).
private static void RunPoints(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, DungeonRooms rooms,
List<Step> steps, int i, int j,
out NavPoint approach, out List<NavPoint> middle, out NavPoint exit, out bool narrow)
{
middle = new List<NavPoint>();
if (i == j)
{
if (!DoorwayPoints(graph, geo, rooms, steps[i].From, steps[i].To, out approach, out exit, out narrow)) narrow = false;
return;
}
DoorwayPoints(graph, geo, rooms, steps[i].From, steps[i].To, out approach, out _, out bool n0);
DoorwayPoints(graph, geo, rooms, steps[j].From, steps[j].To, out _, out exit, out bool n1);
narrow = n0 || n1;
var doors = new List<(DungeonDoorway Door, uint From)>();
for (int k = i; k <= j; k++)
{
if (!geo.TryGetDoorway(steps[k].From, steps[k].To, out var d)) continue;
doors.Add((d, steps[k].From));
narrow |= !d.IsWide;
}
bool turns = false;
for (int k = 1; k < doors.Count && !turns; k++)
{
var (ax, ay) = doors[k - 1].Door.NormalFrom(doors[k - 1].From);
var (bx, by) = doors[k].Door.NormalFrom(doors[k].From);
turns = ax * bx + ay * by < Math.Cos(25.0 * Math.PI / 180.0);
}
if (turns)
foreach (var (d, _) in doors) middle.Add(WorldPoint(d.X, d.Y, d.Z, !d.IsWide));
if (narrow) { approach.Doorway = true; exit.Doorway = true; }
}
// ── Doorway points ───────────────────────────────────────────────────────
/// <summary>
/// The approach point (in a, centred in front of the opening) and exit point (in b, centred
/// beyond it) for stepping from cell a into cell b. True when the opening is known;
/// <paramref name="narrow"/> when it is a doorway (the points are then flagged
/// NavPoint.Doorway). Unknown openings fall back to the old 30% / 50% points.
/// </summary>
private static bool DoorwayPoints(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, DungeonRooms rooms,
uint a, uint b, out NavPoint approach, out NavPoint exit, out bool narrow)
{
narrow = false;
if (geo.TryGetDoorway(a, b, out var d))
{
var (nx, ny) = d.NormalFrom(a);
narrow = !d.IsWide;
double sa = PickStandoff(geo, rooms, a, d, -nx, -ny);
double sb = PickStandoff(geo, rooms, b, d, nx, ny);
approach = WorldPoint(d.X - nx * sa, d.Y - ny * sa, d.Z, narrow);
exit = WorldPoint(d.X + nx * sb, d.Y + ny * sb, d.Z, narrow);
return true;
}
var na = graph[a]; var nb = graph[b];
double dNS = nb.NS - na.NS, dEW = nb.EW - na.EW, dZ = nb.Z - na.Z;
approach = new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.3, EW = na.EW + dEW * 0.3, Z = (na.Z + dZ * 0.3) / 240.0 };
exit = new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.5, EW = na.EW + dEW * 0.5, Z = (na.Z + dZ * 0.5) / 240.0 };
return false;
}
// The longest standoff whose point is on the floor of the cell's room (or the shortest).
private static double PickStandoff(DungeonGeometry geo, DungeonRooms rooms, uint cell, DungeonDoorway d, double dirX, double dirY)
{
var cells = rooms.RoomOf.TryGetValue(cell, out int r) ? (IEnumerable<uint>)rooms.Cells[r] : new[] { cell };
foreach (double s in DoorwayStandoffs)
if (geo.OnFloorOfAny(cells, d.X + dirX * s, d.Y + dirY * s, d.Z)) return s;
return DoorwayStandoffs[DoorwayStandoffs.Length - 1];
}
// ── Crossing a room ──────────────────────────────────────────────────────
/// <summary>
/// Adds the points needed to walk from <paramref name="from"/> (in cell fromCell) to
/// <paramref name="to"/> (in cell toCell) inside one room, neither end included: nothing
/// when the straight line is clear, else the room's cells string-pulled. A revisit (in and
/// out by one doorway) first goes to the room's middle.
/// </summary>
private static void CrossRoom(List<NavPoint> pts, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo,
DungeonRooms rooms, int room, NavPoint from, uint fromCell, NavPoint to, uint toCell,
bool revisit)
{
var cells = rooms.Cells[room];
Trace?.Invoke($"cross room {room} ({cells.Count}) revisit={revisit} from={fromCell:X8} to={toCell:X8}");
if (revisit)
{
var mid = RoomMiddle(graph, geo, cells, out uint midCell);
if (mid != null)
{
PullThrough(pts, graph, geo, rooms, cells, from, fromCell, mid, midCell);
Append(pts, mid);
PullThrough(pts, graph, geo, rooms, cells, mid, midCell, to, toCell);
return;
}
}
PullThrough(pts, graph, geo, rooms, cells, from, fromCell, to, toCell);
}
internal static Action<string>? Trace;
private static void PullThrough(List<NavPoint> pts, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo,
DungeonRooms rooms, List<uint> cells, NavPoint from, uint fromCell, NavPoint to, uint toCell)
{
if (Clear(geo, cells, from, to)) return;
// Through the room's own cells: the openings between them (or cell-centre midpoints).
var cellPath = CellBfs(graph, rooms, fromCell, toCell);
var corners = new List<NavPoint>();
for (int i = 0; i + 1 < cellPath.Count; i++)
{
uint a = cellPath[i], b = cellPath[i + 1];
if (geo.TryGetDoorway(a, b, out var d)) corners.Add(WorldPoint(d.X, d.Y, d.Z, false));
else
{
var na = graph[a]; var nb = graph[b];
corners.Add(new NavPoint { Type = NavPointType.Point, NS = (na.NS + nb.NS) * 0.5, EW = (na.EW + nb.EW) * 0.5, Z = (na.Z + nb.Z) * 0.5 / 240.0 });
}
}
corners.Add(to);
// String-pull: from the anchor, the farthest corner in a clear straight line.
NavPoint anchor = from;
int at = 0;
int guard = corners.Count + 2;
while (at < corners.Count - 1 && guard-- > 0)
{
int pick = at; // always move on at least one corner
for (int k = corners.Count - 1; k > at; k--)
if (Clear(geo, cells, anchor, corners[k])) { pick = k; break; }
if (pick == corners.Count - 1) break; // the end is in sight
Append(pts, corners[pick]);
anchor = corners[pick];
at = pick + 1;
if (Clear(geo, cells, anchor, to)) break;
}
}
private static bool Clear(DungeonGeometry geo, List<uint> cells, NavPoint a, NavPoint b)
=> geo.SegmentClear(cells,
DungeonGeometry.NavToWorld(a.EW), DungeonGeometry.NavToWorld(a.NS), a.Z * 240.0,
DungeonGeometry.NavToWorld(b.EW), DungeonGeometry.NavToWorld(b.NS), b.Z * 240.0,
CrossingClearance);
// Shortest cell path inside one room (inclusive), or just [from, to] when there is none.
private static List<uint> CellBfs(Dictionary<uint, DungeonNavNode> graph, DungeonRooms rooms, uint from, uint to)
{
if (from == to) return new List<uint> { from };
int room = rooms.RoomOf.TryGetValue(from, out int r) ? r : -1;
var prev = new Dictionary<uint, uint>();
var seen = new HashSet<uint> { from };
var q = new Queue<uint>();
q.Enqueue(from);
while (q.Count > 0)
{
uint c = q.Dequeue();
if (c == to) return RebuildPath(prev, from, to);
if (!graph.TryGetValue(c, out var n)) continue;
foreach (uint nb in n.Neighbors)
{
if (!rooms.RoomOf.TryGetValue(nb, out int rn) || rn != room) continue;
if (!seen.Add(nb)) continue;
prev[nb] = c;
q.Enqueue(nb);
}
}
return new List<uint> { from, to };
}
// The point a patrol visits to look into a room: the middle of its cell centres when that
// is on its floor, else the cell centre nearest that middle.
private static NavPoint? RoomMiddle(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, List<uint> cells, out uint midCell)
{
midCell = 0;
double sx = 0, sy = 0, sz = 0;
int n = 0;
foreach (uint c in cells)
{
if (!graph.TryGetValue(c, out var node)) continue;
sx += DungeonGeometry.NavToWorld(node.EW); sy += DungeonGeometry.NavToWorld(node.NS); sz += node.Z;
n++;
}
if (n == 0) return null;
sx /= n; sy /= n; sz /= n;
double best = double.MaxValue;
DungeonNavNode? nearest = null;
foreach (uint c in cells)
{
if (!graph.TryGetValue(c, out var node)) continue;
double d = Sq(DungeonGeometry.NavToWorld(node.EW) - sx) + Sq(DungeonGeometry.NavToWorld(node.NS) - sy);
if (d < best) { best = d; nearest = node; }
}
if (nearest == null) return null;
midCell = nearest.CellId;
if (geo.OnCellFloor(nearest.CellId, sx, sy, sz) || geo.OnFloorOfAny(cells, sx, sy, sz) && !geo.HasFloor(nearest.CellId))
return WorldPoint(sx, sy, sz, false);
return WorldPoint(DungeonGeometry.NavToWorld(nearest.EW), DungeonGeometry.NavToWorld(nearest.NS), nearest.Z, false);
}
// ── Point list helpers ───────────────────────────────────────────────────
private static NavPoint WorldPoint(double wx, double wy, double wz, bool doorway) => new()
{
Type = NavPointType.Point,
EW = DungeonGeometry.WorldToNav(wx),
NS = DungeonGeometry.WorldToNav(wy),
Z = wz / 240.0,
Doorway = doorway,
};
// Adds p unless it is on top of the last point (keeping the doorway flag if either has it).
private static void Append(List<NavPoint> pts, NavPoint p)
{
if (pts.Count > 0)
{
var last = pts[pts.Count - 1];
if (NavPointYd(last, p) < MinPointSpacing)
{
last.Doorway |= p.Doorway;
return;
}
}
pts.Add(p);
}
// Drops points within CollinearTolerance of the straight line through their neighbours:
// e.g. the exit and approach points between two openings in line along a corridor.
private static void DropCollinear(List<NavPoint> pts, bool closed)
{
bool changed = true;
while (changed && pts.Count > 2)
{
changed = false;
for (int i = closed ? 0 : 1; i < (closed ? pts.Count : pts.Count - 1); i++)
{
if (pts.Count <= 2) break;
var a = pts[(i - 1 + pts.Count) % pts.Count];
var p = pts[i];
var b = pts[(i + 1) % pts.Count];
if (!NavRouteParser.IsPlainWaypoint(p.Type)) continue;
if (!WithinSegment(a, b, p)) continue;
if (SegDistYards(a, b, p) < CollinearTolerance)
{
pts.RemoveAt(i);
i--;
changed = true;
}
}
}
}
// p lies between a and b along their line (not beyond either end).
private static bool WithinSegment(NavPoint a, NavPoint b, NavPoint p)
{
double abN = b.NS - a.NS, abE = b.EW - a.EW, apN = p.NS - a.NS, apE = p.EW - a.EW;
double dot = abN * apN + abE * apE, len2 = abN * abN + abE * abE;
return dot >= 0 && dot <= len2;
}
private static double NavPointYd(NavPoint a, NavPoint b) => Math.Sqrt(Sq(a.NS - b.NS) + Sq(a.EW - b.EW)) * 240.0;
private static double Sq(double v) => v * v;
}

View file

@ -42,7 +42,7 @@ internal sealed class DungeonNavNode
public List<uint> Neighbors = new(); // portal-connected cells only
}
internal static class DungeonPathfinder
internal static partial class DungeonPathfinder
{
// Angle threshold (degrees) above which a portal edge is classified as a drop.
// A slope has significant horizontal movement relative to its Z change — its
@ -89,6 +89,8 @@ internal static class DungeonPathfinder
{
_cachedGraph = null;
_cachedLandblockKey = 0;
_cachedGeometry = null;
_geoLandblock = 0;
}
// ── Graph construction ──────────────────────────────────────────────────
@ -353,10 +355,21 @@ internal static class DungeonPathfinder
public static NavRouteParser BuildNavRoute(
List<uint> cellPath,
Dictionary<uint, DungeonNavNode> graph,
double destNS, double destEW)
double destNS, double destEW,
DungeonGeometry? geo = null, IReadOnlySet<uint>? hazardCells = null,
double startNS = double.NaN, double startEW = double.NaN, double startZ = 0, double destZ = 0)
{
var route = new NavRouteParser { RouteType = NavRouteType.Once };
// With the dungeon map geometry: straight on through doorways, straight across rooms.
if (geo != null && geo.DoorwayCount > 0 && cellPath.Count > 0 && graph.TryGetValue(cellPath[0], out var s0))
{
double sNs = double.IsNaN(startNS) ? s0.NS : startNS, sEw = double.IsNaN(startEW) ? s0.EW : startEW;
route.Points.AddRange(BuildPathPoints(cellPath, graph, geo, hazardCells, sNs, sEw, startZ, destNS, destEW, destZ, out _));
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = destNS, EW = destEW, Z = destZ / 240.0 });
return route;
}
for (int i = 0; i + 1 < cellPath.Count; i++)
{
if (!graph.TryGetValue(cellPath[i], out var a)) continue;
@ -409,7 +422,7 @@ internal static class DungeonPathfinder
changed = false;
for (int i = 1; i + 1 < route.Points.Count; i++)
{
if (route.Points[i].Type != NavPointType.Point) continue;
if (!NavRouteParser.IsPlainWaypoint(route.Points[i].Type)) continue;
if (SegDistYards(route.Points[i - 1], route.Points[i + 1], route.Points[i]) < thresholdYards)
{
route.Points.RemoveAt(i--);
@ -530,10 +543,19 @@ internal static class DungeonPathfinder
public static NavRouteParser BuildPatrolRoute(
Dictionary<uint, DungeonNavNode> graph,
uint startCell,
IReadOnlySet<uint>? hazardCells = null)
IReadOnlySet<uint>? hazardCells = null,
DungeonGeometry? geo = null)
{
var mainRoute = GetMainRouteNodes(graph, startCell, hazardCells);
// With the dungeon map geometry: the same coverage over rooms instead of cells, rooms
// crossed directly, doorways taken straight on (DungeonPathfinder.Rooms.cs).
if (geo != null && geo.DoorwayCount > 0)
{
var byRoom = BuildRoomPatrol(graph, startCell, mainRoute, hazardCells, geo);
if (byRoom != null && byRoom.Points.Count > 0) return byRoom;
}
// Undirected walkable subgraph over mainRoute (portal-adjacent, non-drop). mainRoute is
// already hazard-filtered, so membership there implies non-hazard.
var adj = new Dictionary<uint, List<uint>>();
@ -715,7 +737,8 @@ internal static class DungeonPathfinder
double playerNS, double playerEW, float playerZ,
double destNS, double destEW,
out int nodeCount, out int pathLength,
IReadOnlySet<uint>? hazardCells = null)
IReadOnlySet<uint>? hazardCells = null,
DungeonLOS? los = null)
{
nodeCount = 0;
pathLength = 0;
@ -736,6 +759,7 @@ internal static class DungeonPathfinder
pathLength = path.Count;
if (pathLength == 0) return null;
return BuildNavRoute(path, graph, destNS, destEW);
var geo = GetGeometry(landblockKey, cellDat, los);
return BuildNavRoute(path, graph, destNS, destEW, geo, hazardCells, playerNS, playerEW, playerZ, playerZ);
}
}

View file

@ -1,9 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.Maps;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.PluginSdk;
using RynthCore.Plugin.RynthAi;
@ -11,22 +8,19 @@ using RynthCore.Plugin.RynthAi;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// <summary>
/// Dungeon map: uses physics floor polygons from the dat for accurate corner coverage.
/// Rasterise floor polygons into a typed 2D grid, then:
/// • Fill — merge grid rows into horizontal strips, draw AddRectFilled.
/// • Edges — emit a coloured line on every filled cell face bordering empty space.
///
/// CellType colouring:
/// Flat → light-blue fill + light-blue edge
/// SlopeUp → green fill + green edge (avg vertex Z > layerZ)
/// SlopeDown → red fill + red edge (avg vertex Z &lt; layerZ)
/// The dungeon geometry cache behind the radar snapshot (RynthRadarUi.BuildSnapshotJson),
/// which feeds the engine's Radar and Dungeon Map faces. Uses physics floor polygons from
/// the dat for accurate corner coverage: they are rasterised into a typed 2D grid, then
/// • Fill — grid rows merged into strips (_fillStrips);
/// • Edges — every filled cell face bordering empty space (_outerEdgesRaw, and merged
/// into the fewest lines in _outerEdges).
/// CellType: Flat, SlopeUp (avg vertex Z above the layer), SlopeDown (below).
/// This was also RynthAi's plugin-drawn Dungeon Map window (with baked D3D9 floor
/// textures); that window is the engine's DungeonMapFace now, so nothing here draws.
/// </summary>
internal sealed class DungeonMapUi
{
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private MainLogic? _raycast;
private WorldObjectCache? _objectCache;
internal uint _cachedLandblock;
@ -40,16 +34,8 @@ internal sealed class DungeonMapUi
internal Dictionary<float, List<(float x0, float y0, float x1, float y1, CellType type)>>? _fillStrips;
// Per-layer floor cell lookup used to build visited strips.
internal Dictionary<float, Dictionary<(int, int), CellType>>? _floorCells;
// Flat cells the player has walked through this session (grid coords at GridCell resolution).
private readonly HashSet<(int gx, int gy)> _visitedCells = new();
internal List<float>? _zLayers;
// Per-layer D3D9 textures: fill + edges baked in, O(1) vertices per layer.
internal Dictionary<float, DungeonMapTexture>? _layerTextures;
// Visited flat cells merged into strips — rebuilt only when _visitedCells grows,
// so drawing stays O(strips) not O(cells). Shared with RynthRadarUi.
internal Dictionary<float, List<(float x0, float y0, float x1, float y1)>>? _visitedFillStrips;
private int _lastVisitedCount = -1;
internal int _autoLayerIdx;
/// <summary>Force the landblock cache to be built. Used by RynthRadarUi to share walls/fills.</summary>
internal void EnsureCache(uint landblock)
{
@ -59,233 +45,29 @@ internal sealed class DungeonMapUi
internal int BestLayerIdxFor(float playerZ) => BestLayerIdx(playerZ);
private readonly HashSet<int> _visibleLayers = new();
private float _zoom = 5.0f;
private Vector2 _pan;
private bool _autoFollow = true;
private bool _show1U1D = true; // show current floor ± 1 (default)
private bool _open = true;
private bool _autoHidden; // true when we auto-hid the map because player went outdoors
public bool IsAutoHidden => _autoHidden;
// Toggle-stabilisation: when toolbar is visible we track both the full window
// rect and the canvas rect. On hide we snap the window to the canvas rect so
// it sits exactly over the map area; on show we restore the full window rect.
private bool _prevHideToolbar;
private Vector2 _fullWindowPos; // window pos when toolbar is visible
private Vector2 _fullWindowSize; // window size when toolbar is visible
private Vector2 _canvasPos; // canvas top-left when toolbar is visible
private Vector2 _canvasSize; // canvas size when toolbar is visible
// Edge colours
private static readonly uint ColBg = ImGui.ColorConvertFloat4ToU32(new Vector4(0.04f, 0.07f, 0.12f, 1.00f));
private static readonly uint ColBorder = ImGui.ColorConvertFloat4ToU32(new Vector4(0.20f, 0.30f, 0.40f, 1.00f));
private static readonly uint ColFlat = ImGui.ColorConvertFloat4ToU32(new Vector4(0.55f, 0.80f, 1.00f, 1.00f));
private static readonly uint ColSlopeUp = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.35f, 0.25f, 1.00f)); // red — leads to higher floor
private static readonly uint ColSlopeDown = ImGui.ColorConvertFloat4ToU32(new Vector4(0.25f, 1.00f, 0.35f, 1.00f)); // green — leads to lower floor
private static readonly uint ColPlayer = ImGui.ColorConvertFloat4ToU32(new Vector4(0.20f, 1.00f, 0.40f, 1.00f));
private static readonly uint ColPortal = ImGui.ColorConvertFloat4ToU32(new Vector4(0.90f, 0.45f, 1.00f, 1.00f)); // purple
private static readonly uint ColPortalRing = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.75f, 1.00f, 0.70f));
private static readonly uint ColPortalLabel = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.88f, 1.00f, 1.00f));
private static readonly uint ColDoor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.75f, 0.55f, 0.25f, 1.00f)); // tan
private static readonly uint ColDoorRing = ImGui.ColorConvertFloat4ToU32(new Vector4(0.90f, 0.75f, 0.50f, 0.70f));
private static readonly uint ColDoorLabel = ImGui.ColorConvertFloat4ToU32(new Vector4(0.95f, 0.85f, 0.65f, 1.00f));
private static readonly uint ColMonster = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.25f, 0.20f, 1.00f)); // red
private static readonly uint ColMonsterRing = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.55f, 0.50f, 0.70f));
private static readonly uint ColNpc = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.85f, 0.20f, 1.00f)); // yellow-gold
private static readonly uint ColNpcRing = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.95f, 0.55f, 0.70f));
private static readonly uint ColCreatureLabel = ImGui.ColorConvertFloat4ToU32(new Vector4(1.00f, 0.90f, 0.90f, 1.00f));
// Fill colours (semi-transparent)
private static readonly uint ColFlatFill = ImGui.ColorConvertFloat4ToU32(new Vector4(0.18f, 0.55f, 0.22f, 0.40f)); // green — unvisited
private static readonly uint ColFlatFillVisited = ImGui.ColorConvertFloat4ToU32(new Vector4(0.30f, 0.42f, 0.58f, 0.72f)); // slate blue — visited
private static readonly uint ColSlopeUpFill = ImGui.ColorConvertFloat4ToU32(new Vector4(0.55f, 0.12f, 0.08f, 0.40f));
private static readonly uint ColSlopeDownFill = ImGui.ColorConvertFloat4ToU32(new Vector4(0.10f, 0.50f, 0.15f, 0.40f));
private const float GridCell = 0.5f;
private const float FloorNormalThreshold = 0.4f; // |Nz|/|N| — must exceed to be floor-like
private const float FlatNormalThreshold = 0.95f; // |Nz|/|N| — must exceed to be flat (not a ramp)
private const byte NotFloor = 255; // sentinel returned by ClassifyPoly
/// <summary>Called immediately whenever a map setting is changed by the user.</summary>
public Action? OnSettingChanged { get; set; }
public DungeonMapUi(RynthCoreHost host, LegacyUiSettings settings) { _host = host; _settings = settings; }
public void SetWorldObjectCache(WorldObjectCache cache) => _objectCache = cache;
public void SetRaycast(MainLogic raycast)
{
_raycast = raycast;
_outerEdges = null;
_fillStrips = null;
_floorCells = null;
_visitedCells.Clear();
_cachedLandblock = 0;
}
public void Render()
{
// Check indoor/outdoor before creating the ImGui window.
// Auto-hide when outdoors (or in portalspace), auto-show when returning indoors.
bool isIndoor = false;
if (_host.HasGetPlayerPose && _host.TryGetPlayerPose(
out uint preCellId, out _, out _, out _, out _, out _, out _, out _))
{
isIndoor = (preCellId & 0xFFFF) >= 0x100 && (preCellId >> 16) != 0;
}
if (!isIndoor)
{
if (!_autoHidden)
{
_autoHidden = true;
DashWindows.ShowDungeonMap = false;
}
return;
}
if (_autoHidden)
{
_autoHidden = false;
_open = true;
DashWindows.ShowDungeonMap = true;
}
// Snapshot map-specific settings so we can detect changes and save immediately.
bool snapDoors = _settings.MapShowDoors;
bool snapCreatures = _settings.MapShowCreatures;
bool snapToolbar = _settings.MapShowToolbar;
float snapOpacity = _settings.MapBgOpacity;
bool snapRotate = _settings.MapRotateWithPlayer;
float op = _settings.MapBgOpacity;
bool hideToolbar = !_settings.MapShowToolbar;
// FirstUseEver must come BEFORE any Always override — each SetNextWindowSize call
// overwrites the previous one, so Always must be last to win.
ImGui.SetNextWindowSize(new Vector2(480, 520), ImGuiCond.FirstUseEver);
// On toggle: snap the window to the canvas rect (hide) or full window rect (show).
bool stateChanged = hideToolbar != _prevHideToolbar;
_prevHideToolbar = hideToolbar;
if (stateChanged)
{
if (hideToolbar && _canvasSize.X > 0)
{
// Shrink to exactly where the canvas was — no title bar / toolbar chrome.
ImGui.SetNextWindowPos(_canvasPos, ImGuiCond.Always);
ImGui.SetNextWindowSize(_canvasSize, ImGuiCond.Always);
}
else if (!hideToolbar && _fullWindowSize.X > 0)
{
// Restore the full window including toolbar and title bar.
ImGui.SetNextWindowPos(_fullWindowPos, ImGuiCond.Always);
ImGui.SetNextWindowSize(_fullWindowSize, ImGuiCond.Always);
}
}
// Remove border and padding when toolbar is hidden so no empty chrome is visible.
int styleVarCount = 0;
if (hideToolbar)
{
ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f);
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
styleVarCount = 2;
}
// Apply opacity to title bar colours too — SetNextWindowBgAlpha only covers the content area.
var titleCol = new Vector4(0.08f, 0.12f, 0.18f, op);
ImGui.PushStyleColor(ImGuiCol.TitleBg, titleCol);
ImGui.PushStyleColor(ImGuiCol.TitleBgActive, new Vector4(0.10f, 0.16f, 0.24f, op));
ImGui.SetNextWindowBgAlpha(op);
ImGuiWindowFlags flags = ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse;
if (hideToolbar) flags |= ImGuiWindowFlags.NoTitleBar;
bool beginVisible = ImGui.Begin("Dungeon Map##RynthAiDungeonMap", ref _open, flags);
if (styleVarCount > 0) ImGui.PopStyleVar(styleVarCount);
ImGui.PopStyleColor(2);
if (!beginVisible) { ImGui.End(); return; }
if (!_open) { DashWindows.ShowDungeonMap = false; ImGui.End(); return; }
// Track full window rect every frame when toolbar is visible.
if (!hideToolbar)
{
_fullWindowPos = ImGui.GetWindowPos();
_fullWindowSize = ImGui.GetWindowSize();
}
if (_raycast is null || !_raycast.IsInitialized)
{
ImGui.TextDisabled(_raycast is null
? "Raycasting not yet initialised — loading DAT files..."
: $"Raycasting failed: {_raycast.StatusMessage}");
ImGui.End(); return;
}
if (!_host.HasGetPlayerPose || !_host.TryGetPlayerPose(
out uint cellId, out float px, out float py, out float pz,
out _, out _, out _, out _))
{ ImGui.TextDisabled("Player position unavailable."); ImGui.End(); return; }
// Indoor check already handled before window creation — this is a safety fallback.
if ((cellId & 0xFFFF) < 0x100)
{ ImGui.End(); return; }
uint landblock = cellId >> 16;
if (landblock != _cachedLandblock || _outerEdges is null)
RefreshMap(landblock);
if (_outerEdges is null || _outerEdges.Count == 0)
{ ImGui.TextDisabled($"No dungeon geometry for 0x{landblock:X4}."); ImGui.End(); return; }
float gx = ((landblock >> 8) & 0xFF) * 192.0f;
float gy = (landblock & 0xFF) * 192.0f;
if (!hideToolbar)
{
if (ImGui.SmallButton("^##tbToggle")) _settings.MapShowToolbar = false;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Hide settings");
ImGui.SameLine(0, 8);
RenderToolbar(pz);
}
RenderCanvas(px + gx, py + gy, pz, hideToolbar);
// Save immediately when any map setting changes.
if (_settings.MapShowDoors != snapDoors ||
_settings.MapShowCreatures != snapCreatures ||
_settings.MapShowToolbar != snapToolbar ||
_settings.MapRotateWithPlayer != snapRotate ||
MathF.Abs(_settings.MapBgOpacity - snapOpacity) > 0.001f)
{
OnSettingChanged?.Invoke();
}
ImGui.End();
}
// ── Data refresh ─────────────────────────────────────────────────────────
private void RefreshMap(uint landblock)
{
_cachedLandblock = landblock;
_pan = Vector2.Zero;
_outerEdges = null;
_outerEdgesRaw = null;
_fillStrips = null;
_floorCells = null;
_visitedFillStrips = null;
_visitedCells.Clear();
_lastVisitedCount = -1;
if (_layerTextures is not null)
{
foreach (var t in _layerTextures.Values) t.Dispose();
_layerTextures = null;
}
var los = _raycast?.GeometryLoader?.DungeonLOS;
if (los is null) return;
@ -300,18 +82,6 @@ internal sealed class DungeonMapUi
foreach (var p in portalPolys) zSet.Add((float)Math.Round(p.CellZ, 1));
_zLayers = new List<float>(zSet);
_autoLayerIdx = 0;
_visibleLayers.Clear();
if (_show1U1D)
{
_visibleLayers.Add(0);
if (_zLayers.Count > 1) _visibleLayers.Add(1);
}
else
{
for (int i = 0; i < _zLayers.Count; i++) _visibleLayers.Add(i);
}
_outerEdges = new Dictionary<float, List<(float, float, float, float, CellType)>>(_zLayers.Count);
_fillStrips = new Dictionary<float, List<(float, float, float, float, CellType)>>(_zLayers.Count);
@ -496,25 +266,8 @@ internal sealed class DungeonMapUi
if (strips.Count > 0) _fillStrips[layerZ] = strips;
}
// ── Per-layer floor textures (fill + edges baked, O(1) vertices each) ──
if (_floorCells is not null && _host.D3DDevice != IntPtr.Zero)
{
var texDict = new Dictionary<float, DungeonMapTexture>(_floorCells.Count);
foreach (var (lz, cells) in _floorCells)
{
int idx = _zLayers!.IndexOf(lz);
var tex = DungeonMapTexture.GetOrBuild(_host.D3DDevice, cells, landblock, idx);
if (tex != null) texDict[lz] = tex;
}
_layerTextures = texDict.Count > 0 ? texDict : null;
}
}
// Reduce a colour to ~25 % opacity for non-current-floor rendering.
// ImGui packs colours as 0xAABBGGRR; the alpha is in bits 31–24.
private static uint DimCol(uint c) =>
((uint)((c >> 24 & 0xFF) * 0.25f) << 24) | (c & 0x00FFFFFFu);
// Merge collinear/adjacent axis-aligned edge segments into the fewest possible lines.
// A 10-unit straight wall built from 20 half-unit grid edges becomes 1 line.
private static List<(float ax, float ay, float bx, float by, CellType type)> MergeEdges(
@ -634,29 +387,6 @@ internal sealed class DungeonMapUi
return result;
}
private void RebuildVisitedStrips()
{
_lastVisitedCount = _visitedCells.Count;
if (_floorCells is null || _visitedCells.Count == 0 || _zLayers is null)
{
_visitedFillStrips = null;
return;
}
var result = new Dictionary<float, List<(float, float, float, float)>>(_zLayers.Count);
foreach (var (layerZ, cells) in _floorCells)
{
var flatVisited = new List<(int, int)>();
foreach (var ((gx, gy), ctype) in cells)
if (ctype == CellType.Flat && _visitedCells.Contains((gx, gy)))
flatVisited.Add((gx, gy));
if (flatVisited.Count == 0) continue;
var strips = BuildVisitedStripsFrom(flatVisited);
if (strips.Count > 0) result[layerZ] = strips;
}
_visitedFillStrips = result.Count > 0 ? result : null;
}
// Classify a polygon as Flat / SlopeUp / SlopeDown, or NotFloor if vertical.
private static CellType ClassifyPoly(Raycasting.Vector3[] verts, float layerZ)
{
@ -768,537 +498,6 @@ internal sealed class DungeonMapUi
// ── Toolbar ──────────────────────────────────────────────────────────────
// Returns true if the last-drawn item's right edge + gap + nextWidth fits before the window's right edge.
private static bool FitsOnLine(float nextWidth, float gap = 8f)
{
float itemRight = ImGui.GetItemRectMax().X;
float windowRight = ImGui.GetWindowPos().X + ImGui.GetWindowSize().X
- ImGui.GetStyle().WindowPadding.X;
return itemRight + gap + nextWidth < windowRight;
}
private void RenderToolbar(float playerZ)
{
// ── 1U1D toggle ───────────────────────────────────────────────────
bool was1U1D = _show1U1D;
if (was1U1D)
{
ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.15f, 0.45f, 0.70f, 1.0f));
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(0.20f, 0.58f, 0.88f, 1.0f));
ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(0.10f, 0.34f, 0.58f, 1.0f));
}
if (ImGui.SmallButton("1U1D##1u1d"))
{
_show1U1D = !_show1U1D;
if (_show1U1D && _zLayers is not null)
{
_visibleLayers.Clear();
if (_autoLayerIdx > 0) _visibleLayers.Add(_autoLayerIdx - 1);
_visibleLayers.Add(_autoLayerIdx);
if (_autoLayerIdx < _zLayers.Count - 1) _visibleLayers.Add(_autoLayerIdx + 1);
}
}
if (was1U1D) ImGui.PopStyleColor(3);
// ── Floor buttons ─────────────────────────────────────────────────
if (_zLayers is not null && _zLayers.Count > 1)
{
float floorsWidth = 52f + _zLayers.Count * 26f + 60f; // "Floors:" + Fn buttons + All/Here
if (FitsOnLine(floorsWidth, 10f)) ImGui.SameLine(0, 10);
ImGui.Text("Floors:");
ImGui.SameLine();
for (int i = 0; i < _zLayers.Count; i++)
{
if (i > 0) ImGui.SameLine();
bool on = _visibleLayers.Contains(i);
bool isCurrent = i == _autoLayerIdx;
if (on && isCurrent)
ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.10f, 0.65f, 0.30f, 1.0f));
else if (on)
ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.15f, 0.45f, 0.70f, 1.0f));
if (ImGui.SmallButton($"F{i + 1}##floor{i}"))
{
_show1U1D = false;
if (on) _visibleLayers.Remove(i); else _visibleLayers.Add(i);
}
if (on) ImGui.PopStyleColor();
}
ImGui.SameLine(0, 6);
if (ImGui.SmallButton("All##floorAll"))
{
_show1U1D = false;
_visibleLayers.Clear();
for (int i = 0; i < _zLayers.Count; i++) _visibleLayers.Add(i);
}
ImGui.SameLine();
if (ImGui.SmallButton("Here##floorHere"))
{
_show1U1D = false;
_visibleLayers.Clear();
_visibleLayers.Add(BestLayerIdx(playerZ));
}
}
// ── Zoom ──────────────────────────────────────────────────────────
if (FitsOnLine(130f, 12f)) ImGui.SameLine(0, 12);
ImGui.Text("Zoom:");
ImGui.SameLine();
ImGui.SetNextItemWidth(80);
ImGui.SliderFloat("##mapzoom", ref _zoom, 1.0f, 20.0f, "%.1fx");
if (!float.IsFinite(_zoom)) _zoom = 5.0f;
// ── Follow / Rotate / Reset ───────────────────────────────────────
if (FitsOnLine(180f, 12f)) ImGui.SameLine(0, 12);
ImGui.Checkbox("Follow##mapfollow", ref _autoFollow);
ImGui.SameLine(0, 6);
ImGui.Checkbox("Rotate##maprotate", ref _settings.MapRotateWithPlayer);
ImGui.SameLine(0, 6);
if (ImGui.SmallButton("Reset##mapreset"))
{ _pan = Vector2.Zero; _zoom = 5.0f; _autoFollow = true; _show1U1D = true; }
// ── Doors / Creatures ─────────────────────────────────────────────
if (FitsOnLine(148f, 12f)) ImGui.SameLine(0, 12);
ImGui.Checkbox("Doors##mapDoors", ref _settings.MapShowDoors);
ImGui.SameLine(0, 6);
ImGui.Checkbox("Creatures##mapCreatures", ref _settings.MapShowCreatures);
// ── Opacity ───────────────────────────────────────────────────────
if (FitsOnLine(130f, 12f)) ImGui.SameLine(0, 12);
ImGui.Text("Opacity:");
ImGui.SameLine(0, 4);
ImGui.SetNextItemWidth(70);
ImGui.SliderFloat("##mapOpacity", ref _settings.MapBgOpacity, 0f, 1f, "%.2f");
_settings.MapBgOpacity = Math.Clamp(_settings.MapBgOpacity, 0f, 1f);
}
// ── Canvas ────────────────────────────────────────────────────────────────
private void RenderCanvas(float playerWX, float playerWY, float playerZ, bool showExpandBtn = false)
{
Vector2 canvasSize = ImGui.GetContentRegionAvail();
if (canvasSize.X < 50 || canvasSize.Y < 50) return;
Vector2 origin = ImGui.GetCursorScreenPos();
// Record canvas screen rect while toolbar is visible so we can snap to it on hide.
if (!showExpandBtn)
{
_canvasPos = origin;
_canvasSize = canvasSize;
}
Vector2 centre = origin + canvasSize * 0.5f;
ImDrawListPtr dl = ImGui.GetWindowDrawList();
// Only the canvas background scales with opacity — fills and edges stay full colour.
uint colBgDyn = SetAlpha(ColBg, _settings.MapBgOpacity);
dl.AddRectFilled(origin, origin + canvasSize, colBgDyn);
dl.AddRect(origin, origin + canvasSize, ColBorder);
dl.PushClipRect(origin, origin + canvasSize, true);
if (_autoFollow) _pan = Vector2.Zero;
if (_zLayers is not null)
{
int best = BestLayerIdx(playerZ);
if (best != _autoLayerIdx)
{
_autoLayerIdx = best;
if (_show1U1D)
{
_visibleLayers.Clear();
if (best > 0) _visibleLayers.Add(best - 1);
_visibleLayers.Add(best);
if (best < _zLayers.Count - 1) _visibleLayers.Add(best + 1);
}
else if (_autoFollow) { _visibleLayers.Clear(); _visibleLayers.Add(best); }
}
}
Span<float> visZ = stackalloc float[_zLayers?.Count ?? 0];
int visCount = 0;
if (_zLayers is not null)
foreach (int idx in _visibleLayers)
if (idx >= 0 && idx < _zLayers.Count)
visZ[visCount++] = _zLayers[idx];
float cxMin = origin.X, cxMax = origin.X + canvasSize.X;
float cyMin = origin.Y, cyMax = origin.Y + canvasSize.Y;
const float Margin = 20f;
float currentLayerZ = (_zLayers is not null && _autoLayerIdx < _zLayers.Count)
? _zLayers[_autoLayerIdx] : float.NaN;
bool rotate = _settings.MapRotateWithPlayer;
float sinH = 0f, cosH = 1f;
if (rotate && _host.HasGetPlayerHeading && _host.TryGetPlayerHeading(out float mapHeading))
{
float hRad = mapHeading * MathF.PI / 180f;
sinH = MathF.Sin(hRad);
cosH = MathF.Cos(hRad);
}
// ── Paint visited flat cells under player each frame ─────────────
if (!float.IsNaN(currentLayerZ))
{
const int PaintRadius = 2;
int pgx = (int)MathF.Floor(playerWX / GridCell);
int pgy = (int)MathF.Floor(playerWY / GridCell);
for (int dy = -PaintRadius; dy <= PaintRadius; dy++)
for (int dx = -PaintRadius; dx <= PaintRadius; dx++)
_visitedCells.Add((pgx + dx, pgy + dy));
}
// Rebuild visited strips only when new cells were added — O(cells) once, O(1) each frame.
if (_visitedCells.Count != _lastVisitedCount)
RebuildVisitedStrips();
// ── Floor texture (fill + edges baked, O(1) vertices per layer) ──
// Falls back to fill-strip geometry when texture creation failed.
if (_layerTextures is not null)
{
for (int vi = 0; vi < visCount; vi++)
{
if (!_layerTextures.TryGetValue(visZ[vi], out var tex)) continue;
if (tex.TexId == IntPtr.Zero) continue;
bool isCurrent = MathF.Abs(visZ[vi] - currentLayerZ) < 0.01f;
uint tint = isCurrent ? 0xFFFFFFFFu : 0x40FFFFFFu;
// Project the four world corners of the texture (NW/NE/SE/SW)
var pNW = Project(tex.WorldX0, tex.WorldY1, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
var pNE = Project(tex.WorldX1, tex.WorldY1, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
var pSE = Project(tex.WorldX1, tex.WorldY0, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
var pSW = Project(tex.WorldX0, tex.WorldY0, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
float qxMin = MathF.Min(MathF.Min(pNW.X, pNE.X), MathF.Min(pSE.X, pSW.X));
float qxMax = MathF.Max(MathF.Max(pNW.X, pNE.X), MathF.Max(pSE.X, pSW.X));
float qyMin = MathF.Min(MathF.Min(pNW.Y, pNE.Y), MathF.Min(pSE.Y, pSW.Y));
float qyMax = MathF.Max(MathF.Max(pNW.Y, pNE.Y), MathF.Max(pSE.Y, pSW.Y));
if (qxMax < cxMin - Margin || qxMin > cxMax + Margin ||
qyMax < cyMin - Margin || qyMin > cyMax + Margin) continue;
// UV: NW=(0,0), NE=(1,0), SE=(1,1), SW=(0,1) (row 0 = northernmost = top of texture)
dl.AddImageQuad(tex.TexId, pNW, pNE, pSE, pSW,
new Vector2(0f, 0f), new Vector2(1f, 0f), new Vector2(1f, 1f), new Vector2(0f, 1f), tint);
}
}
else if (_fillStrips is not null)
{
for (int vi = 0; vi < visCount; vi++)
{
if (!_fillStrips.TryGetValue(visZ[vi], out var strips)) continue;
bool isCurrent = MathF.Abs(visZ[vi] - currentLayerZ) < 0.01f;
foreach (var (x0, y0, x1, y1, type) in strips)
{
var fp00 = Project(x0, y0, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
var fp10 = Project(x1, y0, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
var fp11 = Project(x1, y1, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
var fp01 = Project(x0, y1, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
float fxMin = MathF.Min(fp00.X, MathF.Min(fp10.X, MathF.Min(fp11.X, fp01.X)));
float fxMax = MathF.Max(fp00.X, MathF.Max(fp10.X, MathF.Max(fp11.X, fp01.X)));
float fyMin = MathF.Min(fp00.Y, MathF.Min(fp10.Y, MathF.Min(fp11.Y, fp01.Y)));
float fyMax = MathF.Max(fp00.Y, MathF.Max(fp10.Y, MathF.Max(fp11.Y, fp01.Y)));
if (fxMax < cxMin - Margin || fxMin > cxMax + Margin ||
fyMax < cyMin - Margin || fyMin > cyMax + Margin) continue;
uint fillCol = type switch
{
CellType.SlopeUp => ColSlopeUpFill,
CellType.SlopeDown => ColSlopeDownFill,
_ => ColFlatFill,
};
if (!isCurrent) fillCol = DimCol(fillCol);
if (rotate) dl.AddQuadFilled(fp00, fp10, fp11, fp01, fillCol);
else dl.AddRectFilled(new Vector2(fxMin, fyMin), new Vector2(fxMax, fyMax), fillCol);
}
}
}
// ── Visited flat cell overlay (current floor only, drawn as merged strips) ──
// Uses _visitedFillStrips (rebuilt lazily) to keep vertex count O(strips), not O(cells).
if (_visitedFillStrips is not null && !float.IsNaN(currentLayerZ)
&& _visitedFillStrips.TryGetValue(currentLayerZ, out var visitedStrips))
{
foreach (var (x0, y0, x1, y1) in visitedStrips)
{
var vp00 = Project(x0, y0, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
var vp10 = Project(x1, y0, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
var vp11 = Project(x1, y1, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
var vp01 = Project(x0, y1, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
float vxMin = MathF.Min(vp00.X, MathF.Min(vp10.X, MathF.Min(vp11.X, vp01.X)));
float vxMax = MathF.Max(vp00.X, MathF.Max(vp10.X, MathF.Max(vp11.X, vp01.X)));
float vyMin = MathF.Min(vp00.Y, MathF.Min(vp10.Y, MathF.Min(vp11.Y, vp01.Y)));
float vyMax = MathF.Max(vp00.Y, MathF.Max(vp10.Y, MathF.Max(vp11.Y, vp01.Y)));
if (vxMax < cxMin - Margin || vxMin > cxMax + Margin ||
vyMax < cyMin - Margin || vyMin > cyMax + Margin) continue;
if (rotate) dl.AddQuadFilled(vp00, vp10, vp11, vp01, ColFlatFillVisited);
else dl.AddRectFilled(new Vector2(vxMin, vyMin), new Vector2(vxMax, vyMax), ColFlatFillVisited);
}
}
// ── Outer edges (fallback only — skipped when textures are available) ──
if (_layerTextures is null && _outerEdges is not null)
{
for (int vi = 0; vi < visCount; vi++)
{
if (!_outerEdges.TryGetValue(visZ[vi], out var edges)) continue;
bool isCurrent = MathF.Abs(visZ[vi] - currentLayerZ) < 0.01f;
foreach (var (ax, ay, bx, by, type) in edges)
{
var ep0 = Project(ax, ay, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
var ep1 = Project(bx, by, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
if (MathF.Max(ep0.X, ep1.X) < cxMin - Margin || MathF.Min(ep0.X, ep1.X) > cxMax + Margin ||
MathF.Max(ep0.Y, ep1.Y) < cyMin - Margin || MathF.Min(ep0.Y, ep1.Y) > cyMax + Margin)
continue;
uint col = type switch
{
CellType.SlopeUp => ColSlopeUp,
CellType.SlopeDown => ColSlopeDown,
_ => ColFlat,
};
if (!isCurrent) col = DimCol(col);
dl.AddLine(ep0, ep1, col, 1.5f);
}
}
}
// ── Teleport portals ──────────────────────────────────────────────
if (_objectCache != null && _host.HasGetObjectPosition && _host.HasGetItemType)
{
const uint TypePortal = 0x10000u;
const uint STypePortalDest = 38u;
float gxLB = ((_cachedLandblock >> 8) & 0xFF) * 192f;
float gyLB = (_cachedLandblock & 0xFF) * 192f;
foreach (var wo in _objectCache.GetLandscapeObjects())
{
// Static GUIDs only (portals/lifestones are below 0x80000000)
if ((uint)wo.Id >= 0x80000000u) continue;
if (!_host.TryGetItemType((uint)wo.Id, out uint flags)) continue;
if ((flags & TypePortal) == 0) continue;
if (!_host.TryGetObjectPosition((uint)wo.Id, out uint portalCellId,
out float portalX, out float portalY, out _)) continue;
if ((portalCellId >> 16) != _cachedLandblock) continue;
float worldX = portalX + gxLB;
float worldY = portalY + gyLB;
var ps = Project(worldX, worldY, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
float psx = ps.X, psy = ps.Y;
if (psx < cxMin - 20 || psx > cxMax + 20 ||
psy < cyMin - 20 || psy > cyMax + 20) continue;
var psc = new Vector2(psx, psy);
dl.AddCircleFilled(psc, 5f, ColPortal);
dl.AddCircle(psc, 7f, ColPortalRing, 12, 1.5f);
string label = wo.Name;
if (_host.TryGetObjectStringProperty((uint)wo.Id, STypePortalDest, out string dest)
&& !string.IsNullOrEmpty(dest))
label = dest.Length > 22 ? dest.Substring(0, 22) + "…" : dest;
dl.AddText(new Vector2(psx + 9f, psy - 7f), ColPortalLabel, label);
}
}
// ── Doors ─────────────────────────────────────────────────────────
if (_settings.MapShowDoors && _objectCache != null && _host.HasGetObjectPosition)
{
float gxLBd = ((_cachedLandblock >> 8) & 0xFF) * 192f;
float gyLBd = (_cachedLandblock & 0xFF) * 192f;
foreach (var wo in _objectCache.GetLandscapeObjects())
{
if ((uint)wo.Id >= 0x80000000u) continue;
if (!IsDoorName(wo.Name)) continue;
if (!_host.TryGetObjectPosition((uint)wo.Id, out uint dCellId,
out float dox, out float doy, out _)) continue;
if ((dCellId >> 16) != _cachedLandblock) continue;
float dwx = dox + gxLBd;
float dwy = doy + gyLBd;
var ds = Project(dwx, dwy, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
float dsx = ds.X, dsy = ds.Y;
if (dsx < cxMin - 20 || dsx > cxMax + 20 ||
dsy < cyMin - 20 || dsy > cyMax + 20) continue;
// Diamond symbol
const float Dr = 5.0f;
dl.AddQuadFilled(
new Vector2(dsx, dsy - Dr),
new Vector2(dsx + Dr, dsy),
new Vector2(dsx, dsy + Dr),
new Vector2(dsx - Dr, dsy),
ColDoor);
dl.AddQuad(
new Vector2(dsx, dsy - Dr - 1.5f),
new Vector2(dsx + Dr + 1.5f, dsy),
new Vector2(dsx, dsy + Dr + 1.5f),
new Vector2(dsx - Dr - 1.5f, dsy),
ColDoorRing, 1.2f);
dl.AddText(new Vector2(dsx + 8f, dsy - 7f), ColDoorLabel, wo.Name.Length > 20 ? wo.Name[..20] + "…" : wo.Name);
}
}
// ── Creatures & NPCs ──────────────────────────────────────────────
if (_settings.MapShowCreatures && _objectCache != null && _host.HasGetObjectPosition)
{
const uint STypeCreatureType = 2u;
const int CreatureTypeNpc = 14;
bool canQueryCreatureType = _host.HasGetObjectIntProperty;
float gxLBc = ((_cachedLandblock >> 8) & 0xFF) * 192f;
float gyLBc = (_cachedLandblock & 0xFF) * 192f;
foreach (var wo in _objectCache.GetLandscape())
{
if (!_host.TryGetObjectPosition((uint)wo.Id, out uint cCellId,
out float cox, out float coy, out _)) continue;
if ((cCellId >> 16) != _cachedLandblock) continue;
float cwx = cox + gxLBc;
float cwy = coy + gyLBc;
var csp = Project(cwx, cwy, playerWX, playerWY, centre, _zoom, _pan, rotate, sinH, cosH);
float csx = csp.X, csy = csp.Y;
if (csx < cxMin - 20 || csx > cxMax + 20 ||
csy < cyMin - 20 || csy > cyMax + 20) continue;
bool isNpc = canQueryCreatureType
&& _host.TryGetObjectIntProperty((uint)wo.Id, STypeCreatureType, out int ct)
&& ct == CreatureTypeNpc;
var csc = new Vector2(csx, csy);
if (isNpc)
{
dl.AddCircleFilled(csc, 4f, ColNpc);
dl.AddCircle(csc, 6f, ColNpcRing, 10, 1.2f);
}
else
{
dl.AddCircleFilled(csc, 4f, ColMonster);
dl.AddCircle(csc, 6f, ColMonsterRing, 10, 1.0f);
}
string clabel = wo.Name.Length > 20 ? wo.Name[..20] + "…" : wo.Name;
dl.AddText(new Vector2(csx + 7f, csy - 7f), ColCreatureLabel, clabel);
}
}
// ── Player dot + heading ──────────────────────────────────────────
var playerScreen = new Vector2(centre.X + _pan.X, centre.Y + _pan.Y);
dl.AddCircleFilled(playerScreen, 4.0f, ColPlayer);
if (_host.HasGetPlayerHeading && _host.TryGetPlayerHeading(out float heading))
{
Vector2 tip;
if (rotate)
{
// Map rotates with player — heading arrow always points up.
tip = playerScreen + new Vector2(0f, -10f);
}
else
{
float rad = heading * MathF.PI / 180.0f;
tip = playerScreen + new Vector2(MathF.Cos(rad) * 10f, -MathF.Sin(rad) * 10f);
}
dl.AddLine(playerScreen, tip, ColPlayer, 1.5f);
}
dl.PopClipRect();
// Expand button rendered BEFORE InvisibleButton so ImGui gives it
// input priority over the canvas drag area. SetCursorScreenPos is
// restored afterward so InvisibleButton still covers the full canvas.
if (showExpandBtn)
{
ImGui.SetCursorScreenPos(origin + new Vector2(4, 4));
if (ImGui.SmallButton("v##tbToggle")) _settings.MapShowToolbar = true;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Show settings");
ImGui.SetCursorScreenPos(origin);
}
// InvisibleButton captures mouse so the window title-bar drag handler
// never sees the click — prevents the window from moving when panning.
ImGui.InvisibleButton("##mapcanvas", canvasSize);
// Tell the backend to block mouse events from reaching the game when
// the cursor is over the canvas (fixes click-through to AC world).
bool hovered = ImGui.IsItemHovered();
if (hovered) ImGui.SetNextFrameWantCaptureMouse(true);
if (ImGui.IsItemActive() && ImGui.IsMouseDragging(ImGuiMouseButton.Left))
{
Vector2 delta = ImGui.GetIO().MouseDelta;
if (float.IsFinite(delta.X) && float.IsFinite(delta.Y))
{
_autoFollow = false;
_pan += delta;
}
}
// Scroll-wheel zoom: check mouse position directly against canvas bounds.
// IsWindowHovered can return false if another item is active, so we bypass it.
{
float wheel = ImGui.GetIO().MouseWheel;
if (float.IsFinite(wheel) && wheel != 0f)
{
var mp = ImGui.GetIO().MousePos;
if (mp.X >= origin.X && mp.X <= origin.X + canvasSize.X &&
mp.Y >= origin.Y && mp.Y <= origin.Y + canvasSize.Y)
{
_zoom = Math.Clamp(_zoom + wheel * 0.5f, 1.0f, 20.0f);
ImGui.SetNextFrameWantCaptureMouse(true);
}
}
}
}
// Project a world point to canvas screen coords, optionally rotating around the player.
// AC convention: heading 0=east, 90=north (CCW from east).
// Rotate mode: player's forward direction points screen-up.
// screen_right = sinH*dx - cosH*dy
// screen_forward = cosH*dx + sinH*dy (negated for screen-Y, which increases downward)
// This matches RynthRadarUi.ProjectWorld exactly.
private static Vector2 Project(float wx, float wy, float playerWX, float playerWY,
Vector2 centre, float zoom, Vector2 pan, bool rotate, float sinH, float cosH)
{
float dx = wx - playerWX;
float dy = wy - playerWY;
if (rotate)
{
float rx = sinH * dx - cosH * dy; // screen-right
float ry = cosH * dx + sinH * dy; // screen-forward (screen-up = -ry)
dx = rx; dy = ry;
}
return new Vector2(centre.X + dx * zoom + pan.X, centre.Y - dy * zoom + pan.Y);
}
// Sets the alpha byte of an ImGui ABGR colour to the given 0-1 value.
private static uint SetAlpha(uint col, float alpha)
{
uint a = (uint)(Math.Clamp(alpha, 0f, 1f) * 255f);
return (col & 0x00FFFFFF) | (a << 24);
}
private static bool IsDoorName(string name)
{
if (string.IsNullOrEmpty(name)) return false;
return name.Contains("Door", StringComparison.OrdinalIgnoreCase)
|| name.Contains("Gate", StringComparison.OrdinalIgnoreCase)
|| name.Contains("Portcullis", StringComparison.OrdinalIgnoreCase)
|| name.Contains("Hatch", StringComparison.OrdinalIgnoreCase)
|| name.Contains("Trapdoor", StringComparison.OrdinalIgnoreCase);
}
}

View file

@ -1,184 +0,0 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed class LegacyLuaUi
{
private readonly LegacyUiSettings _settings;
private readonly RynthCoreHost _host;
// Delegates for the main plugin to hook into
public Action? OnSettingsChanged;
public Action<string>? OnExecuteRequested;
public Action? OnStopRequested;
// Internal State
private readonly string _luaFolder = @"C:\Games\RynthSuite\RynthAi\LuaScripts";
private string _newLuaFileName = "MyScript";
private int _selectedLuaIdx = 0;
private readonly List<string> _luaFiles = new();
private readonly string _selectedSnippetKey = "--- Select Snippet ---";
private readonly Dictionary<string, string> _luaSnippets = new()
{
{ "--- 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 LegacyLuaUi(LegacyUiSettings settings, RynthCoreHost host)
{
_settings = settings;
_host = host;
RefreshLuaFiles();
}
public void RefreshLuaFiles()
{
_luaFiles.Clear();
_luaFiles.Add("None");
if (Directory.Exists(_luaFolder))
{
foreach (string file in Directory.GetFiles(_luaFolder, "*.lua"))
_luaFiles.Add(Path.GetFileNameWithoutExtension(file));
}
}
public void Render()
{
if (!DashWindows.ShowLua)
return;
ImGui.SetNextWindowSize(new Vector2(600, 500), ImGuiCond.FirstUseEver);
if (!ImGui.Begin("Lua Scripts##RynthAiLua", ref DashWindows.ShowLua))
{
ImGui.End();
return;
}
// Safety Checks
_settings.LuaScript ??= "";
_settings.LuaConsoleOutput ??= "";
// 1. File & Snippet Bar
RenderTopBar();
ImGui.Separator();
// 2. Toolbar (Run, Stop, Clear)
RenderToolbar();
ImGui.Separator();
// 3. Editor & Console
RenderEditorAndConsole();
ImGui.End();
}
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);
_host.Log($"Saved Lua script: {_newLuaFileName}.lua");
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), ImGuiChildFlags.Borders, ImGuiWindowFlags.HorizontalScrollbar))
{
ImGui.TextUnformatted(_settings.LuaConsoleOutput);
if (ImGui.GetScrollY() >= ImGui.GetScrollMaxY())
ImGui.SetScrollHereY(1.0f);
}
ImGui.EndChild();
}
}

View file

@ -14,7 +14,6 @@ internal sealed class LegacyAdvancedSettingsUi
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 LegacyAdvancedSettingsUi(LegacyUiSettings settings)
{
@ -26,6 +25,10 @@ internal sealed class LegacyAdvancedSettingsUi
private Func<string>? _autoVendorStatus;
public void SetAutoVendorStatusProvider(Func<string> status) => _autoVendorStatus = status;
private Func<string>? _autoTradeStatus;
public void SetAutoTradeStatusProvider(Func<string> status) => _autoTradeStatus = status;
private string _newAutoAcceptPattern = "";
public string MissileCraftingState => _missileCraftingManager?.State.ToString() ?? string.Empty;
public bool MissileCraftingActive => _missileCraftingManager?.IsCrafting ?? false;
public string MissileCraftingStatus => _missileCraftingManager?.StatusMessage ?? string.Empty;
@ -106,6 +109,78 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Spacing();
ImGui.TextDisabled("Never sold: equipped, attuned, bonded, retained, tinkered, imbued,");
ImGui.TextDisabled("inscribed, rare, zero value, packs, or anything a Keep rule could match.");
RenderAutoTrade();
}
private void RenderAutoTrade()
{
ImGui.Spacing();
ImGui.Spacing();
ImGui.Text("AutoTrade (UtilityBelt)");
ImGui.Separator();
ImGui.Spacing();
string status = _autoTradeStatus?.Invoke() ?? "Not logged in";
ImGui.TextDisabled($"Status: {status}");
ImGui.Spacing();
ImGui.Checkbox("Enabled##AT", ref _settings.AutoTradeEnabled);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When a trade window opens, add the items that match Keep / Keep # rules in\n" +
"<Partner Name>.utl or default.utl (your character's AutoTrade folder, the\n" +
"server folder, or " + Trade.AutoTradeManager.MainProfileDir + ").");
ImGui.Checkbox("Test Mode (only print what it would add)##AT", ref _settings.AutoTradeTestMode);
ImGui.Checkbox("Only Trade From Main Pack##AT", ref _settings.AutoTradeOnlyFromMainPack);
ImGui.Checkbox("Auto Accept After Adding##AT", ref _settings.AutoTradeAutoAccept);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Accept the trade once every item AutoTrade added shows in the window.\n" +
"Check what the other player offers first: nothing checks their side.");
ImGui.Checkbox("Think When Finished##AT", ref _settings.AutoTradeThink);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Send 'AutoTrade finished: <partner>' and 'Trade accepted: <partner>' as a /tell\n" +
"to yourself, so a meta's chat condition can wait for it.");
ImGui.Spacing();
ImGui.Text("Auto-accept trades from (name patterns, .NET regex)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When one of these players accepts a trade, this character accepts too.\n" +
"The autoAcceptList.json files from /ub autotrade autoaccept add[g|s] count as well.");
var list = _settings.AutoTradeAutoAcceptChars;
int removeAt = -1;
for (int i = 0; i < list.Count; i++)
{
ImGui.Bullet();
ImGui.SameLine();
ImGui.TextUnformatted(list[i]);
ImGui.SameLine();
if (ImGui.SmallButton($"Remove##ATaac{i}"))
removeAt = i;
}
if (removeAt >= 0)
list.RemoveAt(removeAt);
ImGui.SetNextItemWidth(200);
ImGui.InputText("##ATnewpattern", ref _newAutoAcceptPattern, 128);
ImGui.SameLine();
if (ImGui.Button("Add##ATaddpattern"))
{
string p = _newAutoAcceptPattern.Trim();
if (p.Length > 0 && !list.Contains(p) && IsValidRegex(p))
{
list.Add(p);
_newAutoAcceptPattern = "";
}
}
ImGui.Spacing();
ImGui.TextDisabled("Never added: equipped, attuned, retained, tinkered, imbued, inscribed,");
ImGui.TextDisabled("packs, unidentified items, or items on RynthAi's weapon/consumable lists.");
}
private static bool IsValidRegex(string pattern)
{
try { _ = System.Text.RegularExpressions.Regex.Match(string.Empty, pattern); return true; }
catch { return false; }
}
private void RenderTabContent(int tabIndex)
@ -129,7 +204,7 @@ internal sealed class LegacyAdvancedSettingsUi
case "UI":
ImGui.Text("Radar");
ImGui.Separator();
ImGui.Checkbox("Get Rid of Retail Radar", ref _settings.SuppressRetailRadar);
ImGui.Checkbox("Hide retail radar", ref _settings.SuppressRetailRadar);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Suppress the game's built-in radar (bezel, compass, coords, blips).");
@ -155,7 +230,7 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Power Bar");
ImGui.Checkbox("Get Rid of Retail Power Bar", ref _settings.SuppressRetailPowerbar);
ImGui.Checkbox("Hide retail power bar", ref _settings.SuppressRetailPowerbar);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Hide the vanilla attack/magic power bar that appears under the cursor while charging.\nThe bar's underlying combat state still works — only the on-screen widget is hidden.");
break;
@ -214,8 +289,6 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetNextItemWidth(150);
ImGui.SliderFloat("Atlatl", ref _settings.AtlatlArcVelocity, 10.0f, 60.0f, "%.1f");
ImGui.SetNextItemWidth(150);
ImGui.SliderFloat("Magic Arc", ref _settings.MagicArcVelocity, 10.0f, 60.0f, "%.1f");
ImGui.SetNextItemWidth(150);
ImGui.SliderFloat("Arc Clearance (m)", ref _settings.MissileArcClearance, 0.0f, 3.0f, "%.1f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Extra headroom the arc must have at mid-flight. Raise it if shots\n" +
@ -223,6 +296,13 @@ internal sealed class LegacyAdvancedSettingsUi
"Default 0.5.");
ImGui.Unindent();
}
ImGui.SetNextItemWidth(150);
ImGui.SliderFloat("Magic Arc", ref _settings.MagicArcVelocity, 10.0f, 60.0f, "%.1f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Arc spells' horizontal speed (m/s). ACE: 40. Lower = higher arc.\n" +
"A rule with Arc on casts an arc only when this path reaches the target\n" +
"(walls, and ceilings in dungeons); otherwise its other shape, or a bolt.\n" +
"Needs Enable Raycasting. /ra lostest magic shows the arc to the selected mob.");
ImGui.Checkbox("LoS Debug Log", ref _settings.LosDebugLog);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Log each in-range mob's LoS verdict ([LOS] lines: straight line or arc,\n" +
@ -304,6 +384,15 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Heal At", ref _settings.HealAt, 0, 100);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Emergency Heal At", ref _settings.EmergencyHealAt, 0, 100);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("At or under this health %, a healing kit goes first out of Magic mode,\nand a kit or potion is used while a cast is pending. 0 = off.");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Stamina To Health At", ref _settings.StaminaToHealthAt, 0, 100);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("At or under this health %, cast Stamina to Health Self ahead of Heal At\n(after a kit out of Magic mode). 0 = never cast it.");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Stamina To Health Min Stamina", ref _settings.StaminaToHealthMinStamina, 0, 100);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Don't cast Stamina to Health unless stamina is over this %.");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Re-stam At", ref _settings.RestamAt, 0, 100);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Get Mana At", ref _settings.GetManaAt, 0, 100);
@ -418,6 +507,8 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Text("Ring Spell Override");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Min Ring Targets", ref _settings.MinRingTargets);
ImGui.InputInt("Blast Range (0 = off)", ref _settings.BlastRange);
ImGui.InputInt("Min Blast Targets", ref _settings.MinBlastTargets);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("If this many monsters are within ring range, ring spells are used instead of arc/bolt/streak.");
@ -470,9 +561,10 @@ internal sealed class LegacyAdvancedSettingsUi
case "Navigation":
ImGui.Checkbox("Boost Nav Priority", ref _settings.BoostNavPriority);
ImGui.SetNextItemWidth(120);
ImGui.InputFloat("Follow/Nav Min", ref _settings.FollowNavMin, 0.1f, 1.0f, "%.1f");
ImGui.InputFloat("Nav point reach (yd)", ref _settings.FollowNavMin, 0.1f, 1.0f, "%.1f");
_settings.FollowNavMin = LegacyUiSettings.ClampFollowNavMin(_settings.FollowNavMin);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Arrival distance in yards. Also sets the nav marker ring radius.");
ImGui.SetTooltip("How close to get to each nav point before moving on to the next (yards). VTank calls it Follow/Nav Min Distance. Follow stops this close to its leader; the nav marker ring shows it.");
ImGui.Spacing();
ImGui.Text("Nav Marker Display");
@ -512,15 +604,26 @@ internal sealed class LegacyAdvancedSettingsUi
}
ImGui.Spacing();
ImGui.Text("Movement Engine");
ImGui.SetNextItemWidth(200);
ImGui.Combo("Mode", ref _settings.MovementMode, MovementModes, MovementModes.Length);
ImGui.Separator();
ImGui.Text("Getting Back On Route");
ImGui.Checkbox("Find A Way Back When Stuck", ref _settings.NavRecoveryEnabled);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When a jump doesn't free a stuck character, or navigation wanders far off the route, plan a way back to the route around walls and obstacles (the dungeon map indoors, RynthNav outdoors) and open doors on the way. Off = only the jump and side-step escapes, as before.");
if (_settings.NavRecoveryEnabled)
{
ImGui.SetTooltip(
"Legacy: SetAutorun + smooth heading servo (TurnToHeading)\n" +
"Tier 1: SetAutorun + CM_Movement turn commands (DoMovement)\n" +
"Tier 2: Client physics MoveToPosition (not built yet — falls back to Legacy)");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Off Route Distance (yd)", ref _settings.NavOffTrackYards, 5f, 20f, "%.0f");
_settings.NavOffTrackYards = Math.Clamp(_settings.NavOffTrackYards, 160f, 1000f);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Navigation counts as off the route only beyond this distance, and only if it got there itself. At least 160: metas can take the character up to about 159 yd away on purpose, and coming back from that is normal.");
ImGui.SetNextItemWidth(80);
ImGui.InputInt("Tries Per Waypoint", ref _settings.NavMaxDetourAttempts);
_settings.NavMaxDetourAttempts = Math.Clamp(_settings.NavMaxDetourAttempts, 1, 10);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("How many planned ways back to try for one waypoint before giving up and using only the jump and side-step escapes. Reaching a waypoint resets the count.");
}
ImGui.Spacing();
@ -553,21 +656,10 @@ internal sealed class LegacyAdvancedSettingsUi
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off (aim straight at each waypoint).");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Shortcut Tolerance (yd)", ref _settings.NavShortcutYards, 0.5f, 1f, "%.1f");
_settings.NavShortcutYards = Math.Clamp(_settings.NavShortcutYards, 0f, 10f);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("On reaching a waypoint, skip ahead only while the straight line to a later waypoint passes within this distance of every waypoint skipped. Lower keeps closer to the route; 0 = visit every waypoint.");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Turn Rate (deg/s)", ref _settings.NavTurnRateDegPerSec, 15f, 45f, "%.0f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Mode 0 (heading servo) max turn speed. Higher = snappier turns, lower = gentler. Ignored by Tier 1 / Tier 2.");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Tier1 Turn Speed", ref _settings.NavTier1TurnSpeed, 0.1f, 0.5f, "%.2f");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Tier 1 (CM_Movement) DoMovement turn-command speed. Only used when Movement Engine = Tier 1.");
ImGui.SetTooltip("Max turn speed while navigating. Higher = snappier turns, lower = gentler.");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Post-Portal Delay (s)", ref _settings.PostPortalDelaySec, 0.25f, 1f, "%.2f");
@ -651,6 +743,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Checkbox("Enable Looting", ref _settings.EnableLooting);
ImGui.Checkbox("Boost Loot Priority", ref _settings.BoostLootPriority);
ImGui.Checkbox("Loot Only Rare Corpses", ref _settings.LootOnlyRareCorpses);
ImGui.Checkbox("Learn Unknown Spells", ref _settings.ReadUnknownScrolls);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Loots scrolls of spells you don't know and can learn (magic school trained or\nspecialized, skill high enough), and reads them when it's safe. Scrolls already\nin your pack are read too.");
ImGui.Checkbox("Jump When Looting", ref _settings.LootJumpEnabled);
if (_settings.LootJumpEnabled)
{

View file

@ -1,158 +0,0 @@
using System;
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal static class LegacyDashboardDrawing
{
public static void GridBtn(string label, string icon, ref bool flag)
{
bool wasOn = flag;
const float h = 30f;
ImGui.PushStyleColor(ImGuiCol.Button, LegacyDashboardRenderer.ColBtnFill);
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, LegacyDashboardRenderer.ColBtnHov);
ImGui.PushStyleColor(ImGuiCol.ButtonActive, LegacyDashboardRenderer.ColBtnAct);
ImGui.PushStyleColor(ImGuiCol.Border, wasOn ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColBtnBord);
ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1.0f);
ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 4f);
Vector2 start = ImGui.GetCursorScreenPos();
if (ImGui.Button($"##{label}", new Vector2(-1f, h))) flag = !flag;
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(4);
float w = ImGui.GetItemRectSize().X;
Vector2 text = ImGui.CalcTextSize(label);
DrawIcon(icon, start + new Vector2(8, 6), wasOn ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextMute, 16f);
ImGui.SetCursorScreenPos(start + new Vector2(30, (h - text.Y) / 2));
ImGui.TextColored(wasOn ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextDim, label);
ImGui.SetCursorScreenPos(start + new Vector2(0, h + 2));
ImGui.Dummy(new Vector2(w, 0));
}
public static void DrawSquareToggle(string icon, ref bool state, Vector2 pos, string id)
{
ImDrawListPtr dl = ImGui.GetWindowDrawList();
const float s = 30f;
Vector4 bg = state ? LegacyDashboardRenderer.ColBtnOn : LegacyDashboardRenderer.ColBarBg;
Vector4 iconCol = state ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextMute;
dl.AddRectFilled(pos, pos + new Vector2(s, s), ImGui.ColorConvertFloat4ToU32(bg), 4f);
if (state) dl.AddRect(pos, pos + new Vector2(s, s), ImGui.ColorConvertFloat4ToU32(LegacyDashboardRenderer.ColTeal), 4f, ImDrawFlags.None, 1f);
DrawIcon(icon, pos + new Vector2(6, 6), iconCol, 18f);
ImGui.SetCursorScreenPos(pos);
if (ImGui.InvisibleButton($"##{id}", new Vector2(s, s))) state = !state;
}
public static void DrawWideToggle(string label, string icon, ref bool state, Vector2 pos, string id, float width, float height)
{
ImDrawListPtr dl = ImGui.GetWindowDrawList();
Vector4 bg = state ? LegacyDashboardRenderer.ColBtnOn : LegacyDashboardRenderer.ColBarBg;
Vector4 iconCol = state ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextMute;
dl.AddRectFilled(pos, pos + new Vector2(width, height), ImGui.ColorConvertFloat4ToU32(bg), 4f);
if (state) dl.AddRect(pos, pos + new Vector2(width, height), ImGui.ColorConvertFloat4ToU32(LegacyDashboardRenderer.ColTeal), 4f, ImDrawFlags.None, 1f);
DrawIcon(icon, pos + new Vector2(4, (height - 12) / 2), iconCol, 12f);
Vector2 text = ImGui.CalcTextSize(label);
dl.AddText(pos + new Vector2(18, (height - text.Y) / 2), ImGui.ColorConvertFloat4ToU32(state ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextDim), label);
ImGui.SetCursorScreenPos(pos);
if (ImGui.InvisibleButton($"##{id}", new Vector2(width, height))) state = !state;
}
public static void DrawSegmentedBar(float pct, float width)
{
Vector2 pos = ImGui.GetCursorScreenPos();
ImDrawListPtr dl = ImGui.GetWindowDrawList();
const float h = 10f, gap = 2f;
const int segments = 15;
float sw = (width - (segments - 1) * gap) / segments;
for (int i = 0; i < segments; i++)
{
float t = (float)i / (segments - 1);
Vector4 col = i / (float)segments <= pct ? GetGradientCol(t) : LegacyDashboardRenderer.ColBarBg;
dl.AddRectFilled(pos + new Vector2(i * (sw + gap), 0), pos + new Vector2(i * (sw + gap) + sw, h), ImGui.ColorConvertFloat4ToU32(col), 1f);
}
ImGui.Dummy(new Vector2(width, h + 2));
}
public static void DrawCompactVitalBar(string label, float pct, Vector4 color, string valText, float width)
{
Vector2 pos = ImGui.GetCursorScreenPos();
ImDrawListPtr dl = ImGui.GetWindowDrawList();
const float h = 10f;
float safePct = Math.Clamp(pct, 0f, 1f);
dl.AddRectFilled(pos, pos + new Vector2(width, h), ImGui.ColorConvertFloat4ToU32(LegacyDashboardRenderer.ColBarBg), 3f);
dl.AddRectFilled(pos, pos + new Vector2(width * safePct, h), ImGui.ColorConvertFloat4ToU32(color), 3f);
string text = $"{label} {valText}";
dl.AddText(pos + new Vector2(4, -2), ImGui.ColorConvertFloat4ToU32(new Vector4(1, 1, 1, 0.9f)), text);
ImGui.Dummy(new Vector2(width, h + 1));
}
public static void DrawVitalRow(string icon, string label, float pct, Vector4 color, string valText)
{
float width = ImGui.GetContentRegionAvail().X - 4f;
Vector2 pos = ImGui.GetCursorScreenPos();
ImDrawListPtr dl = ImGui.GetWindowDrawList();
const float h = 14f;
dl.AddRectFilled(pos, pos + new Vector2(width, h), ImGui.ColorConvertFloat4ToU32(LegacyDashboardRenderer.ColBarBg), 4f);
float safePct = Math.Clamp(pct, 0f, 1f);
dl.AddRectFilled(pos, pos + new Vector2(width * safePct, h), ImGui.ColorConvertFloat4ToU32(color), 4f);
DrawIcon(icon, pos + new Vector2(4, 0), LegacyDashboardRenderer.ColTextDim, 13f);
dl.AddText(pos + new Vector2(22, -1), ImGui.ColorConvertFloat4ToU32(new Vector4(1, 1, 1, 1)), $"{label}: {(int)(safePct * 100)}% ({valText})");
ImGui.Dummy(new Vector2(width, h + 1));
}
private static Vector4 GetGradientCol(float t)
{
if (t < 0.33f) { float f = t / 0.33f; return new Vector4(1f, f, 0f, 1f); }
if (t < 0.66f) { float f = (t - 0.33f) / 0.33f; return new Vector4(1f - f, 1f, 0f, 1f); }
float g = (t - 0.66f) / 0.34f;
return new Vector4(0f, 1f, g, 1f);
}
private static void DrawIcon(string type, Vector2 pos, Vector4 color, float s)
{
ImDrawListPtr 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 * (MathF.PI * 2f / 8f); dl.AddLine(pos + new Vector2(s / 2 + MathF.Cos(a) * s / 3, s / 2 + MathF.Sin(a) * s / 3), pos + new Vector2(s / 2 + MathF.Cos(a) * s / 2, s / 2 + MathF.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;
}
}
}

View file

@ -324,6 +324,8 @@ internal sealed class LegacyMetaUi
ConditionData = rule.ConditionData,
Action = rule.Action,
ActionData = rule.ActionData,
CallReturnState = rule.CallReturnState,
ChatColors = rule.ChatColors,
Children = CloneChildren(rule.Children),
ActionChildren = CloneChildren(rule.ActionChildren)
};
@ -413,7 +415,9 @@ internal sealed class LegacyMetaUi
{
if (ImGui.Selectable(state, _settings.CurrentState == state))
{
if (_settings.CurrentState == state) _settings.ForceStateReset = true;
// Always a fresh entry (like SetState): the seconds-in-state timer
// and the old state's watchdog must not carry over to the new state.
_settings.ForceStateReset = true;
_settings.CurrentState = state;
}
}
@ -436,6 +440,7 @@ internal sealed class LegacyMetaUi
if (!string.IsNullOrWhiteSpace(_newStateName))
{
_settings.CurrentState = _newStateName;
_settings.ForceStateReset = true;
_newStateName = "";
}
ImGui.CloseCurrentPopup();
@ -1015,6 +1020,8 @@ internal sealed class LegacyMetaUi
ConditionData = r.ConditionData,
Action = r.Action,
ActionData = r.ActionData,
CallReturnState = r.CallReturnState,
ChatColors = r.ChatColors,
Children = CloneChildren(r.Children),
ActionChildren = CloneChildren(r.ActionChildren)
});
@ -1130,7 +1137,8 @@ internal sealed class LegacyMetaUi
}
}
internal void LoadMacroFile(string filePath)
/// <summary>Loads a .met/.af (empty path clears). False when nothing was loaded; <see cref="LastLoadStatus"/> says why.</summary>
internal bool LoadMacroFile(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
@ -1144,7 +1152,7 @@ internal sealed class LegacyMetaUi
_settings.ForceStateReset = true;
_statusMessage = "Macro cleared.";
_statusTime = DateTime.Now;
return;
return true;
}
try
@ -1160,7 +1168,7 @@ internal sealed class LegacyMetaUi
{
_statusMessage = "Unsupported file type";
_statusTime = DateTime.Now;
return;
return false;
}
LastLoadWarnings = loaded.Warnings;
@ -1170,7 +1178,7 @@ internal sealed class LegacyMetaUi
? $"No rules parsed — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}"
: "No rules found (profile?)";
_statusTime = DateTime.Now;
return;
return false;
}
lock (_settings.MetaRulesLock)
@ -1180,8 +1188,9 @@ internal sealed class LegacyMetaUi
foreach (var kvp in loaded.EmbeddedNavs)
_settings.EmbeddedNavs[kvp.Key] = kvp.Value;
}
_settings.CurrentState = loaded.Rules[0].State;
_settings.CurrentState = loaded.StartState;
_settings.ForceStateReset = true;
_settings.MetaCallStackReset = true;
_settings.CurrentMetaPath = filePath;
string name = Path.GetFileNameWithoutExtension(filePath);
@ -1190,14 +1199,20 @@ internal sealed class LegacyMetaUi
? $"Loaded {loaded.Rules.Count} rules / {stateCount} states / {loaded.EmbeddedNavs.Count} navs from {name}"
: $"Loaded {loaded.Rules.Count} rules / {stateCount} states from {name} — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}";
_statusTime = DateTime.Now;
return true;
}
catch (Exception ex)
{
_statusMessage = $"Load error: {ex.Message}";
_statusTime = DateTime.Now;
return false;
}
}
/// <summary>The status line of the last load (why it failed, or what it loaded).</summary>
internal string LastLoadStatus => _statusMessage ?? string.Empty;
private void TryAutoSaveMeta()
{
_settings.MetaRulesStructuralVersion++; // editor mutation → rebuild meta index

View file

@ -1,460 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.PluginSdk;
using RynthCore.Plugin.RynthAi.CreatureData;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed class LegacyMonstersUi
{
private readonly LegacyUiSettings _settings;
private readonly RynthCoreHost _host;
private readonly Action _onMonstersChanged;
private readonly Action _onLaunchExternalEditor;
private readonly Func<(uint Id, string Name)?> _getCurrentTarget;
/// <summary>Set by the dashboard so we can show captured stats per monster row.</summary>
public Func<string, CreatureProfile?>? CreatureLookup { get; set; }
private string _newMonsterName = string.Empty;
private string _newMonsterCategory = string.Empty;
private readonly Dictionary<string, bool> _categoryExpanded = new(StringComparer.OrdinalIgnoreCase);
// Expression popup state
private int _exprEditIndex = -1;
private string _exprEditBuffer = string.Empty;
// Category rename popup state
private string _catRenameFrom = string.Empty;
private string _catRenameBuffer = string.Empty;
private static readonly string[] Elements =
{ "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
private static readonly uint OnColor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.2f, 1.0f, 0.2f, 1.0f));
private static readonly uint OffColor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.3f, 0.3f, 0.3f, 1.0f));
private static readonly uint ExprOnColor = ImGui.ColorConvertFloat4ToU32(new Vector4(0.2f, 0.85f, 0.4f, 1.0f));
private static readonly uint CatHeaderBg = ImGui.ColorConvertFloat4ToU32(new Vector4(0.10f, 0.18f, 0.26f, 1.0f));
public LegacyMonstersUi(
LegacyUiSettings settings,
RynthCoreHost host,
Action onMonstersChanged,
Action onLaunchExternalEditor,
Func<(uint Id, string Name)?> getCurrentTarget)
{
_settings = settings;
_host = host;
_onMonstersChanged = onMonstersChanged;
_onLaunchExternalEditor = onLaunchExternalEditor;
_getCurrentTarget = getCurrentTarget;
}
public void Render()
{
if (!DashWindows.ShowMonsters) return;
ImGui.SetNextWindowSize(new Vector2(860, 480), ImGuiCond.FirstUseEver);
if (!ImGui.Begin("Monsters##RynthAiMonsters", ref DashWindows.ShowMonsters))
{
ImGui.End();
return;
}
if (ImGui.Button("External Editor", new Vector2(130, 24)))
_onLaunchExternalEditor();
ImGui.SameLine();
ImGui.TextDisabled("(opens standalone Avalonia editor)");
ImGui.Separator();
DrawTable();
ImGui.Separator();
DrawAddRow();
ImGui.End();
}
private void DrawTable()
{
// 19 columns: 10 toggles + Name + P + DmgType + ExVuln + Weapon + Offhand + PetDmg + [E] + Del
if (!ImGui.BeginTable(
"MonstersGrid", 19,
ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.Borders |
ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY,
new Vector2(0, 330)))
return;
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, 30);
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("[E]", ImGuiTableColumnFlags.WidthFixed, 26);
ImGui.TableSetupColumn("Del", ImGuiTableColumnFlags.WidthFixed, 26);
ImGui.TableHeadersRow();
int deleteIndex = -1;
string? currentCat = null;
bool currentCatOpen = true;
for (int i = 0; i < _settings.MonsterRules.Count; i++)
{
var rule = _settings.MonsterRules[i];
bool isDefault = rule.Name.Equals("Default", StringComparison.OrdinalIgnoreCase);
string cat = string.IsNullOrEmpty(rule.Category) ? "Default" : rule.Category;
// Category header row
if (!string.Equals(cat, currentCat, StringComparison.OrdinalIgnoreCase))
{
currentCat = cat;
if (!_categoryExpanded.ContainsKey(cat))
_categoryExpanded[cat] = true;
currentCatOpen = _categoryExpanded[cat];
ImGui.TableNextRow();
ImGui.TableSetBgColor(ImGuiTableBgTarget.RowBg0, CatHeaderBg);
ImGui.TableSetBgColor(ImGuiTableBgTarget.RowBg1, CatHeaderBg);
ImGui.TableNextColumn(); // col 0: expand toggle
string arrow = currentCatOpen ? "v" : ">";
ImGui.PushStyleColor(ImGuiCol.Button, Vector4.Zero);
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, new Vector4(1,1,1,0.1f));
if (ImGui.SmallButton($"{arrow}##cat_{cat}"))
{
currentCatOpen = !currentCatOpen;
_categoryExpanded[cat] = currentCatOpen;
}
ImGui.PopStyleColor(2);
// Name col: category label + right-click rename
ImGui.TableSetColumnIndex(10);
ImGui.TextColored(new Vector4(0.9f, 0.7f, 0.2f, 1f), cat);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Right-click to rename category");
if (ImGui.BeginPopupContextItem($"catctx_{cat}"))
{
ImGui.Text("Rename category:");
if (_catRenameFrom != cat)
{
_catRenameFrom = cat;
_catRenameBuffer = cat;
}
ImGui.SetNextItemWidth(180);
ImGui.InputText("##catren", ref _catRenameBuffer, 64);
if (ImGui.Button("Apply") && !string.IsNullOrWhiteSpace(_catRenameBuffer))
{
string newName = _catRenameBuffer.Trim();
foreach (var r in _settings.MonsterRules)
if (string.Equals(r.Category, cat, StringComparison.OrdinalIgnoreCase))
r.Category = newName;
if (_categoryExpanded.TryGetValue(cat, out bool v))
{
_categoryExpanded.Remove(cat);
_categoryExpanded[newName] = v;
}
_onMonstersChanged();
ImGui.CloseCurrentPopup();
}
ImGui.EndPopup();
}
}
if (!currentCatOpen) continue;
ImGui.TableNextRow();
ImGui.TableNextColumn();
if (DrawToggleLight($"##F{i}", rule.Fester, OnColor, OffColor, "F: Fester (Decrepitude's Grasp / Fester Other I-VIII)"))
{ rule.Fester = !rule.Fester; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##B{i}", rule.Broadside, OnColor, OffColor, "B: Broadside (Broadside of a Barn / Missile Weapons Ineptitude I-VIII)"))
{ rule.Broadside = !rule.Broadside; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##G{i}", rule.GravityWell, OnColor, OffColor, "G: Gravity Well (Vulnerability Other I-VIII)"))
{ rule.GravityWell = !rule.GravityWell; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##I{i}", rule.Imperil, OnColor, OffColor, "I: Imperil (Gossamer Flesh / Imperil Other I-VIII)"))
{ rule.Imperil = !rule.Imperil; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##Y{i}", rule.Yield, OnColor, OffColor, "Y: Yield (Magic Yield Other I-VIII)"))
{ rule.Yield = !rule.Yield; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##V{i}", rule.Vuln, OnColor, OffColor, "V: Vulnerability (element-matched)"))
{ rule.Vuln = !rule.Vuln; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##A{i}", rule.UseArc, OnColor, OffColor, "A: Arc spells\nFor Melee/Missile: Attack toggle"))
{ rule.UseArc = !rule.UseArc; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##Bl{i}", rule.UseBolt, OnColor, OffColor, "Bl: Bolt spells (default)\nIf none of A/Bl/R/S = no attack (buff bot)"))
{ rule.UseBolt = !rule.UseBolt; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##R{i}", rule.UseRing, OnColor, OffColor, "R: Ring spells"))
{ rule.UseRing = !rule.UseRing; _onMonstersChanged(); }
ImGui.TableNextColumn();
if (DrawToggleLight($"##S{i}", rule.UseStreak, OnColor, OffColor, "S: Streak spells"))
{ rule.UseStreak = !rule.UseStreak; _onMonstersChanged(); }
ImGui.TableNextColumn();
CreatureProfile? profile = CreatureLookup?.Invoke(rule.Name);
if (isDefault) ImGui.TextColored(new Vector4(1, 1, 0, 1), rule.Name);
else if (profile != null) ImGui.TextColored(new Vector4(0.55f, 0.95f, 0.65f, 1f), rule.Name);
else ImGui.TextUnformatted(rule.Name);
if (profile != null && ImGui.IsItemHovered())
ImGui.SetTooltip(BuildProfileTooltip(profile));
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
int pr = rule.Priority;
if (ImGui.InputInt($"##P{i}", ref pr, 0)) { rule.Priority = pr; _onMonstersChanged(); }
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
if (ImGui.BeginCombo($"##Dmg{i}", rule.DamageType, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("Auto", rule.DamageType == "Auto")) { rule.DamageType = "Auto"; _onMonstersChanged(); }
foreach (var el in Elements)
if (ImGui.Selectable(el + $"##d{i}", rule.DamageType == el)) { rule.DamageType = el; _onMonstersChanged(); }
ImGui.EndCombo();
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
if (ImGui.BeginCombo($"##Vuln{i}", rule.ExVuln, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("None", rule.ExVuln == "None")) { rule.ExVuln = "None"; _onMonstersChanged(); }
foreach (var el in Elements)
if (ImGui.Selectable(el + $"##v{i}", rule.ExVuln == el)) { rule.ExVuln = el; _onMonstersChanged(); }
ImGui.EndCombo();
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
string wepLabel = "<AUTO>";
if (rule.WeaponId != 0) { var w = _settings.ItemRules.FirstOrDefault(x => x.Id == rule.WeaponId); if (w != null) wepLabel = w.Name; }
if (ImGui.BeginCombo($"##Wep{i}", wepLabel, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("<AUTO>", rule.WeaponId == 0)) { rule.WeaponId = 0; _onMonstersChanged(); }
foreach (var item in _settings.ItemRules)
if (ImGui.Selectable(item.Name + $"##wep{i}_{item.Id}", rule.WeaponId == item.Id)) { rule.WeaponId = item.Id; _onMonstersChanged(); }
ImGui.EndCombo();
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
string offLabel = "<AUTO>";
if (rule.OffhandId != 0) { var o = _settings.ItemRules.FirstOrDefault(x => x.Id == rule.OffhandId); if (o != null) offLabel = o.Name; }
if (ImGui.BeginCombo($"##Off{i}", offLabel, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("<AUTO>", rule.OffhandId == 0)) { rule.OffhandId = 0; _onMonstersChanged(); }
foreach (var item in _settings.ItemRules)
if (ImGui.Selectable(item.Name + $"##off{i}_{item.Id}", rule.OffhandId == item.Id)) { rule.OffhandId = item.Id; _onMonstersChanged(); }
ImGui.EndCombo();
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
if (ImGui.BeginCombo($"##PetDmg{i}", rule.PetDamage, ImGuiComboFlags.NoArrowButton))
{
if (ImGui.Selectable("PAuto", rule.PetDamage == "PAuto")) { rule.PetDamage = "PAuto"; _onMonstersChanged(); }
foreach (var el in Elements)
if (ImGui.Selectable(el + $"##p{i}", rule.PetDamage == el)) { rule.PetDamage = el; _onMonstersChanged(); }
ImGui.EndCombo();
}
// [E] expression button
ImGui.TableNextColumn();
bool hasExpr = !string.IsNullOrWhiteSpace(rule.MatchExpression);
if (hasExpr) ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.1f, 0.5f, 0.2f, 1f));
if (ImGui.SmallButton($"E##e{i}"))
{
_exprEditIndex = i;
_exprEditBuffer = rule.MatchExpression ?? "";
ImGui.OpenPopup($"ExprEdit{i}");
}
if (hasExpr)
{
ImGui.PopStyleColor();
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Expression: {rule.MatchExpression}");
}
else if (ImGui.IsItemHovered())
{
ImGui.SetTooltip(
"Set a match expression.\n" +
"Examples:\n" +
" range>5\n" +
" range>5 && name==drudge ravener\n" +
" metastate==combat\n" +
"Variables: name, range, typeid, maxhp, metastate, true, false");
}
// Expression edit popup (rendered outside table to avoid clipping)
if (ImGui.BeginPopup($"ExprEdit{i}"))
{
ImGui.Text($"Expression for: {rule.Name}");
ImGui.TextColored(new Vector4(0.6f, 0.8f, 1f, 1f),
"Variables: name, range, typeid, maxhp, metastate, true, false");
ImGui.SetNextItemWidth(360);
ImGui.InputText("##exprval", ref _exprEditBuffer, 256);
if (ImGui.Button("Apply", new Vector2(80, 22)))
{
rule.MatchExpression = _exprEditBuffer.Trim();
_onMonstersChanged();
ImGui.CloseCurrentPopup();
}
ImGui.SameLine();
if (ImGui.Button("Clear", new Vector2(80, 22)))
{
rule.MatchExpression = "";
_exprEditBuffer = "";
_onMonstersChanged();
ImGui.CloseCurrentPopup();
}
ImGui.EndPopup();
}
// Del
ImGui.TableNextColumn();
if (isDefault)
{
ImGui.TextDisabled("-");
}
else
{
if (ImGui.SmallButton($"X##del{i}"))
deleteIndex = i;
}
}
ImGui.EndTable();
if (deleteIndex >= 0 && deleteIndex < _settings.MonsterRules.Count)
{
_settings.MonsterRules.RemoveAt(deleteIndex);
_onMonstersChanged();
}
}
private void DrawAddRow()
{
if (!ImGui.BeginTable("AddTable", 4))
return;
ImGui.TableSetupColumn("NameIn", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("CatIn", ImGuiTableColumnFlags.WidthFixed, 100);
ImGui.TableSetupColumn("AddBtn", ImGuiTableColumnFlags.WidthFixed, 60);
ImGui.TableSetupColumn("AddSelBtn", ImGuiTableColumnFlags.WidthFixed, 80);
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
ImGui.InputTextWithHint("##NewMonName", "Monster name...", ref _newMonsterName, 64);
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
ImGui.InputTextWithHint("##NewMonCat", "Category...", ref _newMonsterCategory, 64);
ImGui.TableNextColumn();
if (ImGui.Button("Add", new Vector2(60, 22)))
TryAddMonster(_newMonsterName, _newMonsterCategory);
ImGui.TableNextColumn();
if (ImGui.Button("Add Sel", new Vector2(80, 22)))
{
var target = _getCurrentTarget();
if (target.HasValue && !string.IsNullOrWhiteSpace(target.Value.Name))
TryAddMonster(target.Value.Name, _newMonsterCategory);
}
ImGui.EndTable();
}
private void TryAddMonster(string name, string category)
{
if (string.IsNullOrWhiteSpace(name)) return;
if (_settings.MonsterRules.Any(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase))) return;
_settings.MonsterRules.Add(new MonsterRule
{
Name = name.Trim(),
Category = category.Trim(),
DamageType = "Auto",
WeaponId = 0,
});
_newMonsterName = string.Empty;
_onMonstersChanged();
}
private static string BuildProfileTooltip(CreatureProfile p)
{
var sb = new System.Text.StringBuilder();
sb.Append("Captured: ").Append(p.Name);
if (p.Wcid != 0) sb.Append(" (wcid ").Append(p.Wcid).Append(')');
sb.Append('\n');
if (p.MaxHealth > 0) sb.Append("HP: ").Append(p.MaxHealth).Append('\n');
if (p.MaxStamina > 0) sb.Append("Stam: ").Append(p.MaxStamina).Append('\n');
if (p.MaxMana > 0) sb.Append("Mana: ").Append(p.MaxMana).Append('\n');
if (p.ArmorLevel > 0) sb.Append("Armor: ").Append(p.ArmorLevel).Append('\n');
var (weakType, weakVal) = CreatureProfileStore.GetWeakest(p);
if (weakVal < 1.0)
sb.Append("Weak: ").Append(weakType).Append(" (").Append(weakVal.ToString("0.00")).Append(")\n");
sb.Append("Resists: ")
.Append("Sl ").Append(p.ResistSlash.ToString("0.00")).Append(" ")
.Append("Pi ").Append(p.ResistPierce.ToString("0.00")).Append(" ")
.Append("Bl ").Append(p.ResistBludgeon.ToString("0.00")).Append('\n')
.Append(" ")
.Append("Fi ").Append(p.ResistFire.ToString("0.00")).Append(" ")
.Append("Co ").Append(p.ResistCold.ToString("0.00")).Append(" ")
.Append("Ac ").Append(p.ResistAcid.ToString("0.00")).Append(" ")
.Append("El ").Append(p.ResistElectric.ToString("0.00")).Append('\n');
if (p.KnownSpellIds.Count > 0)
sb.Append("Spells observed: ").Append(p.KnownSpellIds.Count).Append('\n');
sb.Append("Samples: ").Append(p.Samples);
if (!string.IsNullOrEmpty(p.LastSeen))
sb.Append(" (last: ").Append(p.LastSeen).Append(')');
return sb.ToString();
}
private static bool DrawToggleLight(string id, bool isOn, uint onColor, uint offColor, string? tooltip = null)
{
Vector2 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

@ -108,7 +108,7 @@ internal sealed class LegacyNavigationUi
{
NS = ns,
EW = ew,
Z = z
Z = z / 240.0
};
InsertPoint(newPt);
}
@ -154,7 +154,7 @@ internal sealed class LegacyNavigationUi
Type = NavPointType.Recall,
NS = ns,
EW = ew,
Z = z,
Z = z / 240.0,
SpellId = ids[ri]
};
InsertPoint(newPt);
@ -179,18 +179,8 @@ internal sealed class LegacyNavigationUi
ImGui.SameLine();
if (ImGui.Button("Save Route", new Vector2(100, 25)))
{
if (!string.IsNullOrEmpty(_settings.CurrentNavPath))
{
try
{
_settings.CurrentRoute.Save(_settings.CurrentNavPath);
_host.Log("Route saved.");
}
catch (Exception ex)
{
_host.Log($"Failed to save route: {ex.Message}");
}
}
_host.WriteToChat(SaveRoute(), 1);
OnSettingsChanged?.Invoke();
}
if (ImGui.BeginListBox("##RoutePoints", new Vector2(-1, 200)))
@ -207,8 +197,7 @@ internal sealed class LegacyNavigationUi
if (_selectedRouteIndex == i) _selectedRouteIndex = -1;
else if (_selectedRouteIndex > i) _selectedRouteIndex--;
if (_settings.ActiveNavIndex == i) _settings.ActiveNavIndex = 0;
else if (_settings.ActiveNavIndex > i) _settings.ActiveNavIndex--;
_settings.ActiveNavIndex = IndexAfterDelete(_settings.ActiveNavIndex, i, _settings.CurrentRoute.Points.Count);
TryAutoSaveNav();
UpdateRouteGraphics();
@ -241,6 +230,11 @@ internal sealed class LegacyNavigationUi
public void InsertPoint(NavPoint newPt)
{
// The selection is a row of whatever route was showing when it was clicked; a
// meta or /ra nav load since then can have swapped in a shorter one, and
// Insert past the end threw in the middle of the window.
if (_selectedRouteIndex >= _settings.CurrentRoute.Points.Count) _selectedRouteIndex = -1;
if (_addModeIdx == 0 || _settings.CurrentRoute.Points.Count == 0)
_settings.CurrentRoute.Points.Add(newPt);
else if (_addModeIdx == 1 && _selectedRouteIndex >= 0)
@ -255,12 +249,86 @@ internal sealed class LegacyNavigationUi
OnSettingsChanged?.Invoke();
}
/// <summary>
/// The active waypoint after deleting waypoint <paramref name="deleted"/> (the route now
/// has <paramref name="newCount"/> points). Deleting the active one moves on to the one
/// that followed it; this used to jump back to [0], which on a Once route re-ran its
/// opening recall/portal and could walk the bot back across the map.
/// </summary>
internal static int IndexAfterDelete(int active, int deleted, int newCount)
{
if (newCount <= 0) return 0;
if (active > deleted) active--;
return Math.Clamp(active, 0, newCount - 1);
}
public const string NavFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
public void TryAutoSaveNav()
{
if (!string.IsNullOrEmpty(_settings.CurrentNavPath))
string path = _settings.CurrentNavPath;
if (string.IsNullOrEmpty(path)) return;
try
{
try { _settings.CurrentRoute.Save(_settings.CurrentNavPath); } catch { }
if (TryGetEmbeddedKey(path, out string key))
_settings.EmbeddedNavs[key] = _settings.CurrentRoute.ToLines();
else
_settings.CurrentRoute.Save(path);
}
catch (Exception ex) { _host.Log($"[RynthAi] Nav auto-save to {path} failed: {ex.Message}"); }
}
/// <summary>
/// Saves the current route and returns the line to show in chat. With a name it
/// writes NavProfiles\&lt;name&gt;.nav and makes that the current nav. Without one it
/// writes the current nav file; a nav from the loaded meta is updated in the meta
/// (saving the meta keeps it); a route never saved gets a new "Route N" file.
/// These used to do nothing: the button only wrote to an existing file, and a
/// meta's nav path ("&lt;embedded:name&gt;") failed without a word.
/// </summary>
public string SaveRoute(string? name = null)
{
NavRouteParser route = _settings.CurrentRoute;
string path = _settings.CurrentNavPath ?? string.Empty;
try
{
if (!string.IsNullOrWhiteSpace(name))
{
string file = name.Trim();
if (file.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) file = file[..^4].TrimEnd();
if (file.Length == 0 || file.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
return $"[RynthAi] '{name}' can't be used as a file name.";
path = Path.Combine(NavFolder, file + ".nav");
}
else if (TryGetEmbeddedKey(path, out string key))
{
_settings.EmbeddedNavs[key] = route.ToLines();
return $"[RynthAi] '{key}' is a nav inside the loaded meta; updated it there ({route.Points.Count} waypoints). Save the meta to keep it, or /ra nav save <name> for a separate file.";
}
else if (path.Length == 0)
{
if (route.Points.Count == 0) return "[RynthAi] No waypoints to save.";
int n = 1;
do path = Path.Combine(NavFolder, $"Route {n++}.nav"); while (File.Exists(path));
}
route.Save(path);
_settings.CurrentNavPath = path;
return $"[RynthAi] Saved {route.Points.Count} waypoints to {Path.GetFileName(path)}.";
}
catch (Exception ex)
{
_host.Log($"[RynthAi] Nav save to {path} failed: {ex}");
return $"[RynthAi] Nav save failed: {ex.Message}";
}
}
private static bool TryGetEmbeddedKey(string path, out string key)
{
key = string.Empty;
if (!path.StartsWith("<embedded:", StringComparison.Ordinal) || !path.EndsWith('>')) return false;
key = path.Substring(10, path.Length - 11);
return key.Length > 0;
}
public void UpdateRouteGraphics()

View file

@ -44,6 +44,11 @@ public sealed class LegacyUiSettings
public float NavTurnRateDegPerSec = 270f; // mode 0 (heading servo) max turn rate
public float NavTier1TurnSpeed = 3.0f; // mode 1 (CM_Movement) DoMovement turn-command speed (magnitude of CMotionInterp turn_speed; 1.0 = native keyboard rate)
public float PostPortalDelaySec = 4.0f;
// Route recovery (NavigationEngine detours): when stuck after the jump fails, or when nav
// itself wanders off the route, plan a way back with the dungeon map / RynthNav navmesh.
public bool NavRecoveryEnabled = true;
public float NavOffTrackYards = 170f; // off track beyond this (never below 160: metas pull the bot up to ~159 yd away)
public int NavMaxDetourAttempts = 3; // detours per waypoint before falling back to the escape ladder alone
public float T2Speed = 1.0f;
public float T2DistanceTo = 0.5f;
public float T2ReissueMs = 2000f;
@ -62,6 +67,10 @@ public sealed class LegacyUiSettings
public bool EnableAutostack = true;
public bool EnableAutocram = true;
// VTank's ReadUnknownScrolls (default on): loot scrolls of spells the character doesn't
// know and can learn (school trained or specialized, ACE's skill rule), then read them
// at a safe moment; scrolls already in the pack too. Needs looting on for corpses.
public bool ReadUnknownScrolls = true;
public bool EnableCombineSalvage = true;
public bool CombineBagsDuringSalvage = true;
@ -94,6 +103,29 @@ public sealed class LegacyUiSettings
public bool MChargesWhenOff;
public int HealAt = 60;
// Vitals consumables and safety stops (2026-09-28). Stops are options: most
// metas handle a death themselves (run back), so the macro keeps going unless asked.
public bool UsePotions = true;
// Unlimited buff gems (Asheron's Benediction, Blackmoor's Favor) and field rations (2026-09-29).
public bool UseBuffItems = true;
public int MakeRationsBelow = 5; // 0 = don't cook field rations
public bool UseKitsInMagicMode = true;
public bool PeaceModeForKits = false;
// Use a healing/stamina kit only when its success chance (ACE's own skill check) is at
// least this %, else cast the spell instead, as VTank does. 0 = always use kits.
public int KitMinSuccessPct = 70;
// Emergency heal: at or under this health %, a healing kit (out of Magic mode, ahead of Heal
// At's chain) and, while a cast is pending, a kit or potion. 0 = off.
public int EmergencyHealAt = 30;
// Stamina to Health Self: cast at or under this health % ahead of Heal At's chain, when
// stamina is over StaminaToHealthMinStamina %. 0 = never cast it. Both default to the
// values that were hard-wired to Emergency Heal At before (30 / 20).
public int StaminaToHealthAt = 30;
public int StaminaToHealthMinStamina = 20;
public bool StopMacroOnDeath = false;
public bool StopMacroOnNoComponents = false;
public bool StopLootingWhenPackFull = true;
public bool StopMacroWhenPackFull = false;
public int RestamAt = 30;
public int GetManaAt = 40;
public int TopOffHP = 95;
@ -113,11 +145,19 @@ public sealed class LegacyUiSettings
public int RingRange = 5;
public int ApproachRange = 4;
public int MinRingTargets = 4;
// Blast like a ring: with BlastRange > 0, a rule with Blast on casts a blast only when
// MinBlastTargets monsters are within BlastRange in the blast's fan (3 projectiles over 90
// degrees) toward the target; otherwise its other shape. 0 = off: Blast is just a shape.
public int BlastRange = 0;
public int MinBlastTargets = 3;
// Nav point reach (VTank "Follow/Nav Min Distance"), yards: how close nav gets to each
// nav point before moving on to the next, and how close Follow gets to its leader.
// Metas set it as FollowNavMin (yards) or VTank's NavCloseStopRange (landblock units,
// x240 = yards; the same VTank setting). Settings ▸ Navigation and the Nav panel show it.
public float FollowNavMin = 1.5f;
// VTank navclosestoprange: stop this many LANDBLOCK FRACTIONS short of a finite
// (Once) route's final point (×240 = yards; 0.00625 ≈ 1.5yd). 0 = off. Runtime-
// set by migrated metas; not persisted.
public float NavCloseStopRange = 0f;
public const float FollowNavMinLowest = 0.5f, FollowNavMinHighest = 20f;
public static float ClampFollowNavMin(float yards) =>
float.IsNaN(yards) ? 1.5f : Math.Clamp(yards, FollowNavMinLowest, FollowNavMinHighest);
public float NavRingThickness = 6.0f;
public float NavLineThickness = 6.0f;
public float NavHeightOffset = 0.05f;
@ -159,6 +199,12 @@ public sealed class LegacyUiSettings
public int RebuffTopOffSecondsRemaining = 1200;
public bool StartMacroOnLogin;
public bool PatrolOnLogin;
/// <summary>
/// Decal bridge only: when VTank's macro starts, RynthAi's macro stops, and it won't start
/// while VTank runs (one bot per client). On by default; a profile saved before this
/// setting existed loads it as on. Without Decal it does nothing.
/// </summary>
public bool YieldToVTank = true;
public int BlacklistAttempts = 3;
public int BlacklistTimeoutSec = 30;
@ -222,6 +268,22 @@ public sealed class LegacyUiSettings
/// </summary>
public bool UseNativeAttack = false;
public bool UseRecklessness;
/// <summary>
/// Combat and buffing only ever wield weapons from the Items list. With this on (the
/// default), a character whose Items list has no wand at all may still buff and cast with a
/// caster from its pack (by object class, never by name). Any listed wand turns it off.
/// </summary>
public bool WieldUnlistedWandWhenNoneListed = true;
/// <summary>
/// The off hand (the Shield slot) when the monster rule doesn't choose one: "Auto" (a listed
/// shield with a one-handed melee weapon), "Shield", "Weapon" (dual wield a second listed
/// one-handed weapon; needs the Dual Wield skill) or "None" (never touched). A rule chooses
/// with MonsterRule.OffhandId (OffhandRules.RuleAuto..RuleNone). See OffhandPlanner.
/// </summary>
public string OffhandDefault = "Auto";
/// <summary>Auto: dual wield rather than a shield when the Dual Wield skill is trained and a
/// second one-handed melee weapon is listed. Off by default (the shield).</summary>
public bool PreferDualWield;
public int MeleeAttackHeight = 1;
public int MissileAttackHeight = 1;
@ -232,7 +294,20 @@ public sealed class LegacyUiSettings
public float BowArcVelocity = 25.0f;
public float CrossbowArcVelocity = 40.0f;
public float AtlatlArcVelocity = 22.0f;
public float MagicArcVelocity = 25.0f;
/// <summary>
/// Arc spells' HORIZONTAL speed (m/s). ACE flies every player arc at a fixed 40 m/s across
/// the ground under gravity 9.8 (MissileBallistics.SolveLateral). Combat casts an Arc only
/// when that path reaches the target, else the rule's other shape (or Bolt). Until
/// 2026-10-04 this was a launch speed for a flat-ground model, default 25:
/// <see cref="MigrateMagicArcVelocity"/> moves that old default to 40.
/// </summary>
public float MagicArcVelocity = Raycasting.MissileBallistics.AceArcSpellSpeed;
/// <summary>A saved MagicArcVelocity under today's model: the old default (25, a launch
/// speed for the flat-ground model, which as a horizontal speed would make arcs 2.6x higher
/// than ACE flies them) and nonsense values become 40.</summary>
public static float MigrateMagicArcVelocity(float saved)
=> float.IsFinite(saved) && saved > 0f && saved != 25.0f ? saved : Raycasting.MissileBallistics.AceArcSpellSpeed;
/// <summary>
/// Extra headroom (meters) a missile's arc must have at mid-flight for LoS to pass,
/// on top of the modelled flight path (launch speed above, AC gravity 9.8). Covers
@ -295,6 +370,20 @@ public sealed class LegacyUiSettings
/// <summary>Milliseconds between /ub vendor open attempts.</summary>
public int AutoVendorTriesTime = 5000;
// ── AutoTrade (UtilityBelt AutoTrade; /ub autotrade, /ra autotrade) ────────
/// <summary>Fill the trade window from a loot profile when a trade opens (UB default: off).</summary>
public bool AutoTradeEnabled = false;
/// <summary>Only print what would be added to the trade window.</summary>
public bool AutoTradeTestMode = false;
/// <summary>Send "AutoTrade finished: ..." and "Trade accepted: ..." as a /tell to yourself, for metas.</summary>
public bool AutoTradeThink = false;
public bool AutoTradeOnlyFromMainPack = false;
/// <summary>Accept the trade once every item AutoTrade added is in the window.</summary>
public bool AutoTradeAutoAccept = false;
/// <summary>Name patterns (.NET regex) whose accepted trades this character accepts too.
/// The autoAcceptList.json files (/ub autotrade autoaccept ...) are read as well.</summary>
public List<string> AutoTradeAutoAcceptChars { get; set; } = new();
public List<MonsterRule> MonsterRules { get; set; } = new();
public List<ItemRule> ItemRules { get; set; } = new();
public List<ConsumableRule> ConsumableRules { get; set; } = new();
@ -337,8 +426,12 @@ public sealed class LegacyUiSettings
? new Dictionary<string, List<string>>(value, StringComparer.OrdinalIgnoreCase)
: new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
}
public string LuaScript = "-- Enter your Lua script here\nprint('RynthAi Lua Loaded')";
[JsonIgnore] public string LuaConsoleOutput = "--- RynthAi Lua Console ---";
/// <summary>
/// Set once this profile's weapons and consumables have been checked against
/// the character's own pack (new profiles are filled from it; older ones had
/// entries copied from another character removed). See TickPackSetup.
/// </summary>
public bool ProfileItemsChecked;
public string SelectedProfile = "Default";
[JsonIgnore] public NavRouteParser CurrentRoute { get; set; } = new();
@ -417,6 +510,11 @@ public sealed class LegacyUiSettings
[JsonIgnore]
public bool ForceStateReset { get; set; }
/// <summary>Set when a meta file is loaded: the next meta tick empties the
/// CallState/Return stack.</summary>
[JsonIgnore]
public bool MetaCallStackReset { get; set; }
[JsonIgnore]
public string NavStatusLine = string.Empty;
@ -439,6 +537,8 @@ public sealed class LegacyUiSettings
// by the plugin each tick; 0 when not in a fellowship / target not loaded.
[JsonIgnore]
public uint FollowTargetId = 0;
/// <summary>A character picked by name (/ra follow Name, /ub follow[p]); wins over the fellowship leader. Session only.</summary>
[JsonIgnore] public uint FollowNamedTargetId;
public LegacyUiSettings()
{
@ -481,9 +581,18 @@ public sealed class MonsterRule
public bool UseRing { get; set; }
public bool UseStreak { get; set; }
public bool UseBolt { get; set; } = true;
/// <summary>Blast spells (Flame Blast, Frost Blast...: a spread of projectiles). Off in files
/// from before 2026-10-03. Wins over Bolt when both are on; see CombatManager.PickBaseShape.</summary>
public bool UseBlast { get; set; }
public string ExVuln { get; set; } = "None";
/// <summary>The off hand for this rule: 0 = the global setting (OffhandDefault), 1 Auto,
/// 2 Shield, 3 Offhand weapon, 4 None (OffhandRules.Rule*); any other value is a listed
/// item to wield there (the old per-rule picker).</summary>
public int OffhandId { get; set; }
public string PetDamage { get; set; } = "PAuto";
/// <summary>Debuffs the player typed in (Damage panel), comma separated: a spell's base
/// name ("Corrosion Vulnerability Other") casts its best known tier; a full name casts as is.</summary>
public string CustomDebuffs { get; set; } = "";
}
public sealed class BuffRule
@ -499,6 +608,10 @@ public sealed class ItemRule
public string Name { get; set; } = string.Empty;
public string Action { get; set; } = "Loot";
public string Element { get; set; } = "Slash";
/// <summary>Where <see cref="Element"/> came from: "properties" (DamageType after an identify),
/// "icon" (UiEffects), "rending" (an imbue), "name", "set" (picked in the Items panel), or ""
/// (not known, or an entry from before sources were kept).</summary>
public string ElementSource { get; set; } = "";
public bool KeepBuffed { get; set; } = true;
}
@ -552,6 +665,7 @@ public sealed class NavBridgePoint
public int Idx { get; set; }
public string Type { get; set; } = string.Empty; // "Point", "Recall", "Pause", "Chat", "PortalNPC"
public string Desc { get; set; } = string.Empty; // NavPoint.ToString()
public string Text { get; set; } = string.Empty; // Chat points: the command, for editing
public double NS { get; set; }
public double EW { get; set; }
public double Z { get; set; }
@ -580,6 +694,7 @@ public sealed class NavCommand
public int AddMode { get; set; } // 0=End, 1=Above, 2=Below
public int InsertAt { get; set; } = -1;
public string NavName { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty; // addChat: the command or text
}
/// <summary>Bridge payload for the engine-side Avalonia SettingsPanel.</summary>
@ -604,6 +719,8 @@ public sealed class SettingsBridgePayload
public bool PeaceModeWhenIdle { get; set; }
public bool StartMacroOnLogin { get; set; }
public bool PatrolOnLogin { get; set; }
// Absent from an older engine's payload: must not read as off.
public bool YieldToVTank { get; set; } = true;
public bool EnableRaycasting { get; set; }
public bool UseArcs { get; set; }
public float BowArcVelocity { get; set; }
@ -622,6 +739,19 @@ public sealed class SettingsBridgePayload
// Recharge
public int HealAt { get; set; }
public bool UsePotions { get; set; }
public bool UseBuffItems { get; set; } = true;
public int MakeRationsBelow { get; set; } = 5;
public bool UseKitsInMagicMode { get; set; }
public bool PeaceModeForKits { get; set; }
public int KitMinSuccessPct { get; set; } = 70;
public int EmergencyHealAt { get; set; } = 30;
public int StaminaToHealthAt { get; set; } = 30;
public int StaminaToHealthMinStamina { get; set; } = 20;
public bool StopMacroOnDeath { get; set; }
public bool StopMacroOnNoComponents { get; set; }
public bool StopLootingWhenPackFull { get; set; }
public bool StopMacroWhenPackFull { get; set; }
public int RestamAt { get; set; }
public int GetManaAt { get; set; }
public int TopOffHP { get; set; }
@ -646,6 +776,8 @@ public sealed class SettingsBridgePayload
public int AttackSpellIntervalMs { get; set; }
public bool CastDispelSelf { get; set; }
public int MinRingTargets { get; set; }
public int BlastRange { get; set; }
public int MinBlastTargets { get; set; } = 3; // absent from an older engine: keep the default
public int MinSkillLevelTier1 { get; set; }
public int MinSkillLevelTier2 { get; set; }
public int MinSkillLevelTier3 { get; set; }
@ -719,6 +851,7 @@ public sealed class SettingsBridgePayload
public int LootJumpHeight { get; set; }
public int LootOwnership { get; set; }
public bool EnableAutostack { get; set; }
public bool ReadUnknownScrolls { get; set; } = true; // absent from an older engine: keep the default
public bool EnableCombineSalvage { get; set; }
public bool CombineBagsDuringSalvage { get; set; }
public int LootInterItemDelayMs { get; set; }
@ -747,6 +880,9 @@ public sealed class SettingsBridgePayload
public bool? AutoVendorOnlyFromMainPack { get; set; }
public int? AutoVendorTries { get; set; }
public int? AutoVendorTriesTime { get; set; }
// The off hand (only when the sender includes them; today's engine Settings face doesn't).
public string? OffhandDefault { get; set; }
public bool? PreferDualWield { get; set; }
}
public enum MetaConditionType
@ -818,6 +954,14 @@ public sealed class MetaRule
public List<MetaRule> Children { get; set; } = new();
public List<MetaRule> ActionChildren { get; set; } = new();
/// <summary>CallMetaState only: the state pushed on the call stack (VTank's
/// "ret"). Empty means the calling rule's current state, as before.</summary>
public string CallReturnState { get; set; } = string.Empty;
/// <summary>ChatMessageCapture only: VTank's colour (chat type) id list,
/// semicolon-separated ("2;4"). Empty matches every chat type.</summary>
public string ChatColors { get; set; } = string.Empty;
/// <summary>Disabled rules are excluded from the per-state index so they
/// never evaluate. Default true; missing in old JSON/.af → stays true
/// (the property initializer runs, so backward-compatible).</summary>

View file

@ -1,23 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// <summary>
/// The Items list logic behind the engine's Items panel (ItemsFace): add the selected
/// weapon or consumable, fill from pack, prune. Draws nothing; its ImGui window went
/// with the plugin render path.
/// </summary>
internal sealed class LegacyWeaponsUi
{
private readonly LegacyUiSettings _settings;
private readonly RynthCoreHost _host;
private WorldObjectCache? _worldFilter;
private static readonly string[] Elements =
{ "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
private static readonly string[] ConsumableTypes =
{ "General", "Lockpick", "HealthKit", "ManaStone", "Stamina", "Pet" };
public LegacyWeaponsUi(LegacyUiSettings settings, RynthCoreHost host)
{
_settings = settings;
@ -26,184 +24,6 @@ internal sealed class LegacyWeaponsUi
public void SetWorldFilter(WorldObjectCache cache) => _worldFilter = cache;
public void Render()
{
if (!DashWindows.ShowWeapons) return;
ImGui.SetNextWindowSize(new Vector2(480, 440), ImGuiCond.FirstUseEver);
if (!ImGui.Begin("Items##RynthAiWeapons", ref DashWindows.ShowWeapons))
{
ImGui.End();
return;
}
// ── Weapons Section ─────────────────────────────────────────────────
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "Weapons");
ImGui.Spacing();
if (ImGui.BeginTable("WeaponsTable", 3,
ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.Resizable))
{
ImGui.TableSetupColumn("Item Name", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Element", ImGuiTableColumnFlags.WidthFixed, 100);
ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthFixed, 50);
ImGui.TableHeadersRow();
for (int i = 0; i < _settings.ItemRules.Count; i++)
{
var rule = _settings.ItemRules[i];
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool inCache = _worldFilter?[rule.Id] != null;
if (inCache)
{
ImGui.TextUnformatted(rule.Name);
}
else
{
ImGui.TextColored(new Vector4(1f, 0.35f, 0.35f, 1f), rule.Name);
ImGui.SameLine();
ImGui.TextColored(new Vector4(1f, 0.35f, 0.35f, 0.7f), "(Gone)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Item not in inventory.\nRemove and re-add the correct weapon.");
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
int elemIdx = Array.IndexOf(Elements, rule.Element);
if (elemIdx < 0) elemIdx = 0;
if (ImGui.Combo($"##Elem{i}", ref elemIdx, Elements, Elements.Length))
rule.Element = Elements[elemIdx];
ImGui.TableNextColumn();
if (ImGui.SmallButton($"Del##w{i}"))
{
foreach (var mr in _settings.MonsterRules)
if (mr.WeaponId == rule.Id) mr.WeaponId = 0;
_settings.ItemRules.RemoveAt(i);
ImGui.EndTable();
ImGui.End();
return;
}
}
ImGui.EndTable();
}
bool canAdd = _host.HasGetSelectedItemId;
if (!canAdd) ImGui.BeginDisabled();
if (ImGui.Button("Add Selected Weapon", new Vector2(160, 24)))
{
AddSelectedWeapon();
}
if (!canAdd) ImGui.EndDisabled();
ImGui.SameLine();
ImGui.TextDisabled("(Click a weapon in inventory first)");
// ── Consumable Items Section ────────────────────────────────────────
ImGui.Spacing();
ImGui.Separator();
ImGui.Spacing();
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "Consumable Items");
ImGui.Spacing();
if (ImGui.BeginTable("ConsumablesTable", 3,
ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.Resizable))
{
ImGui.TableSetupColumn("Item Name", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthFixed, 100);
ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthFixed, 50);
ImGui.TableHeadersRow();
for (int i = 0; i < _settings.ConsumableRules.Count; i++)
{
var rule = _settings.ConsumableRules[i];
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool inCache = _worldFilter?[rule.Id] != null;
if (inCache)
{
ImGui.TextUnformatted(rule.Name);
}
else
{
ImGui.TextColored(new Vector4(1f, 0.35f, 0.35f, 1f), rule.Name);
ImGui.SameLine();
ImGui.TextColored(new Vector4(1f, 0.35f, 0.35f, 0.7f), "(Gone)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Item not in inventory.\nRemove and re-add the correct item.");
}
ImGui.TableNextColumn();
ImGui.SetNextItemWidth(-1);
int typeIdx = Array.IndexOf(ConsumableTypes, rule.Type);
if (typeIdx < 0) typeIdx = 0;
if (ImGui.Combo($"##CType{i}", ref typeIdx, ConsumableTypes, ConsumableTypes.Length))
rule.Type = ConsumableTypes[typeIdx];
ImGui.TableNextColumn();
if (ImGui.SmallButton($"Del##c{i}"))
{
_settings.ConsumableRules.RemoveAt(i);
ImGui.EndTable();
ImGui.End();
return;
}
}
ImGui.EndTable();
}
if (!canAdd) ImGui.BeginDisabled();
if (ImGui.Button("Add Selected Consumable", new Vector2(180, 24)))
{
AddSelectedConsumable();
}
if (!canAdd) ImGui.EndDisabled();
ImGui.SameLine();
ImGui.TextDisabled("(Click an item in inventory first)");
// ── Mana Stone Tapping ──────────────────────────────────────────────
ImGui.Spacing();
ImGui.Separator();
ImGui.Spacing();
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "Mana Stone Tapping");
ImGui.Spacing();
ImGui.Text("Keep up to:");
ImGui.SameLine();
ImGui.SetNextItemWidth(70);
ImGui.DragInt("##StoneKeep", ref _settings.ManaStoneKeepCount, 0.2f, 1, 999);
if (_settings.ManaStoneKeepCount < 1) _settings.ManaStoneKeepCount = 1;
if (_settings.ManaStoneKeepCount > 999) _settings.ManaStoneKeepCount = 999;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Maximum number of mana stones to keep in inventory.\nStones on corpses are skipped once this count is reached.");
ImGui.SameLine(0, 16);
ImGui.Checkbox("Enable Tapping", ref _settings.EnableManaTapping);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Use mana stones on inventory items with high MaxMana,\nthen apply the charged stone to the player to recharge gear.");
if (_settings.EnableManaTapping)
{
ImGui.SameLine(0, 16);
ImGui.Text("Min MaxMana:");
ImGui.SameLine();
ImGui.SetNextItemWidth(90);
ImGui.DragInt("##TapThresh", ref _settings.ManaTapMinMana, 50f, 100, 99999);
if (_settings.ManaTapMinMana < 100) _settings.ManaTapMinMana = 100;
if (_settings.ManaTapMinMana > 99999) _settings.ManaTapMinMana = 99999;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Only tap items whose MaxMana is at or above this value.");
}
ImGui.End();
}
public void AddSelectedWeapon()
{
uint selId = _host.GetSelectedItemId();
@ -215,23 +35,44 @@ internal sealed class LegacyWeaponsUi
if (_worldFilter == null) { _host.WriteToChat("[RynthAi] Object cache not ready.", 1); return; }
var wo = _worldFilter[(int)selId];
// A class guessed from the name before the item type was known can be wrong: ask the
// game for the real type before refusing (and fix the cached entry for combat too).
if (wo != null && !IsWeapon(wo) && !CombatManager.IsShieldItem(wo))
wo = _worldFilter.ReclassifyFromItemType(wo.Id) ?? wo;
if (wo == null)
_host.WriteToChat($"[RynthAi] Item 0x{selId:X8} not in cache — try again.", 1);
else if (!IsWeapon(wo))
_host.WriteToChat("[RynthAi] Selected item is not a weapon or wand.", 1);
else if (!IsWeapon(wo) && !CombatManager.IsShieldItem(wo))
_host.WriteToChat("[RynthAi] Selected item is not a weapon, wand or shield.", 1);
else if (_settings.ItemRules.Any(x => x.Id == wo.Id))
_host.WriteToChat($"[RynthAi] {wo.Name} is already in the list.", 1);
else
else if (!IsWeapon(wo))
{
string element = DetectWeaponElement(wo);
// A shield: combat wields it in the off hand (the Monsters rule's / global Offhand setting).
_settings.ItemRules.Add(new ItemRule
{
Id = wo.Id,
Name = wo.Name,
Element = element,
Action = "Weapon",
Id = wo.Id,
Name = wo.Name,
Element = "",
ElementSource = "",
Action = WeaponList.ShieldAction,
});
_host.WriteToChat($"[RynthAi] Added weapon: {wo.Name} (0x{(uint)wo.Id:X8}) [{element}]", 1);
string shown = WeaponNames.For(_host, _worldFilter, wo.Id, wo.Name);
_host.WriteToChat($"[RynthAi] Added shield: {shown} (0x{(uint)wo.Id:X8}) — wielded in the off hand with a one-handed weapon (Offhand: {_settings.OffhandDefault})", 1);
}
else
{
var info = WeaponElementTracker.ReadFrom(_host, wo.Id, wo.Name);
_settings.ItemRules.Add(new ItemRule
{
Id = wo.Id,
Name = wo.Name,
Element = info.Element,
ElementSource = info.Source,
Action = "Weapon",
});
string shown = WeaponNames.For(_host, _worldFilter, wo.Id, wo.Name);
string elem = info.Unknown ? "element unknown until identified" : $"{info.Element}, from {info.Source}";
_host.WriteToChat($"[RynthAi] Added weapon: {shown} (0x{(uint)wo.Id:X8}) [{elem}]", 1);
}
}
@ -263,37 +104,104 @@ internal sealed class LegacyWeaponsUi
}
}
/// <summary>
/// Adds every weapon and usable consumable in <paramref name="inventory"/> that
/// isn't listed yet: weapons (melee, missile, wands; the wielded one first, since
/// combat treats the first weapon as the default), healing kits, lockpicks and
/// pet essences. Mana stones are left out on purpose: listing any switches mana
/// tapping from "every mana stone" to "only these names".
/// </summary>
public (int Weapons, int Consumables) FillFromPack(IReadOnlyList<WorldObject> inventory, uint playerId)
{
int weapons = 0, consumables = 0;
var ordered = inventory
.OrderByDescending(wo => playerId != 0 && wo.Wielder == unchecked((int)playerId))
.ThenBy(wo => wo.Name, StringComparer.OrdinalIgnoreCase);
foreach (var wo in ordered)
{
if (IsWeapon(wo))
{
if (_settings.ItemRules.Any(x => x.Id == wo.Id)) continue;
var info = WeaponElementTracker.ReadFrom(_host, wo.Id, wo.Name);
_settings.ItemRules.Add(new ItemRule { Id = wo.Id, Name = wo.Name, Element = info.Element, ElementSource = info.Source, Action = "Weapon" });
weapons++;
continue;
}
string? type = PackConsumableType(wo);
if (type == null || _settings.ConsumableRules.Any(x => x.Id == wo.Id)) continue;
_settings.ConsumableRules.Add(new ConsumableRule { Id = wo.Id, Name = wo.Name, Type = type });
consumables++;
}
return (weapons, consumables);
}
/// <summary>
/// Removes weapons and consumables this character has nothing of, by id or by
/// name: entries a profile picked up from another character. Returns their names.
/// </summary>
public List<string> PruneNotOwned(IReadOnlyList<WorldObject> inventory)
{
var ids = new HashSet<int>(inventory.Select(w => w.Id));
var names = new HashSet<string>(inventory.Select(w => w.Name), StringComparer.OrdinalIgnoreCase);
var removed = new List<string>();
_settings.ItemRules.RemoveAll(r =>
{
bool gone = !ids.Contains(r.Id) && !names.Contains(r.Name);
if (gone) removed.Add(r.Name);
return gone;
});
_settings.ConsumableRules.RemoveAll(r =>
{
bool gone = !ids.Contains(r.Id) && !names.Contains(r.Name);
if (gone) removed.Add(r.Name);
return gone;
});
return removed;
}
internal static string? PackConsumableType(WorldObject wo)
{
switch (wo.ObjectClass)
{
case AcObjectClass.HealingKit: return "HealthKit";
case AcObjectClass.Food: return PotionType(wo);
case AcObjectClass.Lockpick: return "Lockpick";
case AcObjectClass.Misc:
case AcObjectClass.CombatPet:
return wo.Name.Contains("Essence", StringComparison.OrdinalIgnoreCase) ? "Pet" : null;
default: return null;
}
}
/// <summary>HealthPotion / ManaPotion / StaminaPotion for a Food item named for a vital, else null.</summary>
internal static string? PotionType(WorldObject wo)
{
if (wo.ObjectClass != AcObjectClass.Food || string.IsNullOrEmpty(wo.Name)) return null;
string n = wo.Name;
// Field Rations restore stamina (BoostEnum 4) but don't say so in the name.
if (n.EndsWith("Field Rations", StringComparison.OrdinalIgnoreCase)) return "StaminaPotion";
if (n.Contains("Mana", StringComparison.OrdinalIgnoreCase)) return "ManaPotion";
if (n.Contains("Stamina", StringComparison.OrdinalIgnoreCase)) return "StaminaPotion";
if (n.Contains("Heal", StringComparison.OrdinalIgnoreCase) || n.Contains("Health", StringComparison.OrdinalIgnoreCase)) return "HealthPotion";
return null;
}
private static bool IsWeapon(WorldObject wo) =>
wo.ObjectClass == AcObjectClass.MeleeWeapon ||
wo.ObjectClass == AcObjectClass.MissileWeapon ||
wo.ObjectClass == AcObjectClass.WandStaffOrb;
/// <summary>Auto-detect weapon element from the DamageType int property.</summary>
private static string DetectWeaponElement(WorldObject wo)
{
// DamageType (STypeInt 45) — AC damage type flags
int dt = wo.Values(LongValueKey.DamageType, 0);
if (dt == 0) return "Slash"; // no data — default
// Check flags in order of specificity (elemental first, then physical)
if ((dt & 1024) != 0) return "Nether";
if ((dt & 16) != 0) return "Fire";
if ((dt & 8) != 0) return "Cold";
if ((dt & 64) != 0) return "Lightning";
if ((dt & 32) != 0) return "Acid";
if ((dt & 1) != 0) return "Slash";
if ((dt & 2) != 0) return "Pierce";
if ((dt & 4) != 0) return "Bludgeon";
return "Slash";
}
/// <summary>Auto-detect consumable type from item name.</summary>
private static string DetectConsumableType(WorldObject wo)
{
string name = wo.Name;
if (string.IsNullOrEmpty(name)) return "General";
// Potions and elixirs are Food: typed by the vital they restore. A mana
// potion used to become "ManaStone" from the word "Mana".
string? potion = PotionType(wo);
if (potion != null) return potion;
// Health items
if (name.Contains("Heal", StringComparison.OrdinalIgnoreCase) ||
name.Contains("Health", StringComparison.OrdinalIgnoreCase) ||

View file

@ -22,4 +22,6 @@ internal sealed class MetaCommand
public string Path { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
public MetaRuleDto? Rule { get; set; }
/// <summary>The Meta Manager's mm_add / mm_update rule.</summary>
public RynthCore.Plugin.RynthAi.Meta.MetaScheduleRule? ScheduleRule { get; set; }
}

View file

@ -26,7 +26,10 @@ public enum NavPointType
Chat = 4, // trailer: command string
OpenVendor = 5, // trailer: vendorId(int), vendorName(string)
PortalNPC = 6, // VTank "Portal": use a portal object by name. trailer: name, class, tie, ew, ns, z
Npc = 7 // VTank "NPC": use/talk an NPC by name. trailer: name, class, tie, ew, ns, z
Npc = 7, // VTank "NPC": use/talk an NPC by name. trailer: name, class, tie, ew, ns, z
Checkpoint = 8, // walked like a Point; no trailer (confirmed from a real route, 2026-09-28)
Jump = 9 // walk here, face heading, jump. trailer: heading, shift ("true"/"false"), ms
// (order from UtilityBelt's VTNJump.Parse/Write)
}
public sealed class NavPoint
@ -39,6 +42,9 @@ public sealed class NavPoint
public int SpellId { get; set; }
public int PauseTimeMs { get; set; }
public string ChatCommand { get; set; } = string.Empty;
public double JumpHeading { get; set; } // Jump: heading to face (degrees)
public bool JumpShift { get; set; } // Jump: shift (walk) jump
public double JumpMs { get; set; } // Jump: spacebar hold time = power (0-1000)
// Portal (6) / Npc (7) target name; for OpenVendor (5) the vendor's name.
public string TargetName { get; set; } = string.Empty;
@ -61,6 +67,13 @@ public sealed class NavPoint
public double PortalLandEW { get; set; }
public double PortalLandZ { get; set; }
/// <summary>
/// A point the dungeon pathfinder put centred in front of (or beyond) a narrow opening, so
/// the character goes through straight. The engine reaches it within at most 1 yd and does
/// not cut the corner at it. Built in memory only: never read from or written to .nav files.
/// </summary>
public bool Doorway { get; set; }
public override string ToString()
{
return Type switch
@ -72,6 +85,8 @@ public sealed class NavPoint
NavPointType.OpenVendor => $"[Vendor] {TargetName}",
NavPointType.PortalNPC => $"[Portal] {TargetName}",
NavPointType.Npc => $"[NPC] {TargetName}",
NavPointType.Checkpoint => $"[Checkpoint] {NS:F3}, {EW:F3}",
NavPointType.Jump => $"[Jump] {JumpHeading:F0}° {JumpMs:F0}ms{(JumpShift ? " shift" : "")}",
_ => $"[Unknown] {(int)Type}"
};
}
@ -96,6 +111,7 @@ public sealed class NavRouteParser
/// </summary>
public static int TrailerLineCount(NavPointType t) => t switch
{
NavPointType.Jump => 3,
NavPointType.Recall => 1,
NavPointType.Pause => 1,
NavPointType.Chat => 1,
@ -106,7 +122,17 @@ public sealed class NavRouteParser
};
public static bool IsKnownType(int t) =>
t is 0 or 2 or 3 or 4 or 5 or 6 or 7;
t is 0 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9;
/// <summary>A waypoint that is simply walked to (Point, Checkpoint).</summary>
public static bool IsPlainWaypoint(NavPointType t) => t is NavPointType.Point or NavPointType.Checkpoint;
/// <summary>
/// Follow-type nav files (route type 3) name a character to follow instead of
/// listing points: "uTank2 NAV 1.2", 3, name, id. Empty for other routes.
/// </summary>
public string FollowTargetName { get; set; } = string.Empty;
public uint FollowTargetId { get; set; }
public static NavRouteParser Load(string filePath, Action<string>? warn = null)
{
@ -130,6 +156,18 @@ public sealed class NavRouteParser
if (lines.Count < 3 || !lines[0].Contains("uTank2 NAV 1.2", StringComparison.OrdinalIgnoreCase))
return route;
// Follow navs: name + id of the character to follow, no points. Line 2 is
// the name, not a point count, so this has to come before the header check.
if (int.TryParse(lines[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int rt0)
&& rt0 == (int)NavRouteType.Follow && !int.TryParse(lines[2], out _))
{
route.RouteType = NavRouteType.Follow;
route.FollowTargetName = lines[2].Trim();
if (lines.Count > 3 && uint.TryParse(lines[3].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out uint fid))
route.FollowTargetId = fid;
return route;
}
if (!int.TryParse(lines[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int routeType) ||
!int.TryParse(lines[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int pointCount))
{
@ -166,6 +204,10 @@ public sealed class NavRouteParser
NS = double.Parse(lines[idx++], CultureInfo.InvariantCulture),
Z = double.Parse(lines[idx++], CultureInfo.InvariantCulture)
};
// Z is in nav units (metres / 240). Waypoints added from the UI before
// 2026-09-29 stored metres, so they drew hundreds of metres up; no real
// point is 5 units (1.2 km) high, so anything past that is converted.
if (Math.Abs(pt.Z) > 5.0) pt.Z /= 240.0;
idx++; // skip the flag / colour line
switch (pt.Type)
@ -183,6 +225,11 @@ public sealed class NavRouteParser
pt.VendorId = uint.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.TargetName = lines[idx++];
break;
case NavPointType.Jump:
pt.JumpHeading = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.JumpShift = lines[idx++].Trim().Equals("true", StringComparison.OrdinalIgnoreCase);
pt.JumpMs = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
break;
case NavPointType.PortalNPC:
case NavPointType.Npc:
pt.TargetName = lines[idx++];
@ -220,8 +267,30 @@ public sealed class NavRouteParser
Directory.CreateDirectory(Path.GetDirectoryName(filePath) ?? ".");
using var writer = new StreamWriter(filePath, false);
WriteTo(writer);
}
/// <summary>The route as uTank2 nav lines, the form a meta's embedded navs are kept in.</summary>
public List<string> ToLines()
{
using var writer = new StringWriter(CultureInfo.InvariantCulture);
WriteTo(writer);
var lines = new List<string>(writer.ToString().Split('\n'));
for (int i = 0; i < lines.Count; i++) lines[i] = lines[i].TrimEnd('\r');
if (lines.Count > 0 && lines[^1].Length == 0) lines.RemoveAt(lines.Count - 1);
return lines;
}
private void WriteTo(TextWriter writer)
{
writer.WriteLine("uTank2 NAV 1.2");
writer.WriteLine((int)RouteType);
if (RouteType == NavRouteType.Follow && FollowTargetName.Length > 0)
{
writer.WriteLine(FollowTargetName);
writer.WriteLine(FollowTargetId.ToString(CultureInfo.InvariantCulture));
return;
}
writer.WriteLine(Points.Count);
foreach (NavPoint point in Points)
@ -247,6 +316,11 @@ public sealed class NavRouteParser
writer.WriteLine(point.VendorId.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(point.TargetName);
break;
case NavPointType.Jump:
writer.WriteLine(point.JumpHeading.ToString(CultureInfo.InvariantCulture));
writer.WriteLine(point.JumpShift ? "True" : "False");
writer.WriteLine(point.JumpMs.ToString(CultureInfo.InvariantCulture));
break;
case NavPointType.PortalNPC:
case NavPointType.Npc:
writer.WriteLine(point.TargetName);

View file

@ -68,7 +68,9 @@ internal sealed class RadarVisitedLayer
[JsonPropertyName("strips")] public float[] Strips { get; set; } = Array.Empty<float>();
}
// Kind: 0 = monster, 1 = npc, 2 = portal, 3 = door
// Kind (RadarKind in the engine's UI/Data/RadarSnapshotJson.cs): 0 monster, 1 NPC, 2 portal,
// 3 door; appended 2026-10-04: 4 player, 5 fellow, 6 your pet, 7 vendor, 8 corpse, 9 your
// corpse, 10 lifestone, 11 item on the ground. Engines before that drop kinds 4+ (not drawn).
internal sealed class RadarMarker
{
[JsonPropertyName("kind")] public byte Kind { get; set; }
@ -76,6 +78,9 @@ internal sealed class RadarMarker
[JsonPropertyName("y")] public float Y { get; set; }
[JsonPropertyName("z")] public float Z { get; set; }
[JsonPropertyName("label")] public string? Label { get; set; }
// The object's id, so the engine's radar click selects exactly this object
// (engines from 2026-10-01). Older engines skip the unknown field.
[JsonPropertyName("id")] public uint Id { get; set; }
}
[JsonSerializable(typeof(RadarSnapshotPayload))]

View file

@ -16,6 +16,7 @@ namespace RynthCore.Plugin.RynthAi;
[JsonSerializable(typeof(NavCommand))]
[JsonSerializable(typeof(MetaRuleDto))]
[JsonSerializable(typeof(MetaCommand))]
[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Meta.MetaScheduleConfig))]
[JsonSourceGenerationOptions(
WriteIndented = true,
IncludeFields = true,

View file

@ -1,16 +1,14 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// <summary>
/// RynthChat — viewer for incoming chat lines. Subscribes to the plugin's
/// OnChatWindowText handler (via Push). The retail chatbox can be hidden via
/// SuppressRetailChat while AC's chat input/command pipeline still works in the
/// background — typed commands and tells continue to function unchanged.
/// RynthAi's recent-chat buffer: lines arrive through Push (RynthAiPlugin.OnChatWindowText)
/// and SnapshotRecent feeds the dashboard snapshot (the remote status feed). It used to be
/// a plugin-drawn chat window too; the chat window is now the RynthChat plugin's engine
/// face (ChatFace), so nothing here draws.
/// </summary>
internal sealed class RynthChatUi
{
@ -20,25 +18,12 @@ internal sealed class RynthChatUi
private readonly object _lock = new();
private readonly List<ChatLine> _lines = new(512);
private bool _open = true;
private bool _wantScrollToBottom = true;
private bool _prevLDown;
private bool _prevRDown;
// Input field state — Enter outside any widget focuses the input,
// Enter inside the input submits, Esc clears the buffer. The input row
// is always rendered so the scrollback area has a stable layout.
private bool _focusInputNextFrame;
private bool _swallowFirstEnter;
private string _inputBuffer = string.Empty;
public Action? OnSettingChanged { get; set; }
/// <summary>
/// Routes a submitted line. Set by the plugin so /ra, /mt, /ub etc. can be
/// handled locally by OnChatBarEnter before falling back to InvokeChatParser.
/// Without this, plugin slash commands would be keyboard-simulated into the
/// (invisible) retail chatbar — unreliable with ImGui focus in the picture.
/// Nothing calls it since the input line went with the plugin-drawn window.
/// </summary>
public Action<string>? OnSubmit { get; set; }
@ -64,8 +49,6 @@ internal sealed class RynthChatUi
if (overflow > 0)
_lines.RemoveRange(0, overflow);
}
_wantScrollToBottom = true;
}
/// <summary>Snapshot the most recent lines (text + chat-type) for the remote status feed. Thread-safe.</summary>
@ -81,315 +64,4 @@ internal sealed class RynthChatUi
return outArr;
}
}
public void Render()
{
if (!_settings.ShowRynthChat) return;
bool snapShowTs = _settings.ChatShowTimestamps;
float snapOp = _settings.ChatOpacity;
int snapMax = _settings.ChatMaxLines;
ImGui.SetNextWindowSize(new Vector2(520, 220), ImGuiCond.FirstUseEver);
ImGui.SetNextWindowSizeConstraints(new Vector2(220, 110), new Vector2(2400, 1400));
// Use ImGui's native WindowBg with the user's opacity so the platform
// layer can translate it into Platform_SetWindowAlpha on detached
// viewports — that gives a uniformly translucent OS window instead of
// a black-cleared one with a transparent paint over the top.
float opCfg = Math.Clamp(_settings.ChatOpacity, 0f, 1f);
ImGui.SetNextWindowBgAlpha(opCfg);
ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f);
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
ImGui.PushStyleColor(ImGuiCol.WindowBg, new Vector4(0.05f, 0.07f, 0.10f, 1f));
// NoBringToFrontOnFocus keeps the gear sub-window (rendered after) on top
// even when the user clicks into the main chat (to drag, resize, or select text).
ImGuiWindowFlags flags = ImGuiWindowFlags.NoTitleBar
| ImGuiWindowFlags.NoCollapse
| ImGuiWindowFlags.NoBringToFrontOnFocus;
if (_settings.ChatClickThrough)
{
flags |= ImGuiWindowFlags.NoInputs
| ImGuiWindowFlags.NoMove
| ImGuiWindowFlags.NoResize;
}
bool visible = ImGui.Begin("##RynthChat", ref _open, flags);
ImGui.PopStyleVar(2);
ImGui.PopStyleColor();
if (!visible) { ImGui.End(); return; }
Vector2 winPos = ImGui.GetWindowPos();
Vector2 winSize = ImGui.GetWindowSize();
// ImGui paints the WindowBg for us (with platform alpha on detached
// viewports). Just add a thin border for drag/resize affordance.
var dl = ImGui.GetWindowDrawList();
float op = opCfg;
uint br = ImGui.ColorConvertFloat4ToU32(new Vector4(0.30f, 0.34f, 0.40f, 1f));
dl.AddRect(winPos, winPos + winSize, br, 4f, ImDrawFlags.None, 1.5f);
// Gear visual is painted directly on the chat's drawlist (so it's always
// visible above the bg, on the same viewport, regardless of z-order).
// Clicks are detected manually below so they work whether the chat has
// NoInputs (click-through) or not, and on detached viewports.
const float btn = 14f;
Vector2 gearPos = new Vector2(winPos.X + winSize.X - btn - 4f, winPos.Y + 4f);
Vector2 gearBR = gearPos + new Vector2(btn, btn);
var io = ImGui.GetIO();
bool gearHovered = io.MousePos.X >= gearPos.X && io.MousePos.X < gearBR.X
&& io.MousePos.Y >= gearPos.Y && io.MousePos.Y < gearBR.Y;
uint gearBg = ImGui.ColorConvertFloat4ToU32(gearHovered
? new Vector4(0.25f, 0.30f, 0.40f, 0.95f)
: new Vector4(0f, 0f, 0f, 0.65f));
uint gearBorder = ImGui.ColorConvertFloat4ToU32(new Vector4(0.40f, 0.45f, 0.55f, 0.85f));
dl.AddRectFilled(gearPos, gearBR, gearBg, 2f);
dl.AddRect(gearPos, gearBR, gearBorder, 2f, ImDrawFlags.None, 1f);
Vector2 gearTs = ImGui.CalcTextSize("*");
Vector2 gearTextPos = new(gearPos.X + (btn - gearTs.X) * 0.5f, gearPos.Y + (btn - gearTs.Y) * 0.5f);
dl.AddText(gearTextPos, 0xFFFFFFFFu, "*");
// Track L/R click transitions via raw IO state (IsMouseClicked is filtered
// by hovered-window logic, which fails when the chat has NoInputs or sits
// on a detached viewport). We compare current to previous frame ourselves.
bool curLDown = io.MouseDown[0];
bool curRDown = io.MouseDown[1];
bool lClick = curLDown && !_prevLDown;
bool rClick = curRDown && !_prevRDown;
_prevLDown = curLDown;
_prevRDown = curRDown;
bool inChatRect = io.MousePos.X >= winPos.X && io.MousePos.X < winPos.X + winSize.X
&& io.MousePos.Y >= winPos.Y && io.MousePos.Y < winPos.Y + winSize.Y;
bool wantOpenSettings = (gearHovered && lClick) || (inChatRect && rClick);
if (wantOpenSettings)
ImGui.OpenPopup("##rchat_settings");
RenderSettingsPopup();
// Input row is always rendered at the bottom so the scrollback has a
// stable layout and never gets covered when typing.
const float InputRowH = 24f;
float reservedBottom = InputRowH + 4f;
// Scrollback child below the gear. Width reserves room for the gear
// button on the right; height reserves room for the input row below.
ImGui.SetCursorScreenPos(new Vector2(winPos.X + 4f, winPos.Y + 4f));
Vector2 childSize = new Vector2(winSize.X - 8f - btn - 6f, winSize.Y - 8f - reservedBottom);
ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u);
if (ImGui.BeginChild("##rchat_scroll", childSize,
ImGuiChildFlags.None,
ImGuiWindowFlags.NoBackground))
{
// Snapshot under the lock — the producer is on a different thread.
ChatLine[] snap;
lock (_lock) { snap = _lines.ToArray(); }
for (int i = 0; i < snap.Length; i++)
{
var line = snap[i];
var col4 = ColorForType(line.ChatType);
if (snapShowTs)
{
string ts = line.At.ToString("HH:mm:ss ");
ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.55f, 0.62f, 0.70f, 1f));
ImGui.TextUnformatted(ts);
ImGui.PopStyleColor();
ImGui.SameLine(0, 0);
}
ImGui.PushStyleColor(ImGuiCol.Text, col4);
ImGui.TextWrapped(line.Text);
ImGui.PopStyleColor();
}
if (_wantScrollToBottom)
{
ImGui.SetScrollHereY(1.0f);
_wantScrollToBottom = false;
}
}
ImGui.EndChild();
ImGui.PopStyleColor();
// ── Input row (always visible) ──────────────────────────────────
{
float inputY = winPos.Y + winSize.Y - InputRowH - 2f;
ImGui.SetCursorScreenPos(new Vector2(winPos.X + 4f, inputY));
ImGui.SetNextItemWidth(winSize.X - 8f);
if (_focusInputNextFrame)
{
ImGui.SetKeyboardFocusHere();
_focusInputNextFrame = false;
}
// Use the simple 3-arg overload (no flags) so ImGui.NET's internal
// resize callback handles ref-string growth correctly. Enter detection
// is done manually via IsKeyPressed while the input is focused — this
// avoids both the "callback != NULL" assertion and the buffer-corruption
// that comes from supplying a custom user-callback.
//
// FrameBg is tinted to match the chat body so the input looks like
// part of the same panel at whatever opacity the user picked.
Vector4 frameCol = new Vector4(0.05f, 0.07f, 0.10f, op);
Vector4 frameHovered = new Vector4(0.08f, 0.11f, 0.15f, op);
Vector4 frameActive = new Vector4(0.10f, 0.14f, 0.18f, op);
ImGui.PushStyleColor(ImGuiCol.FrameBg, frameCol);
ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, frameHovered);
ImGui.PushStyleColor(ImGuiCol.FrameBgActive, frameActive);
ImGui.InputText("##rchat_input", ref _inputBuffer, 256u);
ImGui.PopStyleColor(3);
bool isFocused = ImGui.IsItemFocused();
bool enterPressed = ImGui.IsKeyPressed(ImGuiKey.Enter, false)
|| ImGui.IsKeyPressed(ImGuiKey.KeypadEnter, false);
// Eat the same Enter that activated the input, so we don't immediately
// submit an empty message on first focus.
if (_swallowFirstEnter)
{
_swallowFirstEnter = false;
enterPressed = false;
}
if (isFocused && enterPressed)
{
string toSend = _inputBuffer.Trim();
if (!string.IsNullOrEmpty(toSend))
{
if (OnSubmit != null)
OnSubmit(toSend);
else if (_host.HasInvokeChatParser)
_host.InvokeChatParser(toSend);
}
_inputBuffer = string.Empty;
// Defocus our window so WASD/key input flows back to the game.
ImGui.SetWindowFocus(null);
}
// Esc clears the buffer.
if (isFocused && ImGui.IsKeyPressed(ImGuiKey.Escape, false))
_inputBuffer = string.Empty;
}
ImGui.End();
if (snapShowTs != _settings.ChatShowTimestamps
|| snapMax != _settings.ChatMaxLines
|| MathF.Abs(snapOp - _settings.ChatOpacity) > 0.001f)
{
OnSettingChanged?.Invoke();
}
}
private void RenderSettingsPopup()
{
if (!ImGui.BeginPopup("##rchat_settings")) return;
ImGui.Text("Chat Settings");
ImGui.Separator();
ImGui.SetNextItemWidth(140);
ImGui.SliderFloat("Opacity", ref _settings.ChatOpacity, 0.15f, 1f, "%.2f");
ImGui.SetNextItemWidth(140);
ImGui.SliderInt("Max Lines", ref _settings.ChatMaxLines, 50, 5000);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Scrollback capacity. Older lines are dropped when this limit is hit.");
ImGui.Checkbox("Timestamps", ref _settings.ChatShowTimestamps);
ImGui.Checkbox("Click-Through", ref _settings.ChatClickThrough);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Mouse passes through to the game. The gear button stays clickable.\nTurn off again from the gear or Advanced Settings.");
if (ImGui.Button("Clear##rchat_clear"))
{
lock (_lock) _lines.Clear();
}
ImGui.SameLine();
if (ImGui.Button("Copy Recent##rchat_copy"))
{
const int lastN = 100;
ChatLine[] tail;
lock (_lock)
{
int start = Math.Max(0, _lines.Count - lastN);
tail = _lines.GetRange(start, _lines.Count - start).ToArray();
}
var sb = new System.Text.StringBuilder();
foreach (var l in tail) sb.AppendLine(l.Text);
ImGui.SetClipboardText(sb.ToString());
}
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Copy the last 100 lines to the clipboard.");
ImGui.EndPopup();
}
/// <summary>Maps an AC eChatTypes value to a display colour.
/// Values come from gmMainChatUI's incoming text dispatch — see
/// Chorizite enum.cs eChatTypes for the canonical list.</summary>
private static Vector4 ColorForType(int chatType) => chatType switch
{
// 0x02 Speech, 0x03 SpeechDirect (you-target), 0x04 SpeechDirectSend (you sending)
2 => new Vector4(0.95f, 0.95f, 0.95f, 1f), // Speech — white
3 => new Vector4(1.00f, 0.55f, 0.85f, 1f), // SpeechDirect (tells to you) — pink
4 => new Vector4(1.00f, 0.55f, 0.85f, 1f), // tells you sent — pink
// 0x05 SystemEvent — soft white-blue
5 => new Vector4(0.85f, 0.90f, 1.00f, 1f),
// 0x06 Combat (general), 0x15 CombatEnemy, 0x16 CombatSelf
6 => new Vector4(1.00f, 0.80f, 0.50f, 1f), // combat — amber
0x15 => new Vector4(1.00f, 0.55f, 0.45f, 1f), // enemy hits you — red-orange
0x16 => new Vector4(0.55f, 1.00f, 0.55f, 1f), // your hits — green
// 0x07 Magic (general), 0x11 MagicCasting
7 => new Vector4(0.55f, 0.80f, 1.00f, 1f), // magic — light blue
0x11 => new Vector4(0.55f, 0.80f, 1.00f, 1f),
// Channels
0x08 => new Vector4(0.70f, 0.95f, 0.90f, 1f), // Channel — teal
0x09 => new Vector4(0.70f, 0.95f, 0.90f, 1f),
0x0A => new Vector4(0.85f, 0.85f, 0.55f, 1f), // SocialChannel — pale yellow
0x0B => new Vector4(0.85f, 0.85f, 0.55f, 1f),
// 0x0C Emote
0x0C => new Vector4(0.75f, 1.00f, 0.75f, 1f),
// 0x0D Advancement (level up etc.)
0x0D => new Vector4(1.00f, 0.95f, 0.30f, 1f),
// 0x0E Abuse, 0x0F Help
0x0E => new Vector4(1.00f, 0.40f, 0.40f, 1f),
0x0F => new Vector4(0.55f, 1.00f, 1.00f, 1f),
// 0x10 Appraisal — soft cyan
0x10 => new Vector4(0.65f, 0.90f, 1.00f, 1f),
// 0x12 Allegiance, 0x13 Fellowship
0x12 => new Vector4(1.00f, 0.55f, 1.00f, 1f), // allegiance — magenta
0x13 => new Vector4(0.55f, 1.00f, 0.85f, 1f), // fellowship — mint
// 0x14 World broadcast
0x14 => new Vector4(1.00f, 0.45f, 0.65f, 1f),
// 0x17 Recall
0x17 => new Vector4(0.85f, 0.70f, 1.00f, 1f),
// 0x18 Craft, 0x19 Salvaging
0x18 => new Vector4(0.95f, 0.80f, 0.50f, 1f),
0x19 => new Vector4(0.85f, 0.95f, 0.55f, 1f),
// 0x1A Transient (mouseover etc.)
0x1A => new Vector4(0.70f, 0.75f, 0.80f, 1f),
// 0x1B General, 0x1C Trade, 0x1D LFG, 0x1E Roleplay
0x1B => new Vector4(0.85f, 0.95f, 1.00f, 1f),
0x1C => new Vector4(0.65f, 1.00f, 0.65f, 1f),
0x1D => new Vector4(1.00f, 0.85f, 0.55f, 1f),
0x1E => new Vector4(1.00f, 0.75f, 0.95f, 1f),
// 0x1F AdminTell — bright orange so it pops
0x1F => new Vector4(1.00f, 0.55f, 0.20f, 1f),
// 0x20 Olthoi, 0x21 Society
0x20 => new Vector4(0.85f, 0.45f, 0.25f, 1f),
0x21 => new Vector4(0.85f, 0.95f, 1.00f, 1f),
// Default / AllChannels / unknown
_ => new Vector4(0.92f, 0.92f, 0.92f, 1f),
};
private static uint SetAlpha(uint col, float alpha)
{
uint a = (uint)(Math.Clamp(alpha, 0f, 1f) * 255f);
return (col & 0x00FFFFFF) | (a << 24);
}
}

File diff suppressed because it is too large Load diff

View file

@ -70,9 +70,24 @@ public sealed class InventoryManager
// 500 ms after an action, so external "dirty" signals aren't needed.
public void MarkDirty() { }
// /ub autostack and /ub autocram: run that pass for up to a minute even with
// the macro stopped or the setting off; ends as soon as there's nothing to do.
private DateTime _manualCramUntil = DateTime.MinValue;
private DateTime _manualStackUntil = DateTime.MinValue;
public void RunManual(bool cram, bool stack)
{
if (cram) _manualCramUntil = DateTime.Now.AddSeconds(60);
if (stack) _manualStackUntil = DateTime.Now.AddSeconds(60);
_nextInventoryActionTime = DateTime.MinValue;
}
private bool ManualCram => DateTime.Now < _manualCramUntil;
private bool ManualStack => DateTime.Now < _manualStackUntil;
public void OnHeartbeat(int busyCount)
{
if (!_settings.IsMacroRunning) return;
if (!_settings.IsMacroRunning && !ManualCram && !ManualStack) return;
if (busyCount != 0) return; // don't move items while the client is busy (casting, crafting, etc.)
// Age-prune the per-entry backoff/pending maps (replaces the old wholesale
@ -108,7 +123,8 @@ public sealed class InventoryManager
return;
}
// Nothing to do — back off re-scan for a bit.
// Nothing to do — back off re-scan for a bit, and end a manual run.
_manualCramUntil = _manualStackUntil = DateTime.MinValue;
_nextInventoryActionTime = DateTime.Now.AddMilliseconds(2000);
}
@ -116,7 +132,7 @@ public sealed class InventoryManager
private bool ProcessAutoCram(List<WorldObject> inv, int playerId)
{
if (!_settings.EnableAutocram) return false;
if (!_settings.EnableAutocram && !ManualCram) return false;
int crammable = 0;
foreach (var item in inv)
@ -227,7 +243,7 @@ public sealed class InventoryManager
private bool ProcessAutoStack(List<WorldObject> inv, int playerId)
{
if (!_settings.EnableAutostack) return false;
if (!_settings.EnableAutostack && !ManualStack) return false;
// Build candidate list — items belonging to the player (directly or in a sub-pack).
var playerItems = new List<WorldObject>();

View file

@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using RynthCore.Loot.Editing;
namespace RynthCore.Plugin.RynthAi.Loot;
/// <summary>
/// RynthAi's side of the engine's ImGui Loot Editor (RynthCore
/// docs/IMGUI_LOOT_EDITOR.md): one LootEditSession, the profile paths, and the
/// hot reload after a save. The engine calls the exports (PluginExports, "Loot
/// editor bridge") from its UI data hub on the plugin pump thread, the same
/// thread as the plugin tick; the lock only guards against any other caller.
/// Nothing here touches AC.
/// </summary>
internal sealed class LootEditorBridge
{
public const string LootFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
private readonly object _sync = new();
private readonly LootEditSession _session = new();
private readonly Func<string> _inUsePath;
private readonly Action<string> _onSaved;
private readonly string[] _vendorFolders;
// Follow RynthAi's loot profile while the editor shows it and has no edits.
private bool _followInUse = true;
private long _nextDiskCheck;
private string? _vocabJson;
public LootEditorBridge(Func<string> inUsePath, Action<string> onSaved, params string[] vendorFolders)
{
_inUsePath = inUsePath;
_onSaved = onSaved;
_vendorFolders = vendorFolders;
}
private string InUse => (_inUsePath() ?? string.Empty).Trim().Trim('"');
/// <summary>
/// Cheap: the session's revision. Every ~2 s it also looks at the file on
/// disk and follows a change of RynthAi's loot profile.
/// </summary>
public int Revision()
{
lock (_sync)
{
long now = Stopwatch.GetTimestamp();
if (now >= _nextDiskCheck)
{
_nextDiskCheck = now + Stopwatch.Frequency * 2;
_session.CheckDisk();
string inUse = InUse;
if (_followInUse && !_session.IsDirty && inUse.Length > 0 && !LootEditSession.SamePath(inUse, _session.Path))
_session.Open(inUse);
}
return unchecked((int)_session.Revision);
}
}
public string StateJson()
{
lock (_sync)
{
string inUse = InUse;
if (!_session.IsOpen && _followInUse && inUse.Length > 0) _session.Open(inUse);
LootEditState state = _session.BuildState(inUse, ListFiles());
return JsonSerializer.Serialize(state, LootEditJsonContext.Default.LootEditState);
}
}
public string RuleJson(int index)
{
lock (_sync)
{
LootEditRule? rule = _session.BuildRule(index);
return rule == null ? "{\"Index\":-1}" : JsonSerializer.Serialize(rule, LootEditJsonContext.Default.LootEditRule);
}
}
public string VocabJson() =>
_vocabJson ??= JsonSerializer.Serialize(LootRuleText.BuildVocab(), LootEditJsonContext.Default.LootEditVocab);
public void Command(string json)
{
LootEditCommand? cmd = JsonSerializer.Deserialize(json, LootEditJsonContext.Default.LootEditCommand);
if (cmd == null) return;
string? saved = null;
lock (_sync)
{
if (cmd.Op == "open")
{
string inUse = InUse;
string path = cmd.Path.Trim().Trim('"');
if (path.Length == 0) path = inUse;
// Showing the panel again on the profile already open keeps its edits.
if (_session.IsOpen && !cmd.Force && LootEditSession.SamePath(path, _session.Path))
return;
cmd.Path = path;
if (path.Length == 0)
{
_followInUse = true;
_session.Apply(cmd); // "No loot profile selected."
return;
}
if (_session.Apply(cmd) == LootEditSession.Outcome.Opened)
_followInUse = LootEditSession.SamePath(path, inUse);
return;
}
if (_session.Apply(cmd) == LootEditSession.Outcome.Saved)
saved = _session.Path;
}
if (saved != null) _onSaved(saved);
}
/// <summary>LootProfiles (*.utl, *.json), then AutoVendor profiles, then the open file if it is elsewhere.</summary>
private List<LootEditFile> ListFiles()
{
var files = new List<LootEditFile>();
try
{
if (Directory.Exists(LootFolder))
{
var names = new List<string>();
names.AddRange(Directory.GetFiles(LootFolder, "*.utl"));
names.AddRange(Directory.GetFiles(LootFolder, "*.json"));
names.Sort(StringComparer.OrdinalIgnoreCase);
foreach (string f in names) files.Add(new LootEditFile { Path = f, Display = Path.GetFileName(f) });
}
foreach (string folder in _vendorFolders)
{
if (!Directory.Exists(folder)) continue;
var names = new List<string>(Directory.GetFiles(folder, "*.utl", new EnumerationOptions { RecurseSubdirectories = true, MaxRecursionDepth = 2 }));
names.Sort(StringComparer.OrdinalIgnoreCase);
foreach (string f in names)
files.Add(new LootEditFile { Path = f, Display = "AutoVendor: " + Path.GetRelativePath(folder, f) });
}
}
catch { }
if (_session.IsOpen && !files.Exists(f => LootEditSession.SamePath(f.Path, _session.Path)))
files.Add(new LootEditFile { Path = _session.Path, Display = Path.GetFileName(_session.Path) });
return files;
}
}

View file

@ -14,7 +14,7 @@ public static class LootEvaluator
public static bool Evaluate(LootCondition condition, WorldObject item, CharacterSkills? skills)
=> condition switch
{
ObjectClassCondition c => item.ObjectClass == (AcObjectClass)(int)c.ObjectClass,
ObjectClassCondition c => ScrollLearner.ClassMatches(item, (int)c.ObjectClass),
LongValKeyGECondition c => item.Values(c.Key, 0) >= c.Value,
LongValKeyLECondition c => item.Values(c.Key, 0) <= c.Value,
LongValKeyECondition c => item.Values(c.Key, 0) == c.Value,
@ -55,8 +55,12 @@ public static class LootEvaluator
private static bool EvalString(WorldObject item, StringValueCondition c)
{
string value = item.Values((StringValueKey)c.Key, string.Empty);
return Regex.IsMatch(value, c.Pattern,
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
// Through the shared cache, like the VTank path: an invalid pattern in a JSON
// profile threw out of the tick on every pass while a corpse was open (combat
// and nav skipped until the corpse timed out). A bad pattern now never matches.
// An empty pattern matched everything before; the cache treats it as no match.
if (string.IsNullOrEmpty(c.Pattern)) return true;
return Meta.RegexCache.IsMatch(value, c.Pattern, RegexOptions.IgnoreCase);
}
private static int EvalTotalRatings(WorldObject item)

View file

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.Loot;
/// <summary>
/// Keep # (KeepUpTo) arithmetic, split out of <c>RynthAiPlugin.UnderKeepCap</c> so it can be
/// tested offline. The plugin passes in the live pack snapshot and its per-corpse "approved
/// but not in the pack yet" table; nothing here touches the host.
/// </summary>
internal static class LootKeepCap
{
/// <summary>How much one item counts toward a cap: its stack size, never less than 1.</summary>
internal static int StackOf(WorldObject item) => Math.Max(1, item.Values(LongValueKey.StackCount, 1));
/// <summary>
/// How many of what a Keep # rule matches the player already has: whole stacks of every
/// named pack item the rule matches (a matcher that throws counts as no match), plus items
/// approved on this corpse that are not in the pack yet. An approved item that is already in
/// the pack snapshot, or that no longer exists (a looted stack merged into a pack stack and
/// was deleted), is not counted twice.
/// </summary>
internal static int CountHave(
IEnumerable<WorldObject>? inventory,
Func<WorldObject, bool> matches,
IReadOnlyDictionary<int, int> pending,
Func<int, bool> stillExists)
{
int have = 0;
var liveIds = new HashSet<int>();
if (inventory != null)
{
foreach (var inv in inventory)
{
liveIds.Add(inv.Id);
if (string.IsNullOrEmpty(inv.Name)) continue;
bool m;
try { m = matches(inv); } catch { m = false; }
if (m) have += StackOf(inv);
}
}
foreach (var kv in pending)
if (!liveIds.Contains(kv.Key) && stillExists(kv.Key)) have += kv.Value;
return have;
}
/// <summary>True while the player holds fewer than <paramref name="cap"/>; a cap of 0 or less never loots.</summary>
internal static bool UnderCap(int have, int cap) => have < cap;
}

View file

@ -0,0 +1,65 @@
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.Loot;
/// <summary>What <see cref="LootPickup.Send"/> did.</summary>
internal enum LootPickupResult
{
/// <summary>MoveItemExternal into one of our packs was sent.</summary>
Moved,
/// <summary>UseObject was sent (no move call on this engine, and the item can't be worn).</summary>
Used,
/// <summary>No pack of ours has a free slot.</summary>
NoRoom,
/// <summary>No move call, and a use could put the item on the character, so nothing was sent.</summary>
Refused,
/// <summary>The engine turned the call down.</summary>
Failed,
}
/// <summary>
/// Picks a corpse item up into a pack. Looting used to send UseObject (a double-click). On
/// a wearable item outside the pack the client turns a use into get-and-wield when the slot
/// is free, so jewellery looted for salvage went onto the character whenever its ring,
/// bracelet or necklace slot was empty (2026-10-02 tester report). A move into a pack never
/// wields anything, so it is the only call used when the engine has it.
/// </summary>
internal static class LootPickup
{
public static LootPickupResult Send(RynthCoreHost host, WorldObjectCache? cache, uint itemId, uint playerId,
out uint destination)
{
destination = 0;
if (itemId == 0) return LootPickupResult.Failed;
if (host.HasMoveItemExternal)
{
if (playerId == 0) return LootPickupResult.Failed;
int pid = unchecked((int)playerId);
int dest = cache == null
? pid
: WorldObjectCache.FindLootDestination(cache.GetDirectInventory(forceRefresh: false), pid, host);
if (dest == 0) return LootPickupResult.NoRoom;
destination = unchecked((uint)dest);
return host.MoveItemExternal(itemId, destination, 0) ? LootPickupResult.Moved : LootPickupResult.Failed;
}
if (CouldBeWorn(cache?[unchecked((int)itemId)]))
return LootPickupResult.Refused;
return host.HasUseObject && host.UseFor(itemId, "Loot", "pick up from the open corpse") ? LootPickupResult.Used : LootPickupResult.Failed;
}
/// <summary>
/// True when a use on <paramref name="wo"/> could wield it: it has equip slots, or it is
/// a kind of thing that is worn or wielded. Unknown items count as wearable.
/// </summary>
public static bool CouldBeWorn(WorldObject? wo)
{
if (wo == null) return true;
if (wo.Values(LongValueKey.Locations, 0) != 0) return true;
return wo.ObjectClass is AcObjectClass.Unknown or AcObjectClass.Jewelry or AcObjectClass.Armor
or AcObjectClass.Clothing or AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon
or AcObjectClass.WandStaffOrb;
}
}

View file

@ -1,41 +1,96 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.Loot;
/// <summary>
/// Drives the salvage state machine for loot-rule items marked Salvage.
/// Items are enqueued by CorpseOpenController after pickup confirmation.
///
/// Flow per item:
/// Idle → call OpenSalvagePanel(ustId), wait OpenDelay
/// → call AddNewItem(itemId), wait AddDelay
/// → call Salvage(), wait SalvageDelay
/// → wait ResultDelay → Idle (next item or CombineSalvage)
/// Items come from looting: <see cref="NoteLootedForSalvage"/> when the pickup is sent and
/// <see cref="EnqueueItem"/> when it is confirmed. Every such item is TRACKED until it has
/// been salvaged or has left the pack, and a sweep every couple of seconds queues tracked
/// items that are in the pack. Before 2026-10-02 the queue was the only record: a pickup
/// whose confirm was lost (busy reset, corpse closed), an item salvaged before it reached
/// the pack, a missing UST, or three failed tries dropped the item for good, and it sat in
/// the pack.
///
/// First-open delays (400ms/600ms) let the panel animate open and the
/// gmSalvageUI singleton hook fire before we make thiscall instance calls.
/// Fast delays (50ms) apply once the panel has been opened at least once.
/// Flow per batch (up to <see cref="MaxBatchItems"/> items in one panel cycle):
/// Idle → UseObject(UST), wait OpenDelay
/// → SalvagePanelAddItem each item (AddDelayFast apart), plus matching under-full bags
/// → SalvagePanelExecute, wait SalvageDelay
/// → poll until the items leave the pack (or ResultMaxWaitMs) → one summary log line
/// Items that are worn, retained, on the Items list or the UST itself are skipped with the
/// reason in the log; RynthAi never takes off anything the character is wearing.
///
/// First-open delays (400ms/600ms) let the panel animate open and the gmSalvageUI singleton
/// hook fire before we make thiscall instance calls. Fast delays (50ms) apply once the panel
/// has been opened at least once.
/// </summary>
public sealed class SalvageManager
{
private enum Phase { Idle, OpeningPanel, AddingItem, Salvaging, WaitingForResult, CombiningSalvage }
private enum Phase { Idle, OpeningPanel, AddingItems, ReadyToExecute, Salvaging, WaitingForResult, CombiningSalvage }
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private readonly WorldObjectCache? _cache;
// ── Single-item salvage: queue, tracking, batch ──────────────────────────
private readonly Queue<uint> _queue = new();
private readonly HashSet<uint> _queued = new();
private Phase _phase = Phase.Idle;
private long _phaseReadyAt;
private uint _currentItemId;
private uint _currentUstId;
private bool _panelEverOpened;
private bool _firstResultCycle = true;
private bool _pendingCombineScan;
/// <summary>Most items added to the panel for one Salvage press.</summary>
internal const int MaxBatchItems = 20;
/// <summary>A batch starts this long after the last item was queued (or when a full batch is
/// waiting), so one corpse's salvage goes in one panel cycle instead of one cycle per item.</summary>
internal const long GatherMs = 1_000;
private const long SweepIntervalMs = 2_000;
/// <summary>A tracked item that never shows up in the pack is forgotten after this.</summary>
internal const long ArrivalGraceMs = 60_000;
/// <summary>After <see cref="MaxItemRetries"/> failed tries in a row an item rests this long...</summary>
internal const long GiveUpCooldownMs = 60_000;
/// <summary>...and after this many rests it is left in the pack for good (logged).</summary>
internal const int MaxGiveUpRounds = 3;
private const long NoUstRetryMs = 10_000;
private sealed class TrackedItem
{
public string Name = string.Empty;
public long NotedAt;
public bool SeenInPack;
public long CooldownUntil;
public int GiveUps;
}
private readonly Dictionary<uint, TrackedItem> _tracked = new();
private long _lastEnqueueAt;
private long _lastSweepAt;
private long _noUstWarnedAt = long.MinValue / 2;
// The batch in flight: what we meant to add, what the panel took, and per-batch notes.
private readonly List<uint> _batch = new();
private readonly List<uint> _batchAdded = new();
private readonly Dictionary<uint, string> _batchNames = new();
private int _batchAddIdx;
private int _batchBagsAdded;
private int _batchNumber;
private int _batchAddFailures;
private readonly SkipNotes _batchSkips = new();
// Session totals for /ra salvstate.
private int _itemsSalvagedThisSession;
private int _itemsSkippedThisSession;
private int _batchesThisSession;
// Combine-salvage state — process one material group per cycle by opening
// the salvage panel, adding all under-full bags of that material, and hitting
// Salvage so the server merges them server-side. Far more reliable than the
@ -68,16 +123,15 @@ public sealed class SalvageManager
private int _bagsMergedThisSession;
// Per-item retry counter so a failed salvage gets re-queued a few times
// before we give up. AC sometimes drops a Salvage execute when the bot is
// before it rests. AC sometimes drops a Salvage execute when the bot is
// busy with other actions; the item stays in the pack and we want to try
// again when the queue gets back to idle.
private readonly Dictionary<uint, int> _itemRetryCount = new();
private const int MaxItemRetries = 3;
// Backoff after a refused panel step. Without it a failed UseObject/AddItem
// re-queues the item and TickIdle dequeues it again on the very next tick,
// so one busy hiccup burns all three attempts inside ~50ms and the item is
// dropped. A second is long enough for the action queue to clear.
// re-queues the items and TickIdle dequeues them again on the very next tick,
// so one busy hiccup burns all three attempts inside ~50ms.
private long _idleRetryReadyAt;
private const long RetryBackoffMs = 1000;
@ -100,7 +154,9 @@ public sealed class SalvageManager
private long _lastCombineSweepAt;
private const long CombineSweepIntervalMs = 30_000;
private static long NowMs => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
/// <summary>Milliseconds clock. Tests replace it to step time; the game uses wall time.</summary>
internal Func<long> Clock { get; set; } = () => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
private long NowMs => Clock();
/// <summary>
/// Set by the plugin to point at the currently-loaded loot profile's
@ -120,6 +176,17 @@ public sealed class SalvageManager
/// <summary>Returns true while a salvage operation is in flight.</summary>
public bool IsBusy => _phase != Phase.Idle || _queue.Count > 0;
/// <summary>
/// Looting sent the pickup of an item whose rule says Salvage. Tracks it without queueing:
/// the sweep queues it once it is in the pack, even if the pickup confirm never comes.
/// </summary>
public void NoteLootedForSalvage(uint itemId, string? name = null)
{
if (itemId == 0) return;
if (IsSalvageBag(name ?? _cache?[unchecked((int)itemId)]?.Name)) return;
Track(itemId, name);
}
/// <summary>Enqueue an item to be salvaged. Called by CorpseOpenController after pickup.</summary>
public void EnqueueItem(uint itemId)
{
@ -140,10 +207,42 @@ public sealed class SalvageManager
return;
}
Track(itemId, name);
QueueItem(itemId);
}
private void Track(uint itemId, string? name)
{
long now = NowMs;
if (!_tracked.TryGetValue(itemId, out TrackedItem? t))
{
t = new TrackedItem { NotedAt = now };
_tracked[itemId] = t;
}
if (!string.IsNullOrWhiteSpace(name)) t.Name = name!;
}
private void Untrack(uint itemId)
{
_tracked.Remove(itemId);
_itemRetryCount.Remove(itemId);
}
private void QueueItem(uint itemId)
{
if (!_queued.Add(itemId)) return;
_queue.Enqueue(itemId);
_lastEnqueueAt = NowMs;
_pendingCombineScan = false; // reset; will be set again when queue drains
}
private uint DequeueItem()
{
uint id = _queue.Dequeue();
_queued.Remove(id);
return id;
}
/// <summary>Called every game tick from RynthAiPlugin.OnTick.</summary>
public void OnTick(int busyCount)
{
@ -160,10 +259,20 @@ public sealed class SalvageManager
case Phase.OpeningPanel:
if (now >= _phaseReadyAt)
BeginAddingItem(now);
{
_batchAddIdx = 0;
_phase = Phase.AddingItems;
_phaseReadyAt = now;
TickAddingItems(now);
}
break;
case Phase.AddingItem:
case Phase.AddingItems:
if (now >= _phaseReadyAt)
TickAddingItems(now);
break;
case Phase.ReadyToExecute:
if (now >= _phaseReadyAt)
BeginSalvaging(now);
break;
@ -175,16 +284,12 @@ public sealed class SalvageManager
case Phase.WaitingForResult:
if (now < _phaseReadyAt) break;
// Poll: if the item is still in inventory and we're under the
// deadline, wait for the next tick. Server delete events for
// salvage-consumed items can lag the result delay by 500ms+.
if (_currentItemId != 0
&& now < _waitingResultDeadline
&& IsItemInDirectInventory(_currentItemId))
{
// Poll: while any added item is still in the pack and we're under the
// deadline, wait. Server delete events for salvage-consumed items can
// lag the result delay by 500ms+.
if (now < _waitingResultDeadline && AnyStillInPack(_batchAdded))
break;
}
OnResultReady(now);
OnBatchResult(now);
break;
case Phase.CombiningSalvage:
@ -197,6 +302,8 @@ public sealed class SalvageManager
private void TickIdle(long now, int busyCount)
{
SweepTracked(now);
if (_queue.Count == 0)
{
if (_pendingCombineScan && _settings.EnableCombineSalvage)
@ -229,43 +336,41 @@ public sealed class SalvageManager
if (now < _idleRetryReadyAt)
return;
uint itemId = _queue.Dequeue();
if (itemId == 0)
// Let a corpse's worth of salvage gather so it goes in one panel cycle.
if (_queue.Count < MaxBatchItems && now - _lastEnqueueAt < GatherMs)
return;
// Backstop for the EnqueueItem guard: the item's name may not have been
// cached at enqueue time. Never run the single-item salvage flow on a
// bag — it's already salvage; the combine sweep consolidates it.
string? dqName = _cache?[unchecked((int)itemId)]?.Name;
if (IsSalvageBag(dqName))
{
Log($"[Salvage] Dequeued a salvage bag 0x{itemId:X8} ({dqName}) — skipping solo salvage; combine sweep will consolidate it.");
if (_settings.EnableCombineSalvage) _pendingCombineScan = true;
if (!BuildBatch(now))
return;
}
uint ustId = FindUst();
if (ustId == 0)
{
_host.WriteToChat("[RynthAi] Salvage: No UST found in inventory — item skipped. Add a Ust to your pack.", 2);
NoteError("no UST in inventory — item skipped");
Log($"[Salvage] No UST found in inventory — skipping 0x{itemId:X8}.");
// Keep the items (they used to be dropped here for good) and look again later.
if (now - _noUstWarnedAt >= 5 * 60_000)
{
_noUstWarnedAt = now;
_host.WriteToChat("[RynthAi] Salvage: no UST in your pack — salvage is waiting. Add a Ust to your pack.", 2);
}
NoteError("no UST in inventory — salvage waiting");
Log($"[Salvage] No UST found — {_batch.Count} item(s) wait; trying again in {NoUstRetryMs / 1000}s.");
ReturnBatchToQueue();
_idleRetryReadyAt = now + NoUstRetryMs;
return;
}
_currentItemId = itemId;
_currentUstId = ustId;
// UseObject on the UST mimics a double-click — this is the reliable path to
// trigger gmSalvageUI::OpenSalvagePanel (our hook captures the instance there).
// SendNotice_OpenSalvagePanel does not reliably call the hooked function.
if (!_host.UseObject(_currentUstId))
if (!_host.UseFor(_currentUstId, "Salvage", "open the salvage panel (UST)"))
{
Log($"[Salvage] UseObject(UST) failed for 0x{_currentUstId:X8} — re-queuing item.");
Log($"[Salvage] UseObject(UST) failed for 0x{_currentUstId:X8} — {_batch.Count} item(s) back in the queue.");
NoteError($"UseObject(UST) failed for 0x{_currentUstId:X8}");
_currentItemId = 0;
_currentUstId = 0;
RequeueOrDrop(itemId, "UseObject(UST) failed");
foreach (uint id in _batch) RequeueOrDrop(id, "UseObject(UST) failed");
ClearBatch();
_idleRetryReadyAt = now + RetryBackoffMs;
return;
}
@ -275,38 +380,191 @@ public sealed class SalvageManager
_phase = Phase.OpeningPanel;
}
private void BeginAddingItem(long now)
/// <summary>
/// Takes up to <see cref="MaxBatchItems"/> items off the queue that can be salvaged now.
/// Items not in the pack yet stay tracked (the sweep queues them on arrival); items that
/// can't be salvaged are skipped with a reason. False when nothing is left to salvage.
/// </summary>
private bool BuildBatch(long now)
{
if (!_host.SalvagePanelAddItem(_currentItemId))
ClearBatch();
if (_cache == null)
{
Log($"[Salvage] SalvagePanelAddItem failed for 0x{_currentItemId:X8} (panel instance not ready — re-queuing).");
NoteError($"SalvagePanelAddItem failed for 0x{_currentItemId:X8} (panel not ready)");
// Re-queue the item so we retry on the next idle cycle. Reset panel-ever-opened
// so the longer first-open delays are applied on retry.
uint failedItemId = _currentItemId;
_currentItemId = 0;
_currentUstId = 0;
_panelEverOpened = false;
_phase = Phase.Idle;
RequeueOrDrop(failedItemId, "SalvagePanelAddItem failed");
_idleRetryReadyAt = now + RetryBackoffMs;
while (_queue.Count > 0) DequeueItem();
return false;
}
var inPack = new Dictionary<uint, WorldObject>();
foreach (WorldObject wo in _cache.GetDirectInventory(forceRefresh: true))
inPack[unchecked((uint)wo.Id)] = wo;
int waiting = 0;
while (_queue.Count > 0 && _batch.Count < MaxBatchItems)
{
uint id = DequeueItem();
_tracked.TryGetValue(id, out TrackedItem? t);
if (!inPack.TryGetValue(id, out WorldObject? wo))
{
string name = t?.Name ?? _cache[unchecked((int)id)]?.Name ?? string.Empty;
if (IsWornByPlayer(_cache[unchecked((int)id)]))
{
SkipForGood(id, name, SkipWorn);
continue;
}
if (t != null && !t.SeenInPack && now - t.NotedAt < ArrivalGraceMs)
{
waiting++; // still on its way; the sweep queues it when it lands
continue;
}
// Already gone (salvaged, sold, dropped) or never arrived.
Untrack(id);
continue;
}
if (t != null) t.SeenInPack = true;
string itemName = wo.Name;
string? reason = SkipReasonFor(id, wo);
if (reason != null)
{
SkipForGood(id, itemName, reason);
continue;
}
_batch.Add(id);
_batchNames[id] = itemName;
}
if (_batch.Count == 0)
{
// Nothing to send: say why once (this runs only when items were queued, and
// skipped/waiting items leave the queue, so it can't repeat every tick).
if (_batchSkips.Count > 0 || waiting > 0)
Log($"[Salvage] Nothing to salvage this round: {_batchSkips.Describe()}"
+ (waiting > 0 ? $"{(_batchSkips.Count > 0 ? "; " : "")}{waiting} not in the pack yet (will salvage when they arrive)" : "")
+ ".");
_batchSkips.Clear();
return false;
}
if (waiting > 0)
_batchSkips.Add("not in the pack yet (will salvage when they arrive)", $"{waiting} item(s)", countOnly: true, n: waiting);
return true;
}
// Skip reasons (also the log wording).
internal const string SkipWorn = "worn (RynthAi never takes off what the character is wearing)";
internal const string SkipRetained = "retained";
internal const string SkipItemsList = "on the Items list";
internal const string SkipUst = "it is the UST";
internal const string SkipBag = "already a salvage bag (the combine sweep handles bags)";
internal const string SkipGaveUp = "salvage failed too often";
/// <summary>Why <paramref name="wo"/> (in the pack) must not be salvaged, or null.</summary>
private string? SkipReasonFor(uint id, WorldObject wo)
{
if (IsSalvageBag(wo.Name)) return SkipBag;
if (IsWornByPlayer(wo)) return SkipWorn;
if (wo.ObjectClass == AcObjectClass.Ust || IsUst(wo.Name)
|| (_host.HasGetObjectWcid && _host.TryGetObjectWcid(id, out uint wcid) && wcid == UstWcid))
return SkipUst;
int sid = unchecked((int)id);
if (_settings.ItemRules.Any(r => r.Id == sid)) return SkipItemsList;
// ACE skips a Retained item without a word (Player_Crafting.HandleSalvaging).
if (_host.TryGetObjectBoolProperty(id, StypeBoolRetained, out bool retained) && retained) return SkipRetained;
return null;
}
private const uint StypeBoolRetained = 91;
private bool IsWornByPlayer(WorldObject? wo)
{
if (wo == null) return false;
if (wo.WieldedLocation > 0) return true;
uint pid = _host.GetPlayerId();
if (pid != 0 && wo.Wielder == unchecked((int)pid)) return true;
return WorldObjectCache.IsWieldedByPlayer(_host, wo);
}
private void SkipForGood(uint id, string name, string reason)
{
_batchSkips.Add(reason, string.IsNullOrWhiteSpace(name) ? $"0x{id:X8}" : name);
_itemsSkippedThisSession++;
Untrack(id);
if (reason == SkipWorn)
_host.WriteToChat($"[RynthAi] Salvage: left {(string.IsNullOrWhiteSpace(name) ? "an item" : $"'{name}'")} alone — the character is wearing it. Take it off by hand if it should be salvaged.", 2);
}
private void ReturnBatchToQueue()
{
foreach (uint id in _batch) QueueItem(id);
ClearBatch();
}
private void ClearBatch()
{
_batch.Clear();
_batchAdded.Clear();
_batchNames.Clear();
_batchSkips.Clear();
_batchAddIdx = 0;
_batchBagsAdded = 0;
_batchAddFailures = 0;
}
/// <summary>Adds the batch to the open panel one item per step, then matching bags.</summary>
private void TickAddingItems(long now)
{
bool wasFirstOpen = !_panelEverOpened;
if (_batchAddIdx < _batch.Count)
{
uint id = _batch[_batchAddIdx];
if (_host.SalvagePanelAddItem(id))
{
_batchAdded.Add(id);
}
else if (_batchAdded.Count == 0 && _batchAddIdx == 0)
{
// The first add failing means the panel instance isn't ready: put the
// whole batch back and retry on the longer first-open delays.
Log($"[Salvage] SalvagePanelAddItem failed (panel instance not ready) — {_batch.Count} item(s) back in the queue.");
NoteError("SalvagePanelAddItem failed (panel not ready)");
foreach (uint b in _batch) RequeueOrDrop(b, "SalvagePanelAddItem failed");
ClearBatch();
_currentUstId = 0;
_panelEverOpened = false;
_phase = Phase.Idle;
_idleRetryReadyAt = now + RetryBackoffMs;
return;
}
else
{
_batchAddFailures++;
RequeueOrDrop(id, "SalvagePanelAddItem failed");
}
_batchAddIdx++;
_phaseReadyAt = now + _settings.SalvageAddDelayFastMs;
return;
}
// Combine-during-salvage: add ALL under-full bags of the same material
// (and workmanship band, if configured) alongside the new item so the
// server merges everything in one operation.
int extraBags = 0;
if (_settings.CombineBagsDuringSalvage)
extraBags = AddAllMatchingUnderFullBags(_currentItemId);
if (_batchAdded.Count == 0)
{
_phase = Phase.Idle;
ClearBatch();
return;
}
// Combine-during-salvage: add ALL under-full bags of the batch's materials
// (and workmanship bands, if configured) so the server merges everything in
// one operation.
if (_settings.CombineBagsDuringSalvage)
_batchBagsAdded = AddAllMatchingUnderFullBags(_batchAdded);
bool wasFirstOpen = !_panelEverOpened;
_panelEverOpened = true;
// Allow 50 ms per extra bag so AC can register each add before Execute fires.
int addDelay = (wasFirstOpen ? _settings.SalvageAddDelayFirstMs : _settings.SalvageAddDelayFastMs)
+ extraBags * _settings.SalvageAddDelayFastMs;
_phaseReadyAt = now + addDelay;
_phase = Phase.AddingItem;
int settle = (wasFirstOpen ? _settings.SalvageAddDelayFirstMs : _settings.SalvageAddDelayFastMs)
+ _batchBagsAdded * _settings.SalvageAddDelayFastMs;
_phaseReadyAt = now + settle;
_phase = Phase.ReadyToExecute;
}
// STypes (canonical values from Chorizite STypes.cs — verified against
@ -323,54 +581,55 @@ public sealed class SalvageManager
/// <summary>
/// Scans inventory for every under-full salvage bag whose material (and
/// workmanship band, if configured) matches <paramref name="itemId"/>, adds
/// each one to the open salvage panel, and returns how many were added.
/// workmanship band, if configured) matches one of <paramref name="itemIds"/>,
/// adds each one to the open salvage panel, and returns how many were added.
/// Adding them all at once lets the server merge everything in one Salvage
/// operation instead of leaving partial bags for the periodic sweep.
/// </summary>
private int AddAllMatchingUnderFullBags(uint itemId)
private int AddAllMatchingUnderFullBags(IReadOnlyCollection<uint> itemIds)
{
if (_cache == null) return 0;
if (!_host.TryGetObjectIntProperty(itemId, StypeMaterialType, out int itemMat) || itemMat == 0)
return 0;
if (_cache == null || itemIds.Count == 0) return 0;
RynthCore.Loot.SalvageCombineSettings? cfg = CombineConfigProvider?.Invoke();
bool useBands = cfg != null && cfg.Enabled;
// The freshly-looted ITEM carries a true 1-10 ItemWorkmanship(#105) —
// A freshly-looted ITEM carries a true 1-10 ItemWorkmanship(#105) —
// unlike a bag, whose #105 is a cumulative sum. So the item's band is
// read directly here; bag keys come from TryGetBagCombineKey (average).
string itemKey;
if (useBands)
var keys = new HashSet<string>(StringComparer.Ordinal);
foreach (uint itemId in itemIds)
{
if (!_host.TryGetObjectIntProperty(itemId, StypeItemWorkmanship, out int itemWm) || itemWm <= 0)
return 0;
string? itemBand = cfg!.GetBandKey(itemMat, itemWm);
if (itemBand == null) return 0;
itemKey = $"{itemMat}|{itemBand}";
}
else
{
itemKey = itemMat.ToString();
if (!_host.TryGetObjectIntProperty(itemId, StypeMaterialType, out int itemMat) || itemMat == 0)
continue;
if (useBands)
{
if (!_host.TryGetObjectIntProperty(itemId, StypeItemWorkmanship, out int itemWm) || itemWm <= 0)
continue;
string? itemBand = cfg!.GetBandKey(itemMat, itemWm);
if (itemBand == null) continue;
keys.Add($"{itemMat}|{itemBand}");
}
else
{
keys.Add(itemMat.ToString());
}
}
if (keys.Count == 0) return 0;
var batch = new HashSet<uint>(itemIds);
int added = 0;
foreach (WorldObject bag in _cache.GetDirectInventory(forceRefresh: true))
{
uint bagId = unchecked((uint)bag.Id);
if (bagId == itemId) continue;
if (batch.Contains(bagId)) continue;
if (!IsSalvageBag(bag.Name)) continue;
if (!IsBagUnderFull(bagId, bag.Name)) continue;
if (!TryGetBagCombineKey(bagId, bag.Name, cfg, useBands, out string bagKey, out _)) continue;
if (bagKey != itemKey) continue;
if (!keys.Contains(bagKey)) continue;
if (_host.SalvagePanelAddItem(bagId))
{
Log($"[Salvage] Combine-during-salvage: added bag {bag.Name} 0x{bagId:X8} ({added + 1}).");
added++;
}
}
return added;
}
@ -378,10 +637,12 @@ public sealed class SalvageManager
{
if (!_host.SalvagePanelExecute())
{
Log($"[Salvage] SalvagePanelExecute failed for 0x{_currentItemId:X8} — re-queuing.");
RequeueOrDrop(_currentItemId, "execute failed");
_currentItemId = 0;
Log($"[Salvage] SalvagePanelExecute failed — {_batchAdded.Count} item(s) back in the queue.");
NoteError("SalvagePanelExecute failed");
foreach (uint id in _batchAdded) RequeueOrDrop(id, "execute failed");
ClearBatch();
_phase = Phase.Idle;
_idleRetryReadyAt = now + RetryBackoffMs;
return;
}
@ -400,34 +661,49 @@ public sealed class SalvageManager
_phase = Phase.WaitingForResult;
}
private void OnResultReady(long now)
private void OnBatchResult(long now)
{
// If the item we tried to salvage is STILL in the player's actual
// inventory after the result delay, the salvage didn't consume it
// (panel closed mid-execute, bot got busy, AC dropped the request,
// etc.). Re-queue so we try again.
//
// We use GetDirectInventory(forceRefresh: true) — a live walk of the
// player's containers — instead of _cache[id] because salvage-consumed
// items don't reliably trigger OnDeleteObject in the cache, leading to
// false positives where successfully-salvaged items get re-queued.
uint itemId = _currentItemId;
bool itemStillPresent = itemId != 0 && IsItemInDirectInventory(itemId);
// An item still in the player's actual inventory after the result wait wasn't
// consumed (panel closed mid-execute, bot got busy, AC dropped the request, ...):
// it goes back in the queue. GetDirectInventory(forceRefresh: true) — a live walk
// of the player's containers — is the ground truth; salvage-consumed items don't
// reliably trigger OnDeleteObject in the cache.
var live = SnapshotDirectInventoryIds();
var salvagedNames = new List<string>();
int stillThere = 0, requeued = 0;
foreach (uint id in _batchAdded)
{
string name = _batchNames.TryGetValue(id, out string? n) ? n : $"0x{id:X8}";
if (live.Contains(id))
{
stillThere++;
if (RequeueOrDrop(id, "still in the pack after Salvage")) requeued++;
}
else
{
salvagedNames.Add(name);
Untrack(id);
}
}
_currentItemId = 0;
_batchNumber++;
_batchesThisSession++;
_itemsSalvagedThisSession += salvagedNames.Count;
string line = $"[Salvage] Batch {_batchNumber}: salvaged {salvagedNames.Count}/{_batchAdded.Count}"
+ (salvagedNames.Count > 0 ? $" ({SkipNotes.NameList(salvagedNames)})" : "")
+ (_batchBagsAdded > 0 ? $", +{_batchBagsAdded} bag(s) combined" : "")
+ (stillThere > 0 ? $"; {stillThere} still in the pack ({requeued} queued again"
+ (stillThere > requeued ? $", {stillThere - requeued} resting or given up, see above" : "") + ")" : "")
+ (_batchAddFailures > 0 ? $"; panel refused {_batchAddFailures} (queued again)" : "")
+ (_batchSkips.Count > 0 ? $"; skipped: {_batchSkips.Describe()}" : "")
+ $". Session: {_itemsSalvagedThisSession} salvaged, {_itemsSkippedThisSession} skipped, {_tracked.Count} still tracked.";
Log(line);
ClearBatch();
_currentUstId = 0;
_phase = Phase.Idle;
if (itemStillPresent)
{
Log($"[Salvage] Item 0x{itemId:X8} still in inventory after salvage cycle — re-queuing.");
RequeueOrDrop(itemId, "item still present after result");
}
else
{
// Successful salvage — clear retry counter for this id.
_itemRetryCount.Remove(itemId);
}
// Always trigger a combine scan on the next idle tick when the queue
// drains — both to consolidate any newly-merged bags and so combine
// doesn't depend on the busyCount==0 gate of the periodic timer (which
@ -437,28 +713,127 @@ public sealed class SalvageManager
}
/// <summary>
/// Re-queue an item that failed a salvage step. Counts retries per id and
/// drops the item once it's failed MaxItemRetries times in a row, so a
/// truly un-salvageable item doesn't trap the queue forever.
/// Every <see cref="SweepIntervalMs"/>: queue tracked items that are in the pack, forget
/// ones that left it (or never arrived), and skip ones the character is wearing. One log
/// line when it queues or skips something; nothing when there's nothing to say.
/// </summary>
private void RequeueOrDrop(uint itemId, string reason)
private void SweepTracked(long now)
{
if (itemId == 0) return;
if (_tracked.Count == 0 || _cache == null) return;
if (now - _lastSweepAt < SweepIntervalMs) return;
_lastSweepAt = now;
var inPack = new Dictionary<uint, WorldObject>();
foreach (WorldObject wo in _cache.GetDirectInventory(forceRefresh: true))
inPack[unchecked((uint)wo.Id)] = wo;
int queuedNow = 0, resting = 0;
List<uint>? forget = null;
List<(uint Id, string Name)>? worn = null;
foreach (var kv in _tracked)
{
uint id = kv.Key;
TrackedItem t = kv.Value;
if (inPack.TryGetValue(id, out WorldObject? wo))
{
t.SeenInPack = true;
if (string.IsNullOrEmpty(t.Name)) t.Name = wo.Name;
if (_queued.Contains(id) || _batch.Contains(id)) continue; // BuildBatch checks it
if (IsWornByPlayer(wo)) { (worn ??= new()).Add((id, wo.Name)); continue; }
if (now < t.CooldownUntil) { resting++; continue; }
QueueItem(id);
queuedNow++;
continue;
}
if (_queued.Contains(id) || _batch.Contains(id)) continue;
WorldObject? cached = _cache[unchecked((int)id)];
if (IsWornByPlayer(cached)) { (worn ??= new()).Add((id, cached?.Name ?? t.Name)); continue; }
if (t.SeenInPack || now - t.NotedAt >= ArrivalGraceMs)
(forget ??= new()).Add(id);
}
if (forget != null)
foreach (uint id in forget) Untrack(id);
if (worn != null)
{
foreach (var (id, name) in worn) SkipForGood(id, name, SkipWorn);
Log($"[Salvage] Sweep: skipped {_batchSkips.Describe()}.");
_batchSkips.Clear();
}
if (queuedNow > 0)
Log($"[Salvage] Sweep: queued {queuedNow} looted-for-salvage item(s) found in the pack"
+ (resting > 0 ? $", {resting} resting after failures" : "")
+ $" ({_tracked.Count} tracked).");
}
/// <summary>
/// Re-queue an item that failed a salvage step. After MaxItemRetries failures in a row
/// the item rests for GiveUpCooldownMs (the sweep queues it again after that); after
/// MaxGiveUpRounds rests it is left in the pack for good, with a log line saying so.
/// True when the item went straight back in the queue.
/// </summary>
private bool RequeueOrDrop(uint itemId, string reason)
{
if (itemId == 0) return false;
int prior = _itemRetryCount.TryGetValue(itemId, out int n) ? n : 0;
int next = prior + 1;
if (next > MaxItemRetries)
if (next < MaxItemRetries)
{
_itemRetryCount.Remove(itemId);
Log($"[Salvage] Giving up on 0x{itemId:X8} after {MaxItemRetries} attempts ({reason}).");
NoteError($"gave up on 0x{itemId:X8} after {MaxItemRetries} attempts ({reason})");
// Trigger a combine scan if dropping this item left the queue empty.
if (_queue.Count == 0) _pendingCombineScan = true;
return;
_itemRetryCount[itemId] = next;
QueueItem(itemId);
return true;
}
_itemRetryCount.Remove(itemId);
string name = _tracked.TryGetValue(itemId, out TrackedItem? t) && t.Name.Length > 0 ? t.Name : $"0x{itemId:X8}";
if (t != null && t.GiveUps + 1 < MaxGiveUpRounds)
{
t.GiveUps++;
t.CooldownUntil = NowMs + GiveUpCooldownMs;
Log($"[Salvage] '{name}' 0x{itemId:X8} failed {MaxItemRetries} times ({reason}) — trying again in {GiveUpCooldownMs / 1000}s (round {t.GiveUps}/{MaxGiveUpRounds}).");
}
else
{
Untrack(itemId);
_itemsSkippedThisSession++;
Log($"[Salvage] Giving up on '{name}' 0x{itemId:X8}: {SkipGaveUp} ({reason}). It stays in the pack.");
NoteError($"gave up on 0x{itemId:X8} ({reason})");
}
// Trigger a combine scan if this left the queue empty.
if (_queue.Count == 0) _pendingCombineScan = true;
return false;
}
/// <summary>Per-batch skip notes, grouped by reason, for one bounded log line.</summary>
private sealed class SkipNotes
{
private readonly List<(string Reason, List<string> Names, int Extra)> _byReason = new();
public int Count { get; private set; }
public void Add(string reason, string name, bool countOnly = false, int n = 1)
{
int i = _byReason.FindIndex(e => e.Reason == reason);
if (i < 0) { _byReason.Add((reason, new List<string>(), 0)); i = _byReason.Count - 1; }
var e = _byReason[i];
if (countOnly) _byReason[i] = (e.Reason, e.Names, e.Extra + n);
else e.Names.Add(name);
Count += n;
}
public void Clear() { _byReason.Clear(); Count = 0; }
public string Describe()
=> string.Join("; ", _byReason.Select(e =>
e.Names.Count == 0 ? $"{e.Extra} {e.Reason}" : $"{e.Reason}: {NameList(e.Names)}"));
/// <summary>"A, B x2, C" — at most 8 distinct names, then "+N more".</summary>
public static string NameList(List<string> names)
{
var groups = names.GroupBy(x => x).Select(g => g.Count() > 1 ? $"{g.Key} x{g.Count()}" : g.Key).ToList();
return groups.Count <= 8 ? string.Join(", ", groups) : string.Join(", ", groups.Take(8)) + $", +{groups.Count - 8} more";
}
_itemRetryCount[itemId] = next;
_queue.Enqueue(itemId);
Log($"[Salvage] Re-queued 0x{itemId:X8} ({reason}) — attempt {next}/{MaxItemRetries}.");
}
// ── Combine salvage bags ──────────────────────────────────────────────────
@ -553,7 +928,7 @@ public sealed class SalvageManager
_phase = Phase.Idle;
return;
}
if (!_host.UseObject(ust))
if (!_host.UseFor(ust, "Salvage", "combine salvage: open the salvage panel (UST)"))
{
_combineOpenAttempts++;
if (_combineOpenAttempts < MaxCombineOpenAttempts)
@ -815,21 +1190,12 @@ public sealed class SalvageManager
// ── Helpers ───────────────────────────────────────────────────────────────
/// <summary>
/// True if <paramref name="id"/> appears in a fresh walk of the player's
/// True if any of <paramref name="ids"/> appears in a fresh walk of the player's
/// inventory containers. Ground truth for "did the server actually destroy
/// this item" — the cache's _byId can hold stale entries for salvage-
/// consumed items because OnDeleteObject doesn't fire on every merge path.
/// </summary>
private bool IsItemInDirectInventory(uint id)
{
if (_cache == null) return false;
var inv = _cache.GetDirectInventory(forceRefresh: true);
foreach (var item in inv)
{
if (unchecked((uint)item.Id) == id) return true;
}
return false;
}
private bool AnyStillInPack(List<uint> ids) => ids.Count > 0 && AnySnapshotBagStillInInventory(ids);
/// <summary>
/// Snapshots the ids currently in the player's direct inventory as a
@ -1036,7 +1402,7 @@ public sealed class SalvageManager
Phase = _phase.ToString(),
PhaseReadyInMs = Math.Max(0, _phaseReadyAt - now),
QueueCount = _queue.Count,
CurrentItemId = _currentItemId,
CurrentItemId = _batch.Count > 0 ? _batch[0] : 0,
CurrentUstId = _currentUstId,
PanelEverOpened = _panelEverOpened,
PendingCombineScan = _pendingCombineScan,
@ -1053,6 +1419,11 @@ public sealed class SalvageManager
BagsMerged = _bagsMergedThisSession,
LastError = _lastError,
MsSinceLastError = _lastErrorAt == 0 ? -1 : now - _lastErrorAt,
TrackedItems = _tracked.Count,
BatchSize = _batch.Count,
Batches = _batchesThisSession,
ItemsSalvaged = _itemsSalvagedThisSession,
ItemsSkipped = _itemsSkippedThisSession,
};
}
@ -1080,5 +1451,10 @@ public sealed class SalvageManager
public int BagsMerged;
public string LastError;
public long MsSinceLastError;
public int TrackedItems;
public int BatchSize;
public int Batches;
public int ItemsSalvaged;
public int ItemsSkipped;
}
}

View file

@ -0,0 +1,618 @@
// ============================================================================
// RynthSuite - Plugins/RynthCore.Plugin.RynthAi/Loot/ScrollLearner.cs
// VTank's "ReadUnknownScrolls" ("Loots and reads unknown scrolls (looting must
// be enabled)", default on): loot scrolls of spells the character doesn't know
// and can learn, then read them at a safe moment. Also reads such scrolls that
// are already in the pack, and every item a loot profile's Read action looted.
//
// "Can learn" is ACE's own rule (ACE.Server Scroll.ActOnUse +
// Player.CanReadScroll), so nothing is looted that the server will refuse:
// - the spell must not be known ("You already know that spell!");
// - power < 50 (level I) or power >= 300 (VII, VIII): anyone may read it;
// - otherwise the spell's school must be trained or specialized and the
// buffed skill at least power - 50 ("You are not trained in ..." /
// "You are not skilled enough in ... to learn this spell.").
// On top of that RynthAi always wants the school trained (VTank's rule: an
// untrained school can't cast the spell anyway).
//
// Data: the scroll's spell is data id 28 (Spell) from its CreateObject header
// (no appraisal needed); school and power from the portal.dat SpellTable
// (ComponentDatabase); known spells from the spellbook snapshot; skills read
// straight from the host (CharacterSkills' "assume capable" fallback would
// loot scrolls we can't read).
// ============================================================================
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Loot;
internal enum ScrollVerdict
{
Learnable,
/// <summary>No spell id on it: not a spell scroll (or the client doesn't know yet).</summary>
NoSpell,
Known,
/// <summary>The spellbook can't be read yet (cold snapshot, no engine call).</summary>
KnownUnreadable,
/// <summary>The spell isn't in the dat's SpellTable (or the dat couldn't be read).</summary>
SchoolUnknown,
SkillUnreadable,
Untrained,
TooDifficult,
/// <summary>A read of this spell failed earlier this session.</summary>
FailedBefore,
}
internal readonly record struct ScrollJudgement(
ScrollVerdict Verdict, int SpellId, string SpellName, string SkillName, int Training, int Skill, int Power)
{
public bool Learnable => Verdict == ScrollVerdict.Learnable;
public int MinSkill => Power - ScrollLearner.AceSkillMargin;
public string TrainingName => Training >= 3 ? "specialized" : Training == 2 ? "trained" : "untrained";
/// <summary>Why, in a few plain words (log lines).</summary>
public string Why => Verdict switch
{
ScrollVerdict.Learnable => $"unknown, {SkillName} {TrainingName}",
ScrollVerdict.NoSpell => "no spell on it",
ScrollVerdict.Known => "already known",
ScrollVerdict.KnownUnreadable => "spellbook not readable yet",
ScrollVerdict.SchoolUnknown => "the spell's school is unknown",
ScrollVerdict.SkillUnreadable => $"{SkillName} not readable yet",
ScrollVerdict.Untrained => $"{SkillName} untrained",
ScrollVerdict.TooDifficult => $"{SkillName} {Skill}, needs {MinSkill}",
ScrollVerdict.FailedBefore => "a read failed earlier this session",
_ => Verdict.ToString(),
};
}
internal sealed class ScrollLearner
{
/// <summary>ACE Player_Skills.magicSkillCheckMargin: the skill may be this far below the spell's power.</summary>
internal const int AceSkillMargin = 50;
/// <summary>PropertyDataId.Spell: the inscribed spell (CreateObject header, SpellDID).</summary>
internal const uint STypeDidSpell = 28;
/// <summary>The loot rule label corpse looting shows for the built-in rule.</summary>
internal const string RuleLabel = "Learn unknown spell";
internal const string ReadAction = "Read";
/// <summary>How long a looted scroll may take to show up in the pack.</summary>
internal const long ArrivalGraceMs = 15_000;
/// <summary>Read animation + 1 s read + return to ready is ~3-4 s on ACE; give up after this.</summary>
internal const long ReadTimeoutMs = 8_000;
/// <summary>Pause between two reads.</summary>
internal const long ReadGapMs = 1_500;
/// <summary>How often the pack is looked through for unknown scrolls.</summary>
internal const long PackSweepMs = 5_000;
/// <summary>A scroll approved for looting holds its spell this long (one copy per spell).</summary>
internal const long ApprovedTtlMs = 60_000;
/// <summary>Reads that time out or are refused as busy before the scroll is given up.</summary>
internal const int MaxReadAttempts = 2;
/// <summary>A spell counts as learned from the spellbook only after this long (a stale snapshot).</summary>
internal const long KnownConfirmMinMs = 1_500;
/// <summary>A pending scroll whose facts can't be read yet is retried this long, then dropped.</summary>
internal const long UnreadableGiveUpMs = 120_000;
private const long LogWindowMs = 10_000;
private const int MaxLogLinesPerWindow = 30;
private enum ChatOutcome { None, Learned, AlreadyKnown, Untrained, TooDifficult, Busy }
private sealed class Pending
{
public string Name = "";
public int SpellId;
public bool FromProfile; // a loot profile's Read action (read even with the setting off)
public long NotedAt;
public bool SeenInPack;
public int Attempts;
public long NotBefore;
}
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private readonly WorldObjectCache? _cache;
/// <summary>Clock (ms); tests replace it.</summary>
public Func<long> NowMs = () => Environment.TickCount64;
/// <summary>Is the spell in the character's spellbook? null = can't tell.</summary>
public Func<int, bool?> KnownSpell = _ => null;
/// <summary>The player's id (0 before login).</summary>
public Func<uint> PlayerId = () => 0;
/// <summary>A chat line for the player (success only).</summary>
public Action<string>? Chat;
private readonly HashSet<int> _failedSpells = new();
private readonly Dictionary<int, (int ItemId, long At)> _approved = new();
private readonly Dictionary<int, Pending> _pending = new();
private readonly Dictionary<int, string> _lastLine = new();
private long _lastSweepAt = long.MinValue / 2;
private long _lastReadEndedAt = long.MinValue / 2;
private long _logWindowStart = long.MinValue / 2;
private int _logWindowLines;
private Dictionary<string, List<int>>? _nameToIds;
// The read in flight.
private int _readItemId;
private int _readSpellId;
private string _readName = "";
private string _readSpellName = "";
private long _readStartedAt;
private ChatOutcome _chat;
private string _chatText = "";
private bool _readItemDeleted;
public ScrollLearner(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache? cache)
{
_host = host;
_settings = settings;
_cache = cache;
}
public bool IsReading => _readItemId != 0;
public int PendingCount => _pending.Count;
public bool IsPending(int itemId) => _pending.ContainsKey(itemId);
public bool HasFailed(int spellId) => _failedSpells.Contains(spellId);
// ── Facts ─────────────────────────────────────────────────────────────────
/// <summary>Could this be a spell scroll? RynthAi files writables as Book; Decal calls them Scroll.</summary>
internal static bool LooksLikeScroll(WorldObject? item)
{
if (item == null) return false;
if (item.ObjectClass == AcObjectClass.Scroll || item.ObjectClass == AcObjectClass.Book) return true;
return item.Name != null && item.Name.StartsWith("Scroll", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Decal's ObjectClass.Scroll (42). RynthAi files every writable as Book (33); Decal splits
/// out scrolls, and VTank loot profiles say "ObjectClass == Scroll". A writable with an
/// inscribed spell (data id 28), or named "Scroll ...", is a scroll.
/// </summary>
internal static bool IsDecalScroll(WorldObject? item)
{
if (item == null) return false;
if (item.ObjectClass == AcObjectClass.Scroll) return true;
if (item.ObjectClass != AcObjectClass.Book) return false;
if ((item.Cache?.GetDataIdProperty(item.Id, STypeDidSpell) ?? 0) != 0) return true;
return item.Name != null && item.Name.StartsWith("Scroll", StringComparison.OrdinalIgnoreCase);
}
/// <summary>ObjectClass test for loot rules: Decal's Scroll class matches RynthAi's scroll Books.</summary>
/// Spell scrolls are classed Scroll at the source now (2026-10-04); a rule written for Book, from
/// when they were filed as Book, still matches them.
internal static bool ClassMatches(WorldObject item, int objectClass)
=> (int)item.ObjectClass == objectClass
|| (objectClass == (int)AcObjectClass.Scroll && IsDecalScroll(item))
|| (objectClass == (int)AcObjectClass.Book && item.ObjectClass == AcObjectClass.Scroll);
/// <summary>
/// The scroll's spell id: data id 28 from its CreateObject header (no appraisal needed),
/// else the one spell an appraisal lists, else a name ("Scroll of X" / "X") that only one
/// spell has. 0 when none.
/// </summary>
internal int ReadSpellId(WorldObject item)
{
uint id = unchecked((uint)item.Id);
try
{
if (_host.TryGetObjectDataIdProperty(id, STypeDidSpell, out uint did) && did != 0 && did < 0x10000)
return (int)did;
}
catch { }
try
{
if (_host.HasGetObjectSpellIds)
{
uint[] buf = new uint[8];
if (_host.GetObjectSpellIds(id, buf, buf.Length) == 1 && buf[0] != 0)
return (int)buf[0];
}
}
catch { }
string name = item.Name ?? "";
if (name.StartsWith("Scroll of ", StringComparison.OrdinalIgnoreCase))
name = name.Substring("Scroll of ".Length);
if (name.Length == 0) return 0;
_nameToIds ??= SpellDatabase.BuildNameToIdsMap();
return _nameToIds.TryGetValue(name.Trim(), out var ids) && ids.Count == 1 ? ids[0] : 0;
}
internal static (uint SType, string Name) SchoolSkill(int school) => school switch
{
1 => (34u, "War Magic"),
2 => (33u, "Life Magic"),
3 => (32u, "Item Enchantment"),
4 => (31u, "Creature Enchantment"),
5 => (43u, "Void Magic"),
_ => (0u, "an unknown school"),
};
/// <summary>ACE Player.CanReadScroll, plus RynthAi's "school trained" (see the file note).</summary>
internal static bool AceCanRead(int training, int buffedSkill, int power)
{
if (training < 2) return false; // RynthAi: the school must be trained
if (power < 50 || power >= 300) return true; // ACE: level I and VII/VIII, anyone
return buffedSkill >= power - AceSkillMargin; // ACE: trained and Current >= power - 50
}
internal ScrollJudgement Judge(WorldObject item) => Judge(ReadSpellId(item));
internal ScrollJudgement Judge(int spellId)
{
if (spellId <= 0) return new(ScrollVerdict.NoSpell, 0, "", "", 0, 0, 0);
string spellName = SpellDatabase.GetSpellName(spellId);
if (_failedSpells.Contains(spellId)) return new(ScrollVerdict.FailedBefore, spellId, spellName, "", 0, 0, 0);
bool? known = null;
try { known = KnownSpell(spellId); } catch { }
if (known == true) return new(ScrollVerdict.Known, spellId, spellName, "", 0, 0, 0);
if (known == null) return new(ScrollVerdict.KnownUnreadable, spellId, spellName, "", 0, 0, 0);
if (!ComponentDatabase.TryGetSpellSchoolAndPower(spellId, out int school, out int power))
return new(ScrollVerdict.SchoolUnknown, spellId, spellName, "", 0, 0, 0);
var (stype, skillName) = SchoolSkill(school);
if (stype == 0) return new(ScrollVerdict.SchoolUnknown, spellId, spellName, skillName, 0, 0, power);
uint player = PlayerId();
if (player == 0 || !_host.HasGetObjectSkill
|| !_host.TryGetObjectSkill(player, stype, out int buffed, out int training)
|| (training >= 2 && buffed <= 0)) // engine qualities artifact (see CharacterSkills)
return new(ScrollVerdict.SkillUnreadable, spellId, spellName, skillName, 0, 0, power);
if (training < 2) return new(ScrollVerdict.Untrained, spellId, spellName, skillName, training, buffed, power);
if (!AceCanRead(training, buffed, power))
return new(ScrollVerdict.TooDifficult, spellId, spellName, skillName, training, buffed, power);
return new(ScrollVerdict.Learnable, spellId, spellName, skillName, training, buffed, power);
}
// ── Looting ───────────────────────────────────────────────────────────────
/// <summary>
/// The built-in loot rule (VTank treats it as one, ahead of the loot profile): with the
/// setting on, a scroll on a corpse whose spell the character doesn't know and can learn.
/// One copy per spell.
/// </summary>
public bool ShouldLootFromCorpse(WorldObject item, out string ruleLabel)
{
ruleLabel = string.Empty;
if (!_settings.ReadUnknownScrolls || !LooksLikeScroll(item)) return false;
ScrollJudgement j = Judge(item);
if (j.Verdict == ScrollVerdict.NoSpell) return false; // a book, a note: not ours to judge
if (!j.Learnable)
{
LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: {j.Why})");
return false;
}
long now = NowMs();
if (OtherCopyTaken(j.SpellId, item.Id, now))
{
LogItem(item.Id, $"[Learn] leaving '{item.Name}' ({j.SpellName}: another copy is already on its way)");
return false;
}
_approved[j.SpellId] = (item.Id, now);
LogItem(item.Id, $"[Learn] looting '{item.Name}' ({j.SpellName}: {j.Why})");
ruleLabel = RuleLabel;
return true;
}
private bool OtherCopyTaken(int spellId, int itemId, long now)
{
if (_approved.TryGetValue(spellId, out var a) && a.ItemId != itemId && now - a.At < ApprovedTtlMs
&& (_cache == null || _cache[a.ItemId] != null))
return true;
foreach (var kv in _pending)
if (kv.Key != itemId && kv.Value.SpellId == spellId) return true;
return false;
}
/// <summary>
/// A Read item's pickup was sent (the built-in rule, or a loot profile's Read action).
/// It is read once it is in the pack.
/// </summary>
public void NoteLooted(int itemId, string? name, bool fromProfile)
{
if (itemId == 0) return;
WorldObject? wo = _cache?[itemId];
if (!_pending.TryGetValue(itemId, out Pending? p))
{
p = new Pending { NotedAt = NowMs() };
_pending[itemId] = p;
}
p.Name = !string.IsNullOrWhiteSpace(name) ? name! : wo?.Name ?? p.Name;
p.FromProfile |= fromProfile;
if (p.SpellId == 0 && wo != null) p.SpellId = ReadSpellId(wo);
}
// ── Reading ───────────────────────────────────────────────────────────────
/// <summary>
/// One tick. <paramref name="safe"/>: macro on, no monster within MonsterRange, not
/// buffing, looting a corpse, salvaging or vendoring. Returns true while a read is in
/// flight and it is still safe: the caller then holds the bot still.
/// </summary>
public bool Tick(bool safe, int busyCount)
{
long now = NowMs();
if (IsReading)
{
if (ResolveRead(now)) return false;
return safe;
}
if (!_settings.IsMacroRunning) return false;
if (!_settings.ReadUnknownScrolls && _pending.Count == 0) return false;
IReadOnlyList<WorldObject>? inv = null;
if (now - _lastSweepAt >= PackSweepMs)
{
_lastSweepAt = now;
inv = Inventory();
SweepPack(inv, now);
}
if (!safe || busyCount > 0 || _pending.Count == 0) return false;
if (now - _lastReadEndedAt < ReadGapMs) return false;
if (inv == null)
{
if (now - _lastStartCheckAt < StartCheckMs) return false; // one pack walk a second at most
inv = Inventory();
}
_lastStartCheckAt = now;
return TryStartRead(inv, now);
}
/// <summary>How often a waiting scroll is looked for in the pack.</summary>
internal const long StartCheckMs = 1_000;
private long _lastStartCheckAt = long.MinValue / 2;
/// <summary>The pack, freshly walked (the cache's unforced list can be seconds old).</summary>
private IReadOnlyList<WorldObject> Inventory()
{
IReadOnlyList<WorldObject> all;
try { all = _cache?.GetDirectInventory(forceRefresh: true) ?? Array.Empty<WorldObject>(); }
catch { return Array.Empty<WorldObject>(); }
// Without the engine's container walk the cache falls back to every non-landscape
// object it knows, corpse contents included. Leave out what is known to sit elsewhere.
int player = unchecked((int)PlayerId());
if (player == 0 || _host.HasGetContainerContents) return all; // the engine's walk is the player's packs only
var mine = new List<WorldObject>(all.Count);
foreach (WorldObject wo in all)
{
int c = wo.Container;
if (c == 0 || c == player || _cache?[c]?.Container == player) mine.Add(wo);
}
return mine;
}
/// <summary>Unknown, learnable scrolls already in the pack join the queue (setting on).</summary>
private void SweepPack(IReadOnlyList<WorldObject> inv, long now)
{
if (!_settings.ReadUnknownScrolls) return;
foreach (WorldObject wo in inv)
{
if (!LooksLikeScroll(wo) || _pending.ContainsKey(wo.Id) || wo.Id == _readItemId) continue;
ScrollJudgement j = Judge(wo);
if (j.Verdict == ScrollVerdict.NoSpell) continue;
if (!j.Learnable)
{
LogItem(wo.Id, $"[Learn] skipped '{wo.Name}' in the pack ({j.SpellName}: {j.Why})");
continue;
}
if (OtherCopyTaken(j.SpellId, wo.Id, now))
continue; // a second copy of a spell already queued: the first one teaches it
_pending[wo.Id] = new Pending { Name = wo.Name, SpellId = j.SpellId, NotedAt = now, SeenInPack = true };
LogItem(wo.Id, $"[Learn] found '{wo.Name}' in the pack ({j.SpellName}: {j.Why}) - will read it");
}
}
private bool TryStartRead(IReadOnlyList<WorldObject> inv, long now)
{
var inPack = new Dictionary<int, WorldObject>(inv.Count);
foreach (WorldObject wo in inv) inPack[wo.Id] = wo;
List<int>? drop = null;
int pickId = 0;
WorldObject? pick = null;
foreach (var kv in _pending)
{
Pending p = kv.Value;
if (!p.FromProfile && !_settings.ReadUnknownScrolls) { (drop ??= new()).Add(kv.Key); continue; }
if (!inPack.TryGetValue(kv.Key, out WorldObject? wo))
{
if (!p.SeenInPack && now - p.NotedAt < ArrivalGraceMs) continue; // still on its way
LogItem(kv.Key, $"[Learn] '{p.Name}' never reached the pack (or left it) - dropped");
(drop ??= new()).Add(kv.Key);
continue;
}
p.SeenInPack = true;
if (now < p.NotBefore) continue;
pickId = kv.Key;
pick = wo;
break;
}
if (drop != null) foreach (int id in drop) _pending.Remove(id);
if (pick == null) return false;
Pending pp = _pending[pickId];
int spellId = ReadSpellId(pick);
if (spellId == 0 && !LooksLikeScroll(pick))
{
// VTank: "Lootplugin attempted to classify item ... for reading, but that item does
// not appear to be a scroll. Ignoring it."
LogItem(pickId, $"[Learn] '{pick.Name}' was looted to read, but it isn't a scroll - kept, not read");
_pending.Remove(pickId);
return false;
}
ScrollJudgement j = Judge(spellId);
if (!j.Learnable)
{
bool waitable = j.Verdict is ScrollVerdict.KnownUnreadable or ScrollVerdict.SkillUnreadable or ScrollVerdict.SchoolUnknown;
if (waitable && now - pp.NotedAt < UnreadableGiveUpMs)
{
pp.NotBefore = now + PackSweepMs;
LogItem(pickId, $"[Learn] waiting to read '{pick.Name}' ({j.SpellName}: {j.Why})");
return false;
}
LogItem(pickId, $"[Learn] skipped '{pick.Name}' ({(j.SpellName.Length > 0 ? j.SpellName + ": " : "")}{j.Why}) - kept in the pack");
_pending.Remove(pickId);
return false;
}
pp.Attempts++;
_readItemId = pickId;
_readSpellId = j.SpellId;
_readName = pick.Name;
_readSpellName = j.SpellName;
_readStartedAt = now;
_chat = ChatOutcome.None;
_chatText = "";
_readItemDeleted = false;
bool sent = false;
try { sent = _host.UseFor(unchecked((uint)pickId), "Learn", $"read the scroll to learn {j.SpellName} ({j.Why})"); }
catch { }
if (!sent)
{
EndRead(now);
if (pp.Attempts >= MaxReadAttempts) Fail(pickId, pp, "the use was refused");
else pp.NotBefore = now + 3_000;
return false;
}
LogLine($"[Learn] reading '{pick.Name}' ({j.SpellName}: {j.Why})");
return true;
}
/// <summary>True when the read in flight is over (learned, refused, or timed out).</summary>
private bool ResolveRead(long now)
{
_pending.TryGetValue(_readItemId, out Pending? p);
long age = now - _readStartedAt;
bool knownNow = false;
if (age >= KnownConfirmMinMs)
{
try { knownNow = KnownSpell(_readSpellId) == true; } catch { }
}
if (_chat == ChatOutcome.Learned || _readItemDeleted || knownNow)
{
string how = _chat == ChatOutcome.Learned ? "the scroll is destroyed" : _readItemDeleted ? "the scroll is gone" : "it is in the spellbook";
LogLine($"[Learn] read '{_readName}' - learned {_readSpellName} ({how})");
try { Chat?.Invoke($"[RynthAi] Learned {_readSpellName} from a scroll."); } catch { }
_pending.Remove(_readItemId);
EndRead(now);
return true;
}
if (_chat is ChatOutcome.AlreadyKnown or ChatOutcome.Untrained or ChatOutcome.TooDifficult)
{
if (p != null) Fail(_readItemId, p, $"the server said: {_chatText}");
else _failedSpells.Add(_readSpellId);
EndRead(now);
return true;
}
if (_chat == ChatOutcome.Busy || age >= ReadTimeoutMs)
{
string why = _chat == ChatOutcome.Busy ? "too busy" : $"no answer in {ReadTimeoutMs / 1000} s";
if (p != null)
{
if (p.Attempts >= MaxReadAttempts) Fail(_readItemId, p, why);
else
{
p.NotBefore = now + 3_000;
LogLine($"[Learn] read of '{_readName}' not confirmed ({why}) - will try again");
}
}
EndRead(now);
return true;
}
return false;
}
private void Fail(int itemId, Pending p, string why)
{
int spellId = p.SpellId != 0 ? p.SpellId : _readSpellId;
if (spellId != 0) _failedSpells.Add(spellId);
_pending.Remove(itemId);
LogLine($"[Learn] read '{p.Name}' failed ({why}) - not looted or read again this session");
}
private void EndRead(long now)
{
_readItemId = 0;
_readSpellId = 0;
_readName = "";
_readSpellName = "";
_chat = ChatOutcome.None;
_chatText = "";
_readItemDeleted = false;
_lastReadEndedAt = now;
}
/// <summary>ACE's answers to a scroll read (Scroll.ActOnUse, Player.LearnSpellWithNetworking).</summary>
public void OnChat(string? text)
{
if (!IsReading || string.IsNullOrEmpty(text)) return;
string t = text.Trim();
ChatOutcome o =
t == "The scroll is destroyed." ? ChatOutcome.Learned
: t == "You already know that spell!" ? ChatOutcome.AlreadyKnown
: t.StartsWith("You are not trained in ", StringComparison.Ordinal) && t.EndsWith("!", StringComparison.Ordinal) ? ChatOutcome.Untrained
: t.StartsWith("You are not skilled enough in ", StringComparison.Ordinal) && t.EndsWith(" to learn this spell.", StringComparison.Ordinal) ? ChatOutcome.TooDifficult
: t.StartsWith("You're too busy", StringComparison.Ordinal) ? ChatOutcome.Busy
: ChatOutcome.None;
if (o == ChatOutcome.None) return;
_chat = o;
_chatText = t;
}
/// <summary>The scroll is consumed on success (TryConsumeFromInventoryWithNetworking).</summary>
public void OnObjectDeleted(uint objectId)
{
int id = unchecked((int)objectId);
if (IsReading && id == _readItemId) _readItemDeleted = true;
else if (!IsReading) _pending.Remove(id);
_lastLine.Remove(id);
}
/// <summary>Logout: the session memory goes with the character.</summary>
public void Reset()
{
_failedSpells.Clear();
_approved.Clear();
_pending.Clear();
_lastLine.Clear();
EndRead(NowMs());
}
// ── Logging ───────────────────────────────────────────────────────────────
/// <summary>One line per scroll decision: an item's line is written again only when it changes.</summary>
private void LogItem(int itemId, string line)
{
if (_lastLine.TryGetValue(itemId, out string? last) && last == line) return;
if (_lastLine.Count > 2000) _lastLine.Clear();
_lastLine[itemId] = line;
LogLine(line);
}
private void LogLine(string line)
{
long now = NowMs();
if (now - _logWindowStart >= LogWindowMs) { _logWindowStart = now; _logWindowLines = 0; }
if (++_logWindowLines > MaxLogLinesPerWindow) return;
try { _host.Log(line); } catch { }
}
}

View file

@ -158,6 +158,25 @@ public static class VTankLootEvaluator
}
}
/// <summary>
/// The first rule, in list order, that matches the item (rule Priority is not consulted),
/// or null when none does; <paramref name="index"/> is its position, or -1.
/// Corpse looting classifies items with this.
/// </summary>
public static VTankLootRule? FirstMatch(VTankLootProfile profile, WorldObject? item, VTankLootContext? ctx, out int index)
{
for (int i = 0; i < profile.Rules.Count; i++)
{
if (Match(profile.Rules[i], item, ctx))
{
index = i;
return profile.Rules[i];
}
}
index = -1;
return null;
}
/// <summary>
/// One condition on its own, same semantics as inside <see cref="Match(VTankLootRule, WorldObject?, VTankLootContext?)"/>.
/// AutoVendor judges conditions one at a time so it can tell "no" from "can't tell".
@ -178,7 +197,7 @@ public static class VTankLootEvaluator
VTankNodeTypes.DoubleValKeyLE => Double(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) <= val,
VTankNodeTypes.DoubleValKeyGE => Double(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) >= val,
VTankNodeTypes.DamagePercentGE => false, // VTank source returns false unconditionally
VTankNodeTypes.ObjectClass => (int)item.ObjectClass == ReadInt(d, 0),
VTankNodeTypes.ObjectClass => ScrollLearner.ClassMatches(item, ReadInt(d, 0)), // Scroll (42) also matches scroll Books
VTankNodeTypes.SpellCountGE => ctx is null || ctx.GetItemSpellIds(itemId).Length >= ReadInt(d, 0),
VTankNodeTypes.SpellMatch => MatchSpellMatch(itemId, ctx, d),
VTankNodeTypes.MinDamageGE => MatchMinDamageGE(item, d),

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
@ -194,6 +195,7 @@ public sealed partial class RynthAiPlugin
// set via /ub opt / /mt opt resolve the same as /vt opt set).
["autocram"] = "EnableAutocram",
["autostack"] = "EnableAutostack",
["readunknownscrolls"] = "ReadUnknownScrolls", // VTank: loots and reads unknown scrolls
["usedispelitems"] = "UseDispelItems",
["castdispelself"] = "CastDispelSelf",
["opendoorrange"] = "OpenDoorRange",
@ -209,6 +211,7 @@ public sealed partial class RynthAiPlugin
["manastonelootcount"] = "ManaStoneKeepCount",
["rebuftimeremainingseconds"] = "RebuffSecondsRemaining",
["navclosestoprange"] = "NavCloseStopRange",
["follownavmin"] = "FollowNavMin",
// UtilityBelt AutoVendor options (/ub opt set AutoVendor.TestMode true)
["autovendor.enabled"] = "AutoVendorEnabled",
["autovendor.enablebuying"] = "AutoVendorEnableBuying",
@ -219,6 +222,12 @@ public sealed partial class RynthAiPlugin
["autovendor.onlyfrommainpack"] = "AutoVendorOnlyFromMainPack",
["autovendor.tries"] = "AutoVendorTries",
["autovendor.triestime"] = "AutoVendorTriesTime",
// UtilityBelt AutoTrade options (/ub opt set AutoTrade.AutoAccept true)
["autotrade.enabled"] = "AutoTradeEnabled",
["autotrade.testmode"] = "AutoTradeTestMode",
["autotrade.think"] = "AutoTradeThink",
["autotrade.onlyfrommainpack"] = "AutoTradeOnlyFromMainPack",
["autotrade.autoaccept"] = "AutoTradeAutoAccept",
};
private string? GetOptionValue(string optName)
@ -386,7 +395,12 @@ public sealed partial class RynthAiPlugin
// Special targets: closestnpc, closestvendor, closestportal
string lower = argStr.ToLower();
if (lower == "closestnpc" || lower == "closestvendor" || lower == "closestportal")
if (lower == "closestportal")
{
UseClosestPortal();
return true;
}
if (lower == "closestnpc" || lower == "closestvendor")
{
return HandleMtUseClosest(lower);
}
@ -436,7 +450,7 @@ public sealed partial class RynthAiPlugin
return true;
}
Host.UseObject(unchecked((uint)best.Id));
Host.UseFor(unchecked((uint)best.Id), "Command", $"/mt use {type}", UseKind.Asked);
Host.Log($"[RynthAi] /mt use {type}: {best.Name} (0x{(uint)best.Id:X8}) at {bestDist:F1}m");
return true;
}
@ -588,7 +602,7 @@ public sealed partial class RynthAiPlugin
if (found == null) return; // items may not be available yet — try again next tick
Host.SelectItem(found.Value.Id);
Host.UseObject(found.Value.Id);
Host.UseFor(found.Value.Id, "Command", "/mt loot (waited for the container)", UseKind.Asked);
Host.Log($"[RynthAi] /mt loot (deferred): {found.Value.Name} (0x{found.Value.Id:X8}) from container 0x{(uint)container:X8}");
_pendingMtLootName = null;
}
@ -609,7 +623,7 @@ public sealed partial class RynthAiPlugin
if (found != null)
{
Host.SelectItem(found.Value.Id);
Host.UseObject(found.Value.Id);
Host.UseFor(found.Value.Id, "Command", "/mt loot", UseKind.Asked);
Host.Log($"[RynthAi] /mt loot: {found.Value.Name} (0x{found.Value.Id:X8}) from container 0x{(uint)container:X8}");
_pendingMtLootName = null;
return true;
@ -668,7 +682,7 @@ public sealed partial class RynthAiPlugin
var item = FindObject(name, inv: true, land: false, partial: partial);
if (item == null) { ChatLine($"[RynthAi] Item not found: '{name}'"); return true; }
Host.UseObject(unchecked((uint)item.Id));
Host.UseFor(unchecked((uint)item.Id), "Command", "/mt use item", UseKind.Asked);
Host.Log($"[RynthAi] /mt equip: {item.Name} (0x{(uint)item.Id:X8})");
return true;
}

View file

@ -4,6 +4,7 @@ using System.Linq;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
@ -13,8 +14,9 @@ namespace RynthCore.Plugin.RynthAi;
/// Each think tick from Idle picks one of two actions:
/// 1. If any worn item has CurrentMana below the threshold AND we have a
/// charged stone in inventory, use the stone on the player.
/// 2. Otherwise, if we have an empty stone and an inventory item with at
/// least the threshold of CurrentMana, drain it.
/// 2. Otherwise, if we have an empty stone and an item the looter picked up
/// as "ManaTap" (looted only to be drained) still holds at least the
/// threshold of CurrentMana, drain it. Nothing else is ever drained.
///
/// Single-shot semantics:
/// - Using an empty stone on an item destroys the item and charges the stone.
@ -63,12 +65,36 @@ internal sealed class ManaStoneManager
// below this fraction of its MaxMana. Prevents the bot from continually
// dumping stones on the player just because an item dipped slightly.
private const double WornRefillPctOfMax = 0.25;
// With an Eternal Mana Charge (never used up) there's no reason to wait for 25%: top
// gear up below 75% (Lucy carried one on her Items list and it was never used, 2026-09-30).
private const double WornRefillPctOfMaxEternal = 0.75;
private long _lastGearDiagAt;
private readonly Dictionary<int, long> _manaIdRequestedAt = new();
private const long ThinkIntervalMs = 600;
private const long ActionTimeoutMs = 8000;
private static long NowMs => Environment.TickCount64;
/// <summary>
/// Set by the plugin: true when a Keep or Keep # rule in the active loot profile
/// matches the item. Draining destroys the item, so kept loot is never a tap target.
/// </summary>
public Func<WorldObject, bool>? IsLootKept { get; set; }
// Items the looter picked up as "ManaTap" (looted only to be drained), with the
// time each was recorded. Draining destroys the item, so these are the ONLY tap
// targets: gear, quest items, bought items and loot kept by a rule are never in
// here. Session memory only: a hot reload or relog builds a new manager and the
// set starts empty, so anything looted for tapping before that just stays in
// the pack undrained (the safe direction).
private readonly Dictionary<int, long> _lootedForTap = new();
// An entry is not pruned for "not in the pack" this soon after it was recorded:
// the pickup is recorded when it is sent, before the item arrives.
private const long LootedForTapGraceMs = 30_000;
private const long LootedForTapPruneIntervalMs = 1_000;
private long _lootedForTapPrunedAt;
public ManaStoneManager(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache objectCache)
{
_host = host;
@ -80,7 +106,12 @@ internal sealed class ManaStoneManager
public void OnHeartbeat(int busyCount)
{
if (!_settings.EnableManaTapping) { Reset(); return; }
// Before the early returns: items sold, given away or dropped while tapping is
// off or the macro is stopped must leave the set too.
PruneLootedForTap(NowMs);
// An Eternal Mana Charge refills gear for free, so it works with tapping off too.
if (!_settings.EnableManaTapping && !HasEternalCharge()) { Reset(); return; }
if (!_settings.IsMacroRunning) { Reset(); return; }
long now = NowMs;
@ -96,6 +127,7 @@ internal sealed class ManaStoneManager
if (itemGone || stoneGone)
{
_host.Log($"[RynthAi] ManaStone: tap completion detected (itemGone={itemGone} stoneGone={stoneGone}).");
if (itemGone) _lootedForTap.Remove(_activeItemId); // drained and destroyed
GoIdle();
}
}
@ -174,6 +206,7 @@ internal sealed class ManaStoneManager
|| text.Contains("is destroyed")
|| text.Contains("has been destroyed"))
{
if (_activeItemId != 0) _lootedForTap.Remove(_activeItemId); // drained and destroyed
GoIdle();
return;
}
@ -206,20 +239,64 @@ internal sealed class ManaStoneManager
}
}
/// <summary>
/// CorpseOpenController calls this when it picks an item up as "ManaTap" (no loot
/// rule matched, it holds enough mana and an empty stone is free): when the pickup
/// is sent, and again when it is confirmed. Only these items are ever drained.
/// </summary>
public void MarkLootedForTap(int itemId)
{
if (itemId != 0) _lootedForTap[itemId] = NowMs;
}
/// <summary>
/// Drops entries whose item has left the pack: drained (destroyed), sold, given
/// away, salvaged, dropped, or never arrived. Also drops items the player has
/// since put on or added to the Weapons tab: that is the player choosing to keep
/// it, so it stops being tap fodder for good.
/// </summary>
private void PruneLootedForTap(long now)
{
if (_lootedForTap.Count == 0) return;
if (now - _lootedForTapPrunedAt < LootedForTapPruneIntervalMs) return;
_lootedForTapPrunedAt = now;
int playerId = unchecked((int)_host.GetPlayerId());
List<int>? drop = null;
foreach (var kv in _lootedForTap)
{
WorldObject? item = _objectCache[kv.Key];
bool keptByPlayer = item != null
&& ((playerId != 0 && item.Wielder == playerId)
|| WorldObjectCache.IsWieldedByPlayer(_host, item)
|| _settings.ItemRules.Any(r => r.Id == item.Id));
if (!keptByPlayer)
{
if (now - kv.Value < LootedForTapGraceMs) continue; // pickup may still be arriving
if (item != null && IsOwnedByPlayer(item, playerId)) continue;
}
(drop ??= new List<int>()).Add(kv.Key);
}
if (drop == null) return;
foreach (int id in drop)
_lootedForTap.Remove(id);
_host.Log($"[RynthAi] ManaStone: {drop.Count} looted-for-tap item(s) left the pack or were kept by the player; {_lootedForTap.Count} left to drain.");
}
// ── Private helpers ───────────────────────────────────────────────────────
private void TryBeginAction()
{
int threshold = _settings.ManaTapMinMana;
// Priority 1 (was 2): drain a tappable looted item into an empty stone.
// Priority 1 (was 2): drain an item looted for tapping into an empty stone.
// This wins over refilling worn gear because:
// * draining is the user's primary goal (loot-for-tap behavior),
// * the use-on-player path only accepts certain equipment slots and
// can loop forever on items like wielded weapons that AC won't
// refill via stone — that loop blacklists stones one by one and
// starves the drain path entirely.
int stoneId = FindEmptyStone();
int stoneId = _settings.EnableManaTapping ? FindEmptyStone() : 0;
int targetId = stoneId != 0 ? FindTapTarget(threshold) : 0;
if (stoneId != 0 && targetId != 0)
@ -251,7 +328,7 @@ internal sealed class ManaStoneManager
{
_state = TapState.TappingItem;
_actionIssuedAt = NowMs;
_host.UseObjectOn(unchecked((uint)stoneId), unchecked((uint)itemId));
_host.UseOnFor(unchecked((uint)stoneId), unchecked((uint)itemId), "ManaStone", "tap an item into a mana stone");
}
private void IssueUseOnPlayer()
@ -265,7 +342,7 @@ internal sealed class ManaStoneManager
_host.Log($"[RynthAi] ManaStone: using charged stone 0x{(uint)_activeStoneId:X8} on player");
_state = TapState.UsingOnPlayer;
_actionIssuedAt = NowMs;
_host.UseObjectOn(unchecked((uint)_activeStoneId), playerId);
_host.UseOnFor(unchecked((uint)_activeStoneId), playerId, "ManaStone", "charged mana stone on yourself");
}
private void GoIdle()
@ -317,8 +394,9 @@ internal sealed class ManaStoneManager
}
/// <summary>
/// Items already in the player's inventory that match the tap-target criteria
/// (mana ≥ threshold, not equipped, not loot-kept, not blacklisted). Each one
/// Items looted for tapping that are in the player's inventory and match the
/// tap-target criteria (mana ≥ threshold, not equipped, not on the Weapons tab,
/// not loot-kept, not blacklisted). Each one
/// will eventually consume one empty stone, so they count against the
/// "free slots" quota that CorpseOpenController uses for ManaTap pickup.
/// </summary>
@ -331,8 +409,10 @@ internal sealed class ManaStoneManager
long now = NowMs;
int count = 0;
foreach (var item in _objectCache.AllKnownObjects())
foreach (int id in _lootedForTap.Keys) // keep in sync with FindTapTarget
{
WorldObject? item = _objectCache[id];
if (item == null) continue;
if (IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
if (IsWandLike(item)) continue; // wands are never tap targets — keep this in sync with FindTapTarget
@ -341,11 +421,33 @@ internal sealed class ManaStoneManager
&& wield != 0) continue;
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int curMana)
|| curMana < threshold) continue;
if (IsProtectedFromTap(item, playerId)) continue; // keep in sync with FindTapTarget
count++;
}
return count;
}
/// <summary>
/// Items a drain must never touch (the drain destroys the item): gear the player
/// is wearing or wielding, weapons and wands on the Weapons tab (the bow sits in
/// the pack while the wand buffs), and loot the profile keeps. Stype 10 can read 0
/// for a wielded item, so worn gear is also checked by its wielder.
/// </summary>
private bool IsProtectedFromTap(WorldObject item, int playerId)
{
if (playerId != 0 && item.Wielder == playerId) return true;
if (WorldObjectCache.IsWieldedByPlayer(_host, item)) return true;
foreach (var rule in _settings.ItemRules)
if (rule.Id == item.Id) return true;
var kept = IsLootKept;
if (kept != null)
{
try { if (kept(item)) return true; }
catch { return true; }
}
return false;
}
/// <summary>
/// Free empty-stone slots = empty stones in inventory minus drain candidates
/// already in inventory waiting to be tapped. CorpseOpenController only
@ -369,6 +471,7 @@ internal sealed class ManaStoneManager
/// </summary>
public bool IsManaStone(WorldObject item)
{
if (IsEternal(item)) return true;
bool hasRule = false;
foreach (var rule in _settings.ConsumableRules)
{
@ -384,14 +487,57 @@ internal sealed class ManaStoneManager
if (item.ObjectClass == AcObjectClass.ManaStone) return true;
return !string.IsNullOrEmpty(item.Name)
&& item.Name.Contains("Mana Stone", StringComparison.OrdinalIgnoreCase);
&& (item.Name.Contains("Mana Stone", StringComparison.OrdinalIgnoreCase)
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// An unlimited mana charge (Eternal Mana Charge: 10,000 mana, never used up). Always
/// "charged", never an empty stone to drain into, and preferred for refilling gear.
/// </summary>
private static bool IsEternal(WorldObject item) =>
!string.IsNullOrEmpty(item.Name) && item.Name.StartsWith("Eternal Mana", StringComparison.OrdinalIgnoreCase);
private bool HasEternalCharge()
{
int playerId = unchecked((int)_host.GetPlayerId());
foreach (var item in _objectCache.GetDirectInventory(forceRefresh: false))
if (IsEternal(item) && IsOwnedByPlayer(item, playerId)) return true;
return false;
}
/// <summary>True if the item's container chain roots at the player's pack.</summary>
// What the player owns, rebuilt at most every 600 ms: the pack walk (GetContainerContents,
// what kits and potions already use) plus the cache's inventory set (wielded items too).
// The per-object container/wielder fields below read 0 off AC's thread, so every item
// looked like it lay on the ground: gear-check logged worn=0 and eternal=False for a
// character wearing gear with an Eternal Mana Charge in the pack (2026-09-30).
private readonly HashSet<int> _ownedIds = new();
private long _ownedIdsAt;
private HashSet<int> OwnedIds()
{
long now = NowMs;
if (now - _ownedIdsAt < ThinkIntervalMs && _ownedIds.Count > 0) return _ownedIds;
_ownedIdsAt = now;
_ownedIds.Clear();
foreach (var wo in _objectCache.GetDirectInventory(forceRefresh: false)) _ownedIds.Add(wo.Id);
foreach (var wo in _objectCache.GetInventory()) _ownedIds.Add(wo.Id);
return _ownedIds;
}
private bool IsOwnedByPlayer(WorldObject item, int playerId)
{
if (item.ObjectClass == AcObjectClass.Corpse) return false;
if (OwnedIds().Contains(item.Id)) return true;
if (item.Wielder != 0 && playerId != 0 && item.Wielder != playerId) return false;
// In no container and wielded by nobody = lying on the ground. Those passed as
// owned (the scans walk every known object), so a Mana Stone on a dungeon floor
// became the "empty stone": the tap could never complete, timed out after 8 s
// and shelved the real tap target for 5 minutes. Only when the engine can read
// ownership; without it every object reads 0 and the old behaviour stays.
if (item.Container == 0 && item.Wielder == 0 && playerId != 0 && _host.HasGetObjectOwnershipInfo)
return false;
if (item.Container != 0 && playerId != 0 && item.Container != playerId)
{
var owner = _objectCache[item.Container];
@ -410,7 +556,7 @@ internal sealed class ManaStoneManager
foreach (var item in _objectCache.AllKnownObjects())
{
if (!IsManaStone(item)) continue;
if (!IsManaStone(item) || IsEternal(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
// Stones AC has explicitly told us are charged ("already full of
@ -467,6 +613,10 @@ internal sealed class ManaStoneManager
if (_stoneUseOnPlayerCooldownUntil.TryGetValue(item.Id, out long until) && now < until)
continue;
// Eternal: always charged (its mana often can't be read), never used up — first choice.
if (IsEternal(item)) return item.Id;
if (!_settings.EnableManaTapping) continue; // tapping off: only the free charge
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int cur))
continue;
if (cur <= 0) continue;
@ -477,14 +627,22 @@ internal sealed class ManaStoneManager
return bestId;
}
/// <summary>
/// The next item to drain. Only items the looter picked up as "ManaTap" are
/// candidates (the drain destroys the item); every check below is a second
/// safety net on top of that.
/// </summary>
private int FindTapTarget(int threshold)
{
if (!_host.HasGetObjectIntProperty) return 0;
if (_lootedForTap.Count == 0) return 0;
int playerId = unchecked((int)_host.GetPlayerId());
long now = NowMs;
foreach (var item in _objectCache.AllKnownObjects())
foreach (int id in _lootedForTap.Keys)
{
WorldObject? item = _objectCache[id];
if (item == null) continue;
if (IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
@ -510,6 +668,10 @@ internal sealed class ManaStoneManager
|| curMana < threshold)
continue;
// Worn gear (stype 10 can read 0), Weapons-tab items and kept loot.
if (IsProtectedFromTap(item, playerId))
continue;
return item.Id;
}
@ -550,34 +712,72 @@ internal sealed class ManaStoneManager
{
if (!_host.HasGetObjectIntProperty) return false;
int playerId = unchecked((int)_host.GetPlayerId());
bool eternal = HasEternalCharge();
double pct = eternal ? WornRefillPctOfMaxEternal : WornRefillPctOfMax;
int worn = 0, readable = 0, lowestPct = 101;
string lowestName = "";
bool needs = false;
bool requestedThisPass = false;
foreach (var item in _objectCache.AllKnownObjects())
{
if (IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield)
|| wield == 0)
// The live slot read can fail off AC's thread; the cache's copy (what /ra wielded
// uses) is the fallback.
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield) || wield == 0)
wield = item.Values(LongValueKey.CurrentWieldedLocation, 0);
if (wield == 0)
continue;
worn++;
// Only items that actually consume mana matter
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.MaxMana, out int maxMana)
|| maxMana <= 0)
// Only items that actually consume mana matter. Off AC's thread an item's mana is
// only known once it has been identified (appraisal cache); worn gear often never
// is, so nothing ever read as low and no stone or charge was used. Identify one such
// item per check, each at most every 5 minutes (a request bumps the busy count).
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.MaxMana, out int maxMana))
{
long nowMs = NowMs;
if (!requestedThisPass && _host.HasRequestId
&& (!_manaIdRequestedAt.TryGetValue(item.Id, out long at) || nowMs - at > 300_000))
{
_manaIdRequestedAt[item.Id] = nowMs;
_host.RequestId(unchecked((uint)item.Id));
requestedThisPass = true;
}
continue;
}
if (maxMana <= 0)
continue;
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int curMana))
continue;
readable++;
_manaIdRequestedAt.Remove(item.Id);
int p = (int)(curMana * 100L / maxMana);
if (p < lowestPct) { lowestPct = p; lowestName = item.Name ?? ""; }
// Refill only when an item has dropped to a small fraction of its
// MaxMana. The configured threshold is for *draining* loose items,
// not for "the player's robe is at 88% of full" — using min(threshold,
// maxMana) caused the bot to dump charged stones constantly on
// Refill only when an item has dropped to a fraction of its MaxMana (25%, or
// 75% with an Eternal charge). The configured threshold is for *draining* loose
// items, not for "the player's robe is at 88% of full" — using
// min(threshold, maxMana) caused the bot to dump charged stones constantly on
// near-full equipment.
int floor = (int)(maxMana * WornRefillPctOfMax);
int floor = (int)(maxMana * pct);
if (curMana < floor)
return true;
needs = true;
}
return false;
// Once a minute: what it can see, so "the charge is never used" can be told apart
// from "the gear's mana can't be read".
long now = NowMs;
if (now - _lastGearDiagAt > 60_000)
{
_lastGearDiagAt = now;
_host.Log($"[RynthAi] ManaStone: gear check - worn={worn} manaReadable={readable} lowest={(readable > 0 ? $"{lowestPct}% ({lowestName})" : "n/a")} " +
$"refillBelow={(int)(pct * 100)}% eternal={eternal} needs={needs} tapping={_settings.EnableManaTapping}");
}
return needs;
}
}

View file

@ -1,236 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.Maps;
/// <summary>
/// One D3D9 POOL_MANAGED A8R8G8B8 texture baked from a single Z-layer's floor cells.
/// Each texel covers one GridCell (0.5 AC units). Edge cells (cells bordering empty space)
/// use the bright wall colour; interior cells use the semi-transparent fill colour;
/// empty cells are fully transparent (alpha=0).
///
/// Displayed via dl.AddImageQuad — O(1) vertices per layer vs O(strips + edges) otherwise.
/// Disk-cached to C:\Games\RynthSuite\RynthAi\Maps\{landblock:X8}_{layerIdx}.bin so
/// re-entering a dungeon skips the rasterise step.
/// </summary>
internal sealed class DungeonMapTexture : IDisposable
{
private const float GridCell = 0.5f;
private const string CacheDir = @"C:\Games\RynthSuite\RynthAi\Maps";
private const uint Magic = 0x524D5458u; // "XTMR"
// D3D9 vtable indices on IDirect3DDevice9 / IDirect3DTexture9
private const int VtCreateTexture = 23;
private const int VtLockRect = 19;
private const int VtUnlockRect = 20;
private const int VtRelease = 2;
private const uint D3DFMT_A8R8G8B8 = 21;
private const uint D3DPOOL_MANAGED = 1;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage, uint fmt, uint pool, out IntPtr ppTex, IntPtr shared);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int LockRectD(IntPtr tex, uint level, ref D3DLockedRect locked, IntPtr pRect, uint flags);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int UnlockRectD(IntPtr tex, uint level);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseD(IntPtr obj);
[StructLayout(LayoutKind.Sequential)]
private struct D3DLockedRect { public int Pitch; public IntPtr pBits; }
// ── D3D9 A8R8G8B8 colour helpers (ARGB uint: A<<24|R<<16|G<<8|B) ─────
private static uint Argb(float r, float g, float b, float a) =>
((uint)(a * 255f) << 24) | ((uint)(r * 255f) << 16) | ((uint)(g * 255f) << 8) | (uint)(b * 255f);
// Match DungeonMapUi colour definitions
private static readonly uint FillFlat = Argb(0.18f, 0.55f, 0.22f, 0.40f);
private static readonly uint FillSlopeUp = Argb(0.55f, 0.12f, 0.08f, 0.40f);
private static readonly uint FillSlopeDown = Argb(0.10f, 0.50f, 0.15f, 0.40f);
private static readonly uint EdgeFlat = Argb(0.55f, 0.80f, 1.00f, 1.00f);
private static readonly uint EdgeSlopeUp = Argb(1.00f, 0.35f, 0.25f, 1.00f);
private static readonly uint EdgeSlopeDown = Argb(0.25f, 1.00f, 0.35f, 1.00f);
// World bounds of the baked area
public float WorldX0, WorldY0, WorldX1, WorldY1;
public IntPtr TexId => _tex;
private IntPtr _tex;
private DungeonMapTexture() {}
/// <summary>
/// Returns a texture for the given floor-cell grid. Checks the disk cache first;
/// if absent, rasterises, uploads to D3D9, and saves to disk.
/// Returns null if device is invalid or texture upload fails.
/// </summary>
public static DungeonMapTexture? GetOrBuild(
IntPtr device,
Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells,
uint landblock, int layerIdx)
{
if (device == IntPtr.Zero || cells.Count == 0) return null;
// Bounding box
int xMin = int.MaxValue, xMax = int.MinValue;
int yMin = int.MaxValue, yMax = int.MinValue;
foreach (var (gx, gy) in cells.Keys)
{
if (gx < xMin) xMin = gx; if (gx > xMax) xMax = gx;
if (gy < yMin) yMin = gy; if (gy > yMax) yMax = gy;
}
int w = xMax - xMin + 1, h = yMax - yMin + 1;
if (w <= 0 || h <= 0 || w > 8192 || h > 8192) return null;
// Try disk cache first (only valid when dimensions match the dat-computed bounds)
var cached = TryLoadFromDisk(device, landblock, layerIdx, xMin, yMin, w, h);
if (cached != null) return cached;
// Rasterise → upload → cache
var pixels = Rasterise(cells, xMin, yMax, w, h);
IntPtr tex = Upload(device, w, h, pixels);
if (tex == IntPtr.Zero) return null;
SaveToDisk(landblock, layerIdx, xMin, yMin, w, h, pixels);
return new DungeonMapTexture
{
_tex = tex,
WorldX0 = xMin * GridCell,
WorldY0 = yMin * GridCell,
WorldX1 = (xMax + 1) * GridCell,
WorldY1 = (yMax + 1) * GridCell,
};
}
public void Dispose()
{
if (_tex == IntPtr.Zero) return;
try { GetVtFunc<ReleaseD>(_tex, VtRelease)(_tex); } catch { }
_tex = IntPtr.Zero;
}
// ── Rasterisation ─────────────────────────────────────────────────────
private static uint[] Rasterise(
Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells,
int xMin, int yMax, int w, int h)
{
var pixels = new uint[w * h]; // 0 = transparent
foreach (var ((gx, gy), ctype) in cells)
{
bool isEdge = !cells.ContainsKey((gx + 1, gy))
|| !cells.ContainsKey((gx - 1, gy))
|| !cells.ContainsKey((gx, gy + 1))
|| !cells.ContainsKey((gx, gy - 1));
uint col = isEdge
? ctype switch
{
DungeonMapUi.CellType.SlopeUp => EdgeSlopeUp,
DungeonMapUi.CellType.SlopeDown => EdgeSlopeDown,
_ => EdgeFlat,
}
: ctype switch
{
DungeonMapUi.CellType.SlopeUp => FillSlopeUp,
DungeonMapUi.CellType.SlopeDown => FillSlopeDown,
_ => FillFlat,
};
// Row 0 = northernmost cells (highest gy), so flip Y
pixels[(yMax - gy) * w + (gx - xMin)] = col;
}
return pixels;
}
// ── D3D9 upload ───────────────────────────────────────────────────────
private static unsafe IntPtr Upload(IntPtr device, int w, int h, uint[] pixels)
{
try
{
int hr = GetVtFunc<CreateTextureD>(device, VtCreateTexture)(
device, (uint)w, (uint)h, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out IntPtr tex, IntPtr.Zero);
if (hr < 0 || tex == IntPtr.Zero) return IntPtr.Zero;
var locked = new D3DLockedRect();
hr = GetVtFunc<LockRectD>(tex, VtLockRect)(tex, 0, ref locked, IntPtr.Zero, 0);
if (hr < 0) { GetVtFunc<ReleaseD>(tex, VtRelease)(tex); return IntPtr.Zero; }
// Copy row by row — pitch may be wider than w*4
for (int row = 0; row < h; row++)
{
IntPtr dst = IntPtr.Add(locked.pBits, row * locked.Pitch);
fixed (uint* src = &pixels[row * w])
Buffer.MemoryCopy(src, (void*)dst, (nuint)(w * 4), (nuint)(w * 4));
}
GetVtFunc<UnlockRectD>(tex, VtUnlockRect)(tex, 0);
return tex;
}
catch { return IntPtr.Zero; }
}
// ── Disk cache ────────────────────────────────────────────────────────
private static DungeonMapTexture? TryLoadFromDisk(
IntPtr device, uint lb, int layerIdx,
int expXMin, int expYMin, int expW, int expH)
{
try
{
string path = Path.Combine(CacheDir, $"{lb:X8}_{layerIdx}.bin");
if (!File.Exists(path)) return null;
using var br = new BinaryReader(File.OpenRead(path));
if (br.ReadUInt32() != Magic) return null;
int xMin = br.ReadInt32(), yMin = br.ReadInt32();
int w = br.ReadInt32(), h = br.ReadInt32();
// Invalidate if bounds no longer match the dat
if (w != expW || h != expH || xMin != expXMin || yMin != expYMin) return null;
if (br.BaseStream.Length < 20L + (long)w * h * 4) return null;
var pixels = new uint[w * h];
for (int i = 0; i < pixels.Length; i++) pixels[i] = br.ReadUInt32();
IntPtr tex = Upload(device, w, h, pixels);
if (tex == IntPtr.Zero) return null;
return new DungeonMapTexture
{
_tex = tex,
WorldX0 = xMin * GridCell,
WorldY0 = yMin * GridCell,
WorldX1 = (xMin + w) * GridCell,
WorldY1 = (yMin + h) * GridCell,
};
}
catch { return null; }
}
private static void SaveToDisk(uint lb, int layerIdx, int xMin, int yMin, int w, int h, uint[] pixels)
{
try
{
Directory.CreateDirectory(CacheDir);
string path = Path.Combine(CacheDir, $"{lb:X8}_{layerIdx}.bin");
using var bw = new BinaryWriter(File.Open(path, FileMode.Create));
bw.Write(Magic); bw.Write(xMin); bw.Write(yMin); bw.Write(w); bw.Write(h);
foreach (uint px in pixels) bw.Write(px);
}
catch { }
}
// ── VTable helper ─────────────────────────────────────────────────────
private static unsafe TDelegate GetVtFunc<TDelegate>(IntPtr obj, int idx) where TDelegate : Delegate
{
void** vt = *(void***)obj;
return Marshal.GetDelegateForFunctionPointer<TDelegate>((IntPtr)vt[idx]);
}
}

View file

@ -410,9 +410,11 @@ internal static class AfFileParser
case MetaConditionType.ChatMessageCapture:
{
// ChatCapture {pattern} {replacement} — we only use the pattern
// ChatCapture {pattern} {colour id list, e.g. 2;4}
string pattern = ExtractBraceContent(rest, out int endPos);
rule.ConditionData = pattern;
string r1 = endPos > 0 && endPos < rest.Length ? rest.Substring(endPos).Trim() : "";
rule.ChatColors = r1.StartsWith('{') ? ExtractBraceContent(r1, out _).Trim() : "";
break;
}
@ -523,8 +525,17 @@ internal static class AfFileParser
switch (actionType)
{
case MetaActionType.SetMetaState:
case MetaActionType.CallMetaState:
{
// CallState {ToState} {ReturnState}: the second brace is what gets
// pushed on the call stack (it was dropped, so Return went back to the caller).
rule.ActionData = ExtractBraceContent(rest, out int e1);
string r1 = e1 < rest.Length ? rest.Substring(e1).Trim() : "";
rule.CallReturnState = r1.StartsWith('{') ? ExtractBraceContent(r1, out _) : "";
break;
}
case MetaActionType.SetMetaState:
case MetaActionType.ChatCommand:
case MetaActionType.ExpressionAction:
case MetaActionType.ChatExpression:
@ -571,9 +582,11 @@ internal static class AfFileParser
case MetaActionType.GetRAOption:
{
string variable = ExtractBraceContent(rest, out int e1);
// metaf: GetOpt {Option} {Variable} (GetOpt {OpenDoors} {doors}).
// ActionData stays "variable;option".
string option = ExtractBraceContent(rest, out int e1);
string r1 = e1 < rest.Length ? rest.Substring(e1).Trim() : "";
string option = ExtractBraceContent(r1, out _);
string variable = ExtractBraceContent(r1, out _);
rule.ActionData = $"{variable};{option}";
break;
}
@ -706,8 +719,20 @@ internal static class AfFileParser
}
break;
case "pau": // pau seconds
if (tokens.Length >= 2)
case "pau": // metaf: pau X Y Z PauseMs (old RynthAi form: pau seconds)
if (tokens.Length >= 5)
{
// The metaf form was read as "pau seconds": the X coordinate became
// the pause (e.g. -62144 ms) and the point moved to 0,0,0.
navFileLines.Add("3"); // type 3 = Pause
navFileLines.Add(tokens[1]); // EW
navFileLines.Add(tokens[2]); // NS
navFileLines.Add(tokens[3]); // Z
navFileLines.Add("0");
double.TryParse(tokens[4], NumberStyles.Any, CultureInfo.InvariantCulture, out double pauseMs);
navFileLines.Add(((int)pauseMs).ToString(CultureInfo.InvariantCulture));
}
else if (tokens.Length >= 2)
{
navFileLines.Add("3"); // type 3 = Pause
navFileLines.Add("0");
@ -731,35 +756,49 @@ internal static class AfFileParser
}
break;
case "ptl": // ptl EW NS Z destEW destNS destZ objectClass {PortalName}
// The trailer for type 6 is exactly the 6 lines NavRouteParser reads: name,
// class, tie, targetEW, targetNS, targetZ. ptl wrote 5 extra "0" lines and
// vnd/tlk 5 more too, which NavRouteParser (and CountNavPoints) then read as
// an extra Point at 0,0,0 after every portal, vendor or NPC: after using a
// portal the bot headed for the middle of Dereth.
case "ptl": // metaf: ptl X Y Z TargetX TargetY TargetZ ObjectClass {Name}
case "tlk": // metaf: tlk X Y Z TargetX TargetY TargetZ ObjectClass {Name}
if (tokens.Length >= 8)
{
navFileLines.Add("6"); // type 6 = PortalNPC
navFileLines.Add("6"); // type 6 = PortalNPC (used by name; NPC talk too)
navFileLines.Add(tokens[1]); // EW
navFileLines.Add(tokens[2]); // NS
navFileLines.Add(tokens[3]); // Z
navFileLines.Add("0");
string portalName = tokens.Length >= 9 ? tokens[8] : tokens[7];
int objClass = 14; // Portal class
int.TryParse(tokens[7], out objClass);
navFileLines.Add(portalName);
string targetName = tokens.Length >= 9 ? tokens[8] : tokens[7];
if (!int.TryParse(tokens[7], out int objClass))
objClass = nodeType == "tlk" ? 37 : 14; // NPC / Portal
navFileLines.Add(targetName);
navFileLines.Add(objClass.ToString());
navFileLines.Add("False");
navFileLines.Add(tokens[4]); // dest EW
navFileLines.Add(tokens[5]); // dest NS
navFileLines.Add(tokens[6]); // dest Z
navFileLines.Add("0");
navFileLines.Add("0"); // land EW
navFileLines.Add("0"); // land NS
navFileLines.Add("0"); // land Z
navFileLines.Add(tokens[4]); // target EW
navFileLines.Add(tokens[5]); // target NS
navFileLines.Add(tokens[6]); // target Z
}
else if (nodeType == "tlk" && tokens.Length >= 5)
{
// Old RynthAi form: tlk EW NS Z objectId {NPCName}
navFileLines.Add("6");
navFileLines.Add(tokens[1]);
navFileLines.Add(tokens[2]);
navFileLines.Add(tokens[3]);
navFileLines.Add("0");
navFileLines.Add(tokens.Length >= 6 ? tokens[5] : "NPC");
navFileLines.Add("37"); // NPC class
navFileLines.Add("False");
navFileLines.Add(tokens[1]); navFileLines.Add(tokens[2]); navFileLines.Add(tokens[3]);
}
break;
case "vnd": // vnd EW NS Z vendorId {VendorName}
case "vnd": // metaf: vnd X Y Z TargetGUID {TargetName}
if (tokens.Length >= 5)
{
navFileLines.Add("6"); // treat vendor as PortalNPC type
navFileLines.Add("6"); // treat vendor as PortalNPC type (used by name)
navFileLines.Add(tokens[1]); // EW
navFileLines.Add(tokens[2]); // NS
navFileLines.Add(tokens[3]); // Z
@ -768,25 +807,7 @@ internal static class AfFileParser
navFileLines.Add(vndName);
navFileLines.Add("12"); // NPC class
navFileLines.Add("False");
navFileLines.Add("0"); navFileLines.Add("0"); navFileLines.Add("0"); navFileLines.Add("0");
navFileLines.Add("0"); navFileLines.Add("0"); navFileLines.Add("0"); navFileLines.Add("0");
}
break;
case "tlk": // tlk EW NS Z objectId {NPCName}
if (tokens.Length >= 5)
{
navFileLines.Add("6");
navFileLines.Add(tokens[1]);
navFileLines.Add(tokens[2]);
navFileLines.Add(tokens[3]);
navFileLines.Add("0");
string tlkName = tokens.Length >= 6 ? tokens[5] : "NPC";
navFileLines.Add(tlkName);
navFileLines.Add("37"); // NPC class
navFileLines.Add("False");
navFileLines.Add("0"); navFileLines.Add("0"); navFileLines.Add("0"); navFileLines.Add("0");
navFileLines.Add("0"); navFileLines.Add("0"); navFileLines.Add("0"); navFileLines.Add("0");
navFileLines.Add(tokens[1]); navFileLines.Add(tokens[2]); navFileLines.Add(tokens[3]);
}
break;

View file

@ -144,7 +144,7 @@ internal static class AfFileWriter
break;
case MetaConditionType.ChatMessageCapture:
writer.Write($"{keyword} {{{data}}} {{}}");
writer.Write($"{keyword} {{{data}}} {{{rule.ChatColors}}}");
break;
case MetaConditionType.InventoryItemCount_LE:
@ -228,7 +228,7 @@ internal static class AfFileWriter
case MetaActionType.CallMetaState:
// Format: CallState {<target>} {<return>}
writer.Write($"{keyword} {{{data}}} {{{rule.State}}}");
writer.Write($"{keyword} {{{data}}} {{{(string.IsNullOrEmpty(rule.CallReturnState) ? rule.State : rule.CallReturnState)}}}");
break;
case MetaActionType.EmbeddedNavRoute:
@ -263,7 +263,7 @@ internal static class AfFileWriter
var parts = data.Split(';');
string variable = parts.Length > 0 ? parts[0] : "";
string option = parts.Length > 1 ? parts[1] : "";
writer.Write($"{keyword} {{{variable}}} {{{option}}}");
writer.Write($"{keyword} {{{option}}} {{{variable}}}"); // metaf order
break;
}

View file

@ -112,6 +112,22 @@ META / SCRIPTING
myCount (number) = 5
myName (string) = Aluvian Warrior
/ra metamgr on|off|status
The Meta Manager: loads another meta when a timer runs out. Rules are
set up in the Meta panel's Schedule view (see Docs\META_MANAGER.md).
Triggers: a quest's /myquests timer running out, N minutes on the
current meta, every N minutes, or a countdown you start. The first
due rule wins; the switch waits for combat, looting and buffing to end
(60 s at most) and never happens while the macro is stopped.
status lists every rule with its time left.
/ra metamgr poll [minutes]
Check /myquests now, or set how often it checks (default 5, minimum 1).
/ra metamgr start <#> [minutes] | stop <#>
Start (or stop) countdown rule number #, optionally for a different time.
Example: /ra metamgr start 2 45
/ra metamgr reset <#|all>
Re-arm a rule: clears "fired" (one-shot), "holding" and an error.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DIAGNOSTICS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

View file

@ -9,6 +9,7 @@ using RynthCore.Plugin.RynthAi.CreatureData;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.Meta;
@ -58,9 +59,15 @@ internal sealed class ExpressionEngine
= new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, (RynthCore.Loot.LootProfile Profile, DateTime Mtime)> _giveNativeProfileCache
= new(StringComparer.OrdinalIgnoreCase);
private static readonly string ItemGiverDir
// The three data paths are settable only so offline tests can point them at a scratch
// folder before anything reads or writes them; the plugin never changes them.
internal static string ItemGiverDir { get; set; }
= Path.Combine(@"C:\Games\RynthSuite\RynthAi", "ItemGiver");
/// <summary>Millisecond tick for delayexec and the var-flush throttle. Tests swap it for a
/// fake clock; the plugin never changes it.</summary>
internal Func<long> TickMs { get; set; } = static () => Environment.TickCount64;
// Stopwatch store: handle → Stopwatch. Persistent (not cleared per eval) — handles are stored in variables.
private readonly Dictionary<string, System.Diagnostics.Stopwatch> _stopwatches = new(StringComparer.Ordinal);
private int _nextSwId;
@ -100,8 +107,8 @@ internal sealed class ExpressionEngine
private long _lastVarFlushMs;
private string? _pvarPathCached;
private const long VarFlushIntervalMs = 2000;
private static readonly string PvarsDir = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "pvars");
private static readonly string GvarsPath = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "gvars.txt");
internal static string PvarsDir { get; set; } = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "pvars");
internal static string GvarsPath { get; set; } = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "gvars.txt");
private Dictionary<string, (Func<string> Get, Action<string> Set)>? _settingsMap;
public IReadOnlyDictionary<string, string> Variables => _variables;
@ -416,9 +423,9 @@ internal sealed class ExpressionEngine
"cstrf" => EvalCstrf(A(0), Tmpl(1)),
"cnumber" => ToDouble(A(0)).ToString("G", CultureInfo.InvariantCulture),
"strlen" => A(0).Length.ToString(CultureInfo.InvariantCulture),
"floor" => Math.Floor(ToDouble(A(0))).ToString("G", CultureInfo.InvariantCulture),
"ceiling" => Math.Ceiling(ToDouble(A(0))).ToString("G", CultureInfo.InvariantCulture),
"round" => Math.Round(ToDouble(A(0)), MidpointRounding.AwayFromZero).ToString("G", CultureInfo.InvariantCulture),
"floor" => Fmt(Math.Floor(ToDouble(A(0)))),
"ceiling" => Fmt(Math.Ceiling(ToDouble(A(0)))),
"round" => Fmt(Math.Round(ToDouble(A(0)), MidpointRounding.AwayFromZero)),
"abs" => Math.Abs(ToDouble(A(0))).ToString("G", CultureInfo.InvariantCulture),
"ord" => EvalOrd(A(0)),
"chr" => EvalChr(A(0)),
@ -485,7 +492,10 @@ internal sealed class ExpressionEngine
// ── RynthAi settings / meta state (VTank-compatible names) ────────
"rasetmetastate" or "vtsetmetastate" or "setmetastate" => EvalVtSetMetaState(Tmpl(0)),
"ragetmetastate" => _settings?.CurrentState ?? "",
"ragetmetastate" or "vtgetmetastate" or "getmetastate" => _settings?.CurrentState ?? "",
// UB vtgetmeta[]: the loaded meta's name (file name without extension).
"vtgetmeta" or "ragetmeta" => string.IsNullOrEmpty(_settings?.CurrentMetaPath)
? "" : Path.GetFileNameWithoutExtension(_settings!.CurrentMetaPath),
"rasetsetting" or "vtsetsetting" => EvalVtSetSetting(Tmpl(0), A(1)),
"ragetsetting" or "vtgetsetting" or "vtankgetsetting" => EvalVtGetSetting(Tmpl(0)),
@ -649,7 +659,7 @@ internal sealed class ExpressionEngine
public void FlushVars(bool force = false)
{
if (!_pvarsDirty && !_gvarsDirty) return;
long now = Environment.TickCount64;
long now = TickMs();
if (!force && now - _lastVarFlushMs < VarFlushIntervalMs) return;
if (_pvarsDirty && _pvars != null) { SaveVarFile(GetPvarPath(), _pvars); _pvarsDirty = false; }
if (_gvarsDirty && _gvars != null) { SaveVarFile(GvarsPath, _gvars); _gvarsDirty = false; }
@ -1314,7 +1324,9 @@ internal sealed class ExpressionEngine
private string EvalVitae()
{
if (!_host.HasGetVitae || _playerId == 0) return "100";
// Unreadable (no engine call, or before login): no known penalty. It returned
// 100, a full penalty, while a real "no vitae" reading is 0.
if (!_host.HasGetVitae || _playerId == 0) return "0";
float v = _host.GetVitae(_playerId);
// Convert multiplier to penalty: 1.0 → 0 (no penalty), 0.95 → 5 (5% penalty).
int penalty = 100 - (int)Math.Round(v * 100.0f);
@ -2044,10 +2056,40 @@ internal sealed class ExpressionEngine
return free < 0 ? "0" : free.ToString(CultureInfo.InvariantCulture);
}
// Last automatic ID request per object (TickCount64), see EnsureIdentified.
private readonly Dictionary<uint, long> _autoIdAt = new();
/// <summary>
/// Asks the server to identify an object a meta or script reads properties
/// from, if it hasn't been identified this session. Many properties (uses
/// left on a pet essence, workmanship, spells ...) only arrive with an ID:
/// before this, a meta reading them got 0 until the item was identified by
/// hand, e.g. endlessly "refilling" a full essence. At most once per 10 s
/// per object; the value is right on the next read once the ID lands.
/// </summary>
private void EnsureIdentified(uint uid)
{
if (uid == 0 || !_host.HasHasAppraisalData || !_host.HasRequestId) return;
// Used (or used on) since its last identify: the identified values may be
// stale, e.g. an essence's uses after a summon or refill. Re-identify.
bool stale = ObjectChangeTracker.IsStale(uid, _host.HasGetLastIdTime ? _host.GetLastIdTime(uid) : 0);
if (!stale && _host.HasAppraisalData(uid)) return;
long now = Environment.TickCount64;
long gap = stale ? 2_000 : 10_000;
lock (_autoIdAt)
{
if (_autoIdAt.TryGetValue(uid, out long last) && now - last < gap) return;
if (_autoIdAt.Count > 500) _autoIdAt.Clear();
_autoIdAt[uid] = now;
}
_host.RequestId(uid);
}
private string EvalWobjectGetIntProp(string objArg, string propArg)
{
if (!TryParseWobjectHandle(objArg, out uint uid, out _)) return "0";
if (!uint.TryParse(propArg.Trim(), out uint prop)) return "0";
EnsureIdentified(uid);
// UB extended property 218103808 (0xD000000) = TEMPLATE_TYPE → reads WCID from PublicWeenieDesc
if (prop == 218103808u)
@ -2066,6 +2108,7 @@ internal sealed class ExpressionEngine
{
if (!TryParseWobjectHandle(objArg, out uint uid, out _)) return "0";
if (!uint.TryParse(propArg.Trim(), out uint prop)) return "0";
EnsureIdentified(uid);
// UB extended double property constants use their own index, not AC STypeFloat values.
// Map each known UB extended constant to the correct AC STypeFloat (or special path).
@ -2085,6 +2128,7 @@ internal sealed class ExpressionEngine
{
if (!TryParseWobjectHandle(objArg, out uint uid, out _)) return "0";
if (!uint.TryParse(propArg.Trim(), out uint prop)) return "0";
EnsureIdentified(uid);
if (!_host.HasGetObjectBoolProperty) return "0";
return _host.TryGetObjectBoolProperty(uid, prop, out bool value) ? (value ? "1" : "0") : "0";
}
@ -2093,6 +2137,7 @@ internal sealed class ExpressionEngine
{
if (!TryParseWobjectHandle(objArg, out uint uid, out _)) return "";
if (!uint.TryParse(propArg.Trim(), out uint prop)) return "";
EnsureIdentified(uid);
if (!_host.HasGetObjectStringProperty) return "";
return _host.TryGetObjectStringProperty(uid, prop, out string? value) ? value ?? "" : "";
}
@ -2160,31 +2205,52 @@ internal sealed class ExpressionEngine
: "0";
}
private string EvalCreatureGetResist(string arg, string typeArg)
// Resists come from CreatureWeakness (the shipped server table, else the creature
// type's average): ACE never sends them on appraisal, so the profile's were all 1.0
// and creaturegetweakest always said "slash" (2026-09-29). Values are damage taken.
private CreatureWeakness.Ranking? ResolveWeakness(string arg)
{
var p = ResolveCreatureProfile(arg);
if (p == null) return "1";
string t = (typeArg ?? "").Trim().ToLowerInvariant();
double v = t switch
uint wcid = 0;
string? name = null;
if (TryParseWobjectHandle(arg, out uint uid, out _) && uid != 0)
{
"slash" or "sl" => p.ResistSlash,
"pierce" or "pi" => p.ResistPierce,
"bludgeon" or "bl" or "b" => p.ResistBludgeon,
"fire" or "fi" or "f" => p.ResistFire,
"cold" or "co" or "c" => p.ResistCold,
"acid" or "ac" or "a" => p.ResistAcid,
"electric" or "lightning" or "el" or "li" => p.ResistElectric,
_ => 1.0,
};
return v.ToString("G", CultureInfo.InvariantCulture);
if (_host.HasGetObjectName && _host.TryGetObjectName(uid, out string n)) name = n;
if (_host.HasGetObjectWcid) _host.TryGetObjectWcid(uid, out wcid);
}
if (string.IsNullOrEmpty(name)) name = arg;
int ctype = ResolveCreatureProfile(arg)?.CreatureType ?? 0;
return CreatureWeakness.Rank(wcid, name, ctype, null);
}
private string EvalCreatureGetResist(string arg, string typeArg)
{
string t = (typeArg ?? "").Trim().ToLowerInvariant();
string element = t switch
{
"slash" or "sl" => "Slash",
"pierce" or "pi" => "Pierce",
"bludgeon" or "bl" or "b" => "Bludgeon",
"fire" or "fi" or "f" => "Fire",
"cold" or "co" or "c" => "Cold",
"acid" or "ac" or "a" => "Acid",
"electric" or "lightning" or "el" or "li" => "Lightning",
"nether" or "ne" or "n" => "Nether",
_ => "",
};
var r = ResolveWeakness(arg);
if (r != null && element.Length > 0)
foreach (var (e, m) in r.Order)
if (e == element && !double.IsNaN(m)) return m.ToString("G", CultureInfo.InvariantCulture);
return "1";
}
/// <summary>The element the creature takes most damage from, spelled as before ("electric" for lightning); "" when unknown.</summary>
private string EvalCreatureGetWeakest(string arg)
{
var p = ResolveCreatureProfile(arg);
if (p == null) return "";
var (type, _) = CreatureProfileStore.GetWeakest(p);
return type;
var r = ResolveWeakness(arg);
if (r == null || r.Order.Count == 0) return "";
string e = r.Order[0].Element.ToLowerInvariant();
return e == "lightning" ? "electric" : e;
}
private string EvalCreatureGetArmor(string arg)
@ -2354,7 +2420,7 @@ internal sealed class ExpressionEngine
{
if (!TryParseWobjectHandle(arg, out uint uid, out _) || uid == 0) return "0";
if (!_host.HasUseObject) return "0";
_host.UseObject(uid);
_host.UseFor(uid, "Meta", "actiontryuseitem", UseKind.Asked);
return "0";
}
@ -2363,7 +2429,7 @@ internal sealed class ExpressionEngine
if (!TryParseWobjectHandle(useArg, out uint useId, out _) || useId == 0) return "0";
if (!TryParseWobjectHandle(onArg, out uint onId, out _) || onId == 0) return "0";
if (!_host.HasUseObjectOn) return "0";
return _host.UseObjectOn(useId, onId) ? "1" : "0";
return _host.UseOnFor(useId, onId, "Meta", "actiontryapplyitem", UseKind.Asked) ? "1" : "0";
}
private string EvalActionTryCastByIdOnTarget(string spellArg, string targetArg)
@ -2512,7 +2578,7 @@ internal sealed class ExpressionEngine
_castBowDequipPendingId = 0; // bow confirmed unwielded — fall through to wield the wand
}
_host.UseObject((uint)wandId);
_host.UseFor((uint)wandId, "Meta", "meta cast: wield the wand", UseKind.Asked);
_castWieldPendingId = wandId;
_castWieldPendingAt = now;
return false; // yield — let the server equip the wand
@ -2539,7 +2605,7 @@ internal sealed class ExpressionEngine
_castStanceLastRecoverAt = now;
_castStanceReEquips++;
_host.Log($"[MetaCast] stance STUCK {stuckMs:0}ms (wielded, mode≠Magic) — re-equip {_castStanceReEquips}/{CastStanceReEquipMax} 0x{(uint)wandId:X8}");
_host.UseObject((uint)wandId);
_host.UseFor((uint)wandId, "Meta", "meta cast: stance stuck, wield the wand again", UseKind.Asked);
return false;
}
@ -2566,7 +2632,7 @@ internal sealed class ExpressionEngine
}
else if (bowId != 0 && !IsCastWielded(bowId) && _host.HasUseObject)
{
_host.UseObject((uint)bowId); // re-wield the bow we dequipped
_host.UseFor((uint)bowId, "Meta", "meta cast done: wield the bow again", UseKind.Asked); // re-wield the bow we dequipped
}
_castWieldPendingId = 0;
_castBowDequipPendingId = 0;
@ -2593,7 +2659,7 @@ internal sealed class ExpressionEngine
if (id == 0 || _worldObjectCache == null) return false;
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: true))
if (wo.Id == id)
return wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0;
return WorldObjectCache.IsWieldedByPlayer(_host, wo);
if (_host.HasGetObjectWielderInfo)
{
uint pid = _host.GetPlayerId();
@ -2611,9 +2677,10 @@ internal sealed class ExpressionEngine
{
if (wo.Id == wandId) continue;
if (IsCastWandObject(wo)) continue;
if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0
&& (wo.ObjectClass == AcObjectClass.MeleeWeapon
|| wo.ObjectClass == AcObjectClass.MissileWeapon))
if (WorldObjectCache.IsAmmo(wo)) continue; // arrows stay on; only the bow blocks the wand
if ((wo.ObjectClass == AcObjectClass.MeleeWeapon
|| wo.ObjectClass == AcObjectClass.MissileWeapon)
&& WorldObjectCache.IsWieldedByPlayer(_host, wo))
return wo.Id;
}
return 0;
@ -2668,7 +2735,7 @@ internal sealed class ExpressionEngine
}
if (unequipped != null)
_host.UseObject(unchecked((uint)unequipped.Id));
_host.UseFor(unchecked((uint)unequipped.Id), "Meta", "actiontryequipanywand", UseKind.Asked);
return "0";
}
@ -2955,7 +3022,7 @@ internal sealed class ExpressionEngine
{
if (string.Equals(item.Name, "Ust", StringComparison.OrdinalIgnoreCase))
{
_host.UseObject((uint)item.Id);
_host.UseFor((uint)item.Id, "Meta", "ustopen", UseKind.Asked);
return "1";
}
}
@ -3173,6 +3240,8 @@ internal sealed class ExpressionEngine
if (_settings == null || string.IsNullOrEmpty(name)) return "";
var map = BuildSettingsMap();
if (map.TryGetValue(name, out var entry)) return entry.Get();
// VTank option names (EnableNav, NavPriorityBoost, Recharge-Norm-Hitp...) → RynthAi setting.
if (MetaManager.TryMapVtOption(name, out string raName) && map.TryGetValue(raName, out entry)) return entry.Get();
return _options.TryGetValue(name, out string? v) ? v : "";
}
@ -3180,7 +3249,14 @@ internal sealed class ExpressionEngine
{
if (_settings == null || string.IsNullOrEmpty(name)) return "0";
var map = BuildSettingsMap();
if (map.TryGetValue(name, out var entry)) { entry.Set(value); return "1"; }
// VTank option names map to RynthAi settings, and bool text (True/false/on/off)
// becomes 1/0: the bool setters read a number, so 'True' used to switch it OFF.
if (map.TryGetValue(name, out var entry)
|| (MetaManager.TryMapVtOption(name, out string raName) && map.TryGetValue(raName, out entry)))
{
entry.Set(MetaManager.NormalizeVtValue(value));
return "1";
}
_options[name] = value;
return "1";
}
@ -3213,9 +3289,23 @@ internal sealed class ExpressionEngine
["MissileArcClearance"] = (() => F(s.MissileArcClearance), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.MissileArcClearance = Math.Clamp(f, 0f, 3f); }),
["EnableAutostack"] = (() => B(s.EnableAutostack), v => s.EnableAutostack = ToDouble(v) != 0),
["EnableAutocram"] = (() => B(s.EnableAutocram), v => s.EnableAutocram = ToDouble(v) != 0),
["ReadUnknownScrolls"] = (() => B(s.ReadUnknownScrolls), v => s.ReadUnknownScrolls = ToDouble(v) != 0),
["EnableCombineSalvage"]= (() => B(s.EnableCombineSalvage),v => s.EnableCombineSalvage= ToDouble(v) != 0),
["PeaceModeWhenIdle"] = (() => B(s.PeaceModeWhenIdle), v => s.PeaceModeWhenIdle = ToDouble(v) != 0),
["RebuffWhenIdle"] = (() => B(s.RebuffWhenIdle), v => s.RebuffWhenIdle = ToDouble(v) != 0),
["UsePotions"] = (() => B(s.UsePotions), v => s.UsePotions = ToDouble(v) != 0),
["UseBuffItems"] = (() => B(s.UseBuffItems), v => s.UseBuffItems = ToDouble(v) != 0),
["MakeRationsBelow"] = (() => s.MakeRationsBelow.ToString(CultureInfo.InvariantCulture), v => s.MakeRationsBelow = Math.Clamp((int)ToDouble(v), 0, 100)),
["UseKitsInMagicMode"] = (() => B(s.UseKitsInMagicMode), v => s.UseKitsInMagicMode = ToDouble(v) != 0),
["PeaceModeForKits"] = (() => B(s.PeaceModeForKits), v => s.PeaceModeForKits = ToDouble(v) != 0),
["KitMinSuccessPct"] = (() => s.KitMinSuccessPct.ToString(CultureInfo.InvariantCulture), v => s.KitMinSuccessPct = Math.Clamp((int)ToDouble(v), 0, 100)),
["EmergencyHealAt"] = (() => s.EmergencyHealAt.ToString(CultureInfo.InvariantCulture), v => s.EmergencyHealAt = Math.Clamp((int)ToDouble(v), 0, 100)),
["StaminaToHealthAt"] = (() => s.StaminaToHealthAt.ToString(CultureInfo.InvariantCulture), v => s.StaminaToHealthAt = Math.Clamp((int)ToDouble(v), 0, 100)),
["StaminaToHealthMinStamina"] = (() => s.StaminaToHealthMinStamina.ToString(CultureInfo.InvariantCulture), v => s.StaminaToHealthMinStamina = Math.Clamp((int)ToDouble(v), 0, 100)),
["StopMacroOnDeath"] = (() => B(s.StopMacroOnDeath), v => s.StopMacroOnDeath = ToDouble(v) != 0),
["StopMacroOnNoComponents"] = (() => B(s.StopMacroOnNoComponents), v => s.StopMacroOnNoComponents = ToDouble(v) != 0),
["StopLootingWhenPackFull"] = (() => B(s.StopLootingWhenPackFull), v => s.StopLootingWhenPackFull = ToDouble(v) != 0),
["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0),
["SummonPets"] = (() => B(s.SummonPets), v => s.SummonPets = ToDouble(v) != 0),
["MineOnly"] = (() => B(s.MineOnly), v => s.MineOnly = ToDouble(v) != 0),
["UseDispelItems"] = (() => B(s.UseDispelItems), v => s.UseDispelItems = ToDouble(v) != 0),
@ -3223,10 +3313,16 @@ internal sealed class ExpressionEngine
["AutoFellowMgmt"] = (() => B(s.AutoFellowMgmt), v => s.AutoFellowMgmt = ToDouble(v) != 0),
["UseRecklessness"] = (() => B(s.UseRecklessness), v => s.UseRecklessness = ToDouble(v) != 0),
["UseNativeAttack"] = (() => B(s.UseNativeAttack), v => s.UseNativeAttack = ToDouble(v) != 0),
["WieldUnlistedWandWhenNoneListed"] = (() => B(s.WieldUnlistedWandWhenNoneListed), v => s.WieldUnlistedWandWhenNoneListed = ToDouble(v) != 0),
// The off hand when a monster rule doesn't choose: Auto, Shield, Weapon or None (or 0-3).
["OffhandDefault"] = (() => s.OffhandDefault, v => { if (OffhandRules.TryParse(v, out var m)) s.OffhandDefault = OffhandRules.SettingValue(m); }),
["PreferDualWield"] = (() => B(s.PreferDualWield), v => s.PreferDualWield = ToDouble(v) != 0),
["MonsterRange"] = (() => I(s.MonsterRange), v => { if (int.TryParse(v, out int i)) s.MonsterRange = i; }),
["RingRange"] = (() => I(s.RingRange), v => { if (int.TryParse(v, out int i)) s.RingRange = i; }),
["ApproachRange"] = (() => I(s.ApproachRange), v => { if (int.TryParse(v, out int i)) s.ApproachRange = i; }),
["MinRingTargets"] = (() => I(s.MinRingTargets), v => { if (int.TryParse(v, out int i)) s.MinRingTargets = i; }),
["BlastRange"] = (() => I(s.BlastRange), v => { if (int.TryParse(v, out int i)) s.BlastRange = i; }),
["MinBlastTargets"] = (() => I(s.MinBlastTargets), v => { if (int.TryParse(v, out int i)) s.MinBlastTargets = i; }),
["HealAt"] = (() => I(s.HealAt), v => { if (int.TryParse(v, out int i)) s.HealAt = i; }),
["RestamAt"] = (() => I(s.RestamAt), v => { if (int.TryParse(v, out int i)) s.RestamAt = i; }),
["GetManaAt"] = (() => I(s.GetManaAt), v => { if (int.TryParse(v, out int i)) s.GetManaAt = i; }),
@ -3254,7 +3350,20 @@ internal sealed class ExpressionEngine
["AutoVendorOnlyFromMainPack"] = (() => B(s.AutoVendorOnlyFromMainPack), v => s.AutoVendorOnlyFromMainPack = ToDouble(v) != 0),
["AutoVendorTries"] = (() => I(s.AutoVendorTries), v => { if (int.TryParse(v, out int i)) s.AutoVendorTries = Math.Clamp(i, 1, 20); }),
["AutoVendorTriesTime"] = (() => I(s.AutoVendorTriesTime), v => { if (int.TryParse(v, out int i)) s.AutoVendorTriesTime = Math.Clamp(i, 500, 30000); }),
["NavCloseStopRange"] = (() => F(s.NavCloseStopRange), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavCloseStopRange = f; }),
// AutoTrade (UB names map here through /ub opt: AutoTrade.Enabled -> AutoTradeEnabled, ...)
["AutoTradeEnabled"] = (() => B(s.AutoTradeEnabled), v => s.AutoTradeEnabled = ToDouble(v) != 0),
["AutoTradeTestMode"] = (() => B(s.AutoTradeTestMode), v => s.AutoTradeTestMode = ToDouble(v) != 0),
["AutoTradeThink"] = (() => B(s.AutoTradeThink), v => s.AutoTradeThink = ToDouble(v) != 0),
["AutoTradeOnlyFromMainPack"] = (() => B(s.AutoTradeOnlyFromMainPack), v => s.AutoTradeOnlyFromMainPack = ToDouble(v) != 0),
["AutoTradeAutoAccept"] = (() => B(s.AutoTradeAutoAccept), v => s.AutoTradeAutoAccept = ToDouble(v) != 0),
// Nav point reach: how close nav gets to each nav point before moving on (yards).
["FollowNavMin"] = (() => F(s.FollowNavMin), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.FollowNavMin = LegacyUiSettings.ClampFollowNavMin(f); }),
// VTank's NavCloseStopRange IS its "Follow/Nav Min Distance" box (the box shows it x240
// in yards; utank2-i.dll fills txtWPRange from it). It used to be read here as a
// separate "stop short of a Once route's last point" range, so a meta's
// navclosestoprange never changed how close nav got to each point. Same setting now,
// in VTank's landblock units: 0.00625 = 1.5 yd.
["NavCloseStopRange"] = (() => F(s.FollowNavMin / 240f), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && f > 0f) s.FollowNavMin = LegacyUiSettings.ClampFollowNavMin(f * 240f); }),
["NavShortcutYards"] = (() => F(s.NavShortcutYards), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavShortcutYards = Math.Clamp(f, 0f, 10f); }),
["MaxMonRange"] = (() => D(s.MaxMonRange), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.MaxMonRange = d; }),
["NavRingThickness"] = (() => F(s.NavRingThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavRingThickness = f; }),
@ -3263,6 +3372,9 @@ internal sealed class ExpressionEngine
["CurrentLootPath"] = (() => s.CurrentLootPath, v => s.CurrentLootPath = v),
["CurrentMetaPath"] = (() => s.CurrentMetaPath, v => s.CurrentMetaPath = v),
["OpenDoors"] = (() => B(s.OpenDoors), v => s.OpenDoors = ToDouble(v) != 0),
["NavRecoveryEnabled"] = (() => B(s.NavRecoveryEnabled), v => s.NavRecoveryEnabled = ToDouble(v) != 0),
["NavOffTrackYards"] = (() => F(s.NavOffTrackYards), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavOffTrackYards = Math.Clamp(f, 160f, 1000f); }),
["NavMaxDetourAttempts"] = (() => I(s.NavMaxDetourAttempts), v => { if (int.TryParse(v, out int i)) s.NavMaxDetourAttempts = Math.Clamp(i, 1, 10); }),
["OpenDoorRange"] = (() => F(s.OpenDoorRange), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.OpenDoorRange = f; }),
["BoostNavPriority"] = (() => B(s.BoostNavPriority), v => s.BoostNavPriority = ToDouble(v) != 0),
["BoostLootPriority"] = (() => B(s.BoostLootPriority), v => s.BoostLootPriority = ToDouble(v) != 0),
@ -3278,7 +3390,7 @@ internal sealed class ExpressionEngine
CultureInfo.InvariantCulture, out double delayMs))
delayMs = 0;
long ms = (long)Math.Max(0, delayMs);
_delayedExecs.Add((Environment.TickCount64 + ms, exprArg));
_delayedExecs.Add((TickMs() + ms, exprArg));
return "1";
}
@ -3292,7 +3404,7 @@ internal sealed class ExpressionEngine
public void PumpDelayedExecs()
{
if (_delayedExecs.Count == 0) return;
long now = Environment.TickCount64;
long now = TickMs();
List<string>? due = null;
for (int i = _delayedExecs.Count - 1; i >= 0; i--)
{
@ -3419,7 +3531,7 @@ internal sealed class ExpressionEngine
/// <summary>"0" and "" are false; everything else is true.</summary>
internal static bool ToBool(string s)
=> s.Length > 0 && s != "0"
=> s.Length > 0 && s != "0" && s != "-0"
&& !string.Equals(s, "false", StringComparison.OrdinalIgnoreCase)
// An evaluation error / depth-guard sentinel is never "true" — keeps
// if[]/iif[]/&&/|| on a broken sub-expression failing closed too.
@ -3434,7 +3546,8 @@ internal sealed class ExpressionEngine
return (long)ToDouble(s);
}
private static string Fmt(double d) => d.ToString("G", CultureInfo.InvariantCulture);
// -0 (ceiling[-0.5], round[-0.4], 0*-1) printed "-0", and "-0" counted as true.
private static string Fmt(double d) => (d == 0 ? 0.0 : d).ToString("G", CultureInfo.InvariantCulture);
private static string Fmt(long l) => l.ToString(CultureInfo.InvariantCulture);
/// <summary>Equality: numeric if both sides parse as numbers, otherwise case-INSENSITIVE
@ -3682,13 +3795,60 @@ internal sealed class ExpressionEngine
Ws();
while (Try("#"))
{
var pattern = ParseUnary();
var pattern = ParseRegexOperand();
l = RegexCache.IsMatch(l, pattern, RegexOptions.IgnoreCase) ? "1" : "0";
Ws();
}
return l;
}
/// <summary>
/// The right side of #. A backtick string, $var, (group), function call, number or
/// plain word is parsed as before. Anything else is taken as raw pattern text, as
/// the reference documents (getcharstringprop[1] # ^Virindi,
/// getvar[lastchat] # killed.*olthoi): up to whitespace, a ',' or an unmatched
/// ')' / ']', or ==, !=, &amp;&amp;, ||. Only the unquoted pattern read as an expression
/// before (^ as XOR, * as multiply), so it never matched.
/// </summary>
private string ParseRegexOperand()
{
Ws();
if (_p >= _s.Length) return "";
char c = _s[_p];
if (c is '`' or '$' or '(' or '~' or '-') return ParseUnary();
int wordEnd = _p;
while (wordEnd < _s.Length && (char.IsLetterOrDigit(_s[wordEnd]) || _s[wordEnd] == '_' || _s[wordEnd] == '.'))
wordEnd++;
if (wordEnd > _p && wordEnd < _s.Length && _s[wordEnd] == '[') return ParseUnary(); // function call
int start = _p, q = _p, depth = 0;
while (q < _s.Length)
{
char ch = _s[q];
if (ch is ' ' or '\t' or '\r' or '\n') break;
if (ch == '\\' && q + 1 < _s.Length) { q += 2; continue; } // escaped char stays in the pattern
if (ch is '[' or '(') depth++;
else if (ch is ']' or ')') { if (depth == 0) break; depth--; }
else if (depth == 0)
{
if (ch == ',') break;
if (q + 1 < _s.Length)
{
char n = _s[q + 1];
if ((ch == '=' && n == '=') || (ch == '!' && n == '=')
|| (ch == '&' && n == '&') || (ch == '|' && n == '|')) break;
}
}
q++;
}
// A plain word (or number) reads exactly as before.
if (q <= wordEnd) return ParseUnary();
_p = q;
return _s.Substring(start, q - start);
}
// Priority 12: unary ~ (also unary - on non-digit expressions)
private string ParseUnary()
{
@ -3760,7 +3920,9 @@ internal sealed class ExpressionEngine
while (_p < _s.Length && (char.IsLetterOrDigit(_s[_p]) || _s[_p] == '_'))
_p++;
string varName = _s.Substring(vs, _p - vs);
return _eng._variables.TryGetValue(varName, out string? vv) ? vv ?? "" : "";
// Same as getvar[name]: an unset variable reads "0" (it read "", so
// '$kills == 0' was false until kills was first set).
return _eng._variables.TryGetValue(varName, out string? vv) ? vv ?? "" : "0";
}
// Hex literal: 0x / 0X (positive or negative)

View file

@ -22,4 +22,22 @@ internal sealed class LoadedMeta
/// silently producing zero or partial rules.
/// </summary>
public List<string> Warnings { get; } = new();
/// <summary>
/// The state a freshly loaded meta starts in. VTank always starts a meta in
/// "Default"; RynthAi used the first rule's state, and its writer sorts
/// states by name, so a saved meta began mid-sequence (e.g. ApostateFinal
/// in '1.0 To Sparkling Apostate Shard'). Falls back to the first rule's
/// state when there is no Default.
/// </summary>
public string StartState
{
get
{
foreach (var r in Rules)
if (string.Equals(r.State, "Default", StringComparison.OrdinalIgnoreCase))
return r.State;
return Rules.Count > 0 ? Rules[0].State : "Default";
}
}
}

View file

@ -44,7 +44,8 @@ internal static class MetFileParser
/* 24 */ MetaConditionType.BurdenPercentage_GE,
/* 25 */ MetaConditionType.DistAnyRoutePT_GE,
/* 26 */ MetaConditionType.Expression,
/* 27 */ MetaConditionType.ChatMessageCapture,
/* 27 */ null, // VTank "Client Dialog Popup" (unsupported → Never)
/* 28 */ MetaConditionType.ChatMessageCapture, // TABLE {p: pattern, c: colour id list}
};
// ── VTank AType → RynthAi MetaActionType ────────────────────────────────
@ -240,10 +241,11 @@ internal static class MetFileParser
break;
case 26: // Expression
case 27: // ChatMessageCapture
rule.ConditionData = ReadExpressionTable(r);
if (vtCType == 27 && string.IsNullOrEmpty(rule.ConditionData))
rule.ConditionData = ReadTypedString(r);
break;
case 28: // ChatMessageCapture
ParseChatCaptureTable(rule, r);
break;
case 4: // ChatMessage
@ -350,6 +352,34 @@ internal static class MetFileParser
return expression;
}
/// <summary>ChatCapture data: TABLE {p: regex pattern, c: colour id list "2;4"}.</summary>
private static void ParseChatCaptureTable(MetaRule rule, MetReader r)
{
string type = r.PeekLine().Trim();
if (type != "TABLE")
{
rule.ConditionData = ReadTypedString(r);
return;
}
r.ReadLine(); // TABLE
int colCount = ParseInt(r.ReadLine());
for (int i = 0; i < colCount; i++) r.ReadLine();
for (int i = 0; i < colCount; i++) r.ReadLine();
int rowCount = ParseInt(r.ReadLine());
for (int row = 0; row < rowCount && r.HasMore; row++)
{
string k = ReadTypedString(r);
switch (k)
{
case "p": rule.ConditionData = ReadTypedString(r); break;
case "c": rule.ChatColors = ReadTypedString(r); break;
default: SkipTypedValue(r); break;
}
}
}
private static void ParseInventoryCountData(MetaRule rule, MetReader r)
{
string type = r.PeekLine().Trim();
@ -550,10 +580,13 @@ internal static class MetFileParser
break;
case 1: // SetMetaState
case 5: // CallMetaState
rule.ActionData = ReadTypedString(r);
break;
case 5: // CallMetaState — VTank stores TABLE {st: to, ret: return}
ParseCallStateTable(rule, r);
break;
case 2: // ChatCommand
rule.ActionData = ReadTypedString(r);
break;
@ -772,6 +805,38 @@ internal static class MetFileParser
rule.ActionData = $"{state};{range.ToString(CultureInfo.InvariantCulture)};{time.ToString(CultureInfo.InvariantCulture)}";
}
/// <summary>
/// CallState data is a TABLE with keys st (the state to call) and ret (the
/// state pushed for Return). Reading it as a string skipped the table and
/// left the action empty, so it never called anything.
/// </summary>
private static void ParseCallStateTable(MetaRule rule, MetReader r)
{
string type = r.PeekLine().Trim();
if (type != "TABLE")
{
rule.ActionData = ReadTypedString(r);
return;
}
r.ReadLine(); // TABLE
int colCount = ParseInt(r.ReadLine());
for (int i = 0; i < colCount; i++) r.ReadLine();
for (int i = 0; i < colCount; i++) r.ReadLine();
int rowCount = ParseInt(r.ReadLine());
for (int row = 0; row < rowCount && r.HasMore; row++)
{
string k = ReadTypedString(r);
switch (k)
{
case "st": rule.ActionData = ReadTypedString(r); break;
case "ret": rule.CallReturnState = ReadTypedString(r); break;
default: SkipTypedValue(r); break;
}
}
}
private static void ParseSetOptionTable(MetaRule rule, MetReader r)
{
string type = r.PeekLine().Trim();

View file

@ -31,7 +31,13 @@ internal sealed class MetaManager
// ── State tracking ───────────────────────────────────────────────────────
private string _lastState = "";
private DateTime _stateStartTime = DateTime.Now;
/// <summary>Wall clock for seconds-in-state, the watchdog and the chat window. Tests swap it
/// for a fake clock; the plugin never changes it.</summary>
internal Func<DateTime> Clock { get; set; } = static () => DateTime.Now;
private bool _lastMacroRunning;
// PSecsInStateGE's clock: restarts on a real state entry, not on macro stop/start.
private DateTime _statePStartTime = DateTime.Now;
// Observability (GetStateSnapshot / §3.4). Written on the plugin-tick thread
// inside the locked rule-eval pass; read by the bridge under the same lock.
@ -51,8 +57,15 @@ internal sealed class MetaManager
private int _idxVersion = -1;
// ── Chat tracking ────────────────────────────────────────────────────────
private string _lastChatText = "";
private DateTime _lastChatTime = DateTime.MinValue;
// Every line from the last second is kept (it used to be one slot, so the
// earlier lines of a burst were never checked). A rule consumes the line it
// fired on, so re-entering its state can't fire it again on the same line.
private readonly record struct ChatLine(long Seq, DateTime At, string Text, int Type);
private readonly List<ChatLine> _chatLines = new();
private long _chatSeq;
private readonly Dictionary<MetaRule, long> _chatConsumed = new();
private MetaRule? _evalRule; // top-level rule being evaluated
private long _evalChatSeq; // newest chat line its condition matched
private Match? _lastChatMatch;
// ── Call stack (CallMetaState / ReturnFromCall) ──────────────────────────
@ -74,6 +87,14 @@ internal sealed class MetaManager
// ── Vendor state tracking ─────────────────────────────────────────────────
private uint _openVendorId;
private bool _vendorClosedThisTick;
private bool _vendorClosedNow; // the edge this tick's rule pass sees
// ── Death (one-shot) ─────────────────────────────────────────────────────
// The plugin holds every tick from a death until 5 s after the respawn, so
// Think never runs while health reads 0. The death is latched here and the
// first meta tick after the hold sees it.
private bool _deathPending;
private bool _deathNow;
// ── Enchantment read buffers (reused per tick to avoid allocation) ────────
private readonly uint[] _enchSpellIds = new uint[256];
@ -139,7 +160,7 @@ internal sealed class MetaManager
for (int i = 0; i < route.Points.Count; i++)
{
NavPoint point = route.Points[i];
if (point.Type != NavPointType.Point)
if (!NavRouteParser.IsPlainWaypoint(point.Type))
continue;
double distance = Math.Sqrt(Math.Pow(point.NS - ns, 2) + Math.Pow(point.EW - ew, 2));
@ -182,12 +203,21 @@ internal sealed class MetaManager
return engine;
}
public void HandleChat(string text)
public void HandleChat(string text, int chatType = -1)
{
_lastChatText = text;
_lastChatTime = DateTime.Now;
DateTime now = Clock();
while (_chatLines.Count > 0 && ((now - _chatLines[0].At).TotalSeconds > 1.0 || _chatLines.Count >= 64))
_chatLines.RemoveAt(0);
_chatLines.Add(new ChatLine(++_chatSeq, now, text ?? "", chatType));
}
/// <summary>Writes pending setpvar/setgvar values now (they are otherwise
/// throttled to one write every 2 s). Called when the session is torn down.</summary>
public void FlushPendingVars() => _expressions?.FlushVars(force: true);
/// <summary>The player died (called every tick while dead; one-shot for the meta).</summary>
public void OnPlayerDeath() => _deathPending = true;
public void OnVendorOpen(uint vendorId)
{
if (vendorId == 0) return;
@ -215,9 +245,16 @@ internal sealed class MetaManager
if (_lastMacroRunning && !_settings.IsMacroRunning)
_expressions?.FlushVars(force: true); // persist pending vars on stop
_lastMacroRunning = _settings.IsMacroRunning;
_vendorClosedThisTick = false; // a close while stopped never fires later
_deathPending = false; // nor does a death
return;
}
// A real state entry (anything but a bare macro stop/start) restarts the
// persistent seconds-in-state clock too.
bool realStateEntry = _settings.ForceStateReset
|| !string.Equals(_settings.CurrentState, _lastState, StringComparison.OrdinalIgnoreCase);
// Macro just started — force reset so rules re-evaluate even if state
// name matches where we stopped. Otherwise HasFired stays latched across
// a stop/start cycle and IF:Always rules like EmbedNav never re-fire.
@ -225,6 +262,14 @@ internal sealed class MetaManager
_settings.ForceStateReset = true;
_lastMacroRunning = true;
// A freshly loaded meta starts with an empty call stack; a Return must
// not pop a state name left over from the previous meta.
if (_settings.MetaCallStackReset)
{
_settings.MetaCallStackReset = false;
_stateStack.Clear();
}
// ── State change / forced reset ──────────────────────────────────────
// Only reset HasFired on ForceStateReset (set by meta actions: SetState,
// CallState, ReturnFromCall, macro start, meta load, watchdog).
@ -233,15 +278,18 @@ internal sealed class MetaManager
// otherwise EmbedNav reloads the nav route from index 0 on every cycle.
if (_settings.ForceStateReset)
{
_stateStartTime = DateTime.Now;
if (realStateEntry)
_host.Log($"[Meta] state '{_lastState}' -> '{_settings.CurrentState}' after {(Clock() - _stateStartTime).TotalSeconds:0}s");
_stateStartTime = Clock();
_watchdogActive = false;
if (realStateEntry) _statePStartTime = Clock();
_settings.ForceStateReset = false;
lock (_settings.MetaRulesLock)
foreach (var r in _settings.MetaRules) r.HasFired = false;
}
_lastState = _settings.CurrentState;
double secondsInState = (DateTime.Now - _stateStartTime).TotalSeconds;
double secondsInState = (Clock() - _stateStartTime).TotalSeconds;
// ── Portal state edge detection ───────────────────────────────────────
bool currentPortal = _host.HasIsPortaling && _host.IsPortaling();
@ -249,8 +297,14 @@ internal sealed class MetaManager
_portalExitedThisTick = !currentPortal && _lastPortalState;
_lastPortalState = currentPortal;
// ── Vendor edge detection (reset one-shot flag each tick) ─────────────
// ── Vendor edge detection (one-shot) ──────────────────────────────────
// OnVendorClose arrives between ticks. Hand the edge to this tick's
// rule pass, then clear it; clearing it before the pass (as before)
// meant VendorClosed could never be true.
_vendorClosedNow = _vendorClosedThisTick;
_vendorClosedThisTick = false;
_deathNow = _deathPending;
_deathPending = false;
// ── Watchdog ─────────────────────────────────────────────────────────
if (_watchdogActive &&
@ -262,9 +316,11 @@ internal sealed class MetaManager
if (distMoved < _watchdogMetersRequired)
{
if (DateTime.Now > _watchdogExpiration)
if (Clock() > _watchdogExpiration)
{
_watchdogActive = false;
// VTank calls the watchdog state: a Return in it re-enters this one.
_stateStack.Push(_settings.CurrentState);
_settings.CurrentState = _watchdogState;
_settings.ForceStateReset = true;
_host.WriteToChat($"[RynthAi] WATCHDOG TRIGGERED \u2192 {_watchdogState}", 1);
@ -274,7 +330,7 @@ internal sealed class MetaManager
else
{
_lastWatchdogPos = currentPos;
_watchdogExpiration = DateTime.Now.AddSeconds(_watchdogSecondsConfig);
_watchdogExpiration = Clock().AddSeconds(_watchdogSecondsConfig);
}
}
@ -299,16 +355,23 @@ internal sealed class MetaManager
// clear before each rule so a ChatMessageCapture match can't bleed
// its {0}/{1} groups into a later rule's action (or the next tick).
_lastChatMatch = null;
_evalRule = rule;
_evalChatSeq = 0;
if (EvaluateCondition(rule, secondsInState))
{
if (_evalChatSeq > 0) _chatConsumed[rule] = _evalChatSeq;
rule.HasFired = true;
rule.LastFiredAt = DateTime.Now;
rule.LastFiredAt = Clock();
_lastFiredState = rule.State;
_lastFiredCond = DescribeCondition(rule);
_lastFiredAct = DescribeAction(rule);
_lastFiredAt = rule.LastFiredAt;
// Always in the log (a rule fires at most once per state entry): a tester's meta
// that stopped loading its nav left no trace of which state it was in or which
// rules fired (2026-10-01). Chat only with MetaDebug.
_host.Log($"[Meta] fired: state '{rule.State}' | {_lastFiredCond} -> {_lastFiredAct}");
if (_settings.MetaDebug)
_host.WriteToChat($"[Meta] {rule.State} | {DescribeCondition(rule)} → {DescribeAction(rule)}", 1);
@ -330,7 +393,7 @@ internal sealed class MetaManager
if (_settings.MetaDebug)
_host.WriteToChat($"[Meta] Think exception: {ex.Message}", 1);
_lastExprError = $"Think: {ex.GetType().Name}: {Truncate(ex.Message, 100)}";
_lastExprErrorAt = DateTime.Now;
_lastExprErrorAt = Clock();
_settings.ForceStateReset = true;
}
}
@ -354,7 +417,8 @@ internal sealed class MetaManager
case MetaConditionType.Any:
{
if (rule.Children == null || rule.Children.Count == 0) return true;
// VTank: an empty Any is false (and Not of it is true); metas use it as a "disabled" gate.
if (rule.Children == null || rule.Children.Count == 0) return false;
foreach (var child in rule.Children)
if (EvaluateCondition(child, secondsInState)) return true;
return false;
@ -365,28 +429,35 @@ internal sealed class MetaManager
return !EvaluateCondition(rule.Children[0], secondsInState);
// ── Vital checks (value) ──────────────────────────────────────────
// Compared signed: a (uint) cast made a negative threshold ~4 billion,
// so "health <= -1" was always true. MaxHealth > 0 = the vitals have been
// read at least once (they are all 0 until the first poll after login).
case MetaConditionType.MainHealthLE:
return int.TryParse(rule.ConditionData, out int hv) && _vitals.CurrentHealth <= (uint)hv;
return int.TryParse(rule.ConditionData, out int hv) && _vitals.MaxHealth > 0 && (long)_vitals.CurrentHealth <= hv;
case MetaConditionType.MainManaLE:
return int.TryParse(rule.ConditionData, out int mv) && _vitals.CurrentMana <= (uint)mv;
return int.TryParse(rule.ConditionData, out int mv) && _vitals.MaxHealth > 0 && (long)_vitals.CurrentMana <= mv;
case MetaConditionType.MainStamLE:
return int.TryParse(rule.ConditionData, out int sv) && _vitals.CurrentStamina <= (uint)sv;
return int.TryParse(rule.ConditionData, out int sv) && _vitals.MaxHealth > 0 && (long)_vitals.CurrentStamina <= sv;
// ── Vital checks (percentage) ─────────────────────────────────────
// "Main Health/Mana % >=" (the UI label, the engine meta panel and
// RynthScript's healthPct/manaPct >= N all mean >=, like VitaePHE).
// These are RynthAi-only conditions (VTank has no vital conditions,
// so no .met or metaf file carries them); the runtime used <=.
case MetaConditionType.MainHealthPHE:
return int.TryParse(rule.ConditionData, out int hpct) &&
_vitals.MaxHealth > 0 &&
(_vitals.CurrentHealth * 100.0 / _vitals.MaxHealth) <= hpct;
(_vitals.CurrentHealth * 100.0 / _vitals.MaxHealth) >= hpct;
case MetaConditionType.MainManaPHE:
return int.TryParse(rule.ConditionData, out int mpct) &&
_vitals.MaxMana > 0 &&
(_vitals.CurrentMana * 100.0 / _vitals.MaxMana) <= mpct;
(_vitals.CurrentMana * 100.0 / _vitals.MaxMana) >= mpct;
case MetaConditionType.CharacterDeath:
return _vitals.CurrentHealth == 0;
return _deathNow || (_vitals.MaxHealth > 0 && _vitals.CurrentHealth == 0);
case MetaConditionType.VitaePHE:
{
@ -399,32 +470,36 @@ internal sealed class MetaManager
// ── Time ──────────────────────────────────────────────────────────
case MetaConditionType.SecondsInState_GE:
case MetaConditionType.SecondsInStateP_GE:
return double.TryParse(rule.ConditionData, out double reqSecs) && secondsInState >= reqSecs;
// VTank: "Persistent timer; does not reset if meta is stopped/started."
// It still restarts when the state is entered again (SetState, Call, Return).
case MetaConditionType.SecondsInStateP_GE:
return double.TryParse(rule.ConditionData, out double reqPSecs)
&& (Clock() - _statePStartTime).TotalSeconds >= reqPSecs;
// ── Chat ──────────────────────────────────────────────────────────
case MetaConditionType.ChatMessage:
case MetaConditionType.ChatMessageCapture:
{
if (string.IsNullOrEmpty(rule.ConditionData)) return false;
if ((DateTime.Now - _lastChatTime).TotalSeconds > 1.0) return false;
var match = RegexCache.Match(_lastChatText, rule.ConditionData);
if (match.Success)
{
if (rule.Condition == MetaConditionType.ChatMessageCapture)
_lastChatMatch = match;
return true;
}
return false;
}
return EvaluateChat(rule);
// ── Pack slots ────────────────────────────────────────────────────
case MetaConditionType.PackSlots_LE:
{
if (!int.TryParse(rule.ConditionData, out int targetSlots) || _objectCache == null) return false;
if (!int.TryParse(rule.ConditionData, out int targetSlots) || _objectCache == null || _playerId == 0) return false;
// Empty slots in the MAIN pack (VTank "Pack Slots <="): only loose items
// whose container is the player count. Side packs, their contents and
// foci don't use the 102 item slots (same rule as GetMainPackEmptySlots).
int used = 0;
int pid = unchecked((int)_playerId);
foreach (var item in _objectCache.GetDirectInventory())
if (item.WieldedLocation <= 0) used++;
{
if (item.WieldedLocation > 0) continue;
if (item.Container != pid) continue;
if (item.ObjectClass is AcObjectClass.Container or AcObjectClass.Foci) continue;
if (item.Values(LongValueKey.EquippedSlots, 0) > 0) continue;
used++;
}
return (102 - used) <= targetSlots;
}
@ -436,10 +511,12 @@ internal sealed class MetaManager
var parts = rule.ConditionData.Split(',');
if (parts.Length < 2 || !int.TryParse(parts[1], out int targetCount)) return false;
string itemName = parts[0].Trim();
// The supply, not the number of stacks: a stack of 80 tapers is 80
// (VTank's "Inventory Item Count"; getitemcountininventorybyname sums the same way).
int count = 0;
foreach (var item in _objectCache.GetDirectInventory())
if (item.Name.Equals(itemName, StringComparison.OrdinalIgnoreCase))
count++;
count += Math.Max(1, item.Values(LongValueKey.StackCount, 1));
return rule.Condition == MetaConditionType.InventoryItemCount_LE
? count <= targetCount
: count >= targetCount;
@ -537,7 +614,12 @@ internal sealed class MetaManager
if (!_host.TryGetPlayerPose(out uint cellId, out _, out _, out _, out _, out _, out _, out _)) return false;
uint landblock = cellId >> 16;
if (uint.TryParse(rule.ConditionData, System.Globalization.NumberStyles.HexNumber, null, out uint hex))
{
// metaf writes the full value ("BlockE 00070000", "BlockE 8B370000"),
// and VTank matches its leading 4 digits. RynthAi's own files use 4.
if (hex > 0xFFFF) hex >>= 16;
return landblock == hex;
}
if (uint.TryParse(rule.ConditionData, out uint dec))
return landblock == dec;
return false;
@ -564,7 +646,7 @@ internal sealed class MetaManager
return _openVendorId != 0;
case MetaConditionType.VendorClosed:
return _vendorClosedThisTick;
return _vendorClosedNow;
case MetaConditionType.Expression:
{
@ -577,7 +659,7 @@ internal sealed class MetaManager
if (v.StartsWith("ERR:", StringComparison.Ordinal))
{
_lastExprError = $"{rule.State}: {Truncate(v, 120)}";
_lastExprErrorAt = DateTime.Now;
_lastExprErrorAt = Clock();
if (_settings.MetaDebug)
_host.WriteToChat($"[Meta] expr error in '{rule.State}': {Truncate(v, 80)}", 1);
return false;
@ -606,11 +688,13 @@ internal sealed class MetaManager
double minDist = double.MaxValue;
foreach (var pt in _settings.CurrentRoute.Points)
{
if (pt.Type != NavPointType.Point) continue;
if (!NavRouteParser.IsPlainWaypoint(pt.Type)) continue;
double d = Math.Sqrt((pt.NS - ns) * (pt.NS - ns) + (pt.EW - ew) * (pt.EW - ew));
if (d < minDist) minDist = d;
}
return minDist != double.MaxValue && minDist >= threshold;
// NS/EW are map coordinates (1.0 = 240 yd); the threshold is in yards
// (metaf: "shortest distance to current navroute >= Distance (in yards)").
return minDist != double.MaxValue && minDist * 240.0 >= threshold;
}
// ── Priority monster count within distance ────────────────────────
@ -647,6 +731,51 @@ internal sealed class MetaManager
}
}
/// <summary>
/// True if a chat line from the last second (checked oldest first) matches
/// the rule's pattern and the rule being evaluated hasn't already fired on
/// that line or a later one.
/// </summary>
private bool EvaluateChat(MetaRule rule)
{
if (string.IsNullOrEmpty(rule.ConditionData) || _chatLines.Count == 0) return false;
bool capture = rule.Condition == MetaConditionType.ChatMessageCapture;
long consumed = _evalRule != null && _chatConsumed.TryGetValue(_evalRule, out long c) ? c : 0;
DateTime now = Clock();
for (int i = 0; i < _chatLines.Count; i++)
{
ChatLine line = _chatLines[i];
if (line.Seq <= consumed) continue;
if ((now - line.At).TotalSeconds > 1.0) continue;
if (capture && !ChatColorListAllows(rule.ChatColors, line.Type)) continue;
var match = RegexCache.Match(line.Text, rule.ConditionData);
if (!match.Success) continue;
if (line.Seq > _evalChatSeq) _evalChatSeq = line.Seq;
if (capture)
{
_lastChatMatch = match;
// VTank: each named group goes to capturegroup_<name>, the line's
// colour (chat type) to capturecolor.
foreach (Group g in match.Groups)
if (!int.TryParse(g.Name, out _))
Expressions.SetVariable("capturegroup_" + g.Name, g.Value);
Expressions.SetVariable("capturecolor", line.Type.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
return true;
}
return false;
}
/// <summary>VTank ChatCapture colour list ("2;4"): empty matches any line. A line
/// whose chat type the engine didn't give (-1) isn't filtered.</summary>
private static bool ChatColorListAllows(string? colors, int chatType)
{
if (string.IsNullOrWhiteSpace(colors) || chatType < 0) return true;
foreach (string part in colors.Split(new[] { ';', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries))
if (int.TryParse(part, out int id) && id == chatType) return true;
return false;
}
// ── Action execution ─────────────────────────────────────────────────────
private void ExecuteAction(MetaRule rule)
@ -701,7 +830,9 @@ internal sealed class MetaManager
string callState = ProcessData(rule.ActionData);
if (!string.IsNullOrEmpty(callState))
{
_stateStack.Push(_settings.CurrentState);
// VTank pushes the rule's ReturnState; empty (older RynthAi rules) = this state.
string ret = ProcessData(rule.CallReturnState);
_stateStack.Push(string.IsNullOrEmpty(ret) ? _settings.CurrentState : ret);
_settings.CurrentState = callState;
_settings.ForceStateReset = true;
}
@ -796,7 +927,7 @@ internal sealed class MetaManager
_watchdogState = parts[0].Trim();
if (!float.TryParse(parts[1].Trim(), out _watchdogMetersRequired)) _watchdogMetersRequired = 5f;
if (!double.TryParse(parts[2].Trim(), out _watchdogSecondsConfig)) _watchdogSecondsConfig = 5.0;
_watchdogExpiration = DateTime.Now.AddSeconds(_watchdogSecondsConfig);
_watchdogExpiration = Clock().AddSeconds(_watchdogSecondsConfig);
if (_host.HasGetPlayerPose &&
_host.TryGetPlayerPose(out _, out float wx, out float wy, out float wz, out _, out _, out _, out _))
_lastWatchdogPos = new Vector3(wx, wy, wz);
@ -810,12 +941,26 @@ internal sealed class MetaManager
case MetaActionType.SetRAOption:
{
// VTank SetOpt {Option} {Expression}: evaluate the expression and set the
// real option, the same way '/vt opt set' does. It used to store the raw
// text in a private option table nothing reads, so SetOpt {EnableNav} {True}
// (and every other SetOpt) did nothing.
string optData = ProcessData(rule.ActionData);
if (!string.IsNullOrEmpty(optData))
{
var parts = optData.Split(';');
var parts = optData.Split(';', 2);
if (parts.Length >= 2)
Expressions.SetOption(parts[0].Trim(), parts[1].Trim());
{
string raw = parts[1].Trim();
string value = Expressions.Evaluate(raw);
if (value.StartsWith("ERR:", StringComparison.Ordinal))
{
_lastExprError = $"{rule.State}: SetOpt {parts[0].Trim()}: {Truncate(value, 100)}";
_lastExprErrorAt = Clock();
value = raw;
}
TrySetVtOption(parts[0].Trim(), value);
}
}
break;
}
@ -830,7 +975,7 @@ internal sealed class MetaManager
{
string varName = parts[0].Trim();
string optName = parts[1].Trim();
Expressions.SetVariable(varName, Expressions.GetOption(optName));
Expressions.SetVariable(varName, GetVtOption(optName) ?? "0");
}
}
break;
@ -876,7 +1021,7 @@ internal sealed class MetaManager
{
_viewsWarned = true;
_lastExprError = $"{rule.Action} ignored — VTank Views are not supported in RynthAi";
_lastExprErrorAt = DateTime.Now;
_lastExprErrorAt = Clock();
_host.WriteToChat("[RynthAi] Meta uses VTank Views (CreateView/DestroyView) — not supported; those actions are ignored.", 1);
_host.Log($"[Meta] {rule.Action} ignored — VTank Views unsupported");
}
@ -909,6 +1054,38 @@ internal sealed class MetaManager
return TrySetVtOption(optName, optVal);
}
// /vt opt get <option> — show one option's value.
if (sub == "opt" && parts.Length >= 4 &&
parts[2].Equals("get", StringComparison.OrdinalIgnoreCase))
{
string optName = parts[3];
_host.WriteToChat($"[RynthAi] {optName} = {GetVtOption(optName) ?? "(not set)"}", 1);
return true;
}
// /vt opt list — every VTank option RynthAi maps, with its value.
if (sub == "opt" && parts.Length >= 3 &&
parts[2].Equals("list", StringComparison.OrdinalIgnoreCase))
{
var line = new System.Text.StringBuilder();
foreach (string name in System.Linq.Enumerable.OrderBy(VtOptionMap.Keys, k => k, StringComparer.OrdinalIgnoreCase))
{
string item = $"{name}={GetVtOption(name) ?? "?"}";
if (line.Length + item.Length > 180) { _host.WriteToChat("[RynthAi] " + line, 1); line.Clear(); }
if (line.Length > 0) line.Append(", ");
line.Append(item);
}
if (line.Length > 0) _host.WriteToChat("[RynthAi] " + line, 1);
return true;
}
// /vt start | /vt stop — the macro, as VTank's own start/stop.
if (sub is "start" or "stop")
{
_raCommandHandler?.Invoke("/ra " + sub);
return true;
}
// /vt meta load <name> — load a meta file from MetaFiles folder
if (sub == "meta" && parts.Length >= 4 &&
parts[2].Equals("load", StringComparison.OrdinalIgnoreCase))
@ -932,8 +1109,9 @@ internal sealed class MetaManager
_settings.EmbeddedNavs.Clear();
foreach (var kvp in loaded.EmbeddedNavs)
_settings.EmbeddedNavs[kvp.Key] = kvp.Value;
_settings.CurrentState = loaded.Rules[0].State;
_settings.CurrentState = loaded.StartState;
_settings.ForceStateReset = true;
_settings.MetaCallStackReset = true;
_settings.CurrentMetaPath = loadPath;
_host.WriteToChat(
$"[RynthAi] Loaded meta '{name}': {loaded.Rules.Count} rules, {loaded.EmbeddedNavs.Count} navs"
@ -956,12 +1134,14 @@ internal sealed class MetaManager
}
// /vt nav load <name> — load a nav route
// It used to store only the bare name as the nav path, so nothing loaded.
// /vt nav save <name> saves the current route under that name.
if (sub == "nav" && parts.Length >= 4 &&
parts[2].Equals("load", StringComparison.OrdinalIgnoreCase))
(parts[2].Equals("load", StringComparison.OrdinalIgnoreCase)
|| parts[2].Equals("save", StringComparison.OrdinalIgnoreCase)))
{
string name = string.Join(" ", parts, 3, parts.Length - 3);
_settings.CurrentNavPath = name;
_host.WriteToChat($"[RynthAi] Nav route set: {name}", 1);
_raCommandHandler?.Invoke($"/ra nav {parts[2].ToLowerInvariant()} {name}");
return true;
}
@ -969,9 +1149,27 @@ internal sealed class MetaManager
if ((sub == "loot" || sub == "lootprofile") && parts.Length >= 4 &&
parts[2].Equals("load", StringComparison.OrdinalIgnoreCase))
{
string name = string.Join(" ", parts, 3, parts.Length - 3);
_settings.CurrentLootPath = name;
_host.WriteToChat($"[RynthAi] Loot profile set: {name}", 1);
string name = string.Join(" ", parts, 3, parts.Length - 3).Trim().Trim('"');
// A bare name is a file in LootProfiles (.utl, else .json). Storing the
// bare name made the loader report "not found" and looting stopped.
string path = name;
if (!File.Exists(path))
{
string folder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
string stem = name.EndsWith(".utl", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".json", StringComparison.OrdinalIgnoreCase)
? name : name + ".utl";
string candidate = Path.Combine(folder, stem);
if (!File.Exists(candidate) && !stem.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
candidate = Path.Combine(folder, name + ".json");
path = candidate;
}
if (!File.Exists(path))
{
_host.WriteToChat($"[RynthAi] Loot profile not found: {name}", 1);
return true;
}
_settings.CurrentLootPath = path;
_host.WriteToChat($"[RynthAi] Loot profile set: {Path.GetFileName(path)}", 1);
return true;
}
@ -990,7 +1188,7 @@ internal sealed class MetaManager
// /vt <verb> aliases → existing /ra handlers (Phase 1.3 VTank-meta migration).
// Re-dispatch through the /ra path (_raCommandHandler → HandleRaCommand).
if (sub is "forcebuff" or "cancelforcebuff" or "addnavpt")
if (sub is "forcebuff" or "cancelforcebuff" or "addnavpt" or "mexec" or "clearbusy")
{
_raCommandHandler?.Invoke("/ra " + string.Join(" ", parts, 1, parts.Length - 1));
return true;
@ -1039,6 +1237,24 @@ internal sealed class MetaManager
return false;
}
/// <summary>The RynthAi setting a VTank option name maps to (EnableNav → EnableNavigation).</summary>
internal static bool TryMapVtOption(string vtName, out string raName)
{
if (VtOptionMap.TryGetValue(vtName, out string? n)) { raName = n; return true; }
raName = "";
return false;
}
/// <summary>VTank bool text (true/false/on/off, any case) as 1/0; anything else unchanged.</summary>
internal static string NormalizeVtValue(string vtValue) => vtValue.ToLowerInvariant() switch
{
"true" => "1",
"false" => "0",
"on" => "1",
"off" => "0",
_ => vtValue
};
// VTank option name → RynthAi settings mapping
private static readonly Dictionary<string, string> VtOptionMap = new(StringComparer.OrdinalIgnoreCase)
{
@ -1063,12 +1279,16 @@ internal sealed class MetaManager
// Phase 1.2 VTank-meta migration aliases (targets verified in BuildSettingsMap)
["autocram"] = "EnableAutocram",
["autostack"] = "EnableAutostack",
["readunknownscrolls"] = "ReadUnknownScrolls", // VTank: loots and reads unknown scrolls
["usedispelitems"] = "UseDispelItems",
["castdispelself"] = "CastDispelSelf",
["opendoorrange"] = "OpenDoorRange",
// Phase 2 migration: vital recharge is 2-tier — norm = with-target/in-combat,
// notarg = idle/no-target (RynthAi has both: HealAt/… vs TopOff…). Percent 0-100.
["recharge-norm-hitp"] = "HealAt",
["usekitsinmagicmode"] = "UseKitsInMagicMode",
["gotopeacemodetousekits"] = "PeaceModeForKits",
["stopmacroondeath"] = "StopMacroOnDeath",
["recharge-norm-mana"] = "GetManaAt",
["recharge-norm-stam"] = "RestamAt",
["recharge-notarg-hitp"] = "TopOffHP",
@ -1079,30 +1299,46 @@ internal sealed class MetaManager
["corpseapproachrange-min"] = "CorpseApproachRangeMin",
["manastonelootcount"] = "ManaStoneKeepCount",
["rebuftimeremainingseconds"] = "RebuffSecondsRemaining",
["navclosestoprange"] = "NavCloseStopRange", // landblock fraction; nav reads ×240
// VTank's "Follow/Nav Min Distance" box: landblock units (x240 = yards). The settings map
// converts it into FollowNavMin, the nav point reach (see ExpressionEngine).
["navclosestoprange"] = "NavCloseStopRange",
["follownavmin"] = "FollowNavMin", // RynthAi's own name, yards
};
/// <summary>A VTank option's current value (mapped setting, else a stored generic option).</summary>
private string? GetVtOption(string vtName)
{
var map = Expressions.BuildSettingsMapPublic();
if (VtOptionMap.TryGetValue(vtName, out string? raName))
{
if (map.TryGetValue(raName, out var entry)) return entry.Get();
}
// A RynthAi setting named directly (EnableCombat, OpenDoors, NavCloseStopRange...).
if (map.TryGetValue(vtName, out var direct)) return direct.Get();
string v = Expressions.GetOption(vtName);
return string.IsNullOrEmpty(v) ? null : v;
}
private bool TrySetVtOption(string vtName, string vtValue)
{
// Translate VTank bool strings to numeric
string value = vtValue.ToLower() switch
{
"true" => "1",
"false" => "0",
"on" => "1",
"off" => "0",
_ => vtValue
};
string value = NormalizeVtValue(vtValue);
var map = Expressions.BuildSettingsMapPublic();
if (VtOptionMap.TryGetValue(vtName, out string? raName))
{
var map = Expressions.BuildSettingsMapPublic();
if (map.TryGetValue(raName, out var entry))
{
entry.Set(value);
return true;
}
}
// A RynthAi setting named directly (EnableCombat, OpenDoors, NavCloseStopRange...).
if (map.TryGetValue(vtName, out var direct))
{
direct.Set(value);
return true;
}
// Not mapped — store as a generic option so expressions can still read it
Expressions.SetOption(vtName, value);
@ -1141,6 +1377,7 @@ internal sealed class MetaManager
private void RebuildStateIndex()
{
_stateIndex.Clear();
_chatConsumed.Clear(); // drop rules that are gone; at worst a line is seen again
var list = _settings.MetaRules;
foreach (var r in list)
{
@ -1170,20 +1407,20 @@ internal sealed class MetaManager
MacroRunning = _settings.IsMacroRunning,
MetaEnabled = _settings.EnableMeta,
CurrentState = _settings.CurrentState ?? "",
SecondsInState = (DateTime.Now - _stateStartTime).TotalSeconds,
SecondsInState = (Clock() - _stateStartTime).TotalSeconds,
StackDepth = _stateStack.Count,
WatchdogActive = _watchdogActive,
WatchdogState = _watchdogState ?? "",
WatchdogSecondsRemaining = _watchdogActive
? Math.Max(0, (_watchdogExpiration - DateTime.Now).TotalSeconds) : 0,
? Math.Max(0, (_watchdogExpiration - Clock()).TotalSeconds) : 0,
LastFiredState = _lastFiredState,
LastFiredCondition = _lastFiredCond,
LastFiredAction = _lastFiredAct,
LastFiredSecondsAgo = _lastFiredAt == DateTime.MinValue
? -1 : (DateTime.Now - _lastFiredAt).TotalSeconds,
? -1 : (Clock() - _lastFiredAt).TotalSeconds,
LastExprError = _lastExprError,
LastExprErrorSecondsAgo = _lastExprErrorAt == DateTime.MinValue
? -1 : (DateTime.Now - _lastExprErrorAt).TotalSeconds,
? -1 : (Clock() - _lastExprErrorAt).TotalSeconds,
};
if (_settings.MetaRules != null)
lock (_settings.MetaRulesLock)

View file

@ -0,0 +1,761 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json.Serialization;
namespace RynthCore.Plugin.RynthAi.Meta;
// ============================================================================
// Meta Manager ("schedule"): loads a different meta when a timer runs out.
// Design: Docs\META_MANAGER.md. This class is the whole decision - pure, no
// host, the clock passed in - so the tests drive it directly. The glue in
// RynthAiPlugin.MetaSchedule.cs feeds it chat lines and the bot's state on
// RynthAi's pump and carries out what Tick returns (send /myquests, load a meta).
// ============================================================================
internal enum ScheduleTrigger
{
/// <summary>The named quest's /myquests timer has run out (or it has never been done).</summary>
QuestReady = 0,
/// <summary>The current meta has been loaded for N minutes.</summary>
AfterMinutesOnMeta = 1,
/// <summary>N minutes since the manager was switched on or the rule last fired.</summary>
EveryMinutes = 2,
/// <summary>A countdown the player starts has run out.</summary>
Countdown = 3,
}
/// <summary>One "when TRIGGER, load META" rule. Also the wire format of the engine's mm_add / mm_update.</summary>
internal sealed class MetaScheduleRule
{
public bool Enabled { get; set; } = true;
public ScheduleTrigger Trigger { get; set; }
/// <summary>QuestReady: the quest's name as /myquests prints it (case is ignored).</summary>
public string Quest { get; set; } = string.Empty;
/// <summary>The time triggers' N.</summary>
public double Minutes { get; set; } = 30;
/// <summary>The meta to load: a file name in MetaFiles (farm.met, farm.af; no extension tries .af then .met).</summary>
public string Meta { get; set; } = string.Empty;
/// <summary>Only fire while this meta is loaded (file name, extension ignored). Empty = any.</summary>
public string OnlyOnMeta { get; set; } = string.Empty;
/// <summary>False = one-shot: fires once, then stays <see cref="Fired"/> until reset.</summary>
public bool Repeat { get; set; } = true;
/// <summary>A one-shot rule that has fired. Saved.</summary>
public bool Fired { get; set; }
/// <summary>Countdown end (unix ms), 0 = not running. Saved, so a countdown survives a relog.</summary>
public long CountdownEndsUnixMs { get; set; }
// ── Runtime only ────────────────────────────────────────────────────
/// <summary>A repeating quest rule that fired and whose quest is still ready: it holds first place.</summary>
[JsonIgnore] public bool Latched;
[JsonIgnore] public DateTime EveryAnchorUtc = DateTime.MinValue;
[JsonIgnore] public int FireCount;
[JsonIgnore] public DateTime LastFiredUtc = DateTime.MinValue;
/// <summary>Why the last load failed; the rule is skipped until reset or edited.</summary>
[JsonIgnore] public string Error = string.Empty;
/// <summary>A copy of the saved settings (runtime state starts fresh).</summary>
public MetaScheduleRule CloneSettings() => new()
{
Enabled = Enabled, Trigger = Trigger, Quest = Quest ?? string.Empty, Minutes = Minutes,
Meta = Meta ?? string.Empty, OnlyOnMeta = OnlyOnMeta ?? string.Empty, Repeat = Repeat,
Fired = Fired, CountdownEndsUnixMs = CountdownEndsUnixMs,
};
}
/// <summary>Everything saved in &lt;character folder&gt;\metamanager.json.</summary>
internal sealed class MetaScheduleConfig
{
public bool Enabled { get; set; }
public int PollMinutes { get; set; } = 5;
public int MaxWaitSeconds { get; set; } = 60;
public int MinGapSeconds { get; set; } = 30;
public bool AllowWhileStopped { get; set; }
public List<MetaScheduleRule> Rules { get; set; } = new();
}
/// <summary>What the bot is doing this tick, gathered by the glue.</summary>
internal readonly record struct ScheduleInputs(
bool InWorld, bool MacroRunning, string CurrentMetaPath, string? Blocker, bool CanPoll);
internal enum ScheduleActionKind { None, SendPoll, LoadMeta }
/// <summary>What the glue must do now. LoadMeta: load <see cref="Meta"/> and print the reason.</summary>
internal readonly record struct ScheduleAction(
ScheduleActionKind Kind, int RuleIndex = -1, string Meta = "", string Reason = "", bool Forced = false)
{
public static readonly ScheduleAction None = new(ScheduleActionKind.None);
}
internal enum QuestState { Unknown, Ready, Waiting, Never }
internal sealed class MetaScheduler
{
public const double ReplySilenceSeconds = 1.5;
public const double ReplyTimeoutSeconds = 15;
/// <summary>How long after our poll the chat bar may still hand us our own "/myquests" back.</summary>
public const double OwnEchoSeconds = 5;
public const string ConfigFileName = "metamanager.json";
public MetaScheduleConfig Config { get; private set; } = new();
// ── Quest table ─────────────────────────────────────────────────────
private readonly Dictionary<string, MyQuestsEntry> _quests = new(StringComparer.OrdinalIgnoreCase);
private bool _haveFullList; // a whole reply was read: a quest missing from it was never done
private DateTime _lastPollUtc = DateTime.MinValue; // last poll sent, or last full reply of anyone's
private bool _serverDisabled;
// ── The reply in flight ─────────────────────────────────────────────
private enum ReplyOwner { None, Ours, Shown }
private ReplyOwner _owner;
private DateTime _querySentUtc, _lastReplyLineUtc;
private bool _gotReplyLine;
private readonly HashSet<string> _seenThisReply = new(StringComparer.OrdinalIgnoreCase);
private bool _expectOwnEcho;
// ── Switching ───────────────────────────────────────────────────────
private int _pendingRule = -1;
private DateTime _pendingSinceUtc;
private string _waitReason = string.Empty;
private DateTime _lastSwitchUtc = DateTime.MinValue;
private string _lastMetaPath = string.Empty;
private DateTime _metaSinceUtc = DateTime.MinValue;
private bool _dirty;
public string LastSwitchText { get; private set; } = string.Empty;
public int PendingRule => _pendingRule;
public string WaitReason => _waitReason;
public bool ServerDisabled => _serverDisabled;
public bool HaveQuestList => _haveFullList;
public int QuestCount => _quests.Count;
public DateTime LastPollUtc => _lastPollUtc;
public bool PollInFlight => _owner == ReplyOwner.Ours;
public DateTime LastSwitchUtc => _lastSwitchUtc;
/// <summary>True once after the saved settings changed (a fired one-shot, a countdown, an edit).</summary>
public bool ConsumeDirty()
{
bool d = _dirty;
_dirty = false;
return d;
}
// =====================================================================
// Settings
// =====================================================================
public void Load(MetaScheduleConfig? cfg)
{
Config = cfg ?? new MetaScheduleConfig();
Config.Rules ??= new List<MetaScheduleRule>();
Config.Rules.RemoveAll(r => r == null);
Config.PollMinutes = ClampPoll(Config.PollMinutes);
Config.MaxWaitSeconds = Math.Clamp(Config.MaxWaitSeconds, 0, 3600);
Config.MinGapSeconds = Math.Clamp(Config.MinGapSeconds, 0, 3600);
foreach (var r in Config.Rules) Sanitize(r);
_pendingRule = -1;
_waitReason = string.Empty;
_dirty = false;
}
public static int ClampPoll(int minutes) => Math.Clamp(minutes, 1, 1440);
private static void Sanitize(MetaScheduleRule r)
{
r.Quest = (r.Quest ?? string.Empty).Trim();
r.Meta = (r.Meta ?? string.Empty).Trim();
r.OnlyOnMeta = (r.OnlyOnMeta ?? string.Empty).Trim();
if (double.IsNaN(r.Minutes) || r.Minutes < 0) r.Minutes = 0;
if (r.Minutes > 100000) r.Minutes = 100000;
if (!Enum.IsDefined(r.Trigger)) r.Trigger = ScheduleTrigger.QuestReady;
}
public void SetEnabled(bool on)
{
if (Config.Enabled == on) return;
Config.Enabled = on;
if (on)
{
_serverDisabled = false; // try again: the server may have turned it on
foreach (var r in Config.Rules) r.EveryAnchorUtc = DateTime.MinValue;
}
_pendingRule = -1;
_waitReason = string.Empty;
_dirty = true;
}
public void SetPollMinutes(int m) { Config.PollMinutes = ClampPoll(m); _dirty = true; }
public void SetMaxWaitSeconds(int s) { Config.MaxWaitSeconds = Math.Clamp(s, 0, 3600); _dirty = true; }
public void SetMinGapSeconds(int s) { Config.MinGapSeconds = Math.Clamp(s, 0, 3600); _dirty = true; }
public void SetAllowWhileStopped(bool on) { Config.AllowWhileStopped = on; _dirty = true; }
public void AddRule(MetaScheduleRule rule)
{
var r = rule.CloneSettings();
r.Fired = false;
Sanitize(r);
Config.Rules.Add(r);
_pendingRule = -1;
_dirty = true;
}
/// <summary>Replaces rule <paramref name="index"/>'s settings. An edit re-arms it; a running countdown keeps running.</summary>
public bool UpdateRule(int index, MetaScheduleRule rule)
{
if (index < 0 || index >= Config.Rules.Count) return false;
var old = Config.Rules[index];
var r = rule.CloneSettings();
r.Fired = false;
r.CountdownEndsUnixMs = r.Trigger == ScheduleTrigger.Countdown && old.Trigger == ScheduleTrigger.Countdown
? old.CountdownEndsUnixMs : 0;
Sanitize(r);
Config.Rules[index] = r;
_pendingRule = -1;
_dirty = true;
return true;
}
public bool DeleteRule(int index)
{
if (index < 0 || index >= Config.Rules.Count) return false;
Config.Rules.RemoveAt(index);
_pendingRule = -1;
_dirty = true;
return true;
}
public bool MoveRule(int index, int direction)
{
int other = index + Math.Sign(direction);
if (index < 0 || index >= Config.Rules.Count || other < 0 || other >= Config.Rules.Count) return false;
(Config.Rules[index], Config.Rules[other]) = (Config.Rules[other], Config.Rules[index]);
_pendingRule = -1;
_dirty = true;
return true;
}
public bool SetRuleEnabled(int index, bool on)
{
if (index < 0 || index >= Config.Rules.Count) return false;
Config.Rules[index].Enabled = on;
_pendingRule = -1;
_dirty = true;
return true;
}
/// <summary>Starts rule <paramref name="index"/>'s countdown (its own minutes, or <paramref name="minutes"/>).</summary>
public bool StartCountdown(int index, double? minutes, DateTime now)
{
if (index < 0 || index >= Config.Rules.Count) return false;
var r = Config.Rules[index];
if (r.Trigger != ScheduleTrigger.Countdown) return false;
double m = minutes is > 0 ? minutes.Value : r.Minutes;
r.CountdownEndsUnixMs = ToUnixMs(now) + (long)(m * 60_000);
r.Fired = false;
r.Error = string.Empty;
_dirty = true;
return true;
}
public bool StopCountdown(int index)
{
if (index < 0 || index >= Config.Rules.Count) return false;
var r = Config.Rules[index];
if (r.CountdownEndsUnixMs == 0) return false;
r.CountdownEndsUnixMs = 0;
_dirty = true;
return true;
}
/// <summary>Re-arms a rule: not fired, not holding, no error, its "every" timer restarted.</summary>
public bool ResetRule(int index)
{
if (index < 0 || index >= Config.Rules.Count) return false;
var r = Config.Rules[index];
r.Fired = false;
r.Latched = false;
r.Error = string.Empty;
r.EveryAnchorUtc = DateTime.MinValue;
_pendingRule = -1;
_dirty = true;
return true;
}
/// <summary>The next Tick sends /myquests (if the manager is on and in world).</summary>
public void RequestPoll() => _lastPollUtc = DateTime.MinValue;
public bool HasQuestRules
{
get
{
foreach (var r in Config.Rules)
if (r.Enabled && r.Trigger == ScheduleTrigger.QuestReady && !(r.Fired && !r.Repeat) && r.Quest.Length > 0)
return true;
return false;
}
}
// =====================================================================
// /myquests replies
// =====================================================================
/// <summary>
/// A "/myquests" went out through the chat bar: typed by the player, sent by a script or
/// another plugin, or our own poll coming back through the plugins' chat-bar hook. Its reply
/// is shown - unless it is the echo of the poll we just sent.
/// </summary>
public void NoteTypedQuery(DateTime now)
{
if (_expectOwnEcho && (now - _querySentUtc).TotalSeconds <= OwnEchoSeconds)
{
_expectOwnEcho = false;
return;
}
NoteShownQuery(now);
}
/// <summary>Someone other than the manager asked (RynthAi's quest refresh): don't eat that reply.</summary>
public void NoteShownQuery(DateTime now)
{
if (_owner == ReplyOwner.None)
{
_seenThisReply.Clear();
_gotReplyLine = false;
}
_owner = ReplyOwner.Shown; // a query on top of ours: show the rest of the lines
_querySentUtc = now;
_expectOwnEcho = false;
}
private void BeginOwnPoll(DateTime now)
{
_owner = ReplyOwner.Ours;
_querySentUtc = now;
_gotReplyLine = false;
_seenThisReply.Clear();
_expectOwnEcho = true;
_lastPollUtc = now;
}
/// <summary>Every incoming chat line. Returns true to eat it (it answers our own poll).</summary>
public bool OnChatLine(string? text, DateTime now)
{
MyQuestsLineKind kind = MyQuestsParser.Parse(text, out MyQuestsEntry entry);
if (kind == MyQuestsLineKind.None) return false;
bool eat = _owner == ReplyOwner.Ours;
switch (kind)
{
case MyQuestsLineKind.Quest:
_quests[entry.Name] = entry;
if (_owner != ReplyOwner.None)
{
_seenThisReply.Add(entry.Name);
_gotReplyLine = true;
_lastReplyLineUtc = now;
}
break;
case MyQuestsLineKind.Empty:
_quests.Clear();
_haveFullList = true;
if (_owner != ReplyOwner.Ours) _lastPollUtc = now; // someone else's full list counts as a poll
_owner = ReplyOwner.None;
break;
case MyQuestsLineKind.Disabled:
_serverDisabled = true;
_owner = ReplyOwner.None;
break;
case MyQuestsLineKind.RateLimited:
_owner = ReplyOwner.None;
break;
}
return eat;
}
private void TickReply(DateTime now)
{
if (_owner == ReplyOwner.None) return;
if (_gotReplyLine)
{
if ((now - _lastReplyLineUtc).TotalSeconds >= ReplySilenceSeconds)
{
// The whole list arrived: a quest that is not in it has never been done.
var gone = new List<string>();
foreach (string k in _quests.Keys) if (!_seenThisReply.Contains(k)) gone.Add(k);
foreach (string k in gone) _quests.Remove(k);
_haveFullList = true;
// Our polls keep their send time (a steady interval); someone else's full list counts as a poll.
if (_owner != ReplyOwner.Ours) _lastPollUtc = now;
_owner = ReplyOwner.None;
}
}
else if ((now - _querySentUtc).TotalSeconds >= ReplyTimeoutSeconds)
{
_owner = ReplyOwner.None; // nothing came back; try again at the next poll
}
if (_expectOwnEcho && (now - _querySentUtc).TotalSeconds > OwnEchoSeconds) _expectOwnEcho = false;
}
public QuestState GetQuestState(string quest, DateTime now, out DateTime readyAtUtc)
{
readyAtUtc = DateTime.MinValue;
if (string.IsNullOrWhiteSpace(quest)) return QuestState.Unknown;
if (_quests.TryGetValue(quest.Trim(), out MyQuestsEntry e))
{
if (e.AtSolveLimit) { readyAtUtc = DateTime.MaxValue; return QuestState.Never; }
readyAtUtc = e.ReadyAtUtc;
return now >= readyAtUtc ? QuestState.Ready : QuestState.Waiting;
}
// Not in a full list = never done = can be solved now (ACE: no registry entry → can solve).
return _haveFullList ? QuestState.Ready : QuestState.Unknown;
}
// =====================================================================
// Tick
// =====================================================================
public ScheduleAction Tick(DateTime now, in ScheduleInputs inputs)
{
string path = inputs.CurrentMetaPath ?? string.Empty;
if (_metaSinceUtc == DateTime.MinValue || !string.Equals(path, _lastMetaPath, StringComparison.OrdinalIgnoreCase))
{
_lastMetaPath = path;
_metaSinceUtc = now;
}
TickReply(now);
if (!Config.Enabled)
{
_pendingRule = -1;
_waitReason = string.Empty;
return ScheduleAction.None;
}
foreach (var r in Config.Rules)
if (r.Trigger == ScheduleTrigger.EveryMinutes && r.EveryAnchorUtc == DateTime.MinValue)
r.EveryAnchorUtc = now;
if (inputs.InWorld && inputs.CanPoll && !_serverDisabled && _owner == ReplyOwner.None && HasQuestRules
&& (_lastPollUtc == DateTime.MinValue || (now - _lastPollUtc).TotalMinutes >= ClampPoll(Config.PollMinutes)))
{
BeginOwnPoll(now);
return new ScheduleAction(ScheduleActionKind.SendPoll);
}
// A repeating quest rule that fired re-arms once its quest is seen waiting again.
foreach (var r in Config.Rules)
if (r.Latched && GetQuestState(r.Quest, now, out _) is QuestState.Waiting or QuestState.Never)
r.Latched = false;
int win = FindWinner(now, path);
if (win != _pendingRule)
{
_pendingRule = win;
_pendingSinceUtc = now;
}
if (win < 0)
{
_waitReason = string.Empty;
return ScheduleAction.None;
}
if (!inputs.InWorld)
{
_waitReason = "not in world";
_pendingSinceUtc = now;
return ScheduleAction.None;
}
if (!inputs.MacroRunning && !Config.AllowWhileStopped)
{
_waitReason = "macro stopped";
_pendingSinceUtc = now; // the wait cap only counts while the macro runs
return ScheduleAction.None;
}
DateTime gapEnds = _lastSwitchUtc == DateTime.MinValue ? DateTime.MinValue : _lastSwitchUtc.AddSeconds(Config.MinGapSeconds);
if (now < gapEnds)
{
_waitReason = "minimum gap";
return ScheduleAction.None;
}
// The safe-switch wait starts when the rule won or the gap ended, whichever is later.
DateTime waitStart = _pendingSinceUtc > gapEnds ? _pendingSinceUtc : gapEnds;
bool capped = (now - waitStart).TotalSeconds >= Config.MaxWaitSeconds;
if (inputs.Blocker != null && !capped)
{
_waitReason = inputs.Blocker;
return ScheduleAction.None;
}
var rule = Config.Rules[win];
string reason = ReasonText(rule, path);
if (inputs.Blocker != null) reason += $"; waited {Config.MaxWaitSeconds} s for {inputs.Blocker}";
MarkFired(rule, now, reason);
return new ScheduleAction(ScheduleActionKind.LoadMeta, win, rule.Meta, reason, inputs.Blocker != null);
}
/// <summary>The meta could not be loaded: the rule shows the error and is skipped until reset or edited.</summary>
public void ReportLoadFailed(int index, string error)
{
if (index < 0 || index >= Config.Rules.Count) return;
Config.Rules[index].Error = string.IsNullOrEmpty(error) ? "load failed" : error;
LastSwitchText = $"failed: {Config.Rules[index].Meta} ({Config.Rules[index].Error})";
}
/// <summary>
/// First due rule, top to bottom. A repeating quest rule that already fired and whose
/// quest is still ready holds first place: nothing below it fires (returns -1).
/// </summary>
public int FindWinner(DateTime now, string currentMetaPath)
{
for (int i = 0; i < Config.Rules.Count; i++)
{
var r = Config.Rules[i];
if (!r.Enabled || (r.Fired && !r.Repeat) || r.Error.Length > 0) continue;
if (r.Trigger == ScheduleTrigger.QuestReady && r.Latched)
{
if (GetQuestState(r.Quest, now, out _) == QuestState.Ready) return -1;
continue;
}
if (!MetaMatches(r.OnlyOnMeta, currentMetaPath)) continue;
if (IsDue(r, now)) return i;
}
return -1;
}
public bool IsDue(MetaScheduleRule r, DateTime now)
{
if (r.Meta.Length == 0) return false;
switch (r.Trigger)
{
case ScheduleTrigger.QuestReady:
return GetQuestState(r.Quest, now, out _) == QuestState.Ready;
case ScheduleTrigger.AfterMinutesOnMeta:
return _metaSinceUtc != DateTime.MinValue && (now - _metaSinceUtc).TotalMinutes >= r.Minutes;
case ScheduleTrigger.EveryMinutes:
return r.EveryAnchorUtc != DateTime.MinValue && (now - r.EveryAnchorUtc).TotalMinutes >= r.Minutes;
case ScheduleTrigger.Countdown:
return r.CountdownEndsUnixMs != 0 && ToUnixMs(now) >= r.CountdownEndsUnixMs;
}
return false;
}
private void MarkFired(MetaScheduleRule r, DateTime now, string reason)
{
r.FireCount++;
r.LastFiredUtc = now;
_lastSwitchUtc = now;
_metaSinceUtc = now; // a reload of the same meta counts as a new load
_pendingRule = -1;
_waitReason = string.Empty;
if (!r.Repeat) r.Fired = true;
switch (r.Trigger)
{
case ScheduleTrigger.QuestReady: r.Latched = r.Repeat; break;
case ScheduleTrigger.EveryMinutes: r.EveryAnchorUtc = now; break;
case ScheduleTrigger.Countdown:
r.CountdownEndsUnixMs = r.Repeat ? ToUnixMs(now) + (long)(r.Minutes * 60_000) : 0;
break;
}
LastSwitchText = $"{r.Meta} ({reason})";
_dirty = true;
}
public static string ReasonText(MetaScheduleRule r, string currentMetaPath) => r.Trigger switch
{
ScheduleTrigger.QuestReady => $"quest {r.Quest} ready",
ScheduleTrigger.AfterMinutesOnMeta => $"{Num(r.Minutes)} min on {(currentMetaPath.Length > 0 ? Path.GetFileName(currentMetaPath) : "no meta")}",
ScheduleTrigger.EveryMinutes => $"every {Num(r.Minutes)} min",
ScheduleTrigger.Countdown => $"{Num(r.Minutes)} min countdown done",
_ => "timer",
};
public static string TriggerText(MetaScheduleRule r) => r.Trigger switch
{
ScheduleTrigger.QuestReady => $"quest {(r.Quest.Length > 0 ? r.Quest : "?")} ready",
ScheduleTrigger.AfterMinutesOnMeta => $"after {Num(r.Minutes)} min on the meta",
ScheduleTrigger.EveryMinutes => $"every {Num(r.Minutes)} min",
ScheduleTrigger.Countdown => $"countdown {Num(r.Minutes)} min",
_ => "?",
};
/// <summary>Only-on filter: empty matches anything; names compare without extension, ignoring case.</summary>
public static bool MetaMatches(string onlyOn, string currentMetaPath)
{
if (string.IsNullOrWhiteSpace(onlyOn)) return true;
if (string.IsNullOrEmpty(currentMetaPath)) return false;
return string.Equals(Path.GetFileNameWithoutExtension(onlyOn.Trim()),
Path.GetFileNameWithoutExtension(currentMetaPath), StringComparison.OrdinalIgnoreCase);
}
private static string Num(double v) => v.ToString("0.##", CultureInfo.InvariantCulture);
public static long ToUnixMs(DateTime utc) => (long)(utc - DateTime.UnixEpoch).TotalMilliseconds;
/// <summary>A never-done quest's ready time (unix ms 1; 0 means "unknown" in the snapshot).</summary>
private static readonly DateTime NeverDoneReadyAt = DateTime.UnixEpoch.AddMilliseconds(1);
// =====================================================================
// Status (chat) and snapshot (engine panel)
// =====================================================================
/// <summary>When rule <paramref name="r"/> is due: a time, MaxValue = never, null = not known / not running.</summary>
public DateTime? DueAt(MetaScheduleRule r, DateTime now)
{
switch (r.Trigger)
{
case ScheduleTrigger.QuestReady:
return GetQuestState(r.Quest, now, out DateTime at) switch
{
QuestState.Unknown => null,
QuestState.Never => DateTime.MaxValue,
// Never done: "ready since forever" (a fixed time, so the snapshot doesn't change every call).
QuestState.Ready => at == DateTime.MinValue ? NeverDoneReadyAt : at,
_ => at,
};
case ScheduleTrigger.AfterMinutesOnMeta:
return _metaSinceUtc == DateTime.MinValue ? null : _metaSinceUtc.AddMinutes(r.Minutes);
case ScheduleTrigger.EveryMinutes:
return r.EveryAnchorUtc == DateTime.MinValue ? null : r.EveryAnchorUtc.AddMinutes(r.Minutes);
case ScheduleTrigger.Countdown:
return r.CountdownEndsUnixMs == 0 ? null : DateTime.UnixEpoch.AddMilliseconds(r.CountdownEndsUnixMs);
}
return null;
}
/// <summary>A rule's state in a few words, or "" when its due time says it all.</summary>
public string RuleState(int index, DateTime now)
{
var r = Config.Rules[index];
if (!r.Enabled) return "off";
if (r.Error.Length > 0) return "error: " + r.Error;
if (r.Fired && !r.Repeat) return "fired (one-shot)";
if (r.Meta.Length == 0) return "no meta picked";
if (index == _pendingRule && _waitReason.Length > 0) return "waiting: " + _waitReason;
if (index == _pendingRule) return "switching";
if (r.Trigger == ScheduleTrigger.QuestReady)
{
if (r.Quest.Length == 0) return "no quest named";
QuestState qs = GetQuestState(r.Quest, now, out _);
if (r.Latched && qs == QuestState.Ready) return "fired, holding while the quest is ready";
if (qs == QuestState.Unknown) return _serverDisabled ? "/myquests is off on this server" : "no /myquests yet";
if (qs == QuestState.Never) return "never (solve limit reached)";
}
if (r.Trigger == ScheduleTrigger.Countdown && r.CountdownEndsUnixMs == 0) return "not started";
return string.Empty;
}
/// <summary>The /ra metamgr status lines.</summary>
public List<string> StatusLines(DateTime now, string currentMetaPath)
{
var lines = new List<string>();
var c = Config;
string poll = !HasQuestRules ? "no quest rules, not polling"
: _serverDisabled ? "the server has /myquests off"
: _lastPollUtc == DateTime.MinValue ? $"polls every {c.PollMinutes} min"
: $"polls every {c.PollMinutes} min, last {Ago(now - _lastPollUtc)} ago, {_quests.Count} quest(s)";
lines.Add($"Meta Manager is {(c.Enabled ? "ON" : "OFF")}: {c.Rules.Count} rule(s); {poll}; wait up to {c.MaxWaitSeconds} s, gap {c.MinGapSeconds} s{(c.AllowWhileStopped ? ", switches while stopped" : "")}.");
int win = c.Enabled ? FindWinner(now, currentMetaPath) : -1;
for (int i = 0; i < c.Rules.Count; i++)
{
var r = c.Rules[i];
string when = RuleState(i, now);
if (when.Length == 0)
{
DateTime? due = DueAt(r, now);
when = due == null ? "?" : due.Value <= now ? "ready" : "in " + Ago(due.Value - now);
}
string mark = i == win ? " <- first match" : "";
lines.Add($"#{i + 1} when {TriggerText(r)}{(r.OnlyOnMeta.Length > 0 ? $" (on {r.OnlyOnMeta})" : "")}, load {(r.Meta.Length > 0 ? r.Meta : "?")}"
+ $" [{(r.Repeat ? "repeat" : "once")}] - {when}{(r.FireCount > 0 ? $", fired {r.FireCount}x" : "")}{mark}");
}
if (LastSwitchText.Length > 0) lines.Add("Last: " + LastSwitchText);
return lines;
}
public static string Ago(TimeSpan t)
{
if (t < TimeSpan.Zero) t = TimeSpan.Zero;
if (t.TotalHours >= 24) return $"{(int)t.TotalDays}d {t.Hours}h";
if (t.TotalMinutes >= 60) return $"{(int)t.TotalHours}h {t.Minutes:00}m";
if (t.TotalSeconds >= 60) return $"{(int)t.TotalMinutes}m {t.Seconds:00}s";
return $"{(int)t.TotalSeconds}s";
}
/// <summary>
/// The engine panel's snapshot (the "schedule" object in RynthPluginGetMetaJson). Times are
/// absolute (unix ms) so the text only changes on events; the panel counts down itself.
/// dueAtMs: 0 = unknown / not running, -1 = never.
/// </summary>
public string BuildSnapshotJson(DateTime now, string currentMetaPath)
{
var c = Config;
var inv = CultureInfo.InvariantCulture;
var sb = new StringBuilder(256 + c.Rules.Count * 200);
sb.Append('{');
Bool(sb, "enabled", c.Enabled).Append(',');
sb.Append("\"pollMinutes\":").Append(c.PollMinutes).Append(',');
sb.Append("\"maxWaitSeconds\":").Append(c.MaxWaitSeconds).Append(',');
sb.Append("\"minGapSeconds\":").Append(c.MinGapSeconds).Append(',');
Bool(sb, "allowWhileStopped", c.AllowWhileStopped).Append(',');
Bool(sb, "polling", c.Enabled && HasQuestRules && !_serverDisabled).Append(',');
Bool(sb, "serverDisabled", _serverDisabled).Append(',');
Bool(sb, "haveQuestList", _haveFullList).Append(',');
sb.Append("\"questCount\":").Append(_quests.Count).Append(',');
sb.Append("\"lastPollMs\":").Append(_lastPollUtc == DateTime.MinValue ? 0 : ToUnixMs(_lastPollUtc)).Append(',');
Str(sb, "lastSwitch", LastSwitchText).Append(',');
sb.Append("\"lastSwitchMs\":").Append(_lastSwitchUtc == DateTime.MinValue ? 0 : ToUnixMs(_lastSwitchUtc)).Append(',');
int win = c.Enabled ? (_pendingRule >= 0 ? _pendingRule : FindWinner(now, currentMetaPath)) : -1;
sb.Append("\"firstMatch\":").Append(win).Append(',');
sb.Append("\"rules\":[");
for (int i = 0; i < c.Rules.Count; i++)
{
var r = c.Rules[i];
if (i > 0) sb.Append(',');
sb.Append('{');
Bool(sb, "enabled", r.Enabled).Append(',');
sb.Append("\"trigger\":").Append((int)r.Trigger).Append(',');
Str(sb, "quest", r.Quest).Append(',');
sb.Append("\"minutes\":").Append(r.Minutes.ToString("0.###", inv)).Append(',');
Str(sb, "meta", r.Meta).Append(',');
Str(sb, "onlyOnMeta", r.OnlyOnMeta).Append(',');
Bool(sb, "repeat", r.Repeat).Append(',');
Bool(sb, "fired", r.Fired).Append(',');
sb.Append("\"fireCount\":").Append(r.FireCount).Append(',');
sb.Append("\"lastFiredMs\":").Append(r.LastFiredUtc == DateTime.MinValue ? 0 : ToUnixMs(r.LastFiredUtc)).Append(',');
DateTime? due = DueAt(r, now);
long dueMs = due == null ? 0 : due.Value == DateTime.MaxValue ? -1 : ToUnixMs(due.Value);
sb.Append("\"dueAtMs\":").Append(dueMs).Append(',');
Str(sb, "state", RuleState(i, now));
sb.Append('}');
}
sb.Append("]}");
return sb.ToString();
}
private static StringBuilder Bool(StringBuilder sb, string key, bool v)
=> sb.Append('"').Append(key).Append("\":").Append(v ? "true" : "false");
private static StringBuilder Str(StringBuilder sb, string key, string v)
{
sb.Append('"').Append(key).Append("\":\"");
foreach (char ch in v ?? string.Empty)
{
switch (ch)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (ch < 0x20) sb.Append("\\u").Append(((int)ch).ToString("X4", CultureInfo.InvariantCulture));
else sb.Append(ch);
break;
}
}
return sb.Append('"');
}
}

View file

@ -0,0 +1,81 @@
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>What one chat line is, as far as /myquests goes.</summary>
internal enum MyQuestsLineKind
{
/// <summary>Not a /myquests line.</summary>
None,
/// <summary>One quest: <see cref="MyQuestsEntry"/>.</summary>
Quest,
/// <summary>"Quest list is empty." - the whole (empty) reply.</summary>
Empty,
/// <summary>The server has /myquests turned off.</summary>
Disabled,
/// <summary>GDLe-style "This command may only be run once every ..." (ACE never sends it).</summary>
RateLimited,
}
/// <summary>One /myquests line. Times are the server's unix seconds.</summary>
internal readonly record struct MyQuestsEntry(
string Name, int Solves, long LastSolvedUnix, string Message, int MaxSolves, long MinDeltaSeconds)
{
/// <summary>ACE: a quest with a solve limit (MaxSolves &gt; -1) that has reached it can never be solved again.</summary>
public bool AtSolveLimit => MaxSolves > -1 && Solves >= MaxSolves;
/// <summary>When the timer runs out (last solve + min delta); MaxValue at the solve limit.</summary>
public DateTime ReadyAtUtc => AtSolveLimit
? DateTime.MaxValue
: DateTime.UnixEpoch.AddSeconds((double)LastSolvedUnix + MinDeltaSeconds);
/// <summary>ACE QuestManager.GetNextSolveTime == MinValue: not at the limit and the timer has run out.</summary>
public bool IsReady(DateTime utcNow) => !AtSolveLimit && utcNow >= ReadyAtUtc;
}
/// <summary>
/// Parses ACE's /myquests reply (ACE.Server PlayerCommands.HandleQuests, "GDLe formatting
/// to match plugin expectations"). One Broadcast line per quest:
/// <code>{name lower} - {solves} solves ({last solved unix})"{quest message}" {max solves} {min delta}</code>
/// e.g. <c>stipendtimer_monthly - 2 solves (1759276800)"Monthly stipend" -1 2592000</c>.
/// The min delta is already scaled by the server's quest_mindelta_rate.
/// </summary>
internal static class MyQuestsParser
{
// The name is lowercase and has no spaces in practice; allow anything up to " - N solves (".
// The message is greedy up to the last '" ' so a quote inside it can't cut it short.
private static readonly Regex QuestLine = new(
"^(?<name>\\S.*?) - (?<solves>-?\\d+) solves \\((?<last>\\d+)\\)\"(?<msg>.*)\" (?<max>-?\\d+) (?<delta>\\d+)$",
RegexOptions.CultureInvariant);
public const string EmptyText = "Quest list is empty.";
public const string DisabledText = "The command \"myquests\" is not currently enabled on this server.";
public static MyQuestsLineKind Parse(string? text, out MyQuestsEntry entry)
{
entry = default;
if (string.IsNullOrEmpty(text)) return MyQuestsLineKind.None;
string line = text.Trim();
if (line.Length == 0) return MyQuestsLineKind.None;
if (line.Equals(EmptyText, StringComparison.Ordinal)) return MyQuestsLineKind.Empty;
if (line.Equals(DisabledText, StringComparison.Ordinal)) return MyQuestsLineKind.Disabled;
if (line.StartsWith("This command may only be run once every", StringComparison.Ordinal)) return MyQuestsLineKind.RateLimited;
// Cheap pre-check before the regex: every quest line has " solves (".
if (line.IndexOf(" solves (", StringComparison.Ordinal) < 0) return MyQuestsLineKind.None;
Match m = QuestLine.Match(line);
if (!m.Success) return MyQuestsLineKind.None;
if (!int.TryParse(m.Groups["solves"].Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int solves)
|| !long.TryParse(m.Groups["last"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out long last)
|| !int.TryParse(m.Groups["max"].Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int max)
|| !long.TryParse(m.Groups["delta"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out long delta))
return MyQuestsLineKind.None;
entry = new MyQuestsEntry(m.Groups["name"].Value.Trim(), solves, last, m.Groups["msg"].Value, max, delta);
return MyQuestsLineKind.Quest;
}
}

View file

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// Items this plugin just used, or used something on (Host.ObjectUsed), whose
/// identified properties may now be out of date: uses left on a pet essence after
/// summoning or refilling, a kit's uses, a stack's size. The expression engine
/// re-identifies them on the next property read (ExpressionEngine.EnsureIdentified),
/// so metas don't act on the value from before the use. Engine-independent, so it
/// also covers engines whose property-update hook is missing or broken.
/// </summary>
internal static class ObjectChangeTracker
{
private static readonly Dictionary<uint, long> _changedAtSec = new();
public static void MarkChanged(uint id)
{
if (id == 0) return;
lock (_changedAtSec)
{
if (_changedAtSec.Count > 500) _changedAtSec.Clear();
_changedAtSec[id] = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
}
}
/// <summary>
/// True while <paramref name="id"/> changed after its last identify
/// (<paramref name="lastIdUnixSec"/>). A later identify clears it.
/// </summary>
public static bool IsStale(uint id, long lastIdUnixSec)
{
lock (_changedAtSec)
{
if (!_changedAtSec.TryGetValue(id, out long changed)) return false;
if (lastIdUnixSec > changed) { _changedAtSec.Remove(id); return false; }
return true;
}
}
public static void Clear()
{
lock (_changedAtSec) _changedAtSec.Clear();
}
}

View file

@ -59,11 +59,24 @@ internal sealed class QuestTracker
{
if (_refreshing || !_host.HasInvokeChatParser)
return;
ExpectReply();
RefreshSent?.Invoke();
_host.InvokeChatParser("/myquests");
}
/// <summary>Set by the plugin: told whenever Refresh sends /myquests (the Meta Manager shows that reply).</summary>
public Action? RefreshSent;
/// <summary>
/// Someone else (the Meta Manager's poll) just sent /myquests: read the reply into the
/// cache as if Refresh had sent it, so quest expressions stay fresh.
/// </summary>
public void ExpectReply()
{
_refreshing = true;
_gotFirstQuest = false;
_lastLineTime = DateTime.UtcNow;
_refreshStarted = DateTime.UtcNow;
_host.InvokeChatParser("/myquests");
}
/// <summary>

View file

@ -46,6 +46,20 @@ internal sealed class NavMarkerRenderer
private readonly LegacyUiSettings _settings;
private int _frameCount;
/// <summary>The raycast geometry (dungeon cells, terrain), once loaded; lines follow the floor with it.</summary>
internal Func<Raycasting.GeometryLoader?>? GeometrySource { get; set; }
// Floor-following lines: a straight segment between two points on a slope or stairs
// cut through the floor. Each segment is split into ~1.5 m steps set on the floor
// below them (dungeon floor by a down-ray, terrain height outside). Worked out once per
// route and landblock, cached by segment.
private const float FloorStep = 1.5f;
private object? _floorRoute;
private int _floorRouteCount;
private uint _floorBlock;
private readonly System.Collections.Generic.Dictionary<(int, int), float[]> _floorCache = new();
private uint _frameCell;
public NavMarkerRenderer(RynthCoreHost host, LegacyUiSettings settings)
{
_host = host;
@ -119,6 +133,7 @@ internal sealed class NavMarkerRenderer
if (!_host.TryGetPlayerPose(out uint cellId, out px, out py, out pz,
out _, out _, out _, out _))
return false;
_frameCell = cellId;
// Don't paint during portal animation — portalspace has landblock 0x0000,
// but also check IsPortaling() for the brief window before cellId zeroes out.
@ -128,7 +143,9 @@ internal sealed class NavMarkerRenderer
return false;
route = r;
ringRadius = Math.Max(0.1f, _settings.FollowNavMin);
// The ring is the nav point reach: same floor as NavigationEngine.ArrivalYards (rings were drawn
// down to 0.1 while nav still went to 1.5). Doorway points use their own tighter reach (pass 1).
ringRadius = Math.Max(LegacyUiSettings.FollowNavMinLowest, _settings.FollowNavMin);
heightOffset = _settings.NavHeightOffset;
// Render a contiguous window of the route centered on the active
@ -147,8 +164,7 @@ internal sealed class NavMarkerRenderer
}
else
{
int active = _settings.ActiveNavIndex;
if (active < 0 || active >= n) active = 0;
int active = WindowCenter(r, playerNS, playerEW);
int half = count / 2;
if (r.RouteType == NavRouteType.Circular)
winStart = ((active - half) % n + n) % n;
@ -158,6 +174,51 @@ internal sealed class NavMarkerRenderer
return true;
}
private int _nearestIdx = -1;
private int _nearestFrame;
private NavRouteParser? _nearestRoute;
/// <summary>
/// Route index the marker window is centred on: the active waypoint while it's
/// near the player, otherwise the waypoint nearest the player. With the macro
/// off after a recall, the active waypoint can be far away, which left a long
/// route's markers drawn only around that distant spot and none nearby.
/// </summary>
private int WindowCenter(NavRouteParser r, double playerNS, double playerEW)
{
int n = r.Points.Count;
int active = _settings.ActiveNavIndex;
if (active < 0 || active >= n) active = 0;
var ap = r.Points[active];
double adN = ap.NS - playerNS, adE = ap.EW - playerEW;
if (!HasGroundCoords(ap.Type) || Math.Sqrt(adN * adN + adE * adE) * 240.0 <= NearActiveYards)
return active;
if (!ReferenceEquals(r, _nearestRoute) || _frameCount - _nearestFrame >= 15 || _nearestIdx >= n)
{
_nearestRoute = r;
_nearestFrame = _frameCount;
_nearestIdx = active;
double best = double.MaxValue;
for (int i = 0; i < n; i++)
{
var p = r.Points[i];
if (!HasGroundCoords(p.Type)) continue;
double dN = p.NS - playerNS, dE = p.EW - playerEW;
double d = dN * dN + dE * dE;
if (d < best) { best = d; _nearestIdx = i; }
}
}
return _nearestIdx;
}
private const double NearActiveYards = 60.0;
// Waypoints whose coordinates are real ground positions (drawn as markers).
// Recall/Portal/Chat/Pause carry placeholder coordinates and are skipped.
private static bool HasGroundCoords(NavPointType t)
=> NavRouteParser.IsPlainWaypoint(t) || t == NavPointType.Jump;
// Absolute route index of the k-th point in the render window. The modulo
// wraps circular routes; for non-circular routes winStart is clamped so the
// window never runs off the end and the modulo is a no-op.
@ -205,7 +266,7 @@ internal sealed class NavMarkerRenderer
// placeholder coordinates (a PortalNPC coord pointing "to the
// abyss" is the recurring case), so a ring drawn there floats far
// off in empty space.
if (pt.Type != NavPointType.Point)
if (!HasGroundCoords(pt.Type))
continue;
// D3D coords: X=EW, Y=height(up), Z=NS
@ -220,7 +281,8 @@ internal sealed class NavMarkerRenderer
uint color = isActive ? ColorRed3D : ColorCyan3D;
float thick = isActive ? ringThick * 1.3f : ringThick;
_host.Nav3DAddRing(wx, wy, wz, ringRadius, thick, color);
float reach = pt.Doorway ? Math.Min(ringRadius, (float)NavigationEngine.DoorwayReachYd) : ringRadius;
_host.Nav3DAddRing(wx, wy, wz, reach, thick, color);
}
@ -231,15 +293,32 @@ internal sealed class NavMarkerRenderer
// portal, you don't walk — so no segment should span it (this is what
// produced the "line to the abyss", whether to the portal's placeholder
// coord or onward to the post-teleport destination point).
PrepareFloorCache(route);
for (int k = 0; k < count; k++)
{
if (!validArr[k]) continue;
int nk = NextInWindow(k, count, n, circular);
if (nk < 0 || nk >= count || !validArr[nk]) continue;
_host.Nav3DAddLine(wxArr[k], wyArr[k], wzArr[k],
wxArr[nk], wyArr[nk], wzArr[nk],
lineThick, ColorLine3D);
float[]? heights = FloorHeights(WindowAbsIdx(winStart, k, n), WindowAbsIdx(winStart, nk, n),
wxArr[k], wyArr[k], wzArr[k], wxArr[nk], wyArr[nk], wzArr[nk], heightOffset);
if (heights == null)
{
_host.Nav3DAddLine(wxArr[k], wyArr[k], wzArr[k],
wxArr[nk], wyArr[nk], wzArr[nk],
lineThick, ColorLine3D);
continue;
}
// heights[s] is the line's height at step s of heights.Length-1 equal steps.
int steps = heights.Length - 1;
for (int s = 0; s < steps; s++)
{
float t0 = (float)s / steps, t1 = (float)(s + 1) / steps;
_host.Nav3DAddLine(
wxArr[k] + (wxArr[nk] - wxArr[k]) * t0, heights[s], wzArr[k] + (wzArr[nk] - wzArr[k]) * t0,
wxArr[k] + (wxArr[nk] - wxArr[k]) * t1, heights[s + 1], wzArr[k] + (wzArr[nk] - wzArr[k]) * t1,
lineThick, ColorLine3D);
}
}
// ── Pass 3: live portal marker + line ────────────────────────
@ -262,6 +341,83 @@ internal sealed class NavMarkerRenderer
}
}
private void PrepareFloorCache(NavRouteParser route)
{
uint block = _frameCell >> 16;
if (!ReferenceEquals(route, _floorRoute) || route.Points.Count != _floorRouteCount || block != _floorBlock)
{
_floorCache.Clear();
_floorRoute = route;
_floorRouteCount = route.Points.Count;
_floorBlock = block;
}
}
/// <summary>
/// Line heights at equal steps from point a to point b following the floor, or null when
/// the segment is short, flat, or no floor data is available (draw it straight). The frame
/// here is the player's landblock: x = EW metres, y = height, z = NS metres.
/// </summary>
private float[]? FloorHeights(int ia, int ib, float ax, float ay, float az, float bx, float by, float bz, float lift)
{
if (_floorCache.TryGetValue((ia, ib), out float[]? cached)) return cached.Length == 0 ? null : cached;
float[]? result = ComputeFloorHeights(ax, ay, az, bx, by, bz, lift);
_floorCache[(ia, ib)] = result ?? Array.Empty<float>();
return result;
}
private float[]? ComputeFloorHeights(float ax, float ay, float az, float bx, float by, float bz, float lift)
{
var geo = GeometrySource?.Invoke();
if (geo == null) return null;
float dx = bx - ax, dz = bz - az;
float run = MathF.Sqrt(dx * dx + dz * dz);
if (run < FloorStep * 1.5f) return null;
uint cell = _frameCell;
bool dungeon = (cell & 0xFFFF) >= 0x0100;
float baseX = ((cell >> 24) & 0xFF) * 192f, baseY = ((cell >> 16) & 0xFF) * 192f;
System.Collections.Generic.List<Raycasting.BoundingVolume>? geometry = dungeon ? geo.GetLandblockGeometry(cell) : null;
if (dungeon && (geometry == null || geometry.Count == 0)) return null;
int steps = Math.Clamp((int)MathF.Ceiling(run / FloorStep), 2, 64);
var heights = new float[steps + 1];
bool anyFloor = false;
for (int s = 0; s <= steps; s++)
{
float t = (float)s / steps;
float lineY = ay + (by - ay) * t; // straight-line height (already lifted)
float gx = baseX + ax + dx * t, gy = baseY + az + dz * t;
float floor = dungeon ? DungeonFloor(geometry!, gx, gy, lineY - lift) : geo.GetTerrainZWorld(gx, gy);
// Only snap to a floor near the straight line: never to a floor on another level.
if (!float.IsNaN(floor) && MathF.Abs(floor + lift - lineY) < 4f)
{
heights[s] = floor + lift;
anyFloor = true;
}
else heights[s] = lineY;
}
// Keep the ends on the rings.
heights[0] = ay;
heights[steps] = by;
return anyFloor ? heights : null;
}
/// <summary>Highest floor at or below (gx, gy, nearZ + 2): a down-ray against the dungeon's cell geometry.</summary>
private static float DungeonFloor(System.Collections.Generic.List<Raycasting.BoundingVolume> geometry, float gx, float gy, float nearZ)
{
var origin = new Raycasting.Vector3(gx, gy, nearZ + 2f);
var down = new Raycasting.Vector3(0, 0, -1);
float best = float.MaxValue;
foreach (var v in geometry)
{
if (v.IsDoor) continue;
if (v.RayIntersect(origin, down, 6f, out float d) && d < best) best = d;
}
return best == float.MaxValue ? float.NaN : origin.Z - best;
}
// ═══════════════════════════════════════════════════════════════════
// ImGui fallback path — 2D projected lines (original implementation)
// ═══════════════════════════════════════════════════════════════════
@ -317,7 +473,7 @@ internal sealed class NavMarkerRenderer
// placeholder coordinates (a PortalNPC coord pointing "to the
// abyss" is the recurring case), so a ring drawn there floats far
// off in empty space.
if (pt.Type != NavPointType.Point)
if (!HasGroundCoords(pt.Type))
continue;
float wx = px + (float)((pt.EW - playerEW) * 240.0);
@ -365,7 +521,7 @@ internal sealed class NavMarkerRenderer
// placeholder coordinates (a PortalNPC coord pointing "to the
// abyss" is the recurring case), so a ring drawn there floats far
// off in empty space.
if (pt.Type != NavPointType.Point)
if (!HasGroundCoords(pt.Type))
continue;
float cx = px + (float)((pt.EW - playerEW) * 240.0);

View file

@ -0,0 +1,432 @@
// ============================================================================
// NavRecovery.cs — the planning half of nav stuck / off-track recovery.
//
// NavigationEngine decides WHEN to recover (stuck watchdog, off-track check)
// and walks the result. This class answers two questions for it:
//
// 1. TryPlan: a walkable way from the character to a route waypoint.
// Indoors (the character is in an EnvCell and the waypoint is in the same
// cell graph): DungeonPathfinder A* over the EnvCell portal graph, laid out
// by DungeonPathfinder.BuildPathPoints: approach and exit points centred on
// the real doorway openings (DungeonGeometry), rooms crossed directly.
// Outdoors: RynthNav's navmesh through the "RynthNav.Path" plugin interface
// (Shared/RynthNavPathApi.cs), resolved again on every call.
// Neither: no plan, and the engine falls back to the jump / side-step ladder.
//
// 2. CheckArea: is the route waypoint in a different area from the character
// (a dungeon vs the landscape, or another dungeon)? No pathfinder can join
// those, so the engine holds navigation instead of running the ladder.
//
// Units: nav coordinates (NS/EW, 1.0 = 240 world units) and world units, which
// the rest of the nav code calls yards. Everything runs on the plugin pump thread.
// All caches are instance fields; the engine drops this object at session teardown.
// ============================================================================
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>What a recovery plan looks like to the engine.</summary>
internal sealed class NavRecoveryPlan
{
/// <summary>Detour points to walk, in order. The route waypoint itself is not included.</summary>
public List<NavPoint> Points = new();
/// <summary>Straight-line length of player → points → route waypoint, in yards.</summary>
public double LengthYd;
/// <summary>"dungeon map" or "RynthNav navmesh".</summary>
public string Planner = string.Empty;
/// <summary>Doorways (dungeon portals) the path goes through.</summary>
public int Doorways;
}
/// <summary>Result of <see cref="NavRecoveryPlanner.CheckArea"/>.</summary>
internal enum NavAreaCheck
{
/// <summary>Same area, or nothing contradicts it.</summary>
Match,
/// <summary>Can't tell yet (dats not loaded, no pose). Treated as a match.</summary>
Unknown,
/// <summary>The waypoint is in another dungeon, or dungeon vs landscape.</summary>
Mismatch,
}
/// <summary>The two questions NavigationEngine asks a planner (lets tests supply a fake).</summary>
internal interface INavRecoveryPlanner
{
NavRecoveryPlan? TryPlan(NavPoint target, out string why);
NavAreaCheck CheckArea(uint playerCell, double tNs, double tEw, out string routeArea, out string playerArea);
}
internal sealed class NavRecoveryPlanner : INavRecoveryPlanner
{
// A dungeon waypoint is always inside some cell; its distance to that cell's centre
// is at most about half the biggest room. Used to decide "this waypoint is in that
// cell graph" for both planning and the area check.
private const double DungeonCellReachYd = 30.0;
// Building interiors on the landscape are small; a waypoint farther than this from
// every building cell is outdoors, not inside.
private const double BuildingCellReachYd = 8.0;
// Area check: dungeon cells can sit outside their landblock's 192-unit square, so a
// waypoint that maps to a neighbouring landblock still counts as "in this dungeon"
// when it is this close to one of its cells.
private const double AreaCellReachYd = 60.0;
private const int MaxNavmeshCorners = 128;
private readonly RynthCoreHost _host;
private readonly Func<MainLogic?> _raycast;
private readonly Func<IReadOnlySet<uint>?> _hazards;
// Per-session caches (dropped with this object).
private readonly Dictionary<uint, bool> _dungeonLandblock = new();
public NavRecoveryPlanner(RynthCoreHost host, Func<MainLogic?> raycast, Func<IReadOnlySet<uint>?> hazards)
{
_host = host;
_raycast = raycast;
_hazards = hazards;
}
private DatDatabase? CellDat
{
get
{
var ray = _raycast();
var dat = ray?.GeometryLoader?.CellDat;
return dat != null && dat.IsLoaded ? dat : null;
}
}
// ══════════════════════════════════════════════════════════════════════
// PLANNING
// ══════════════════════════════════════════════════════════════════════
/// <summary>
/// Plans a walkable way from the character to <paramref name="target"/>. Returns null
/// with <paramref name="why"/> set when no pathfinder can help (the caller then uses
/// the old escape ladder).
/// </summary>
public NavRecoveryPlan? TryPlan(NavPoint target, out string why)
{
why = string.Empty;
if (!_host.HasGetPlayerPose ||
!_host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz, out _, out _, out _, out _) ||
!NavCoordinateHelper.TryConvertPoseToCoords(cell, lx, ly, out double pNs, out double pEw))
{
why = "no player position";
return null;
}
// Route Z is stored as world z / 240; 0 means "not recorded", so use ours.
float tz = target.Z != 0.0 ? (float)(target.Z * 240.0) : lz;
bool inEnvCell = (cell & 0xFFFF) >= 0x0100;
string indoorWhy = string.Empty;
if (inEnvCell)
{
var plan = PlanIndoor(cell, pNs, pEw, lz, target.NS, target.EW, tz, out bool applicable, out indoorWhy);
if (plan != null) return plan;
if (applicable) { why = indoorWhy; return null; }
// In a dungeon the landscape navmesh is meaningless: a tile baked for this
// landblock (the bake-ahead watcher bakes around wherever the player is) is
// flat ground at height 0, and a path on it walks through the dungeon walls.
var cellDat = CellDat;
if (cellDat != null && IsDungeonLandblock(cell >> 16, cellDat))
{
why = indoorWhy.Length > 0 ? indoorWhy : "no dungeon map path";
return null;
}
// Inside a building with the waypoint outdoors: try the navmesh.
}
var outdoor = PlanOutdoor(cell, lx, ly, lz, target.NS, target.EW, tz, out string outdoorWhy);
if (outdoor != null) return outdoor;
why = indoorWhy.Length > 0 ? $"{indoorWhy}; {outdoorWhy}" : outdoorWhy;
return null;
}
private NavRecoveryPlan? PlanIndoor(uint playerCell, double pNs, double pEw, float pz,
double tNs, double tEw, float tz,
out bool applicable, out string why)
{
applicable = false;
why = string.Empty;
var cellDat = CellDat;
if (cellDat == null) { why = "dungeon data not loaded yet"; return null; }
uint lb = playerCell >> 16;
var graph = DungeonPathfinder.GetGraph(lb, cellDat);
if (graph.Count == 0) { why = "no cell graph here"; return null; }
// The waypoint's room is the cell whose FLOOR contains it. The nearest cell centre was
// wrong for a waypoint just behind a wall in a big room: it named the player's own room,
// "already in the waypoint's room, the map has no way around", and the bot ran into the
// wall for an hour (Lucy, 6346, 2026-10-01). Nearest centre is only the fallback.
uint goal = ContainingCell(lb, NavToWorld(tEw), NavToWorld(tNs), tz);
if (goal == 0 || !graph.ContainsKey(goal))
goal = DungeonPathfinder.NearestCell(graph, tNs, tEw, tz);
if (goal == 0 || !graph.TryGetValue(goal, out var goalNode)) { why = "waypoint not on the dungeon map"; return null; }
bool dungeon = IsDungeonLandblock(lb, cellDat);
double reach = dungeon ? DungeonCellReachYd : BuildingCellReachYd;
if (NavYd(goalNode.NS - tNs, goalNode.EW - tEw) > reach)
{
why = dungeon ? "waypoint isn't near any room of this dungeon" : "waypoint is outside this building";
return null; // not applicable: let the navmesh try
}
applicable = true;
uint start = graph.ContainsKey(playerCell) ? playerCell : DungeonPathfinder.NearestCell(graph, pNs, pEw, pz);
if (start == 0) { why = "can't place you on the dungeon map"; return null; }
if (start == goal) { why = "already in the waypoint's room, the map has no way around"; return null; }
var path = DungeonPathfinder.FindPath(start, goal, graph, _hazards());
if (path.Count < 2) { why = "no walkable way on the dungeon map"; return null; }
// The same points the dungeon patrol uses: an approach and an exit point centred on
// every narrow opening (flagged, so the engine goes through straight), rooms crossed
// directly. Without the map geometry, cell-centre midpoints.
var plan = new NavRecoveryPlan { Planner = "dungeon map" };
var geo = DungeonPathfinder.GetGeometry(lb, cellDat, _raycast()?.GeometryLoader?.DungeonLOS);
plan.Points = DungeonPathfinder.BuildPathPoints(path, graph, geo, _hazards(), pNs, pEw, pz, tNs, tEw, tz, out int doorways);
plan.Doorways = doorways;
if (plan.Points.Count == 0) { why = "empty path"; return null; }
plan.LengthYd = PathLengthYd(pNs, pEw, plan.Points, tNs, tEw);
return plan;
}
private NavRecoveryPlan? PlanOutdoor(uint cell, float lx, float ly, float lz,
double tNs, double tEw, float tz, out string why)
{
why = string.Empty;
if (!_host.HasGetPluginInterface) { why = "RynthNav needs a newer RynthCore"; return null; }
double sx = ((cell >> 24) & 0xFF) * 192.0 + lx;
double sy = ((cell >> 16) & 0xFF) * 192.0 + ly;
double gx = (tEw * 10.0 + 1019.5) * 24.0;
double gy = (tNs * 10.0 + 1019.5) * 24.0;
int result;
int count = 0;
double[] buf = new double[MaxNavmeshCorners * 3];
unsafe
{
// Resolved on every call: RynthNav may be missing, or reloaded since last time.
IntPtr p = _host.GetPluginInterface(RynthNavPathApiV1.PluginName, RynthNavPathApiV1.InterfaceName, RynthNavPathApiV1.InterfaceVersion);
var t = (RynthNavPathApiV1*)p;
if (t == null || t->Version < 1 || t->StructSize < (uint)sizeof(RynthNavPathApiV1) || t->FindPath == null)
{
why = "RynthNav isn't loaded";
return null;
}
fixed (double* pts = buf)
result = t->FindPath(sx, sy, lz, gx, gy, tz, pts, MaxNavmeshCorners, &count);
}
if (result == RynthNavPathApiV1.ResultNoMesh) { why = "no RynthNav navmesh here"; return null; }
if (result != RynthNavPathApiV1.ResultOk || count < 2) { why = "RynthNav found no walkable way"; return null; }
var plan = new NavRecoveryPlan { Planner = "RynthNav navmesh" };
// Corners 1..count-2 are the turns; the first is our position and the last the waypoint.
for (int i = 1; i < count - 1; i++)
{
double wx = buf[i * 3], wy = buf[i * 3 + 1], wz = buf[i * 3 + 2];
plan.Points.Add(new NavPoint
{
Type = NavPointType.Point,
EW = (wx / 24.0 - 1019.5) / 10.0,
NS = (wy / 24.0 - 1019.5) / 10.0,
Z = wz / 240.0,
});
}
if (plan.Points.Count == 0) { why = "RynthNav sees a clear straight line (the snag isn't on its map)"; return null; }
double pNs = (sy / 24.0 - 1019.5) / 10.0, pEw = (sx / 24.0 - 1019.5) / 10.0;
plan.LengthYd = PathLengthYd(pNs, pEw, plan.Points, tNs, tEw);
return plan;
}
// ══════════════════════════════════════════════════════════════════════
// AREA CHECK (route in another dungeon / on the landscape)
// ══════════════════════════════════════════════════════════════════════
/// <summary>
/// Compares where the character is with where route waypoint (tNs, tEw) is. On a
/// mismatch, <paramref name="routeArea"/> and <paramref name="playerArea"/> name the
/// two places for the chat line ("dungeon 0x01D9", "the landscape").
/// </summary>
public NavAreaCheck CheckArea(uint playerCell, double tNs, double tEw, out string routeArea, out string playerArea)
{
routeArea = string.Empty;
playerArea = string.Empty;
var cellDat = CellDat;
if (cellDat == null || playerCell == 0) return NavAreaCheck.Unknown;
return ClassifyArea(playerCell, tNs, tEw,
lb => IsDungeonLandblock(lb, cellDat),
(lb, ns, ew) => NearAnyCell(lb, cellDat, ns, ew),
out routeArea, out playerArea);
}
/// <summary>
/// The decision half of <see cref="CheckArea"/>, given the two dat lookups: is a
/// landblock a dungeon, and is (ns, ew) within reach of one of that landblock's cells.
/// </summary>
internal static NavAreaCheck ClassifyArea(uint playerCell, double tNs, double tEw,
Func<uint, bool> isDungeonLandblock, Func<uint, double, double, bool> nearAnyCell,
out string routeArea, out string playerArea)
{
routeArea = string.Empty;
playerArea = string.Empty;
double wx = NavToWorld(tEw), wy = NavToWorld(tNs);
if (wx < 0 || wy < 0 || wx >= 256 * 192.0 || wy >= 256 * 192.0) return NavAreaCheck.Unknown;
uint tLb = ((uint)(wx / 192.0) << 8) | (uint)(wy / 192.0);
uint pLb = playerCell >> 16;
bool playerInDungeon = (playerCell & 0xFFFF) >= 0x0100 && isDungeonLandblock(pLb);
if (playerInDungeon)
{
if (tLb == pLb) return NavAreaCheck.Match;
if (nearAnyCell(pLb, tNs, tEw)) return NavAreaCheck.Match;
routeArea = isDungeonLandblock(tLb) ? $"dungeon 0x{tLb:X4}" : "the landscape";
playerArea = $"in dungeon 0x{pLb:X4}";
return NavAreaCheck.Mismatch;
}
// Inside a cell of a landblock that doesn't pass the dungeon test: a building, or a
// dungeon the test misses (the excluded north-west corner, one with terrain). Its
// rooms can map onto a neighbouring dungeon landblock, so nothing is provable.
if ((playerCell & 0xFFFF) >= 0x0100) return NavAreaCheck.Match;
// On the landscape.
if (!isDungeonLandblock(tLb)) return NavAreaCheck.Match;
if (!nearAnyCell(tLb, tNs, tEw)) return NavAreaCheck.Match; // not provably in a dungeon cell
routeArea = $"dungeon 0x{tLb:X4}";
playerArea = "on the landscape";
return NavAreaCheck.Mismatch;
}
private static bool NearAnyCell(uint lb, DatDatabase cellDat, double ns, double ew)
{
var graph = DungeonPathfinder.GetGraph(lb, cellDat);
foreach (var node in graph.Values)
if (NavYd(node.NS - ns, node.EW - ew) <= AreaCellReachYd) return true;
return false;
}
/// <summary>
/// A landblock with no landscape of its own: every terrain height 0, at least one
/// EnvCell, and no buildings (the same test ACE uses). The far north-west corner is
/// excluded because some real landscape there is flat at height 0.
/// </summary>
public bool IsDungeonLandblock(uint lb, DatDatabase cellDat)
{
if (_dungeonLandblock.TryGetValue(lb, out bool cached)) return cached;
bool result = ComputeIsDungeon(lb, cellDat);
if (_dungeonLandblock.Count > 512) _dungeonLandblock.Clear();
_dungeonLandblock[lb] = result;
return result;
}
private static bool ComputeIsDungeon(uint lb, DatDatabase cellDat)
{
try
{
uint x = (lb >> 8) & 0xFF, y = lb & 0xFF;
if (x < 0x08 && y > 0xF8) return false;
byte[]? info = cellDat.GetFileData((lb << 16) | 0xFFFE);
if (info == null || info.Length < 12) return false;
uint numCells = BitConverter.ToUInt32(info, 4);
if (numCells == 0) return false;
uint numObjects = BitConverter.ToUInt32(info, 8);
long buildingsAt = 12 + (long)numObjects * 32;
if (buildingsAt + 2 <= info.Length && BitConverter.ToUInt16(info, (int)buildingsAt) > 0) return false;
// CellLandblock: id, hasObjects, ushort terrain[81], byte height[81].
byte[]? land = cellDat.GetFileData((lb << 16) | 0xFFFF);
const int heightsAt = 8 + 81 * 2;
if (land == null || land.Length < heightsAt + 81) return false;
for (int i = 0; i < 81; i++)
if (land[heightsAt + i] != 0) return false;
return true;
}
catch
{
return false;
}
}
// ── Helpers ─────────────────────────────────────────────────────────────
private static double NavToWorld(double navCoord) => (navCoord * 10.0 + 1019.5) * 24.0;
/// <summary>The cell whose floor polygon contains (wx, wy) at height wz (world space), from
/// the dungeon map geometry DungeonLOS caches; 0 when unknown.</summary>
private uint ContainingCell(uint lb, double wx, double wy, float wz)
{
var los = _raycast()?.GeometryLoader?.DungeonLOS;
if (los == null) return 0;
try
{
// The physics floor polygons. GetDungeonMapPolygons (render geometry) never sets
// IsFloor, so filtering it on IsFloor matched nothing and the nearest-centre fallback
// always decided: the b66e790 fix never ran in game. That list holds ceilings too;
// only the polygons facing up are floors.
var polys = los.GetDungeonMapFloorPolygons(lb);
var floors = new List<(uint, Vector3[])>(polys.Count);
foreach (var p in polys)
if (!p.IsPortal && p.Vertices != null && DungeonGeometry.IsUpwardFloor(p.Vertices)) floors.Add((p.CellId, p.Vertices));
return PickContainingCell(floors, wx, wy, wz);
}
catch { return 0; }
}
/// <summary>
/// Of the floor polygons, the cell of the one under (wx, wy): the point inside it (2D) with
/// the floor at most 1 m above and 4 m below wz (stacked floors: the closest one under the
/// feet wins). 0 when no floor contains it.
/// </summary>
internal static uint PickContainingCell(IReadOnlyList<(uint CellId, Vector3[] Verts)> floors, double wx, double wy, float wz)
{
uint best = 0;
float bestDz = float.MaxValue;
foreach (var (cellId, v) in floors)
{
if (v.Length < 3 || !InsidePolygon2D(v, wx, wy)) continue;
float avgZ = 0;
foreach (var p in v) avgZ += p.Z;
avgZ /= v.Length;
float dz = wz - avgZ; // feet above the floor
if (!float.IsNaN(wz) && (dz < -1f || dz > 4f)) continue;
float score = float.IsNaN(wz) ? 0f : MathF.Abs(dz);
if (score < bestDz) { bestDz = score; best = cellId; }
}
return best;
}
private static bool InsidePolygon2D(Vector3[] v, double x, double y)
{
bool inside = false;
for (int i = 0, j = v.Length - 1; i < v.Length; j = i++)
{
double xi = v[i].X, yi = v[i].Y, xj = v[j].X, yj = v[j].Y;
if ((yi > y) != (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi)
inside = !inside;
}
return inside;
}
private static double NavYd(double dNs, double dEw) => Math.Sqrt(dNs * dNs + dEw * dEw) * 240.0;
private static double PathLengthYd(double fromNs, double fromEw, List<NavPoint> pts, double toNs, double toEw)
{
double len = 0, ns = fromNs, ew = fromEw;
foreach (var p in pts) { len += NavYd(p.NS - ns, p.EW - ew); ns = p.NS; ew = p.EW; }
return len + NavYd(toNs - ns, toEw - ew);
}
}

File diff suppressed because it is too large Load diff

View file

@ -11,13 +11,38 @@ namespace RynthCore.Plugin.RynthAi;
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthAiPlugin> Runtime = new();
internal static readonly RynthPluginRuntime<RynthAiPlugin> Runtime = new();
// Typed interfaces for other plugins (host GetPluginInterface, API v68): "RynthAi.Script" v1
// for RynthLua, "RynthAi.Status" v1 for RynthNet (the bot state it shares with the other clients). Fixed signature: void* (const char* iface, uint version).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version)
{
try
{
string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? "";
IntPtr table = ScriptInterface.Query(iface, version);
return table != IntPtr.Zero ? table : StatusInterface.Query(iface, version);
}
catch
{
return IntPtr.Zero;
}
}
[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();
public static void Shutdown()
{
Runtime.Shutdown();
StatusInterface.Release();
// The loot editor's state can be a few hundred KB (LootSnobV4): don't leave it behind on a reload.
foreach (IntPtr p in new[] { Interlocked.Exchange(ref _lootStatePtr, IntPtr.Zero),
Interlocked.Exchange(ref _lootRulePtr, IntPtr.Zero), Interlocked.Exchange(ref _lootVocabPtr, IntPtr.Zero) })
if (p != IntPtr.Zero) Marshal.FreeCoTaskMem(p);
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUIInitialized", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUIInitialized() => Runtime.OnUIInitialized();
@ -28,9 +53,6 @@ public static unsafe class PluginExports
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBarAction", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnBarAction() => Runtime.OnBarAction();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnSelectedTargetChange", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnSelectedTargetChange(uint currentTargetId, uint previousTargetId) => Runtime.OnSelectedTargetChange(currentTargetId, previousTargetId);
@ -43,9 +65,6 @@ public static unsafe class PluginExports
[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 = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
@ -195,7 +214,7 @@ public static unsafe class PluginExports
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginToggleMacro", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void ToggleMacro() => SafeInvoke(() => Runtime.Plugin?.DashboardRenderer?.TogglePanelMacro());
public static void ToggleMacro() => SafeInvoke(() => Runtime.Plugin?.ToggleMacroFromPanel()); // refuses a start while VTank runs
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetSubsystemEnabled", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetSubsystemEnabled(int subsystemId, int enabled)
@ -269,6 +288,26 @@ public static unsafe class PluginExports
}
private static IntPtr _monsterDamageJsonPtr = IntPtr.Zero;
private static IntPtr _monsterDetailJsonPtr = IntPtr.Zero;
// One monster's breakdown for the Damage tab's detail panel (freed on the next call).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetMonsterDetailJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetMonsterDetailJson(uint wcid)
{
try
{
string json = Runtime.Plugin?.BuildMonsterDetailJson(wcid) ?? "{}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _monsterDetailJsonPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
// Structured per-monster rows for the interactive Damage panel (UTF-8/ANSI JSON).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetMonsterDamageJson", CallConvs = new[] { typeof(CallConvCdecl) })]
@ -290,6 +329,37 @@ public static unsafe class PluginExports
}
// Manual HP override from the Damage panel (hp <= 0 clears it).
private static IntPtr _awakenedTierJsonPtr = IntPtr.Zero;
// Aelrynth difficulty tiers (2026-10-03): the Damage panel's tier label and picker.
// {"show":false} off Aelrynth or until the server has sent a tier; else
// {"show":true,"current":N,"view":M,"following":bool,"percent":5,"tiers":[0,...]}.
// An engine without the picker never calls this; the damage JSON then shows the current tier.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetAwakenedTierJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetAwakenedTierJson()
{
try
{
string json = Runtime.Plugin?.BuildAwakenedTierJson() ?? "{\"show\":false}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _awakenedTierJsonPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
// The tier the damage JSON and monster detail describe: -1 = the current one (default).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetDamageViewTier", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetDamageViewTier(int tier)
{
try { Runtime.Plugin?.SetDamageViewTier(tier); } catch { }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetMonsterHp", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetMonsterHp(uint wcid, int hp)
{
@ -346,6 +416,39 @@ public static unsafe class PluginExports
try { Runtime.Plugin?.SetMonsterOffhand(wcid, offhandId); } catch { }
}
// Damage panel Pet column: picker entries (Auto, elements, Items-panel essences)
// and the per-monster choice ("" = Auto, "E:<element>", "I:<essence id>").
private static IntPtr _petChoicesPtr = IntPtr.Zero;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetPetChoicesJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetPetChoicesJson()
{
try
{
string json = Runtime.Plugin?.BuildPetChoicesJson() ?? "[]";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _petChoicesPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetMonsterPet", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SetMonsterPet(uint wcid, IntPtr ansiChoice)
{
try
{
string choice = ansiChoice == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ansiChoice) ?? "";
Runtime.Plugin?.SetMonsterPet(wcid, choice);
}
catch { }
}
// Per-character DEFAULT weapon from the Damage panel's Default line (weaponId == 0 clears →
// monsters on Default fall through to learned-best). Sweeping fallback for all Default monsters.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSetDefaultWeapon", CallConvs = new[] { typeof(CallConvCdecl) })]
@ -565,6 +668,75 @@ public static unsafe class PluginExports
catch { }
}
// ── Loot editor bridge (engine-side ImGui Loot Editor) ──────────────────
// RynthCore docs/IMGUI_LOOT_EDITOR.md. Strings are UTF-8 both ways (the
// bridges above are ANSI). Each Get frees its previous buffer on the next
// call, so the engine's UI data hub is the only caller (plugin pump thread).
private static IntPtr _lootStatePtr = IntPtr.Zero, _lootRulePtr = IntPtr.Zero, _lootVocabPtr = IntPtr.Zero;
private static IntPtr Utf8Swap(ref IntPtr slot, string json)
{
IntPtr newPtr = Marshal.StringToCoTaskMemUTF8(json);
IntPtr oldPtr = Interlocked.Exchange(ref slot, newPtr);
if (oldPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(oldPtr);
return newPtr;
}
/// <summary>Changes whenever the editor's state does; 0 before RynthAi is ready.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginLootEditRevision", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int LootEditRevision()
{
try { return Runtime.Plugin?.LootEditor.Revision() ?? 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetLootEditJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetLootEditJson()
{
try
{
string? json = Runtime.Plugin?.LootEditor.StateJson();
return json == null ? IntPtr.Zero : Utf8Swap(ref _lootStatePtr, json);
}
catch { return IntPtr.Zero; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetLootEditRuleJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetLootEditRuleJson(int index)
{
try
{
string? json = Runtime.Plugin?.LootEditor.RuleJson(index);
return json == null ? IntPtr.Zero : Utf8Swap(ref _lootRulePtr, json);
}
catch { return IntPtr.Zero; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetLootEditVocabJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetLootEditVocabJson()
{
try
{
string? json = Runtime.Plugin?.LootEditor.VocabJson();
return json == null ? IntPtr.Zero : Utf8Swap(ref _lootVocabPtr, json);
}
catch { return IntPtr.Zero; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSendLootEditCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SendLootEditCommand(IntPtr utf8Json)
{
try
{
if (utf8Json == IntPtr.Zero) return;
string? json = Marshal.PtrToStringUTF8(utf8Json);
if (string.IsNullOrEmpty(json)) return;
Runtime.Plugin?.LootEditor.Command(json);
}
catch { }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginAddSelectedWeapon", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void AddSelectedWeapon()
{

View file

@ -645,13 +645,11 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
if (ms.Position + 4 > ms.Length) break;
uint key = reader.ReadUInt32();
var geo = ParseCellStruct(reader, ms, renderOnly);
var geo = ParseCellStruct(reader, ms, renderOnly, out bool readToEnd);
if (geo != null)
result[key] = geo;
else
{
break; // CellStruct parse failed — stream position unknown, can't continue
}
if (geo == null || !readToEnd)
break; // CellStruct not read to its end: stream position unknown, can't continue
}
}
}
@ -680,9 +678,10 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
/// Header (3 × uint32) → VertexArray → RenderPolygons → PortalIndices → [align]
/// → CellBSP → PhysicsPolygons → PhysicsBSP → [DrawingBSP] → [align]
/// </summary>
private CellGeometry ParseCellStruct(BinaryReader reader, MemoryStream ms, bool renderOnly = false)
private CellGeometry ParseCellStruct(BinaryReader reader, MemoryStream ms, bool renderOnly, out bool readToEnd)
{
var geo = new CellGeometry();
readToEnd = false;
try
{
@ -727,18 +726,23 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
geo.Polygons.Add(cellPoly);
}
// For map rendering, render polygons with portal tags are all we need.
if (renderOnly)
return geo;
// Render polygons with portal tags are all the walls and the map need, but the
// rest of this CellStruct must still be read past: an Environment holds several
// CellStructs back to back, and the next one starts after this one's BSP trees.
// Returning here left the stream in the Cell BSP, so the next CellStruct parse
// read garbage and ParseEnvironment stopped: only CellStruct 0 of every
// Environment ever had walls, and every EnvCell using CellStruct 1+ (318 of
// 625 cells in landblock 0x6346) was open space to LOS and the dungeon map.
// Now attempt to skip Cell BSP and reach physics polygons
bool canContinue = SkipBSPTree(reader, ms, BSPTreeType.Cell);
// If BSP skip succeeded and physics polygons exist, upgrade to physics data
// (not for render-only geometry, which keeps its render polygons).
if (canContinue && numPhysicsPolygons > 0)
{
var physicsPolys = ParsePolygons(reader, ms, numPhysicsPolygons);
if (physicsPolys != null && physicsPolys.Count > 0)
if (!renderOnly && physicsPolys != null && physicsPolys.Count > 0)
{
// Replace rendering fallback with precise physics collision surfaces
geo.Polygons.Clear();
@ -778,6 +782,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
aligned = (ms.Position + 3) & ~3L;
if (aligned <= ms.Length) ms.Position = aligned;
}
readToEnd = canContinue;
return geo;
}

View file

@ -3,7 +3,7 @@ using System;
namespace RynthCore.Plugin.RynthAi.Raycasting
{
/// <summary>
/// The flight path of an AC missile (arrow, bolt, dart), as pure math: no host, no
/// The flight path of an AC missile (arrow, bolt, dart) or arc spell, as pure math: no host, no
/// geometry, no allocation. Kept dependency-free so Tools/RynthCore.MissileArcTests
/// compiles it directly.
///
@ -142,6 +142,40 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
return new MissileArc(ox, oy, oz, dx / d, dy / d, d, rise, (float)tan, (float)k, valid: true, vertical: false);
}
/// <summary>ACE's launch speed for player arc spells (Flame Arc I-VII, the Incantations,
/// Nether Arc): the projectile weenies (flameboltgravity 20974 and its siblings,
/// ace43232-netherarc) all have MaximumVelocity 40.</summary>
public const float AceArcSpellSpeed = 40f;
/// <summary>
/// The path of an ARC SPELL, which ACE flies differently from a missile: a fixed
/// HORIZONTAL speed (the projectile's MaximumVelocity, 40 m/s for every player arc) and
/// a vertical launch speed chosen so the arc lands on the aim point under gravity 9.8
/// (WorldObject_Magic.CalculateProjectileVelocity → Trajectory.solve_ballistic_arc_lateral,
/// gravity only for ProjectileSpellType.Arc). So it always reaches, and rises
/// g·d²/(8·v²) above the straight line at mid-flight: 0.3 m at 20 m, 1.2 m at 40 m,
/// 2.8 m at 60 m. Same shape as <see cref="Solve"/> (height = x·tanθ − K·x²) with
/// K = g/(2v²) and tanθ = rise/d + K·d.
/// </summary>
public static MissileArc SolveLateral(float ox, float oy, float oz,
float tx, float ty, float tz,
float lateralSpeed, float gravity = AcGravity)
{
float dx = tx - ox, dy = ty - oy;
float rise = tz - oz;
float d = (float)Math.Sqrt(dx * dx + dy * dy);
if (float.IsNaN(d) || float.IsNaN(rise) || !(lateralSpeed > 0f) || !(gravity > 0f))
return new MissileArc(ox, oy, oz, 0f, 0f, 0f, 0f, 0f, 0f, valid: false, vertical: false);
if (d < VerticalEpsilon)
return new MissileArc(ox, oy, oz, 0f, 0f, d, rise, 0f, 0f, valid: true, vertical: true);
double k = gravity / (2.0 * lateralSpeed * lateralSpeed);
double tan = rise / (double)d + k * d;
return new MissileArc(ox, oy, oz, dx / d, dy / d, d, rise, (float)tan, (float)k, valid: true, vertical: false);
}
/// <summary>
/// Extra height added to the tested path: <paramref name="clearance"/> at mid-flight,
/// tapering to zero at both ends (4t(1−t)), so the launch and aim points stay put. It

View file

@ -29,6 +29,49 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
private const float RayLateralOffset = 0.35f; // left/right shoulder spread (meters)
private const float RayVerticalOffset = 0.30f; // up/down spread (meters)
// ── Box pre-filter (2026-10-02 flood work) ─────────────────────────────────────────
// Every ray used to call RayIntersect on every volume of the landblock (883 in the
// Matron Hive, x5 rays per spell target in dungeons, for every monster in range 20
// times a second). A TriangleMesh or AxisAlignedBox volume can only be hit inside its
// Min/Max box (RayIntersect tests that box first), so a volume whose box doesn't touch
// the segment's box is skipped without the call. Same verdicts: LosProof's 4281 pairs
// give the same counts. Other volume types (sphere, cylinder, polygon) are always tested.
private const float BoxSlack = 0.001f; // 1 mm, so float rounding can never skip a real hit
// One spare candidate list, borrowed and given back (no allocation per check, safe if two
// threads ever cast at once: the second just makes its own). Not [ThreadStatic]: the
// plugin can live in a collectible context.
private static List<BoundingVolume>? s_spareCandidates;
private static bool BoxBounded(BoundingVolume v)
=> v.Type == BoundingVolume.VolumeType.TriangleMesh || v.Type == BoundingVolume.VolumeType.AxisAlignedBox;
/// <summary>True when <paramref name="v"/> cannot touch anything inside [lo, hi].</summary>
private static bool OutsideBox(BoundingVolume v, Vector3 lo, Vector3 hi)
{
if (!BoxBounded(v)) return false;
Vector3 mn = v.Min, mx = v.Max;
return mx.X < lo.X || mn.X > hi.X || mx.Y < lo.Y || mn.Y > hi.Y || mx.Z < lo.Z || mn.Z > hi.Z;
}
private static void SegmentBox(Vector3 a, Vector3 b, out Vector3 lo, out Vector3 hi)
{
Vector3 slack = new Vector3(BoxSlack, BoxSlack, BoxSlack);
lo = Vector3.Min(a, b) - slack;
hi = Vector3.Max(a, b) + slack;
}
/// <summary>The non-door volumes that could touch anything inside [lo, hi], into <paramref name="list"/>.</summary>
private static void Candidates(List<BoundingVolume> geometry, Vector3 lo, Vector3 hi, List<BoundingVolume> list)
{
list.Clear();
foreach (var v in geometry)
{
if (v.IsDoor || OutsideBox(v, lo, hi)) continue;
list.Add(v);
}
}
/// <summary>
/// Tests if a straight-line path (magic spells, crossbow bolts) is blocked
/// by any collision geometry.
@ -73,13 +116,30 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
Vector3 L = lateral * RayLateralOffset;
Vector3 U = up * RayVerticalOffset;
// 5 rays: center, left shoulder, right shoulder, slightly up, slightly down
if (IsSingleRayBlocked(origin, target, geometry)) return true;
if (IsSingleRayBlocked(origin - L, target - L, geometry)) return true;
if (IsSingleRayBlocked(origin + L, target + L, geometry)) return true;
if (IsSingleRayBlocked(origin + U, target + U, geometry)) return true;
if (IsSingleRayBlocked(origin - U, target - U, geometry)) return true;
return false;
// One pass picks the volumes whose boxes touch the box around all five rays;
// the five rays then test only those (was five passes over every volume).
Vector3 reach = new Vector3(
Math.Abs(L.X) + Math.Abs(U.X), Math.Abs(L.Y) + Math.Abs(U.Y), Math.Abs(L.Z) + Math.Abs(U.Z));
SegmentBox(origin, target, out Vector3 lo, out Vector3 hi);
var near = System.Threading.Interlocked.Exchange(ref s_spareCandidates, null) ?? new List<BoundingVolume>(256);
try
{
Candidates(geometry, lo - reach, hi + reach, near);
if (near.Count == 0) return false;
// 5 rays: center, left shoulder, right shoulder, slightly up, slightly down
if (IsSingleRayBlocked(origin, target, near)) return true;
if (IsSingleRayBlocked(origin - L, target - L, near)) return true;
if (IsSingleRayBlocked(origin + L, target + L, near)) return true;
if (IsSingleRayBlocked(origin + U, target + U, near)) return true;
if (IsSingleRayBlocked(origin - U, target - U, near)) return true;
return false;
}
finally
{
near.Clear();
s_spareCandidates = near;
}
}
return IsSingleRayBlocked(origin, target, geometry);
@ -92,10 +152,11 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
if (distanceToTarget < 1e-4f) return false;
Vector3 direction = delta / distanceToTarget;
SegmentBox(origin, target, out Vector3 lo, out Vector3 hi);
foreach (var volume in geometry)
{
if (volume.IsDoor) continue;
if (volume.IsDoor || OutsideBox(volume, lo, hi)) continue;
float hitDist;
if (volume.RayIntersect(origin, direction, distanceToTarget, out hitDist))
@ -239,7 +300,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
/// Tests the path a missile really flies: the low ballistic arc at the weapon's launch
/// speed (see <see cref="MissileBallistics"/>), raised by <paramref name="clearance"/>
/// at mid-flight. Unlike <see cref="IsArcPathBlocked"/> (the old flat-ground
/// approximation, kept for magic arcs), the arc passes exactly through the aim point
/// approximation, no longer used by combat), the arc passes exactly through the aim point
/// for any height difference. Floors and ceilings are part of the dungeon geometry, so
/// an arc that rises into a ceiling reports blocked. Out of reach counts as blocked.
/// Hits within 0.5 m of the shooter or 0.3 m of the target are ignored, as in the
@ -254,6 +315,22 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
return false;
var arc = MissileBallistics.Solve(origin.X, origin.Y, origin.Z, target.X, target.Y, target.Z, speed);
return IsBallisticArcBlocked(origin, target, in arc, clearance, geometry, out result);
}
/// <summary>
/// As above for an arc already solved from <paramref name="origin"/> to
/// <paramref name="target"/>: a missile's (<see cref="MissileBallistics.Solve"/>) or an
/// arc spell's (<see cref="MissileBallistics.SolveLateral"/>).
/// </summary>
public static bool IsBallisticArcBlocked(Vector3 origin, Vector3 target, in MissileArc arc, float clearance,
List<BoundingVolume> geometry, out ArcLosResult result)
{
result = default;
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;
result.Sag = arc.MaxRiseAboveChord;
result.Apex = arc.ApexAboveLaunch;
if (!arc.Valid)
@ -286,9 +363,10 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
if (len > 1e-4f)
{
Vector3 dir = seg / len;
SegmentBox(prev, cur, out Vector3 lo, out Vector3 hi);
foreach (var volume in geometry)
{
if (volume.IsDoor) continue;
if (volume.IsDoor || OutsideBox(volume, lo, hi)) continue;
if (!volume.RayIntersect(prev, dir, len, out float hd)) continue;
if (hd < 0f || hd > len) continue;
if (travelled + hd < 0.5f) continue; // at the shooter
@ -319,10 +397,11 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
if (dist < 0.01f) return false;
Vector3 dir = delta / dist;
SegmentBox(start, end, out Vector3 lo, out Vector3 hi);
foreach (var volume in geometry)
{
if (volume.IsDoor) continue;
if (volume.IsDoor || OutsideBox(volume, lo, hi)) continue;
float hitDist;
if (volume.RayIntersect(start, dir, dist, out hitDist))

View file

@ -27,11 +27,12 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
// Attack type determines which raycast to use
public enum AttackType
{
Linear, // Melee, peace, or arcs-disabled missiles
Linear, // Peace, magic, or arcs-disabled missiles
BowArc, // Bows — moderate arc, arrows go higher than you'd think
CrossbowArc, // Crossbows — fastest projectile, flattest arc
AtlatlArc, // Atlatls, thrown weapons, darts — similar arc to bows
MagicArc // War/Void magic Arc spells — same trajectory as missile weapons
MagicArc, // War/Void magic Arc spells: fixed horizontal speed, gravity (MissileBallistics.SolveLateral)
Melee // Melee: one straight ray chest to chest, no silhouette rays (see IsPathBlocked)
}
// Lower velocity = higher arc. Defaults tuned against in-game trajectories;
@ -40,7 +41,17 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
public float BowArcVelocity { get; set; } = 25.0f;
public float CrossbowArcVelocity { get; set; } = 40.0f;
public float AtlatlArcVelocity { get; set; } = 22.0f;
public float MagicArcVelocity { get; set; } = 25.0f;
// Arc spells: the HORIZONTAL speed (ACE flies them at a fixed lateral speed, 40 m/s for
// every player arc; see MissileBallistics.SolveLateral). Lower = higher arc.
public float MagicArcVelocity { get; set; } = MissileBallistics.AceArcSpellSpeed;
/// <summary>
/// How far above the chest-height line (feet + 1 m) an arc spell leaves the caster. ACE
/// spawns arc projectiles at the caster's full height (CalculatePreOffset startFactor 1.0
/// for Arc, 2/3 for every other shape), about 1.8 m for a character, and aims them at
/// 5/6 of the target's height (taken as the usual chest line, feet + 1 m).
/// </summary>
public const float MagicArcLaunchAboveChest = 0.8f;
// If true, use arc checks for missile weapons. If false, treat all as linear.
public bool UseArcs { get; set; } = true;
@ -70,6 +81,19 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
private static bool IsMissileArc(AttackType t) =>
t == AttackType.BowArc || t == AttackType.CrossbowArc || t == AttackType.AtlatlArc;
/// <summary>
/// The path an arc spell flies from <paramref name="chestOrigin"/> to
/// <paramref name="chestTarget"/> (both at chest height, feet + 1 m): it leaves
/// <see cref="MagicArcLaunchAboveChest"/> higher, at <paramref name="lateralSpeed"/>
/// horizontally, and lands on the target. <paramref name="launch"/> is that start point.
/// </summary>
public static MissileArc MagicArcPath(Vector3 chestOrigin, Vector3 chestTarget, float lateralSpeed, out Vector3 launch)
{
launch = new Vector3(chestOrigin.X, chestOrigin.Y, chestOrigin.Z + MagicArcLaunchAboveChest);
return MissileBallistics.SolveLateral(launch.X, launch.Y, launch.Z,
chestTarget.X, chestTarget.Y, chestTarget.Z, lateralSpeed);
}
/// <summary>Launch speed configured for a missile attack type.</summary>
public float VelocityFor(AttackType t) => t switch
{
@ -127,6 +151,68 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
if (targetPos == Vector3.Zero)
return false;
return IsPathBlocked(GetPlayerLandcell(host), origin, targetPos, attackType, out detail);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Error checking LOS: {ex.Message}");
return false;
}
}
/// <summary>
/// Would an ARC SPELL cast at <paramref name="targetId"/> now reach it? The straight line
/// (walls) and the arc the spell really flies (ceilings, in dungeons too), whatever
/// UseArcs says (that setting is about missile target selection). True = blocked.
/// No geometry or no positions: false (clear), the arc is cast as before.
/// </summary>
public bool IsMagicArcBlocked(RynthCoreHost host, uint targetId, out LosDetail detail)
{
detail = default;
detail.Type = AttackType.MagicArc;
if (!_geoLoader.IsInitialized)
return false;
try
{
Vector3 origin = GetPlayerPosition(host);
if (origin == Vector3.Zero)
return false;
Vector3 targetPos = GetObjectPosition(host, targetId);
if (targetPos == Vector3.Zero)
return false;
return IsPathBlockedCore(GetPlayerLandcell(host), origin, targetPos, AttackType.MagicArc, forceArc: true, out detail);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Error checking magic arc: {ex.Message}");
return false;
}
}
/// <summary>As <see cref="IsMagicArcBlocked(RynthCoreHost, uint, out LosDetail)"/> for
/// known feet positions (global meters), for tools running against the dats offline.</summary>
public bool IsMagicArcPathBlocked(uint landcell, Vector3 origin, Vector3 targetPos, out LosDetail detail)
=> IsPathBlockedCore(landcell, origin, targetPos, AttackType.MagicArc, forceArc: true, out detail);
/// <summary>
/// The LOS verdict for known positions: <paramref name="origin"/> is the player's feet
/// and <paramref name="targetPos"/> the target's feet, both in global meters
/// (landblock * 192 + landblock-local origin), <paramref name="landcell"/> the
/// player's cell. No client reads, so tools can run it against the dat files offline
/// (Tools/RynthCore.LosProof).
/// </summary>
public bool IsPathBlocked(uint landcell, Vector3 origin, Vector3 targetPos, AttackType attackType, out LosDetail detail)
=> IsPathBlockedCore(landcell, origin, targetPos, attackType, forceArc: false, out detail);
private bool IsPathBlockedCore(uint landcell, Vector3 origin, Vector3 targetPos, AttackType attackType, bool forceArc, out LosDetail detail)
{
detail = default;
detail.Type = attackType;
if (!_geoLoader.IsInitialized)
return false;
try
{
// Early-out: skip raycast if target is beyond scan distance
float dx = targetPos.X - origin.X;
float dy = targetPos.Y - origin.Y;
@ -138,15 +224,19 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
origin.Z += 1.0f;
targetPos.Z += 1.0f;
uint landcell = GetPlayerLandcell(host);
uint cellPart = landcell & 0xFFFF;
bool isDungeon = cellPart >= 0x0100;
detail.Dungeon = isDungeon;
bool missileArc = UseArcs && IsMissileArc(attackType);
// Arc spells fly the arc ACE gives them (fixed horizontal speed, from the
// caster's head), tested like a missile's: straight line, then the arc, ceilings
// included. They used to get the old flat-ground arc outdoors and a straight line
// in dungeons, so an arc into a low ceiling passed.
bool magicArc = attackType == AttackType.MagicArc && (UseArcs || forceArc);
bool missileArc = (UseArcs && IsMissileArc(attackType)) || magicArc;
// Magic arcs keep the old rule: straight line indoors.
if (isDungeon && !missileArc)
// Arcs off: a straight line indoors. Melee keeps its own test.
if (isDungeon && !missileArc && attackType != AttackType.Melee)
attackType = AttackType.Linear;
detail.Type = attackType;
@ -157,13 +247,16 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
// The missile's real path: solved up front so the pre-filter box covers its apex.
MissileArc arc = default;
Vector3 launch = origin;
float arcHeadroom = 0f;
if (missileArc)
{
detail.Velocity = VelocityFor(attackType);
arc = MissileBallistics.Solve(origin.X, origin.Y, origin.Z,
arc = magicArc
? MagicArcPath(origin, targetPos, detail.Velocity, out launch)
: MissileBallistics.Solve(origin.X, origin.Y, origin.Z,
targetPos.X, targetPos.Y, targetPos.Z, detail.Velocity);
arcHeadroom = arc.ApexAboveLaunch + Math.Max(0f, MissileArcClearance) + 0.5f;
arcHeadroom = arc.ApexAboveLaunch + (launch.Z - origin.Z) + Math.Max(0f, MissileArcClearance) + 0.5f;
}
// Pre-filter: skip full ray test if no geometry near the path
@ -193,7 +286,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
}
detail.ArcChecked = true;
return RaycastEngine.IsBallisticArcBlocked(origin, targetPos, detail.Velocity,
return RaycastEngine.IsBallisticArcBlocked(launch, targetPos, in arc,
MissileArcClearance, geometry, out detail.Arc);
}
@ -205,17 +298,21 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
case AttackType.BowArc: // arcs off (UseArcs=false) → straight line
case AttackType.CrossbowArc:
case AttackType.AtlatlArc:
case AttackType.MagicArc:
detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
return detail.LineBlocked;
case AttackType.MagicArc:
if (UseArcs && !isDungeon)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, MagicArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: false);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
// Melee: nothing flies, so the only question is whether a wall stands
// between the two bodies: one ray, chest to chest. The five silhouette rays
// (0.35 m to each side, 0.3 m up and down) are there for spells slipping
// through corner seams; for melee they clip door jambs and hide a monster
// seen through a doorway at an angle. Offline in landblock 0x6346
// (Tools/RynthCore.LosProof) they blocked 297 of 1404 such open lines, the
// single ray 88, and both block every one of 199 walls, also with the
// player and the monster pressed against it.
case AttackType.Melee:
detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: false);
return detail.LineBlocked;
default:
return false;
@ -353,9 +450,9 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
if (currentCombatMode == 1)
return AttackType.Linear;
// MELEE MODE: Linear (range check only, no projectile arc)
// MELEE MODE: one straight ray, no projectile arc
if (currentCombatMode == 2)
return AttackType.Linear;
return AttackType.Melee;
// MISSILE MODE: Check the weapon name for bow vs crossbow vs thrown.
// No name (weapon not resolved yet) is still a missile shot: bow arc. The

View file

@ -7,6 +7,7 @@ using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
@ -25,6 +26,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] === Commands ===");
ChatLine("[RynthAi] /ra fellow — fellowship diagnostics and queries");
ChatLine("[RynthAi] /ra help — show this list");
ChatLine("[RynthAi] /ra version — RynthAi version and build date, and the engine it runs on");
ChatLine("[RynthAi] /ra power <0-100|auto> — set attack power (auto = recklessness-aware)");
ChatLine("[RynthAi] /ra cast <spellId> — cast spell on current target");
ChatLine("[RynthAi] /ra buffs — show active buff timers");
@ -33,7 +35,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra cache2 — show raw object cache IDs");
ChatLine("[RynthAi] /ra attackable — check if target is attackable");
ChatLine("[RynthAi] /ra wielded — show wielded items");
ChatLine("[RynthAi] /ra dumpprops — dump player properties");
ChatLine("[RynthAi] /ra dumpprops [0xId] — every property of the selection (else yourself)");
ChatLine("[RynthAi] /ra mexec <expr> — evaluate meta expression");
ChatLine("[RynthAi] /ra listvars — show session variables");
ChatLine("[RynthAi] /ra listpvars — show persistent variables");
@ -55,6 +57,12 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra buildinfo — nearby geometry info");
ChatLine("[RynthAi] /ra navdebug — show nav coordinate/debug info");
ChatLine("[RynthAi] /ra addnavpt — append a waypoint at current location to loaded nav");
ChatLine("[RynthAi] /ra nav save [name] — save the route; a name saves it as <name>.nav");
ChatLine("[RynthAi] /ra nav load <name> — load a nav from NavProfiles");
ChatLine("[RynthAi] /ra nav list — list the navs in NavProfiles");
ChatLine("[RynthAi] /ra lua run <name> — run a RynthLua script (same as /lua run; also stop, list, exec <code>)");
ChatLine("[RynthAi] /ra items fill — add weapons, healing kits, lockpicks and pet essences from your pack");
ChatLine("[RynthAi] /ra offhand [auto|shield|weapon|none] [rule] — the off hand (shield / dual wield), global or for a Monsters rule; dual on|off");
ChatLine("[RynthAi] /ra dunnav <NS> <EW> — navigate to NS/EW coords through dungeon (no nav file needed)");
ChatLine("[RynthAi] /ra dunnav-patrol — circular hunt patrol through the whole dungeon (no nav file needed)");
ChatLine("[RynthAi] /ra hazard add|del|list|near — mark current cell as lava/acid so patrol avoids it");
@ -71,6 +79,10 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra why — one-glance diagnosis of why the bot is idle/attacking");
ChatLine("[RynthAi] /ra start | stop — start/stop the macro from chat");
ChatLine("[RynthAi] /ra pause [sec] — stop the macro, auto-resume after sec (default 60)");
ChatLine("[RynthAi] /ra vtankyield [on|off] — with Decal: stop when VTank starts (one bot per client)");
ChatLine("[RynthAi] /ra metamgr on|off|status — Meta Manager: load a meta when a timer or a /myquests quest timer runs out (Meta panel, Schedule)");
ChatLine("[RynthAi] /ra metamgr poll [min] — check /myquests now, or set how often it checks (default 5 min)");
ChatLine("[RynthAi] /ra metamgr start <#> [min] | stop <#> | reset <#|all> — run a countdown rule, stop it, re-arm a rule");
ChatLine("[RynthAi] /ra navstate — dump navigation state machine snapshot");
ChatLine("[RynthAi] /ra salvstate — dump salvage state machine snapshot");
ChatLine("[RynthAi] /ra clearbusy — force-clear busy state (hourglass cursor)");
@ -84,6 +96,72 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ub vendor open[p] <name|id|selected> | opencancel | addbuy[p]/addsell[p] [n] <item> | buyall | sellall | clearbuy | clearsell");
}
/// <summary>
/// /ra offhand: the off hand (the Shield slot). Without arguments it shows the settings;
/// "/ra offhand auto|shield|weapon|none" sets the global one; with a Monsters rule's name
/// after it, that rule's ("default" hands the rule back to the global one);
/// "/ra offhand dual on|off" makes Auto prefer dual wield over a shield.
/// </summary>
private void HandleOffhandCommand(string[] parts)
{
var settings = _dashboard?.Settings;
if (settings == null) { ChatLine("[RynthAi] Settings not ready."); return; }
if (parts.Length < 3)
{
var global = OffhandRules.Parse(settings.OffhandDefault, OffhandMode.Auto);
ChatLine($"[RynthAi] Offhand: {OffhandRules.Label(global)}; Auto prefers dual wield: {(settings.PreferDualWield ? "on" : "off")}");
foreach (var r in settings.MonsterRules)
{
if (r.OffhandId == OffhandRules.RuleDefault) continue;
string what = OffhandRules.RuleMode(r.OffhandId) is OffhandMode m
? OffhandRules.Label(m)
: $"item 0x{(uint)r.OffhandId:X8} '{_objectCache?[r.OffhandId]?.Name ?? "?"}'";
ChatLine($"[RynthAi] rule '{r.Name}': {what}");
}
int shields = settings.ItemRules.Count(WeaponList.IsShieldRule);
ChatLine($"[RynthAi] {shields} shield(s) in the Items list (Add Selected Weapon adds a shield too).");
ChatLine("[RynthAi] Usage: /ra offhand auto|shield|weapon|none [rule name] — /ra offhand default <rule name> — /ra offhand dual on|off");
return;
}
string arg = parts[2];
if (arg.Equals("dual", StringComparison.OrdinalIgnoreCase))
{
bool on = parts.Length < 4 || parts[3].Equals("on", StringComparison.OrdinalIgnoreCase) || parts[3] == "1";
settings.PreferDualWield = on;
_dashboard!.SaveSettings();
ChatLine($"[RynthAi] Auto now prefers {(on ? "dual wield (with the Dual Wield skill and a second listed one-handed weapon)" : "a shield")}.");
return;
}
bool toDefault = arg.Equals("default", StringComparison.OrdinalIgnoreCase);
if (!toDefault && !OffhandRules.TryParse(arg, out _))
{
ChatLine("[RynthAi] Usage: /ra offhand auto|shield|weapon|none [rule name] — /ra offhand default <rule name> — /ra offhand dual on|off");
return;
}
var mode = toDefault ? OffhandMode.Auto : OffhandRules.Parse(arg, OffhandMode.Auto);
if (parts.Length == 3)
{
if (toDefault) { ChatLine("[RynthAi] Usage: /ra offhand default <rule name>"); return; }
settings.OffhandDefault = OffhandRules.SettingValue(mode);
_dashboard!.SaveSettings();
ChatLine($"[RynthAi] Offhand set to {OffhandRules.Label(mode)} (for every Monsters rule that doesn't choose its own).");
return;
}
string ruleName = string.Join(" ", parts.Skip(3));
var rule = settings.MonsterRules.FirstOrDefault(r => r.Name.Equals(ruleName, StringComparison.OrdinalIgnoreCase));
if (rule == null) { ChatLine($"[RynthAi] No Monsters rule named '{ruleName}'."); return; }
rule.OffhandId = toDefault ? OffhandRules.RuleDefault : OffhandRules.RuleValue(mode);
_dashboard!.SaveMonsterRules();
ChatLine(toDefault
? $"[RynthAi] Rule '{rule.Name}' uses the global Offhand setting again."
: $"[RynthAi] Rule '{rule.Name}': Offhand {OffhandRules.Label(mode)}.");
}
private void HandlePowerCommand(string[] parts)
{
var settings = _dashboard?.Settings;
@ -216,6 +294,14 @@ public sealed partial class RynthAiPlugin
ChatLine($"[RynthAi] Raycast: {(_raycast.IsInitialized ? "READY" : "NOT LOADED")}");
ChatLine($"[RynthAi] Status: {_raycast.StatusMessage}");
// What combat itself uses: READY above said nothing about it, and for a day combat had
// no raycast at all while this line (and /ra lostest) worked (see WireRaycastIntoCombat).
if (_combatManager == null)
ChatLine("[RynthAi] Combat: no combat manager");
else
ChatLine($"[RynthAi] Combat LOS: {(_combatManager.RaycastInitialized ? "wired" : "NOT WIRED")}, " +
$"{(_dashboard?.Settings.EnableRaycasting == true ? "on" : "off")}, " +
$"checks {_combatManager.RaycastCheckCount}, blocked {_combatManager.RaycastBlockCount}");
}
private void HandleLosTestCommand(string[] parts)
@ -245,7 +331,7 @@ public sealed partial class RynthAiPlugin
case "bow": isArc = true; arcVelocity = settings?.BowArcVelocity ?? 25.0f; modeLabel = $"Bow arc (v={arcVelocity:F1})"; break;
case "crossbow": isArc = true; arcVelocity = settings?.CrossbowArcVelocity ?? 40.0f; modeLabel = $"Crossbow arc (v={arcVelocity:F1})"; break;
case "atlatl": isArc = true; arcVelocity = settings?.AtlatlArcVelocity ?? 22.0f; modeLabel = $"Atlatl arc (v={arcVelocity:F1})"; break;
case "magic": isArc = true; arcVelocity = settings?.MagicArcVelocity ?? 25.0f; modeLabel = $"Magic arc (v={arcVelocity:F1})"; break;
case "magic": isArc = true; arcVelocity = settings?.MagicArcVelocity ?? 40.0f; modeLabel = $"Magic arc (horizontal v={arcVelocity:F1}, from head height)"; break;
default:
ChatLine($"[RynthAi LOS] Unknown mode '{modeArg}'. Use: linear | bow | crossbow | atlatl | magic");
return;
@ -330,7 +416,17 @@ public sealed partial class RynthAiPlugin
// arc the missile flies plus the clearance headroom (ceilings indoors).
float clearance = settings?.MissileArcClearance ?? 0.5f;
bool lineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
bool arcBlocked = RaycastEngine.IsBallisticArcBlocked(origin, targetPos, arcVelocity, clearance, geometry, out var arc);
// Arc spells: ACE's fixed horizontal speed from the caster's head (what combat's
// Arc-when-clear tests before each arc); missiles: the weapon's launch speed.
bool arcBlocked;
RaycastEngine.ArcLosResult arc;
if (modeArg == "magic")
{
var magicPath = TargetingFSM.MagicArcPath(origin, targetPos, arcVelocity, out var launch);
arcBlocked = RaycastEngine.IsBallisticArcBlocked(launch, targetPos, in magicPath, clearance, geometry, out arc);
}
else
arcBlocked = RaycastEngine.IsBallisticArcBlocked(origin, targetPos, arcVelocity, clearance, geometry, out arc);
staticBlocked = lineBlocked || arcBlocked;
ChatLine($"[RynthAi LOS] Straight line ({(isDungeon ? "multi-ray" : "single-ray")}): {(lineBlocked ? "BLOCKED" : "clear")}");
ChatLine($"[RynthAi LOS] Arc: rises {arc.Sag:F2}m above the line, apex {arc.Apex:F2}m above launch, clearance {clearance:F1}m");
@ -658,14 +754,27 @@ public sealed partial class RynthAiPlugin
ChatLine($"[RynthAi] {kv.Key} = {kv.Value}");
}
private void HandleDumpPropsCommand()
/// <summary>
/// /ra dumpprops [0xId] (and /ub propertydump): every property of the given object, else
/// the selected one, else the character - as UB's propertydump does. It was always the
/// character, whatever was selected.
/// </summary>
private void HandleDumpPropsCommand(string[] parts)
{
uint playerId = Host.GetPlayerId();
if (playerId == 0)
uint me = Host.GetPlayerId();
if (me == 0)
{
ChatLine("[RynthAi] Not logged in.");
return;
}
uint playerId = me; // the object dumped (the name below predates the target choice)
if (parts.Length >= 3 && uint.TryParse(parts[2].StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? parts[2][2..] : parts[2],
System.Globalization.NumberStyles.HexNumber, null, out uint given) && given != 0)
playerId = given;
else if (_currentTargetId != 0)
playerId = _currentTargetId;
string label = Host.TryGetObjectName(playerId, out string nm) && nm.Length > 0 ? nm : "?";
ChatLine($"[RynthAi] === Properties of {label} (0x{playerId:X8}){(playerId == me ? " - nothing selected, your character" : "")} ===");
// Int properties 0-400
int intCount = 0;
@ -727,7 +836,42 @@ public sealed partial class RynthAiPlugin
}
else ChatLine("[RynthAi] String property API not available.");
ChatLine($"[RynthAi] Total: {intCount} int, {boolCount} bool, {strCount} string.");
// Int64 (0-12: experience, luminance, item XP), float (0-400), data id (0-80) and
// instance id (0-50) properties, unnamed. Data ids and instance ids print in hex.
int quadCount = 0, floatCount = 0, didCount = 0, iidCount = 0;
if (Host.HasGetObjectQuadProperty)
for (uint i = 0; i <= 12; i++)
if (Host.TryGetObjectQuadProperty(playerId, i, out long q))
{
ChatLine($"[RynthAi] Int64Prop[{i}] = {q}");
quadCount++;
}
for (uint i = 0; i <= 400; i++)
if (Host.TryGetObjectDoubleProperty(playerId, i, out double d))
{
ChatLine($"[RynthAi] FloatProp[{i}] = {d.ToString("0.#####", System.Globalization.CultureInfo.InvariantCulture)}");
floatCount++;
}
if (Host.HasGetObjectDataIdProperty)
for (uint i = 0; i <= 80; i++)
if (Host.TryGetObjectDataIdProperty(playerId, i, out uint did))
{
ChatLine($"[RynthAi] DataIdProp[{i}] = 0x{did:X8}");
didCount++;
}
if (Host.HasGetObjectInstanceIdProperty)
for (uint i = 0; i <= 50; i++)
if (Host.TryGetObjectInstanceIdProperty(playerId, i, out uint iid))
{
string who = Host.TryGetObjectName(iid, out string wn) && wn.Length > 0 ? $" ({wn})" : "";
ChatLine($"[RynthAi] InstanceIdProp[{i}] = 0x{iid:X8}{who}");
iidCount++;
}
ChatLine($"[RynthAi] Total: {intCount} int, {boolCount} bool, {strCount} string, {quadCount} int64, {floatCount} float, " +
$"{didCount} data id, {iidCount} instance id.");
if (playerId != me && intCount + boolCount + strCount + quadCount + floatCount < 5)
ChatLine("[RynthAi] Few properties: the item may not be identified yet - run it again in a moment.");
}
private void HandleWieldedCommand()
@ -909,7 +1053,7 @@ public sealed partial class RynthAiPlugin
for (int i = 0; i < settings.CurrentRoute.Points.Count; i++)
{
var point = settings.CurrentRoute.Points[i];
if (point.Type != LegacyUi.NavPointType.Point)
if (!LegacyUi.NavRouteParser.IsPlainWaypoint(point.Type))
continue;
double d = Math.Sqrt(Math.Pow(point.NS - basisNS, 2) + Math.Pow(point.EW - basisEW, 2));
@ -1011,6 +1155,7 @@ public sealed partial class RynthAiPlugin
{
case "on":
case "leader":
settings.FollowNamedTargetId = 0;
settings.FollowMode = true;
settings.EnableNavigation = true; // follow is a nav activity
ChatLine(settings.IsMacroRunning
@ -1020,6 +1165,7 @@ public sealed partial class RynthAiPlugin
case "off":
settings.FollowMode = false;
settings.FollowTargetId = 0;
settings.FollowNamedTargetId = 0;
ChatLine("[RynthAi] Follow OFF.");
break;
case "status":
@ -1029,8 +1175,26 @@ public sealed partial class RynthAiPlugin
$"isLeader={(_fellowshipTracker?.IsLeader ?? false)}");
break;
default:
ChatLine("[RynthAi] Usage: /ra follow [on|off|status]");
{
// /ra follow <name>: follow that character (exact name, else partial).
string name = string.Join(" ", parts, 2, parts.Length - 2).Trim();
WorldObject? who = null;
if (_objectCache != null)
{
foreach (var wo in _objectCache.GetLandscapeObjects())
if (wo.Id != unchecked((int)_playerId) && string.Equals(wo.Name, name, StringComparison.OrdinalIgnoreCase)) { who = wo; break; }
if (who == null)
foreach (var wo in _objectCache.GetLandscapeObjects())
if (wo.Id != unchecked((int)_playerId) && wo.ObjectClass != RynthCore.Loot.AcObjectClass.Corpse
&& wo.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0) { who = wo; break; }
}
if (who == null) { ChatLine($"[RynthAi] Follow: no one named '{name}' nearby. Usage: /ra follow [on|off|status|<name>]"); break; }
settings.FollowNamedTargetId = unchecked((uint)who.Id);
settings.FollowMode = true;
settings.EnableNavigation = true;
ChatLine($"[RynthAi] Follow ON — following {who.Name}.");
break;
}
}
}
@ -1059,21 +1223,41 @@ public sealed partial class RynthAiPlugin
return;
}
var newPt = new NavPoint { NS = ns, EW = ew, Z = z };
var newPt = new NavPoint { NS = ns, EW = ew, Z = z / 240.0 }; // nav units, like NS/EW
settings.CurrentRoute.Points.Add(newPt);
string navName = string.IsNullOrEmpty(settings.CurrentNavPath)
? "(unsaved)"
: System.IO.Path.GetFileName(settings.CurrentNavPath);
if (!string.IsNullOrEmpty(settings.CurrentNavPath))
{
try { settings.CurrentRoute.Save(settings.CurrentNavPath); }
catch (Exception ex) { ChatLine($"[RynthAi] Added point but save failed: {ex.Message}"); }
}
_dashboard?.AutoSaveRoute();
int idx = settings.CurrentRoute.Points.Count - 1;
ChatLine($"[RynthAi] Added waypoint [{idx}] NS={ns:F3} EW={ew:F3} Z={z:F2} to {navName}.");
ChatLine($"[RynthAi] Added waypoint [{idx}] NS={ns:F3} EW={ew:F3} Z={z / 240.0:F4} to {navName}.");
}
private void HandleNavCommand(string[] parts)
{
if (_dashboard == null) { ChatLine("[RynthAi] Settings not ready."); return; }
string sub = parts.Length > 2 ? parts[2].ToLowerInvariant() : "";
string rest = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3) : "";
switch (sub)
{
case "save":
ChatLine(_dashboard.SaveRoute(rest.Length > 0 ? rest : null));
break;
case "load":
if (rest.Length == 0) { ChatLine("[RynthAi] Usage: /ra nav load <name>"); break; }
ChatLine(_dashboard.LoadNavByName(rest));
break;
case "list":
var names = _dashboard.NavFileNames();
ChatLine(names.Count == 0 ? "[RynthAi] No navs in NavProfiles." : $"[RynthAi] Navs ({names.Count}): {string.Join(", ", names)}");
break;
default:
ChatLine("[RynthAi] /ra nav save [name] | /ra nav load <name> | /ra nav list");
break;
}
}
private void HandleScanCommand()
@ -1315,6 +1499,45 @@ public sealed partial class RynthAiPlugin
}
}
// ── Loot Editor (engine ImGui panel) ────────────────────────────────────
private LootEditorBridge? _lootEditor;
/// <summary>The in-game Loot Editor's bridge (PluginExports). Created on first use.</summary>
internal LootEditorBridge LootEditor => _lootEditor ??= new LootEditorBridge(
() => _dashboard?.Settings?.CurrentLootPath ?? string.Empty,
OnLootProfileEdited,
Vendor.AutoVendorManager.MainProfileDir);
/// <summary>
/// The Loot Editor saved <paramref name="path"/>: drop the cached copies and,
/// when it is the loot profile in use, load it again now (its chat line says so).
/// Plugin pump thread (the editor's export), the same thread as the tick.
/// </summary>
private void OnLootProfileEdited(string path)
{
bool Same(string a) => RynthCore.Loot.Editing.LootEditSession.SamePath(a, path);
if (Same(_loadedLootProfilePath))
{
_loadedLootProfile = null;
_loadedLootProfileTime = DateTime.MinValue;
}
if (Same(_nativeLootProfilePath))
{
_nativeLootProfile = null;
_nativeLootProfileTime = DateTime.MinValue;
}
string name = System.IO.Path.GetFileName(path);
if (!Same(_dashboard?.Settings?.CurrentLootPath ?? string.Empty))
{
ChatLine($"[RynthAi] Loot Editor saved {name}.");
return;
}
ChatLine($"[RynthAi] Loot Editor saved {name}; reloading it.");
if (path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) TryLoadNativeLootProfile(out _, out _);
else TryLoadLootProfile(string.Empty, out _, out _);
}
private bool TryLoadNativeLootProfile(out RynthCore.Loot.LootProfile profile, out string loadedPath)
{
string candidatePath = (_dashboard?.Settings?.CurrentLootPath ?? string.Empty).Trim().Trim('"');
@ -1383,6 +1606,8 @@ public sealed partial class RynthAiPlugin
+ (_buffManager != null ? $" buffSkip='{_buffManager.GetStateSnapshot().LastBuffSkipReason}'" : ""));
if (s.ScannedCount > 0)
ChatLine($"[RynthAi] closest: '{s.ClosestScannedName}' @ {s.ClosestScannedDist:0.0}yd");
ChatLine($"[RynthAi] melee/missile: lastSwing={_combatManager.LastSwingEvidenceDescription} attackRebinds={_combatManager.AttackRebinds} "
+ $"stallWatch episodes={_combatManager.StallEpisodes} recovered={_combatManager.StallRecoveries}");
// Nav and salvage each own a piece of the "standing there" class, so name
// what they're holding rather than leaving it to /ra navstate + /ra salvstate.
@ -1390,6 +1615,8 @@ public sealed partial class RynthAiPlugin
{
var n = _navigationEngine.GetStateSnapshot();
string navHold = !n.EnableNavigation ? "nav disabled"
: n.Recovery.StartsWith("area hold", StringComparison.Ordinal) ? n.Recovery
: n.Recovery.StartsWith("detour", StringComparison.Ordinal) ? $"recovering: {n.Recovery}"
: n.InRecovery ? $"STUCK-recovery {n.RecoveryKind} ({n.RecoveryRemainMs}ms, x{n.StuckCount})"
: n.InPause ? $"route pause ({n.PauseRemainMs}ms)"
: n.PortalState != "None" ? $"portal/recall {n.PortalState}"
@ -1453,7 +1680,7 @@ public sealed partial class RynthAiPlugin
ChatLine($"[RynthAi] mode cached={cachedMode} live={liveMode} desired={desiredMode}");
ChatLine($"[RynthAi] activeTargetId=0x{(uint)s.ActiveTargetId:X8} lockedTargetId=0x{(uint)s.LockedTargetId:X8} facing={s.FacingTarget}");
ChatLine($"[RynthAi] scanned={s.ScannedCount} closest=0x{(uint)s.ClosestScannedId:X8} '{s.ClosestScannedName}' @ {s.ClosestScannedDist:F1}yd");
ChatLine($"[RynthAi] weapon=0x{(uint)s.PickedWeaponId:X8} '{s.PickedWeaponName}' wieldLoc={s.PickedWeaponWieldLoc} ammoWielded={s.HasWieldedAmmoFlag}");
ChatLine($"[RynthAi] weapon=0x{(uint)s.PickedWeaponId:X8} '{s.PickedWeaponName}' ({s.PickedWeaponWhy}) wieldLoc={s.PickedWeaponWieldLoc} ammoWielded={s.HasWieldedAmmoFlag}");
ChatLine($"[RynthAi] busy={s.BusyCount} sinceAtk={sinceAttackS:F1}s sinceStance={sinceStanceS:F1}s sinceEquip={sinceEquipS:F1}s sinceLost={sinceLostS:F1}s");
// Dump every cache-known object that's wielded — using Host.TryGetObjectWielderInfo
@ -1528,6 +1755,7 @@ public sealed partial class RynthAiPlugin
case "resume":
_macroResumeAt = 0;
if (running) { ChatLine("[RynthAi] Macro already RUNNING."); return; }
if (RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge)
dash.TogglePanelMacro();
ChatLine("[RynthAi] Macro STARTED.");
return;
@ -1576,6 +1804,7 @@ public sealed partial class RynthAiPlugin
ChatLine($"[RynthAi] moving={n.MovingForward} turning={n.Turning} stopped={n.Stopped}");
ChatLine($"[RynthAi] pause={n.InPause} ({n.PauseRemainMs}ms) portal={n.PortalState}");
ChatLine($"[RynthAi] recovery={n.InRecovery} kind={n.RecoveryKind} remain={n.RecoveryRemainMs}ms stuckCount={n.StuckCount}");
ChatLine($"[RynthAi] way back: {n.Recovery} (tries at this waypoint: {n.DetourAttempts})");
if (n.FollowMode)
ChatLine($"[RynthAi] follow: target=0x{n.FollowTargetId:X8}");
ChatLine($"[RynthAi] status: {n.StatusLine}");
@ -1585,7 +1814,8 @@ public sealed partial class RynthAiPlugin
+ $"dist={n.DistYd:F1} err={n.HeadingErrDeg:F1} sinceSteer={n.MsSinceSteer}ms "
+ $"moving={n.MovingForward} turning={n.Turning} stopped={n.Stopped} "
+ $"pause={n.InPause}/{n.PauseRemainMs}ms portal={n.PortalState} "
+ $"recovery={n.InRecovery}/{n.RecoveryKind}/{n.RecoveryRemainMs}ms stuck={n.StuckCount}");
+ $"recovery={n.InRecovery}/{n.RecoveryKind}/{n.RecoveryRemainMs}ms stuck={n.StuckCount} "
+ $"wayBack='{n.Recovery}' tries={n.DetourAttempts}");
}
/// <summary>/ra salvstate — dump the salvage FSM snapshot: which phase, what's queued,
@ -1598,7 +1828,8 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] === Salvage State ===");
ChatLine($"[RynthAi] panelApi={v.HasPanelApi} combineEnabled={v.EnableCombine}");
ChatLine($"[RynthAi] phase={v.Phase} readyIn={v.PhaseReadyInMs}ms queue={v.QueueCount} panelEverOpened={v.PanelEverOpened}");
ChatLine($"[RynthAi] item=0x{v.CurrentItemId:X8} ust=0x{v.CurrentUstId:X8}");
ChatLine($"[RynthAi] batch={v.BatchSize} first=0x{v.CurrentItemId:X8} ust=0x{v.CurrentUstId:X8} tracked={v.TrackedItems}");
ChatLine($"[RynthAi] items: {v.ItemsSalvaged} salvaged in {v.Batches} batch(es), {v.ItemsSkipped} skipped (reasons in the log)");
ChatLine($"[RynthAi] combine: phase={v.CombinePhase} grp={v.CombineGroupIdx + 1}/{v.CombineGroupCount} addIdx={v.CombineAddIdx} openAttempts={v.CombineOpenAttempts}");
ChatLine($"[RynthAi] combine: pendingScan={v.PendingCombineScan} sinceSweep={(v.MsSinceCombineSweep < 0 ? "never" : (v.MsSinceCombineSweep / 1000) + "s")}");
ChatLine($"[RynthAi] retries: tracked={v.RetryTrackedItems} backoffIn={v.RetryBackoffInMs}ms");
@ -1608,7 +1839,7 @@ public sealed partial class RynthAiPlugin
: "[RynthAi] lastError: none");
Host.Log($"[RynthAi salvstate] panelApi={v.HasPanelApi} combine={v.EnableCombine} phase={v.Phase}/{v.PhaseReadyInMs}ms "
+ $"queue={v.QueueCount} item=0x{v.CurrentItemId:X8} ust=0x{v.CurrentUstId:X8} "
+ $"queue={v.QueueCount} batch={v.BatchSize} item=0x{v.CurrentItemId:X8} ust=0x{v.CurrentUstId:X8} tracked={v.TrackedItems} salvaged={v.ItemsSalvaged} skipped={v.ItemsSkipped} "
+ $"cphase={v.CombinePhase} grp={v.CombineGroupIdx}/{v.CombineGroupCount} add={v.CombineAddIdx} "
+ $"openAttempts={v.CombineOpenAttempts} pendingScan={v.PendingCombineScan} sinceSweep={v.MsSinceCombineSweep}ms "
+ $"retries={v.RetryTrackedItems} backoff={v.RetryBackoffInMs}ms ok={v.GroupsSucceeded} fail={v.GroupsFailed} "
@ -1759,9 +1990,10 @@ public sealed partial class RynthAiPlugin
}
// Broader reset for the "AC wedged with item-action notice" failure mode
// that /ra clearbusy can't fix — the orphan attack from a missing
// CancelAttack at the Combat→Buffing handoff lives outside the
// CommandInterpreter / m_cBusy state that clearbusy targets.
// that /ra clearbusy can't fix. The notice comes from two client globals
// outside the CommandInterpreter / m_cBusy state that clearbusy targets:
// AC's pending-item-request slot ("one item at a time") and its attacking
// flag ("while attacking"); /rc unlockactions (engine) clears both.
private void HandlePanicCommand()
{
int before = Host.HasGetBusyState ? Host.GetBusyState() : -1;
@ -1771,6 +2003,11 @@ public sealed partial class RynthAiPlugin
if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat);
if (Host.HasStopCompletely) Host.StopCompletely();
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
// The item-action lock itself is not the busy count: AC refuses every use,
// equip and move while its pending-item-request slot or attacking flag is
// set, and nothing above touches those. The engine opens them (its
// /rc unlockactions; an older engine just logs the unknown command).
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc unlockactions");
_busyCount = 0;
_busyCountLastIncrementAt = 0;
@ -1779,19 +2016,19 @@ public sealed partial class RynthAiPlugin
if (_buffManager != null) _buffManager.BusyCount = 0;
int after = Host.HasGetBusyState ? Host.GetBusyState() : -1;
ChatLine($"[RynthAi] Panic complete (busy {before} → {after}). If still stuck, relog.");
ChatLine($"[RynthAi] Panic complete (busy {before} → {after}). If items still won't use or equip, /rc actionstate shows why.");
}
private void HandleForceBuff()
{
if (_buffManager == null) { ChatLine("[RynthAi] Buff manager not ready."); return; }
_buffManager.ForceFullRebuff();
_buffManager.RequestForceFullRebuff(); // chat commands run on AC's thread; applied on the pump
}
private void HandleCancelForceBuff()
{
if (_buffManager == null) { ChatLine("[RynthAi] Buff manager not ready."); return; }
_buffManager.CancelBuffing();
_buffManager.RequestCancelBuffing();
}
private void HandleBusyInfoCommand()
@ -1979,7 +2216,7 @@ public sealed partial class RynthAiPlugin
var tgt = FindObject(tgtName, inv, land, partial);
if (src == null) { ChatLine($"[RynthAi] Not found: '{srcName}'"); return; }
if (tgt == null) { ChatLine($"[RynthAi] Not found: '{tgtName}'"); return; }
Host.UseObjectOn((uint)src.Id, (uint)tgt.Id);
Host.UseOnFor((uint)src.Id, (uint)tgt.Id, "Command", "/ra use X on Y", UseKind.Asked);
ChatLine($"[RynthAi] UseObjectOn: {src.Name} (0x{src.Id:X}) → {tgt.Name} (0x{tgt.Id:X})");
return;
}
@ -1991,7 +2228,7 @@ public sealed partial class RynthAiPlugin
if (!partial) SuggestPartialMatches(argStr.Trim(), inv, land, parts[1].ToLowerInvariant());
return;
}
Host.UseObject((uint)obj.Id);
Host.UseFor((uint)obj.Id, "Command", "/ra use", UseKind.Asked);
ChatLine($"[RynthAi] UseObject: {obj.Name} (0x{obj.Id:X})");
}
@ -2055,10 +2292,12 @@ public sealed partial class RynthAiPlugin
// allItems: give every matching stack; otherwise honour optional leading count (default 1)
int maxCount = allItems ? int.MaxValue : 1;
bool countGiven = false;
string[] itemTokens = itemPart.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
if (!allItems && itemTokens.Length >= 2 && int.TryParse(itemTokens[0], out int parsedCount) && parsedCount > 0)
{
maxCount = parsedCount;
countGiven = true;
itemPart = itemTokens[1].Trim();
}
@ -2085,6 +2324,8 @@ public sealed partial class RynthAiPlugin
var matches = new List<WorldObject>();
foreach (var wo in _objectCache.GetDirectInventory(forceRefresh: true))
{
// GetDirectInventory includes worn and wielded gear; never give that away.
if (WorldObjectCache.IsWieldedByPlayer(Host, wo)) continue;
bool hit = itemMatch switch
{
GiveItemMatch.Exact => string.Equals(wo.Name, itemPart, StringComparison.OrdinalIgnoreCase),
@ -2107,6 +2348,34 @@ public sealed partial class RynthAiPlugin
}
ChatLine($"[RynthAi] Queued {matches.Count} stack(s) matching '{itemPart}' → {target.Name}");
}
else if (countGiven)
{
// The count is how many items to give. It used to cap only how many stacks
// were collected, and then the whole first stack went: "/ra give 5 Pyreal
// to X" handed over the entire pile. Give min(count, stack) from each stack
// until the count is met (the give carries the amount; the server splits).
int remaining = maxCount;
var gives = new List<(WorldObject Item, int Amount)>();
foreach (var item in matches)
{
if (remaining <= 0) break;
int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1));
int amount = Math.Min(stackSize, remaining);
gives.Add((item, amount));
remaining -= amount;
}
if (gives.Count == 1)
{
Host.MoveItemExternal((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount);
ChatLine($"[RynthAi] Giving {gives[0].Amount} x '{gives[0].Item.Name}' to {target.Name}");
}
else
{
foreach (var (item, amount) in gives)
EnqueueGive((uint)item.Id, (uint)target.Id, amount);
ChatLine($"[RynthAi] Queued {maxCount - remaining} item(s) from {gives.Count} stack(s) matching '{itemPart}' → {target.Name}");
}
}
else
{
var item = matches[0];
@ -2116,6 +2385,21 @@ public sealed partial class RynthAiPlugin
}
}
/// <summary>
/// Items a profile give must skip: GetDirectInventory includes worn and wielded
/// gear, and a broad Keep rule (by object class) would hand over the character's
/// armor, its weapon in hand, or a Weapons-tab weapon waiting in the pack.
/// </summary>
private bool IsGiveProfileExempt(WorldObject item)
{
if (WorldObjectCache.IsWieldedByPlayer(Host, item)) return true;
var rules = _dashboard?.Settings?.ItemRules;
if (rules != null)
foreach (var rule in rules)
if (rule.Id == item.Id) return true;
return false;
}
private void HandleGiveProfileCommand(string[] parts, bool partialPlayer)
{
if (_objectCache == null) { ChatLine("[RynthAi] Object cache not ready."); return; }
@ -2159,6 +2443,7 @@ public sealed partial class RynthAiPlugin
var nativeProfile = RynthCore.Loot.LootProfile.Load(profilePath);
foreach (var item in _objectCache.GetDirectInventory(forceRefresh: true))
{
if (IsGiveProfileExempt(item)) continue;
var (action, _) = Loot.LootEvaluator.Classify(nativeProfile, item, null);
if (action != RynthCore.Loot.LootAction.Keep) continue;
int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1));
@ -2172,6 +2457,7 @@ public sealed partial class RynthAiPlugin
var lootCtx = new VTankLootContext(Host, Host.GetPlayerId()) { Cache = _objectCache };
foreach (var item in _objectCache.GetDirectInventory(forceRefresh: true))
{
if (IsGiveProfileExempt(item)) continue;
VTankLootRule? matched = null;
foreach (var rule in vtProfile.Rules)
if (VTankLootEvaluator.Match(rule, item, lootCtx)) { matched = rule; break; }
@ -2238,7 +2524,8 @@ public sealed partial class RynthAiPlugin
landblockKey, cellDat,
playerNS, playerEW, playerWZ,
destNS, destEW,
out int nodeCount, out int pathLength);
out int nodeCount, out int pathLength,
los: _raycast?.GeometryLoader?.DungeonLOS);
if (route == null)
{
@ -2246,6 +2533,7 @@ public sealed partial class RynthAiPlugin
return;
}
if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge)
settings.IsMacroRunning = true;
settings.CurrentRoute = route;
settings.ActiveNavIndex = 0;
@ -2351,7 +2639,10 @@ public sealed partial class RynthAiPlugin
}
}
var route = DungeonPathfinder.BuildPatrolRoute(graph, startCell, hazards);
// The dungeon map geometry (doorways, floors, walls): doorways taken straight on and
// big rooms crossed directly. Null (old cell walk) until DungeonLOS is up.
var geometry = DungeonPathfinder.GetGeometry(landblockKey, cellDat, _raycast?.GeometryLoader?.DungeonLOS);
var route = DungeonPathfinder.BuildPatrolRoute(graph, startCell, hazards, geometry);
// Lead the bot out of the hazard first.
if (evacuate)
@ -2376,7 +2667,14 @@ public sealed partial class RynthAiPlugin
int startIdx = FindFirstLineOfSightWaypoint(route, playerCell, playerLocalX, playerLocalY, patrolWZ);
if (!isRebuild)
{
if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) // one bot per client (Decal bridge)
{
_dunPatrolActive = false;
return;
}
settings.IsMacroRunning = true;
}
settings.CurrentNavPath = string.Empty;
settings.CurrentRoute = route;
settings.ActiveNavIndex = startIdx;
@ -2398,7 +2696,12 @@ public sealed partial class RynthAiPlugin
else
{
string skipNote = startIdx > 0 ? $", skipped {startIdx} blocked waypoint(s)" : "";
ChatLine($"[RynthAi] DunNav-Patrol: {graph.Count} cells, {route.Points.Count} waypoints → circular patrol started{skipNote}{hazardNote}");
int doorwayPts = 0;
foreach (var p in route.Points) if (p.Doorway) doorwayPts++;
string layout = geometry != null && doorwayPts > 0
? $", {doorwayPts} of them lined up on doorways"
: geometry == null ? " (dungeon map not loaded yet: cell-centre route)" : "";
ChatLine($"[RynthAi] DunNav-Patrol: {graph.Count} cells, {route.Points.Count} waypoints{layout} → circular patrol started{skipNote}{hazardNote}");
}
}
@ -2778,7 +3081,7 @@ public sealed partial class RynthAiPlugin
for (int i = 0; i < route.Points.Count; i++)
{
var p = route.Points[i];
if (p.Type != NavPointType.Point) continue; // skip pause/chat/portal-action nodes
if (!NavRouteParser.IsPlainWaypoint(p.Type)) continue; // skip pause/chat/portal-action nodes
// NavPoint NS/EW use the same basis as NavCoordinateHelper; invert to world:
// globalX = (EW * 10 + 1019.5) * 24

View file

@ -0,0 +1,71 @@
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
namespace RynthCore.Plugin.RynthAi;
// Learn unknown spells (VTank's ReadUnknownScrolls). The decisions live in
// Loot/ScrollLearner.cs; this is the plugin side: when it is safe to read, and the
// known-spell answer from the spellbook snapshot.
public sealed partial class RynthAiPlugin
{
private ScrollLearner CreateScrollLearner(LegacyUiSettings settings) =>
new(Host, settings, _objectCache)
{
PlayerId = () => _playerId,
KnownSpell = IsSpellKnownForScrolls,
Chat = s => Host.WriteToChat(s, 1),
};
/// <summary>
/// From the spellbook snapshot only. With it cold there is no answer: the IsSpellKnown
/// oracle can say "known" for spells the character doesn't know (see SpellManager).
/// </summary>
private bool? IsSpellKnownForScrolls(int spellId)
{
var sm = _spellManager;
if (sm == null) return null;
sm.RefreshKnownSpells();
return sm.IsKnownSnapshotWarm ? sm.IsKnownSpellId(spellId) : null;
}
/// <summary>
/// A safe moment to read a scroll: macro on, no monster within MonsterRange (nor one
/// on top of us), not buffing (no cast in flight), not on a corpse, not salvaging, not
/// in a portal. Reading puts the character in peace mode for a few seconds.
/// </summary>
internal bool IsSafeToReadScroll(LegacyUiSettings s)
{
if (!s.IsMacroRunning) return false;
if (_activity is BotActivity.Combat or BotActivity.Buffing or BotActivity.Looting or BotActivity.Salvaging) return false;
var combat = _combatManager;
if (combat != null && (combat.HasEngageableTarget || combat.IsUnderCloseAttack)) return false;
if (_openedContainerId != 0 || _targetCorpseId != 0) return false;
if (_buffManager != null && _buffManager.PendingSpellId != 0) return false;
if (_salvageManager?.IsBusy == true) return false;
if (_navigationEngine?.IsInPortalAction == true) return false;
return true;
}
/// <summary>One learner tick; true while a read is in flight and the bot should hold still.</summary>
private bool TickScrollLearner(LegacyUiSettings settings)
{
var learner = _scrollLearner;
if (learner == null) return false;
try
{
return learner.Tick(IsSafeToReadScroll(settings), _busyCount);
}
catch (Exception ex)
{
if (Environment.TickCount64 - _lastLearnErrorLogAt > 10_000)
{
_lastLearnErrorLogAt = Environment.TickCount64;
Host.Log($"[Learn] tick threw: {ex.GetType().Name}: {ex.Message}");
}
return false;
}
}
private long _lastLearnErrorLogAt = -100_000;
}

View file

@ -0,0 +1,17 @@
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Lua moved to its own plugin, RynthLua (2026-09-29). "/ra lua ..." (typed, or a meta's chat
/// action) is forwarded to it as the plugin command ("lua", "run X"), so metas that start
/// scripts keep working. RynthLua's own command is /lua.
/// </summary>
public sealed partial class RynthAiPlugin
{
private void ForwardLuaCommand(string[] parts)
{
string rest = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2) : "";
if (Host.HasSendPluginCommand && Host.SendPluginCommand("RynthLua", "lua", rest))
return;
ChatLine("[RynthAi] Lua scripting is now the RynthLua plugin. Add RynthCore.Plugin.RynthLua.dll in the launcher's Plugins tab, then use /lua (or /ra lua).");
}
}

View file

@ -0,0 +1,304 @@
using System;
using System.Collections.Concurrent;
using System.Globalization;
using System.IO;
using System.Text.Json;
using System.Threading;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The Meta Manager's glue (Docs\META_MANAGER.md): feeds MetaScheduler the bot's state and
/// chat on the pump, sends its /myquests polls, loads the metas it picks, saves its rules
/// per character, and serves /ra metamgr and the engine panel's mm_* ops.
/// </summary>
public sealed partial class RynthAiPlugin
{
private MetaScheduler _metaScheduler = new();
private string _metaScheduleFolder = string.Empty; // character folder the rules were loaded from
private volatile string _metaScheduleJson = string.Empty;
private long _metaScheduleSnapAt;
// Chat-bar events and /ra metamgr may arrive off the pump: flags and a queue, drained on it.
private int _mmTypedQuery; // a "/myquests" passed through the chat bar (maybe our own echo)
private int _mmShownQuery; // RynthAi's quest refresh sent /myquests: show that reply
private readonly ConcurrentQueue<string[]> _metaMgrCommands = new();
/// <summary>OnLoginComplete: hook the dashboard (panel snapshot and ops) and the quest refresh.</summary>
private void WireMetaSchedule()
{
if (_dashboard != null)
{
_dashboard.ScheduleJsonProvider = () => _metaScheduleJson;
_dashboard.ScheduleCommandHandler = ApplyScheduleCommand;
}
if (_questTracker != null)
_questTracker.RefreshSent = () => Interlocked.Exchange(ref _mmShownQuery, 1);
}
/// <summary>TeardownSession: save, then forget this character's rules and quest timers.</summary>
private void TeardownMetaSchedule()
{
SaveMetaScheduleIfDirty();
_metaScheduler = new MetaScheduler();
_metaScheduleFolder = string.Empty;
_metaScheduleJson = string.Empty;
}
private void DrainMetaScheduleQueryFlags(DateTime now)
{
if (Interlocked.Exchange(ref _mmShownQuery, 0) != 0) _metaScheduler.NoteShownQuery(now);
if (Interlocked.Exchange(ref _mmTypedQuery, 0) != 0) _metaScheduler.NoteTypedQuery(now);
}
/// <summary>OnChatBarEnter (any thread): note a /myquests going out; its reply is not ours to eat.</summary>
private void NoteChatBarLineForMetaSchedule(string trimmed)
{
if (trimmed.Equals("/myquests", StringComparison.OrdinalIgnoreCase)
|| trimmed.StartsWith("/myquests ", StringComparison.OrdinalIgnoreCase))
Interlocked.Exchange(ref _mmTypedQuery, 1);
}
/// <summary>OnChatWindowText (pump): true to eat the line (it answers our own /myquests poll).</summary>
private bool MetaScheduleChat(string text)
{
var now = DateTime.UtcNow;
DrainMetaScheduleQueryFlags(now);
return _metaScheduler.OnChatLine(text, now);
}
/// <summary>Why a meta switch must wait now, or null when it is safe.</summary>
private string? MetaSwitchBlocker(LegacyUiSettings s)
{
if (_activity == BotActivity.Combat || _combatManager?.IsUnderCloseAttack == true
|| (s.EnableCombat && _combatManager?.HasEngageableTarget == true))
return "combat";
if (_activity == BotActivity.Looting || _targetCorpseId != 0 || _openedContainerId != 0)
return "looting";
if (_activity == BotActivity.Buffing || (_buffManager?.PendingSpellId ?? 0) != 0)
return "buffing";
if (_navigationEngine?.IsInPortalAction == true)
return "a portal";
if (_autoVendor?.HoldsBot == true || _autoTrade?.HoldsBot == true)
return "a vendor or trade";
if (_missileCraftingManager?.IsCrafting == true)
return "crafting";
return null;
}
/// <summary>Every in-world tick, after the arbiter's decision (so it runs even while buffing holds the tick).</summary>
private void TickMetaSchedule(LegacyUiSettings s)
{
var dash = _dashboard;
if (dash == null) return;
string folder = dash.CharFolder ?? string.Empty;
if (!string.Equals(folder, _metaScheduleFolder, StringComparison.OrdinalIgnoreCase))
{
SaveMetaScheduleIfDirty();
// Another character: start clean. From "no folder yet" (login) keep what the login
// /myquests already taught it, so the first own poll isn't a second one at once.
if (_metaScheduleFolder.Length > 0) _metaScheduler = new MetaScheduler();
_metaScheduleFolder = folder;
if (folder.Length > 0) LoadMetaSchedule();
}
if (folder.Length == 0) return; // no character settings yet: nothing to save to
while (_metaMgrCommands.TryDequeue(out var parts))
{
try { HandleMetaMgrCommand(parts); }
catch (Exception ex) { Host.Log($"[RynthAi] /ra metamgr failed: {ex.Message}"); }
}
var now = DateTime.UtcNow;
DrainMetaScheduleQueryFlags(now);
var inputs = new ScheduleInputs(
InWorld: _loginComplete && _playerId != 0,
MacroRunning: s.IsMacroRunning,
CurrentMetaPath: s.CurrentMetaPath ?? string.Empty,
Blocker: MetaSwitchBlocker(s),
CanPoll: Host.HasInvokeChatParser);
ScheduleAction act = _metaScheduler.Tick(now, inputs);
switch (act.Kind)
{
case ScheduleActionKind.SendPoll:
_questTracker?.ExpectReply(); // quest expressions read the same reply
Host.InvokeChatParser("/myquests");
break;
case ScheduleActionKind.LoadMeta:
string? error = dash.LoadMetaForSchedule(act.Meta);
if (error == null)
ChatLine($"[RynthAi] Meta Manager: loading {act.Meta} ({act.Reason})");
else
{
_metaScheduler.ReportLoadFailed(act.RuleIndex, error);
ChatLine($"[RynthAi] Meta Manager: can't load {act.Meta} for rule #{act.RuleIndex + 1}: {error}. The rule is paused until you edit or reset it.");
}
break;
}
SaveMetaScheduleIfDirty();
long t = Environment.TickCount64;
if (t >= _metaScheduleSnapAt || act.Kind != ScheduleActionKind.None)
{
_metaScheduleSnapAt = t + 500;
_metaScheduleJson = _metaScheduler.BuildSnapshotJson(now, s.CurrentMetaPath ?? string.Empty);
}
}
private string MetaScheduleFile => Path.Combine(_metaScheduleFolder, MetaScheduler.ConfigFileName);
private void LoadMetaSchedule()
{
MetaScheduleConfig? cfg = null;
try
{
if (File.Exists(MetaScheduleFile))
cfg = JsonSerializer.Deserialize(File.ReadAllText(MetaScheduleFile), RynthAiJsonContext.Default.MetaScheduleConfig);
}
catch (Exception ex)
{
Host.Log($"[RynthAi] Meta Manager: {MetaScheduleFile} unreadable ({ex.Message}); starting empty.");
}
_metaScheduler.Load(cfg);
}
private void SaveMetaScheduleIfDirty()
{
if (!_metaScheduler.ConsumeDirty() || _metaScheduleFolder.Length == 0) return;
try
{
Directory.CreateDirectory(_metaScheduleFolder);
string json = JsonSerializer.Serialize(_metaScheduler.Config, RynthAiJsonContext.Default.MetaScheduleConfig);
string tmp = MetaScheduleFile + ".tmp";
File.WriteAllText(tmp, json);
File.Move(tmp, MetaScheduleFile, overwrite: true);
}
catch (Exception ex)
{
Host.Log($"[RynthAi] Meta Manager: save failed: {ex.Message}");
}
}
// =====================================================================
// /ra metamgr (queued to the pump by DispatchRaCommand)
// =====================================================================
private void QueueMetaMgrCommand(string[] parts) => _metaMgrCommands.Enqueue(parts);
private void HandleMetaMgrCommand(string[] parts)
{
var now = DateTime.UtcNow;
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "status";
string meta = _dashboard?.Settings.CurrentMetaPath ?? string.Empty;
switch (sub)
{
case "on":
case "off":
_metaScheduler.SetEnabled(sub == "on");
ChatLine(sub == "on"
? $"[RynthAi] Meta Manager ON ({_metaScheduler.Config.Rules.Count} rule(s))."
: "[RynthAi] Meta Manager OFF.");
break;
case "poll":
if (parts.Length >= 4)
{
if (int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out int m))
{
_metaScheduler.SetPollMinutes(m);
ChatLine($"[RynthAi] Meta Manager: /myquests every {_metaScheduler.Config.PollMinutes} min.");
}
else ChatLine("[RynthAi] Usage: /ra metamgr poll [minutes]");
break;
}
_metaScheduler.RequestPoll();
ChatLine(!_metaScheduler.Config.Enabled ? "[RynthAi] Meta Manager is off; it polls only while on."
: !_metaScheduler.HasQuestRules ? "[RynthAi] Meta Manager has no quest rules; nothing to poll for."
: "[RynthAi] Meta Manager: checking /myquests now.");
break;
case "start":
case "stop":
case "reset":
{
if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /ra metamgr {sub} <rule #>{(sub == "start" ? " [minutes]" : sub == "reset" ? "|all" : "")}"); break; }
if (sub == "reset" && parts[3].Equals("all", StringComparison.OrdinalIgnoreCase))
{
for (int i = 0; i < _metaScheduler.Config.Rules.Count; i++) _metaScheduler.ResetRule(i);
ChatLine("[RynthAi] Meta Manager: every rule re-armed.");
break;
}
if (!int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)
|| n < 1 || n > _metaScheduler.Config.Rules.Count)
{
ChatLine($"[RynthAi] Meta Manager: no rule #{parts[3]} (there are {_metaScheduler.Config.Rules.Count}).");
break;
}
int idx = n - 1;
if (sub == "start")
{
double? mins = null;
if (parts.Length >= 5 && double.TryParse(parts[4], NumberStyles.Float, CultureInfo.InvariantCulture, out double mm) && mm > 0) mins = mm;
ChatLine(_metaScheduler.StartCountdown(idx, mins, now)
? $"[RynthAi] Meta Manager: rule #{n} countdown started ({(mins ?? _metaScheduler.Config.Rules[idx].Minutes).ToString("0.##", CultureInfo.InvariantCulture)} min)."
: $"[RynthAi] Meta Manager: rule #{n} is not a countdown.");
}
else if (sub == "stop")
ChatLine(_metaScheduler.StopCountdown(idx)
? $"[RynthAi] Meta Manager: rule #{n} countdown stopped."
: $"[RynthAi] Meta Manager: rule #{n} has no countdown running.");
else
{
_metaScheduler.ResetRule(idx);
ChatLine($"[RynthAi] Meta Manager: rule #{n} re-armed.");
}
break;
}
case "status":
foreach (string line in _metaScheduler.StatusLines(now, meta)) ChatLine("[RynthAi] " + line);
break;
default:
ChatLine("[RynthAi] Usage: /ra metamgr on|off|status|poll [minutes]|start <#> [min]|stop <#>|reset <#|all>");
break;
}
SaveMetaScheduleIfDirty();
}
// =====================================================================
// Engine panel ops (RynthPluginSendMetaCommand "mm_*", drained on the pump)
// =====================================================================
private void ApplyScheduleCommand(MetaCommand cmd)
{
// Before this character's rules are loaded an edit would land in a throwaway scheduler.
if (_metaScheduleFolder.Length == 0) return;
var now = DateTime.UtcNow;
bool on = string.Equals(cmd.Value, "true", StringComparison.OrdinalIgnoreCase);
int.TryParse(cmd.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n);
switch (cmd.Op)
{
case "mm_enabled": _metaScheduler.SetEnabled(on); break;
case "mm_poll_minutes": if (n > 0) _metaScheduler.SetPollMinutes(n); break;
case "mm_max_wait": _metaScheduler.SetMaxWaitSeconds(n); break;
case "mm_min_gap": _metaScheduler.SetMinGapSeconds(n); break;
case "mm_allow_stopped": _metaScheduler.SetAllowWhileStopped(on); break;
case "mm_add": if (cmd.ScheduleRule != null) _metaScheduler.AddRule(cmd.ScheduleRule); break;
case "mm_update": if (cmd.ScheduleRule != null) _metaScheduler.UpdateRule(cmd.Index, cmd.ScheduleRule); break;
case "mm_delete": _metaScheduler.DeleteRule(cmd.Index); break;
case "mm_move": _metaScheduler.MoveRule(cmd.Index, n); break;
case "mm_rule_enabled": _metaScheduler.SetRuleEnabled(cmd.Index, on); break;
case "mm_countdown_start":
_metaScheduler.StartCountdown(cmd.Index,
double.TryParse(cmd.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double m) && m > 0 ? m : null, now);
break;
case "mm_countdown_stop": _metaScheduler.StopCountdown(cmd.Index); break;
case "mm_reset":
if (cmd.Index < 0) for (int i = 0; i < _metaScheduler.Config.Rules.Count; i++) _metaScheduler.ResetRule(i);
else _metaScheduler.ResetRule(cmd.Index);
break;
case "mm_poll_now": _metaScheduler.RequestPoll(); break;
}
SaveMetaScheduleIfDirty();
_metaScheduleSnapAt = 0; // the panel's next read shows the change
_metaScheduleJson = _metaScheduler.BuildSnapshotJson(now, _dashboard?.Settings.CurrentMetaPath ?? string.Empty);
}
}

View file

@ -0,0 +1,162 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Safety stops for bots running unattended. Every stop is an option; each one
/// says in chat why the macro stopped. Most metas handle a death themselves (run
/// back from the lifestone), so Stop Macro On Death is off by default.
/// </summary>
public sealed partial class RynthAiPlugin
{
private bool _deathSeen;
private readonly Queue<long> _noComponentFails = new();
private long _packFullCheckedAt;
private bool _packFull;
private bool _packFullAnnounced;
private const int NoComponentFailsToStop = 3;
private const long NoComponentWindowMs = 60_000;
private const long PackFullCheckMs = 3_000;
/// <summary>Death = health read as 0 (edge). Runs every tick after the vitals poll.</summary>
private void CheckPlayerDeath(LegacyUiSettings s)
{
bool dead = _vitals.MaxHealth > 0 && _vitals.CurrentHealth == 0;
if (dead && !_deathSeen)
{
_deathSeen = true;
Log("[RynthAi] Death detected (health 0).");
if (s.StopMacroOnDeath && s.IsMacroRunning)
{
HandleMacroRunCommand("stop", Array.Empty<string>());
ChatLine("[RynthAi] You died — macro stopped (Stop Macro On Death is on).");
}
}
else if (!dead && _vitals.CurrentHealth > 0)
{
_deathSeen = false;
}
}
private long _deathHoldUntil;
private bool _deathHolding;
private const long DeathSettleMs = 5_000;
/// <summary>
/// True from a death until the character is alive, out of portal space and
/// has had 5 s to settle. While it holds, the bot does nothing: no buffing,
/// combat, weapon swaps, looting, busy clears or navigation. Both death-portal
/// crashes (2026-09-28 12:04 and 18:06, inside AC's code while it tore down and
/// reloaded the world) came with the bot still casting and dequipping through
/// the death. Reads the vitals every tick (the regular poll is every 30).
/// </summary>
private bool HoldForDeath()
{
long now = Environment.TickCount64;
bool dead = Host.HasGetPlayerVitals
&& Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out _, out _, out _, out _)
&& maxHp > 0 && hp == 0;
if (dead)
{
_deathHoldUntil = long.MaxValue;
_metaManager?.OnPlayerDeath(); // the meta's Death condition sees it after the hold
}
else if (_deathHoldUntil == long.MaxValue)
{
// Alive again: wait out the portal to the lifestone, then settle.
if (!(Host.HasIsPortaling && Host.IsPortaling()))
_deathHoldUntil = now + DeathSettleMs;
}
bool hold = now < _deathHoldUntil;
if (hold != _deathHolding)
{
_deathHolding = hold;
if (hold)
{
Log("[RynthAi] Died — holding all actions until respawned and out of portal space.");
_combatManager?.ReleaseHeldTurn();
_navigationEngine?.Stop();
}
else
Log("[RynthAi] Respawned — resuming.");
}
return hold;
}
/// <summary>Chat hook: repeated "don't have all the components" stops the macro when enabled.</summary>
private void CheckChatForSafetyStops(string text)
{
var s = _dashboard?.Settings;
if (s == null || !s.StopMacroOnNoComponents || !s.IsMacroRunning) return;
if (text.IndexOf("have all the components for this spell", StringComparison.OrdinalIgnoreCase) < 0) return;
long now = Environment.TickCount64;
_noComponentFails.Enqueue(now);
while (_noComponentFails.Count > 0 && now - _noComponentFails.Peek() > NoComponentWindowMs)
_noComponentFails.Dequeue();
if (_noComponentFails.Count < NoComponentFailsToStop) return;
_noComponentFails.Clear();
HandleMacroRunCommand("stop", Array.Empty<string>());
ChatLine("[RynthAi] Out of spell components — macro stopped (Stop Macro On No Components is on).");
}
/// <summary>
/// True when no pack (main pack included) has a free slot. Checked at most
/// every 3 s. The first time it turns true: a chat notice, and the macro
/// stops if Stop Macro When Pack Full is on.
/// </summary>
internal bool IsPackFull()
{
long now = Environment.TickCount64;
if (now - _packFullCheckedAt < PackFullCheckMs) return _packFull;
_packFullCheckedAt = now;
bool full = _objectCache != null && _playerId != 0
&& WorldObjectCache.FindPackFor(Host, _objectCache, includeMainPack: true, requireFree: 1) == 0;
_packFull = full;
if (!full) { _packFullAnnounced = false; return false; }
if (!_packFullAnnounced)
{
_packFullAnnounced = true;
var s = _dashboard?.Settings;
if (s != null && s.StopMacroWhenPackFull && s.IsMacroRunning)
{
HandleMacroRunCommand("stop", Array.Empty<string>());
ChatLine("[RynthAi] Your packs are full — macro stopped (Stop Macro When Pack Full is on).");
}
else
{
ChatLine("[RynthAi] Your packs are full — not looting until there's room.");
}
}
return true;
}
private long _lootReserveCheckedAt;
private bool _belowLootReserve;
/// <summary>
/// True when fewer slots are free than looting keeps for weapon swaps
/// (LootReserveFreeSlots). The pickup gate refuses every item then, so a new
/// corpse would only be walked to, opened and given up on. Checked at most every
/// 3 s; -1 (side-pack capacity unknown) is not treated as low.
/// </summary>
internal bool IsBelowLootReserve()
{
long now = Environment.TickCount64;
if (now - _lootReserveCheckedAt < PackFullCheckMs) return _belowLootReserve;
_lootReserveCheckedAt = now;
int free = _playerId != 0 ? WorldObjectCache.CountFreeItemSlots(Host, _objectCache) : -1;
_belowLootReserve = free >= 0 && free < WorldObjectCache.LootReserveFreeSlots;
if (_belowLootReserve)
WorldObjectCache.WarnPackFull(Host, $"not looting with {free} free slot(s) so weapon swaps still work");
return _belowLootReserve;
}
}

View file

@ -0,0 +1,86 @@
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
// One bot per client under the Decal bridge (VTankYield.cs): VTank starting stops RynthAi's
// macro, and RynthAi's macro doesn't start while VTank runs. "Yield to VTank" (settings, on by
// default, /ra vtankyield) turns it off. Without Decal the engine isn't watching and none of
// this ever refuses or stops anything.
public sealed partial class RynthAiPlugin
{
private readonly VTankYield _vtankYield = new();
// Set by the panel's macro button (it can come from another thread): the refusal line is
// printed on the next tick, from the pump thread.
private volatile bool _vtankRefusalPending;
/// <summary>
/// For every explicit start (/ra start, a meta, the phone, a script, a patrol): true = VTank
/// runs and yield is on, so the caller must not start; the refusal line is printed here.
/// Pump thread.
/// </summary>
internal bool RefuseMacroStartForVTank()
{
var dash = _dashboard;
if (dash == null)
return false;
_vtankYield.Poll(Host);
if (!_vtankYield.RefuseStart(dash.Settings, ChatLine))
return false;
Host.Log("[RynthAi] VTank yield: macro start refused (VTank's macro runs).");
return true;
}
/// <summary>The panel's macro button (RynthPluginToggleMacro). Uses the state the last tick read.</summary>
internal void ToggleMacroFromPanel()
{
var dash = _dashboard;
if (dash == null) return;
if (!dash.Settings.IsMacroRunning && _vtankYield.BlocksStart(dash.Settings.YieldToVTank))
{
_vtankRefusalPending = true;
return;
}
dash.TogglePanelMacro();
}
/// <summary>
/// Once per tick, before anything the macro does. Stops the macro the way /ra stop does
/// (the macro-stop edge in OnTick then cancels the attack, stops movement and clears busy).
/// </summary>
private void TickVTankYield(LegacyUiSettings settings)
{
_vtankYield.Poll(Host);
if (_vtankRefusalPending)
{
_vtankRefusalPending = false;
ChatLine(VTankYield.RefusedLine);
}
var verdict = _vtankYield.Apply(settings, _macroWasRunning, onStop: () =>
{
_macroResumeAt = 0; // a /ra pause must not bring it back
_navigationEngine?.Stop(); // as /ra stop: autorun off now
}, ChatLine, Environment.TickCount64);
if (verdict != VTankYield.Verdict.None)
Host.Log($"[RynthAi] VTank yield: {verdict} - macro switched off.");
}
/// <summary>/ra vtankyield [on|off]</summary>
private void HandleVTankYieldCommand(string[] parts)
{
var dash = _dashboard;
if (dash == null) { ChatLine("[RynthAi] Settings not ready."); return; }
if (parts.Length >= 3)
{
string v = parts[2].ToLowerInvariant();
if (v is "on" or "1" or "true") dash.Settings.YieldToVTank = true;
else if (v is "off" or "0" or "false") dash.Settings.YieldToVTank = false;
else { ChatLine("[RynthAi] Usage: /ra vtankyield [on|off]"); return; }
dash.SaveSettings();
}
_vtankYield.Poll(Host);
ChatLine(_vtankYield.Describe(dash.Settings.YieldToVTank, Host.HasGetVTankState));
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,111 @@
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Json;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
/// <summary>
/// /ra version: this RynthAi build (the DLL's version resource, stamped at release with the
/// release number and commit; "dev (commit)" for an unstamped build), when it was built,
/// and the engine it runs on (build stamp from the engine's status export on engines that
/// publish it, and the plugin API version).
/// </summary>
private void HandleVersionCommand()
{
string path = PluginModule.Path();
string version = PluginModule.FormatVersion(path);
string built = PluginModule.BuildDate(path);
ChatLine($"[RynthAi] RynthAi {version} (plugin {PluginModule.HandWrittenVersion}), built {built}.");
string engine = "unknown";
uint api = Host.Version;
string? json = Host.HasGetEngineStatusJson ? Host.GetEngineStatusJson() : null;
if (!string.IsNullOrEmpty(json))
{
try
{
using JsonDocument doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("engineVersion", out JsonElement ev) && ev.ValueKind == JsonValueKind.String)
engine = ev.GetString() ?? engine;
}
catch (JsonException) { }
}
ChatLine(engine == "unknown"
? $"[RynthAi] Engine: plugin API v{api} (this engine doesn't report its build)."
: $"[RynthAi] Engine: RynthCore {engine}, plugin API v{api}.");
}
/// <summary>Where this plugin's DLL was loaded from, and what its version resource says.</summary>
private static unsafe class PluginModule
{
/// <summary>RynthPluginVersion's hand-written string (it never changes between builds).</summary>
public const string HandWrittenVersion = "0.5.0-legacy-ui";
private const uint FromAddress = 0x4, UnchangedRefCount = 0x2;
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetModuleHandleExW(uint flags, IntPtr address, out IntPtr module);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetModuleFileNameW(IntPtr module, char* buffer, int size);
/// <summary>The loaded DLL (the engine's shadow copy), found from an export's address.</summary>
public static string Path()
{
try
{
delegate* unmanaged[Cdecl]<IntPtr> anchor = &PluginExports.GetName;
if (!GetModuleHandleExW(FromAddress | UnchangedRefCount, (IntPtr)anchor, out IntPtr module) || module == IntPtr.Zero)
return string.Empty;
char* buffer = stackalloc char[1024];
int n = GetModuleFileNameW(module, buffer, 1024);
return n > 0 && n < 1024 ? new string(buffer, 0, n) : string.Empty;
}
catch
{
return string.Empty;
}
}
/// <summary>"2026.9.30.1 (8ca322f)" for a release, "dev (8ca322f)" for an unstamped build.</summary>
public static string FormatVersion(string path)
{
string? product = null;
try
{
if (path.Length > 0 && File.Exists(path))
product = FileVersionInfo.GetVersionInfo(path).ProductVersion;
}
catch { }
if (string.IsNullOrWhiteSpace(product)) return "unknown";
string version = product.Trim();
string commit = string.Empty;
int plus = version.IndexOf('+');
if (plus >= 0)
{
commit = version[(plus + 1)..];
version = version[..plus];
}
if (commit.Length > 7) commit = commit[..7];
if (version is "1.0.0" or "1.0.0.0") version = "dev";
return commit.Length > 0 ? $"{version} ({commit})" : version;
}
/// <summary>The DLL's last-write time (the engine's shadow copy keeps the build's), local time.</summary>
public static string BuildDate(string path)
{
try
{
if (path.Length > 0 && File.Exists(path))
return File.GetLastWriteTime(path).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
}
catch { }
return "unknown";
}
}
}

View file

@ -17,12 +17,36 @@
<Platforms>x86</Platforms>
</PropertyGroup>
<ItemGroup>
<!-- Interfaces shared with other RynthSuite plugins (RynthLua uses RynthAi.Script, RynthNet RynthAi.Status). -->
<Compile Include="..\Shared\RynthAiScriptApi.cs" Link="Shared\RynthAiScriptApi.cs" />
<!-- RynthNet reads the bot state through RynthAi.Status. -->
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- RynthNav's navmesh path queries (stuck-recovery detours outdoors). -->
<Compile Include="..\Shared\RynthNavPathApi.cs" Link="Shared\RynthNavPathApi.cs" />
<!-- One logged, guarded way to use an object (who used what, and why). -->
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
</ItemGroup>
<ItemGroup>
<!-- Offline tests (Tools\RynthCore.RynthAiHostTests) reach internal types. Test-only; no runtime effect. -->
<InternalsVisibleTo Include="RynthCore.RynthAiHostTests" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Combat\SpellData.txt" />
<!-- Creature weaknesses (ops/rynth-creature-resists.py builds both). -->
<EmbeddedResource Include="CreatureData\creature_resists.tsv" />
<EmbeddedResource Include="CreatureData\creature_types.txt" />
<!-- Creature weakness table (wcid -> damage multipliers) from the world database. Built in,
and also copied next to the DLL as Data\creature_weakness.json; a copy in
C:\Games\RynthSuite\RynthAi\Data wins over the built-in one. -->
<EmbeddedResource Include="Data\creature_weakness.json" />
<None Include="Data\creature_weakness.json" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>

View file

@ -0,0 +1,275 @@
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// RynthAi's side of the "RynthAi.Script" interface (Shared/RynthAiScriptApi.cs): the
/// table RynthPluginQueryInterface hands out, and the functions behind it. They run on
/// the plugin pump thread (the caller's OnTick), between RynthAi's own ticks, and act on
/// the current plugin instance (Runtime.Plugin), so the table survives a re-Init.
/// </summary>
internal static unsafe class ScriptInterface
{
private static RynthAiScriptApiV1* _table;
private static IntPtr _out; // the last string handed back (valid until the next call)
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthAiScriptApiV1.InterfaceName || version != RynthAiScriptApiV1.InterfaceVersion) return IntPtr.Zero;
if (_table == null)
{
var t = (RynthAiScriptApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiScriptApiV1));
t->Version = RynthAiScriptApiV1.InterfaceVersion;
t->StructSize = (uint)sizeof(RynthAiScriptApiV1);
t->Evaluate = &Evaluate;
t->GetSetting = &GetSetting;
t->SetSetting = &SetSetting;
t->GetSettingNames = &GetSettingNames;
t->IsMacroRunning = &IsMacroRunning;
t->SetMacroRunning = &SetMacroRunning;
t->NavGoTo = &NavGoTo;
t->NavStop = &NavStop;
t->FindNearest = &FindNearest;
t->DistanceTo = &DistanceTo;
t->IsPathClear = &IsPathClear;
t->SubmitCommand = &SubmitCommand;
_table = t;
}
return (IntPtr)_table;
}
private static RynthAiPlugin? P => PluginExports.Runtime.Plugin;
private static string In(byte* s) => s == null ? "" : Marshal.PtrToStringUTF8((IntPtr)s) ?? "";
private static void Out(byte** dst, string value)
{
if (dst == null) return;
IntPtr fresh = Marshal.StringToCoTaskMemUTF8(value ?? "");
IntPtr old = _out;
_out = fresh;
if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old);
*dst = (byte*)fresh;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Evaluate(byte* expr, byte** result)
{
try
{
var p = P;
if (p == null) { Out(result, "RynthAi not ready"); return 0; }
bool ok = p.ScriptEvaluate(In(expr), out string r);
Out(result, r);
return ok ? 1 : 0;
}
catch (Exception ex) { Out(result, ex.Message); return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetSetting(byte* name, byte** value)
{
try
{
string? v = P?.ScriptGetSetting(In(name));
if (v == null) return 0;
Out(value, v);
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetSetting(byte* name, byte* value)
{
try { return P?.ScriptSetSetting(In(name), In(value)) == true ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetSettingNames(byte** names)
{
try
{
string? all = P?.ScriptSettingNames();
if (all == null) return 0;
Out(names, all);
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int IsMacroRunning()
{
try { return P?.ScriptMacroRunning == true ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void SetMacroRunning(int on)
{
try { P?.ScriptSetMacro(on != 0); } catch { }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int NavGoTo(double ns, double ew)
{
try { return P?.ScriptGoTo(ns, ew) == true ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void NavStop()
{
try { P?.ScriptStop(); } catch { }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int FindNearest(byte* name, int flags, uint* id, double* distance)
{
try
{
var p = P;
if (p == null) return 0;
if (!p.ScriptFindNearest(In(name), (flags & 1) != 0, out uint found, out double d)) return 0;
if (id != null) *id = found;
if (distance != null) *distance = d;
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static double DistanceTo(uint id)
{
try { return P?.ScriptDistanceTo(id) ?? -1; }
catch { return -1; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int IsPathClear(uint id)
{
try { return P?.ScriptIsPathClear(id) == false ? 0 : 1; }
catch { return 1; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SubmitCommand(byte* text)
{
try
{
string t = In(text).Trim();
if (t.Length == 0 || P == null) return 0;
P.ScriptSubmitCommand(t);
return 1;
}
catch { return 0; }
}
}
/// <summary>What the "RynthAi.Script" interface does, on the plugin instance.</summary>
public sealed partial class RynthAiPlugin
{
internal bool ScriptEvaluate(string expression, out string result)
{
var engine = _metaManager?.Expressions;
if (engine == null) { result = "not logged in yet (meta engine not ready)"; return false; }
string r = engine.Evaluate(expression);
if (r.StartsWith("ERR:", StringComparison.Ordinal)) { result = r.Substring(4).Trim(); return false; }
result = r;
return true;
}
internal string? ScriptGetSetting(string name)
{
var map = _metaManager?.Expressions.BuildSettingsMapPublic();
return map != null && map.TryGetValue(name, out var entry) ? entry.Get() : null;
}
internal bool ScriptSetSetting(string name, string value)
{
var map = _metaManager?.Expressions.BuildSettingsMapPublic();
if (map == null || !map.TryGetValue(name, out var entry)) return false;
entry.Set(value);
_dashboard?.SaveSettings();
return true;
}
internal string? ScriptSettingNames()
{
var map = _metaManager?.Expressions.BuildSettingsMapPublic();
return map == null ? null : string.Join("\n", map.Keys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase));
}
internal bool ScriptMacroRunning => _dashboard?.Settings.IsMacroRunning == true;
internal void ScriptSetMacro(bool on)
{
if (_dashboard == null || _dashboard.Settings.IsMacroRunning == on) return;
if (on && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge)
if (on) _dashboard.TogglePanelMacro();
else HandleMacroRunCommand("stop", Array.Empty<string>());
}
internal bool ScriptGoTo(double ns, double ew)
{
var dash = _dashboard;
if (dash == null) return false;
var st = dash.Settings;
if (!st.IsMacroRunning && RefuseMacroStartForVTank()) return false; // one bot per client (Decal bridge)
float z = 0;
if (Host.HasGetPlayerPose) Host.TryGetPlayerPose(out _, out _, out _, out z, out _, out _, out _, out _);
var route = new NavRouteParser { RouteType = NavRouteType.Once };
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = z / 240.0 });
st.CurrentRoute = route;
st.CurrentNavPath = string.Empty;
st.ActiveNavIndex = 0;
st.EnableNavigation = true;
if (!st.IsMacroRunning) dash.TogglePanelMacro();
return true;
}
internal void ScriptStop()
{
if (_dashboard?.Settings.IsMacroRunning == true) HandleMacroRunCommand("stop", Array.Empty<string>());
else _navigationEngine?.Stop();
}
internal bool ScriptFindNearest(string name, bool portalOrNpcOnly, out uint id, out double distance)
{
id = 0;
distance = -1;
if (_objectCache == null || string.IsNullOrWhiteSpace(name) || _playerId == 0) return false;
var wo = FindNearestPositioned(w => w.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0
&& (!portalOrNpcOnly || IsPortalObject(w) || w.ObjectClass == AcObjectClass.Npc), out double d);
if (wo == null) return false;
id = unchecked((uint)wo.Id);
distance = d == double.MaxValue ? -1 : Math.Round(d, 2);
return true;
}
internal double ScriptDistanceTo(uint id)
{
if (_objectCache == null || _playerId == 0 || id == 0) return -1;
double d = _objectCache.Distance(unchecked((int)_playerId), unchecked((int)id));
return d == double.MaxValue ? -1 : Math.Round(d, 2);
}
internal bool ScriptIsPathClear(uint id)
{
if (id == 0 || _raycast == null || !_raycast.IsInitialized) return true;
return !_raycast.IsTargetBlocked(Host, id, TargetingFSM.AttackType.Linear);
}
internal void ScriptSubmitCommand(string text) => HandleRynthChatSubmit(text);
}

View file

@ -0,0 +1,100 @@
using System;
using System.Buffers;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.Json;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// RynthAi's side of the "RynthAi.Status" interface (Shared/RynthAiStatusApi.cs): a compact
/// summary of what the bot is doing, which RynthNet shares with the other clients. Runs on
/// the plugin pump thread (the caller's OnTick), on the current plugin instance.
/// </summary>
internal static unsafe class StatusInterface
{
private static RynthAiStatusApiV1* _table;
private static IntPtr _out; // the last string handed back (valid until the next call)
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthAiStatusApiV1.InterfaceName || version == 0 || version > RynthAiStatusApiV1.InterfaceVersion) return IntPtr.Zero;
if (_table == null)
{
var t = (RynthAiStatusApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiStatusApiV1));
t->Version = RynthAiStatusApiV1.InterfaceVersion;
t->StructSize = (uint)sizeof(RynthAiStatusApiV1);
t->GetStatusJson = &GetStatusJson;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Frees the table and the last string (plugin shutdown). Callers resolve it every tick.</summary>
public static void Release()
{
var t = _table;
_table = null;
if (t != null) NativeMemory.Free(t);
IntPtr o = _out;
_out = IntPtr.Zero;
if (o != IntPtr.Zero) Marshal.FreeCoTaskMem(o);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetStatusJson(byte** json)
{
try
{
string? s = PluginExports.Runtime.Plugin?.BuildBotStatusJson();
if (s == null || json == null) return 0;
IntPtr fresh = Marshal.StringToCoTaskMemUTF8(s);
IntPtr old = _out;
_out = fresh;
if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old);
*json = (byte*)fresh;
return 1;
}
catch
{
return 0;
}
}
}
public sealed partial class RynthAiPlugin
{
/// <summary>{macro,action,state,combat,buff,nav,loot,meta,navFile,metaFile,lootFile}; null before login.</summary>
internal string? BuildBotStatusJson()
{
var st = _dashboard?.Settings;
if (st == null || !_loginComplete) return null;
var buffer = new ArrayBufferWriter<byte>(256);
using (var w = new Utf8JsonWriter(buffer))
{
w.WriteStartObject();
w.WriteBoolean("macro", st.IsMacroRunning);
w.WriteString("action", st.BotAction ?? "");
w.WriteString("state", st.CurrentState ?? "");
w.WriteBoolean("combat", st.EnableCombat);
w.WriteBoolean("buff", st.EnableBuffing);
w.WriteBoolean("nav", st.EnableNavigation);
w.WriteBoolean("loot", st.EnableLooting);
w.WriteBoolean("meta", st.EnableMeta);
w.WriteString("navFile", FileName(st.CurrentNavPath));
w.WriteString("metaFile", FileName(st.CurrentMetaPath));
w.WriteString("lootFile", FileName(st.CurrentLootPath));
w.WriteEndObject();
}
return System.Text.Encoding.UTF8.GetString(buffer.WrittenSpan);
}
private static string FileName(string? path)
{
if (string.IsNullOrEmpty(path)) return "";
try { return Path.GetFileName(path); }
catch { return ""; }
}
}

View file

@ -0,0 +1,153 @@
// AutoTrade commands. The /ub autotrade syntax is ported from UtilityBelt
// (https://gitlab.com/utilitybelt/utilitybelt.gitlab.io), MIT License, Copyright (c) the
// UtilityBelt contributors; see THIRD-PARTY-NOTICES.md at the root of this repository.
using System;
using System.Globalization;
using RynthCore.Plugin.RynthAi.Trade;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// /ra autotrade ... (and UtilityBelt's /ub autotrade ...): parsed here (chat thread), run by
/// AutoTradeManager on the plugin tick thread. /ra trade ... drives the engine's trade calls by
/// hand (open, add, accept, decline, reset, close, state) for testing.
/// </summary>
public sealed partial class RynthAiPlugin
{
private AutoTradeManager? _autoTrade;
/// <summary>/ub autotrade ... Returns false when the verb isn't autotrade.</summary>
private bool TryHandleAutoTradeCommand(string cmd, string fullCommand)
{
if (cmd != "autotrade")
return false;
RunAutoTradeCommand(AfterWords(fullCommand, 2));
return true;
}
/// <summary>/ra autotrade [args]: the same commands as /ub autotrade.</summary>
private void HandleAutoTradeRaCommand(string[] parts)
=> RunAutoTradeCommand(parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2) : string.Empty);
private void RunAutoTradeCommand(string args)
{
var at = _autoTrade;
if (at == null)
{
ChatLine("[RynthAi] AutoTrade isn't ready yet (log in first).");
return;
}
at.Enqueue(() => at.Command(args));
}
/// <summary>/ra trade [state | open &lt;name|id|sel&gt; | add &lt;id|sel&gt; | accept | decline | reset | close]</summary>
private void HandleTradeCommand(string[] parts)
{
if (!Host.HasTrade)
{
ChatLine($"[RynthAi] Player trading needs RynthCore 2026.9.x or newer (plugin API v{AutoTradeManager.RequiredApiVersion}; this engine is v{Host.Version}).");
return;
}
string verb = parts.Length > 2 ? parts[2].ToLowerInvariant() : "state";
string arg = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3).Trim() : string.Empty;
switch (verb)
{
case "state":
case "status":
PrintTradeState();
break;
case "open":
{
uint target = ResolveTradeTarget(arg);
if (target == 0) { ChatLine("[RynthAi] Usage: /ra trade open <player name|id|sel>"); break; }
ChatLine(Host.TradeOpen(target)
? $"[RynthAi] Asked {TradeName(target)} to trade."
: "[RynthAi] Could not send the trade request.");
break;
}
case "add":
{
uint item = ParseTradeId(arg);
if (item == 0) { ChatLine("[RynthAi] Usage: /ra trade add <item id|sel>"); break; }
ChatLine(Host.TradeAdd(item)
? $"[RynthAi] Adding {TradeName(item)} to the trade window."
: "[RynthAi] Could not send the add.");
break;
}
case "accept": ChatLine(Host.TradeAccept() ? "[RynthAi] Accepting the trade." : "[RynthAi] Could not send the accept."); break;
case "decline": ChatLine(Host.TradeDecline() ? "[RynthAi] Declining the trade." : "[RynthAi] Could not send the decline."); break;
case "reset": ChatLine(Host.TradeReset() ? "[RynthAi] Clearing the trade window." : "[RynthAi] Could not send the reset."); break;
case "close": ChatLine(Host.TradeClose() ? "[RynthAi] Closing the trade." : "[RynthAi] Could not send the close."); break;
default:
ChatLine("[RynthAi] Usage: /ra trade [state | open <name|id|sel> | add <id|sel> | accept | decline | reset | close]");
break;
}
}
private void PrintTradeState()
{
if (!Host.TryGetTradeState(out TradeState st))
{
ChatLine("[RynthAi] No trade state from the engine.");
return;
}
ChatLine($"[RynthAi] Trade: {(st.IsOpen ? $"open with {TradeName(st.PartnerId)}" : "closed")}, generation {st.Generation}, seq {st.Sequence}, "
+ $"last event 0x{st.LastEventType:X4}, completed {st.CompletedCount}, watching {st.Watching}, actions {st.ActionsAvailable}.");
if (st.IsOpen)
{
ChatLine($"[RynthAi] You ({st.YourItemCount}{(st.YouAccepted ? ", accepted" : string.Empty)}): {DescribeTradeSide(TradeSide.You)}");
ChatLine($"[RynthAi] Them ({st.PartnerItemCount}{(st.PartnerAccepted ? ", accepted" : string.Empty)}): {DescribeTradeSide(TradeSide.Partner)}");
}
if (st.FailureCount > 0)
ChatLine($"[RynthAi] Last failure: {TradeName(st.LastFailureItemId)} error 0x{st.LastFailureReason:X4} ({st.FailureCount} so far).");
if (!st.IsOpen && st.LastCloseReason != 0)
ChatLine($"[RynthAi] Last close reason: 0x{st.LastCloseReason:X}.");
var at = _autoTrade;
if (at != null)
ChatLine($"[RynthAi] AutoTrade: {at.Status}");
}
private string DescribeTradeSide(TradeSide side)
{
uint[] ids = Host.GetTradeItems(side);
if (ids.Length == 0) return "(nothing)";
var names = new System.Collections.Generic.List<string>();
for (int i = 0; i < ids.Length && i < 12; i++) names.Add(TradeName(ids[i]));
return string.Join(", ", names) + (ids.Length > 12 ? $", ...{ids.Length - 12} more" : string.Empty);
}
private string TradeName(uint id)
=> id != 0 && Host.TryGetObjectName(id, out string n) && !string.IsNullOrWhiteSpace(n) ? n : $"0x{id:X8}";
private uint ParseTradeId(string token)
{
string t = token.Trim();
if (t.Length == 0) return 0;
if (t.Equals("sel", StringComparison.OrdinalIgnoreCase) || t.Equals("selected", StringComparison.OrdinalIgnoreCase))
return Host.GetSelectedItemId();
if (t.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
&& uint.TryParse(t.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint hex))
return hex;
return uint.TryParse(t, NumberStyles.Integer, CultureInfo.InvariantCulture, out uint dec) ? dec : 0;
}
/// <summary>A player by id, "sel", or (partial) name among nearby players.</summary>
private uint ResolveTradeTarget(string arg)
{
uint id = ParseTradeId(arg);
if (id != 0) return id;
if (arg.Length == 0 || _objectCache == null) return 0;
int me = unchecked((int)_playerId);
WorldObject? partial = null;
foreach (var wo in _objectCache.GetLandscapeObjects())
{
if (wo == null || wo.Id == me || wo.ObjectClass != AcObjectClass.Player) continue;
if (string.Equals(wo.Name, arg, StringComparison.OrdinalIgnoreCase)) return unchecked((uint)wo.Id);
if (partial == null && wo.Name.IndexOf(arg, StringComparison.OrdinalIgnoreCase) >= 0) partial = wo;
}
return partial != null ? unchecked((uint)partial.Id) : 0;
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,5 @@
using System;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
@ -8,6 +9,73 @@ namespace RynthCore.Plugin.RynthAi;
/// </summary>
public sealed partial class RynthAiPlugin
{
/// <summary>
/// Portal by class, or, for objects the cache classified before their type was
/// known (they stay Unknown), by the live item type, or by a name ending in
/// "Portal" when the type isn't available.
/// </summary>
internal bool IsPortalObject(WorldObject wo)
{
if (wo.ObjectClass == RynthCore.Loot.AcObjectClass.Portal) return true;
if (wo.ObjectClass is RynthCore.Loot.AcObjectClass.Monster or RynthCore.Loot.AcObjectClass.Player
or RynthCore.Loot.AcObjectClass.Corpse or RynthCore.Loot.AcObjectClass.Npc) return false;
// The cached class can be a name guess; the live item type is the truth.
if (Host.TryGetItemType(unchecked((uint)wo.Id), out uint t) && t != 0)
return (t & 0x00010000u) != 0;
return wo.Name.IndexOf("Portal", StringComparison.OrdinalIgnoreCase) >= 0;
}
/// <summary>
/// Nearest object with a position matching <paramref name="accept"/>. Looks at
/// every known object, not only the landscape set: a portal filed as inventory
/// (created before its position arrived) was invisible to closestportal.
/// </summary>
internal WorldObject? FindNearestPositioned(Func<WorldObject, bool> accept, out double distance)
{
distance = double.MaxValue;
if (_objectCache == null || _playerId == 0) return null;
int me = unchecked((int)_playerId);
WorldObject? best = null;
foreach (var wo in _objectCache.AllKnownObjects())
{
if (wo == null || wo.Id == me || !accept(wo)) continue;
double d = _objectCache.Distance(me, wo.Id);
if (d == double.MaxValue) continue; // no position (in a pack)
if (d < distance) { distance = d; best = wo; }
}
return best;
}
/// <summary>After a miss: log the nearest object whose name mentions Portal, with its class and type.</summary>
private void LogPortalMiss(string what)
{
var near = FindNearestPositioned(w => w.Name.IndexOf("Portal", StringComparison.OrdinalIgnoreCase) >= 0, out double d);
if (near == null) { Log($"[RynthAi] {what}: no object named like a portal in range either."); return; }
uint t = Host.TryGetItemType(unchecked((uint)near.Id), out uint tt) ? tt : 0;
Log($"[RynthAi] {what}: nearest '*Portal*' object was {near.Name} 0x{(uint)near.Id:X8} at {d:F1} m, class={near.ObjectClass}, itemType=0x{t:X8}.");
}
private void UseClosestPortal()
{
if (_objectCache == null || _playerId == 0) { ChatLine("[RynthAi] Not logged in."); return; }
var best = FindNearestPositioned(IsPortalObject, out double bestD);
if (best == null) { ChatLine("[RynthAi] No portal nearby."); LogPortalMiss("closestportal"); return; }
ChatLine($"[RynthAi] Using {best.Name} ({bestD:F1} m).");
Host.UseFor(unchecked((uint)best.Id), "Command", "/ub closestportal", UseKind.Asked);
}
/// <summary>
/// UtilityBelt's network commands (/ub bc, /ub bct, /ub netclients) go to the RynthNet
/// plugin as ("ub", "bc ...") through the host broker; RynthNet runs them on its own tick.
/// </summary>
private void ForwardNetCommand(string fullCommand)
{
string rest = fullCommand.Length > 3 ? fullCommand.Substring(3).Trim() : "";
if (Host.HasSendPluginCommand && Host.SendPluginCommand("RynthNet", "ub", rest))
return;
ChatLine("[RynthAi] /ub bc, /ub bct and /ub netclients need the RynthNet plugin (the launcher's Plugins tab).");
}
/// <summary>
/// Handle a /ub command. Returns true if recognized and handled.
/// </summary>
@ -25,10 +93,21 @@ public sealed partial class RynthAiPlugin
return true;
}
// /ub bc, /ub bct, /ub netclients (UtilityBelt's networking) belong to the RynthNet plugin.
if (cmd is "bc" or "bct" or "netclients")
{
ForwardNetCommand(fullCommand);
return true;
}
// /ub autovendor ... and /ub vendor ... (UtilityBelt AutoVendor) — Vendor/AutoVendorCommands.cs
if (TryHandleAutoVendorCommand(cmd, fullCommand))
return true;
// /ub autotrade ... (UtilityBelt AutoTrade) — Trade/AutoTradeCommands.cs
if (TryHandleAutoTradeCommand(cmd, fullCommand))
return true;
// Most remaining /ub verbs (use / usep / uselp / useip / face / give /
// givep / combatstate / cast …) share semantics with the natively
// implemented /mt verbs, which talk to host primitives (UseObject /
@ -41,12 +120,27 @@ public sealed partial class RynthAiPlugin
// Verbs /mt doesn't implement but /ra does — route to the /ra dispatcher
// (VTank-meta migration). "/ub follow X" → "/ra follow X"; myquests → /ra
// quest-flag refresh.
if (sp > 0 && cmd is "follow" or "ig" or "mexec" or "myquests")
if (sp > 0 && cmd is "follow" or "ig" or "mexec" or "myquests"
or "igp" or "giver" or "listvars" or "listgvars" or "listpvars"
or "selecti" or "selectl" or "selectip" or "selectpi" or "selectlp" or "selectpl")
{
HandleRaCommand("/ra" + fullCommand.Substring(sp));
return true;
}
// Same commands under UB's names: /ub propertydump = /ra dumpprops,
// /ub followp <partial name> = /ra follow (which matches partial names).
if (cmd == "propertydump")
{
HandleRaCommand("/ra dumpprops" + (fullCommand.Length > sp + cmd.Length + 1 ? fullCommand.Substring(sp + cmd.Length + 1) : ""));
return true;
}
if (cmd == "followp")
{
HandleRaCommand("/ra follow" + (fullCommand.Length > sp + cmd.Length + 1 ? fullCommand.Substring(sp + cmd.Length + 1) : ""));
return true;
}
// /ub clearbugged is RynthAi's clearbusy (force-reset busy state) under a
// different name.
if (cmd == "clearbugged")
@ -55,6 +149,17 @@ public sealed partial class RynthAiPlugin
return true;
}
// Commands added in the 2026-09-28 parity pass (UtilityBeltExtraCommands.cs).
if (TryHandleUbExtra(cmd, fullCommand))
return true;
// /ub closestportal: use the nearest portal (UtilityBelt's command).
if (cmd == "closestportal")
{
UseClosestPortal();
return true;
}
if (sp > 0)
{
string translated = "/mt" + fullCommand.Substring(sp); // "/ub use X" → "/mt use X"

View file

@ -0,0 +1,383 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// UtilityBelt commands that had no RynthAi equivalent (2026-09-28 parity pass,
/// names and syntax read from UtilityBelt.dll's CommandPattern/Usage attributes):
/// delay, count, date/dateutc, id, pos, vitae, portal/portalp, playsound,
/// setmotion/getmotion/clearmotion, autostack, autocram, opt, help, simplejump,
/// dumpskills, quests, translateroute.
/// </summary>
public sealed partial class RynthAiPlugin
{
// ── /ub delay queue ─────────────────────────────────────────────────────
private readonly List<(long DueMs, string Command)> _delayedCommands = new();
/// <summary>Runs /ub delay commands that are due. Called every tick.</summary>
private void TickDelayedCommands()
{
// Out of world, OnChatBarEnter ignores the line and it went raw to AC's chat
// parser at character select. TeardownSession empties the queue at logout.
if (_delayedCommands.Count == 0 || !_loginComplete) return;
long now = Environment.TickCount64;
for (int i = 0; i < _delayedCommands.Count; i++)
{
if (_delayedCommands[i].DueMs > now) continue;
string cmd = _delayedCommands[i].Command;
_delayedCommands.RemoveAt(i--);
try { HandleRynthChatSubmit(cmd); }
catch (Exception ex) { Log($"[RynthAi] /ub delay: '{cmd}' threw {ex.Message}"); }
}
}
/// <summary>UB Util.Think: "/tell yourself, msg" so metas can watch for it; else a chat line.</summary>
private void UbSay(string msg, bool think)
{
if (think && Host.HasInvokeChatParser && _playerId != 0
&& Host.TryGetObjectName(_playerId, out string me) && !string.IsNullOrWhiteSpace(me))
{
Host.InvokeChatParser($"/tell {me}, {msg}");
return;
}
ChatLine("[RynthAi] " + msg);
}
/// <summary>Handles the commands above. Returns false for anything else.</summary>
internal bool TryHandleUbExtra(string cmd, string fullCommand)
{
int sp = fullCommand.IndexOf(' ');
string rest = sp > 0 ? fullCommand.Substring(sp + 1).Trim() : "";
// rest starts with the verb; args = everything after it
int sp2 = rest.IndexOf(' ');
string args = sp2 > 0 ? rest.Substring(sp2 + 1).Trim() : "";
switch (cmd)
{
case "delay": UbDelay(args); return true;
case "count": UbCount(args); return true;
case "date": UbDate(args, utc: false); return true;
case "dateutc": UbDate(args, utc: true); return true;
case "id": UbId(); return true;
case "pos": UbPos(); return true;
case "vitae": UbSay($"My vitae is {EvalExpr("vitae[]")}%", think: true); return true;
case "portal": UbPortal(args, partial: false); return true;
case "portalp": UbPortal(args, partial: true); return true;
case "playsound": UbPlaySound(args); return true;
case "setmotion": UbSetMotion(args); return true;
case "getmotion": UbGetMotion(); return true;
case "clearmotion": EvalExpr("clearmotion[]"); ChatLine("[RynthAi] Cleared all motions."); return true;
case "autostack": _inventoryManager?.RunManual(cram: false, stack: true); ChatLine("[RynthAi] AutoStack: stacking your inventory."); return true;
case "autocram": _inventoryManager?.RunManual(cram: true, stack: false); ChatLine("[RynthAi] AutoCram: moving items into side packs."); return true;
// /ub opt list|get|set stay on the /mt opt handler (it knows the Mag-Tools
// option aliases); only toggle, which that one lacks, is handled here.
case "opt" when args.StartsWith("toggle", StringComparison.OrdinalIgnoreCase):
UbOpt(args); return true;
case "help": UbHelp(); return true;
case "simplejump": UbSimpleJump(args); return true;
case "dumpskills": UbDumpSkills(); return true;
case "quests": UbQuests(args); return true;
case "translateroute": UbTranslateRoute(args); return true;
}
return false;
}
private string EvalExpr(string expr)
{
var engine = _metaManager?.Expressions;
return engine == null ? "" : engine.Evaluate(expr);
}
// /ub delay <millisecondDelay> <command>
private void UbDelay(string args)
{
int sp = args.IndexOf(' ');
if (sp <= 0 || !int.TryParse(args.AsSpan(0, sp), out int ms) || ms < 0)
{
ChatLine("[RynthAi] Usage: /ub delay <millisecondDelay> <command>");
return;
}
string command = args.Substring(sp + 1).Trim();
if (command.Length == 0) return;
_delayedCommands.Add((Environment.TickCount64 + ms, command));
}
// /ub count {item <name> | profile <lootProfile> | player <range>} [debug] [think]
private void UbCount(string args)
{
var words = args.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList();
bool think = words.RemoveAll(w => w.Equals("think", StringComparison.OrdinalIgnoreCase)) > 0;
words.RemoveAll(w => w.Equals("debug", StringComparison.OrdinalIgnoreCase));
if (words.Count < 2) { ChatLine("[RynthAi] Usage: /ub count {item <name> | profile <lootProfile> | player <range>} [think]"); return; }
string kind = words[0].ToLowerInvariant();
string what = string.Join(" ", words.Skip(1));
var inv = _objectCache?.GetDirectInventory(forceRefresh: true) ?? (IReadOnlyList<WorldObject>)Array.Empty<WorldObject>();
switch (kind)
{
case "item":
{
int n = 0;
foreach (var wo in inv)
if (string.Equals(wo.Name, what, StringComparison.OrdinalIgnoreCase))
n += Math.Max(1, wo.Values(LongValueKey.StackCount, 1));
UbSay($"You have {n} {what}.", think);
break;
}
case "profile":
{
string path = ResolveLootProfilePath(what);
if (path.Length == 0 || !TryLoadLootProfile(path, out VTankLootProfile profile, out _)) { ChatLine($"[RynthAi] count: loot profile not found: {what}"); return; }
var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
int n = 0;
foreach (var wo in inv)
{
var rule = profile.Rules.FirstOrDefault(r => VTankLootEvaluator.Match(r, wo, ctx));
if (rule != null && rule.Action is VTankLootAction.Keep or VTankLootAction.KeepUpTo)
n += Math.Max(1, wo.Values(LongValueKey.StackCount, 1));
}
UbSay($"You have {n} items matching {Path.GetFileName(path)}.", think);
break;
}
case "player":
{
if (!double.TryParse(what, NumberStyles.Float, CultureInfo.InvariantCulture, out double range)) { ChatLine("[RynthAi] count player <range>"); return; }
int n = 0;
int me = unchecked((int)_playerId);
if (_objectCache != null)
foreach (var wo in _objectCache.GetLandscapeObjects())
if (wo.Id != me && wo.ObjectClass == AcObjectClass.Player && _objectCache.Distance(me, wo.Id) <= range) n++;
UbSay($"There are {n} players within {range} meters.", think);
break;
}
default:
ChatLine("[RynthAi] Usage: /ub count {item <name> | profile <lootProfile> | player <range>} [think]");
break;
}
}
private static string ResolveLootProfilePath(string name)
{
string n = name.Trim().Trim('"');
if (File.Exists(n)) return n;
const string folder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
foreach (string cand in new[] { n, n + ".utl", n + ".json" })
{
string p = Path.Combine(folder, cand);
if (File.Exists(p)) return p;
}
return "";
}
// /ub date[utc] [format]
private void UbDate(string format, bool utc)
{
DateTime t = utc ? DateTime.UtcNow : DateTime.Now;
string s;
try { s = format.Length > 0 ? t.ToString(format, CultureInfo.InvariantCulture) : t.ToString(CultureInfo.InvariantCulture); }
catch (FormatException) { ChatLine($"[RynthAi] Bad date format: {format}"); return; }
ChatLine("[RynthAi] " + s);
}
private void UbId()
{
uint sel = Host.GetSelectedItemId();
if (sel == 0) { ChatLine("[RynthAi] Nothing selected."); return; }
string name = Host.TryGetObjectName(sel, out string n) ? n : "?";
ChatLine($"[RynthAi] {name}: id 0x{sel:X8} ({sel})");
}
private void UbPos()
{
uint sel = Host.GetSelectedItemId();
if (sel == 0) sel = _playerId;
if (sel == 0 || !Host.TryGetObjectPosition(sel, out uint cell, out float x, out float y, out float z))
{
ChatLine("[RynthAi] No position for the selected object.");
return;
}
string name = Host.TryGetObjectName(sel, out string n) ? n : "?";
string coords = NavCoordinateHelper.TryConvertPoseToCoords(cell, x, y, out double ns, out double ew)
? $"{Math.Abs(ns):F4}{(ns < 0 ? "S" : "N")}, {Math.Abs(ew):F4}{(ew < 0 ? "W" : "E")}" : "?";
ChatLine($"[RynthAi] {name}: landcell 0x{cell:X8} x={x:F3} y={y:F3} z={z:F3} ({coords})");
}
// /ub portal[p] <portalName>: use the nearest portal (or NPC) by name; portalp = partial.
private void UbPortal(string name, bool partial)
{
if (name.Length == 0 || _objectCache == null || _playerId == 0) { ChatLine("[RynthAi] Usage: /ub portal[p] <portalName>"); return; }
var best = FindNearestPositioned(wo =>
(partial ? wo.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0
: wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
&& (IsPortalObject(wo) || wo.ObjectClass == AcObjectClass.Npc), out double bestD);
if (best == null) { ChatLine($"[RynthAi] No portal named {(partial ? "like " : "")}'{name}' nearby."); LogPortalMiss("portal " + name); return; }
_navigationEngine?.Stop();
ChatLine($"[RynthAi] Using {best.Name} ({bestD:F1} m).");
Host.UseFor(unchecked((uint)best.Id), "Command", "/ub portal", UseKind.Asked);
}
[DllImport("winmm.dll", CharSet = CharSet.Unicode)]
private static extern bool PlaySound(string pszSound, IntPtr hmod, uint fdwSound);
// /ub playsound [volume] <filepath> (volume accepted for compatibility; played at system volume)
private void UbPlaySound(string args)
{
string file = args;
int sp = args.IndexOf(' ');
if (sp > 0 && int.TryParse(args.AsSpan(0, sp), out _)) file = args.Substring(sp + 1).Trim();
file = file.Trim('"');
if (!Path.IsPathRooted(file)) file = Path.Combine(@"C:\Games\RynthSuite\RynthAi", file);
if (!File.Exists(file)) { ChatLine($"[RynthAi] Sound file not found: {file}"); return; }
try { PlaySound(file, IntPtr.Zero, 0x00020000 /*SND_FILENAME*/ | 0x0001 /*SND_ASYNC*/); }
catch (Exception ex) { ChatLine($"[RynthAi] playsound failed: {ex.Message}"); }
}
private static readonly string[] UbMotions = { "Forward", "Backward", "TurnRight", "TurnLeft", "StrafeRight", "StrafeLeft", "Walk" };
// /ub setmotion <Forward|Backward|TurnRight|TurnLeft|StrafeRight|StrafeLeft|Walk> <0|1>
private void UbSetMotion(string args)
{
var w = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (w.Length != 2 || (w[1] != "0" && w[1] != "1")) { ChatLine("[RynthAi] Usage: /ub setmotion <" + string.Join("|", UbMotions) + "> <0|1>"); return; }
EvalExpr($"setmotion[`{w[0]}`,{w[1]}]");
}
private void UbGetMotion()
{
var on = UbMotions.Where(m => EvalExpr($"getmotion[`{m}`]") == "1").ToList();
ChatLine("[RynthAi] Motions on: " + (on.Count > 0 ? string.Join(", ", on) : "none"));
}
// /ub opt {list | get <option> | set <option> <newValue> | toggle <options>}
private void UbOpt(string args)
{
var map = _metaManager?.Expressions.BuildSettingsMapPublic();
if (map == null) { ChatLine("[RynthAi] Settings not ready."); return; }
var w = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string verb = w.Length > 0 ? w[0].ToLowerInvariant() : "list";
switch (verb)
{
case "list":
foreach (var chunk in map.Keys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase).Chunk(12))
ChatLine("[RynthAi] " + string.Join(", ", chunk));
break;
case "get" when w.Length >= 2:
ChatLine(map.TryGetValue(w[1], out var g) ? $"[RynthAi] {w[1]} = {g.Get()}" : $"[RynthAi] No option '{w[1]}' (/ub opt list).");
break;
case "set" when w.Length >= 3:
if (map.TryGetValue(w[1], out var st))
{
string v = string.Join(" ", w.Skip(2));
v = v.Equals("true", StringComparison.OrdinalIgnoreCase) ? "1" : v.Equals("false", StringComparison.OrdinalIgnoreCase) ? "0" : v;
st.Set(v);
_dashboard?.SaveSettings();
ChatLine($"[RynthAi] {w[1]} = {st.Get()}");
}
else ChatLine($"[RynthAi] No option '{w[1]}' (/ub opt list).");
break;
case "toggle" when w.Length >= 2:
foreach (string name in w.Skip(1))
{
if (!map.TryGetValue(name, out var tg)) { ChatLine($"[RynthAi] No option '{name}'."); continue; }
tg.Set(tg.Get() is "0" or "" or "False" ? "1" : "0");
ChatLine($"[RynthAi] {name} = {tg.Get()}");
}
_dashboard?.SaveSettings();
break;
default:
ChatLine("[RynthAi] Usage: /ub opt {list | get <option> | set <option> <newValue> | toggle <options>}");
break;
}
}
private void UbHelp()
{
ChatLine("[RynthAi] /ub commands: use[i][l][p], give[p], ig[p], select, face, fellow, equip, combatstate, close, quit, logout, " +
"follow[p], mexec, myquests, list[g|p]vars, propertydump, jump[swzxc], simplejump, closestportal, portal[p], " +
"autovendor, vendor, autotrade, autostack, autocram, delay, count, date[utc], id, pos, vitae, playsound, " +
"setmotion, getmotion, clearmotion, opt, dumpskills, quests, translateroute, clearbugged.");
}
// /ub simplejump [msToHoldDown]: jump in place.
private void UbSimpleJump(string args)
{
int ms = int.TryParse(args, out int v) ? Math.Clamp(v, 0, 1000) : 0;
_jumper?.Start("", null, ms);
}
private void UbDumpSkills()
{
if (_charSkills == null) { ChatLine("[RynthAi] Skills not ready."); return; }
var lines = new List<string>();
foreach (AcSkillType sk in Enum.GetValues<AcSkillType>())
{
if (sk == AcSkillType.Unknown) continue;
var info = _charSkills[sk];
string tr = info.Training switch { 3 => "spec", 2 => "trained", 1 => "untrained", _ => "?" };
lines.Add($"{sk} {info.Buffed} ({tr})");
}
foreach (var chunk in lines.Chunk(6))
ChatLine("[RynthAi] " + string.Join(", ", chunk));
}
// /ub quests check <questFlag>
private void UbQuests(string args)
{
var w = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
if (w.Length < 2 || !w[0].Equals("check", StringComparison.OrdinalIgnoreCase)) { ChatLine("[RynthAi] Usage: /ub quests check <questFlag>"); return; }
string flag = w[1].Trim();
bool has = EvalExpr($"testquestflag[`{flag}`]") == "1";
string status = EvalExpr($"getqueststatus[`{flag}`]");
UbSay($"Quest {flag}: {(has ? "have flag" : "no flag")}, {(status == "1" ? "ready" : "not ready")}", think: true);
}
// /ub translateroute <startLandblock> <routeToLoad> <endLandblock> <routeToSaveAs> [force]
private void UbTranslateRoute(string args)
{
var w = args.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList();
bool force = w.Count > 0 && w[^1].Equals("force", StringComparison.OrdinalIgnoreCase);
if (force) w.RemoveAt(w.Count - 1);
if (w.Count != 4 || !TryParseLandblock(w[0], out uint start) || !TryParseLandblock(w[2], out uint end))
{
ChatLine("[RynthAi] Usage: /ub translateroute <startLandblock> <routeToLoad> <endLandblock> <routeToSaveAs> [force]");
return;
}
const string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
string inPath = Path.IsPathRooted(w[1]) ? w[1] : Path.Combine(navFolder, w[1]);
string outPath = Path.IsPathRooted(w[3]) ? w[3] : Path.Combine(navFolder, w[3]);
if (!outPath.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) outPath += ".nav";
if (!File.Exists(inPath)) { ChatLine($"[RynthAi] Route not found: {inPath}"); return; }
if (File.Exists(outPath) && !force) { ChatLine($"[RynthAi] {Path.GetFileName(outPath)} exists; add force to overwrite."); return; }
// A landblock is 192 m = 0.8 nav units. Landblock id: 0xXXYY.
double dEW = (((int)(end >> 8) & 0xFF) - ((int)(start >> 8) & 0xFF)) * 0.8;
double dNS = (((int)end & 0xFF) - ((int)start & 0xFF)) * 0.8;
var route = NavRouteParser.Load(inPath);
foreach (var p in route.Points)
{
p.NS += dNS; p.EW += dEW;
if (p.Type is NavPointType.PortalNPC or NavPointType.Npc) { p.PortalExitNS += dNS; p.PortalExitEW += dEW; }
}
route.Save(outPath);
ChatLine($"[RynthAi] Translated {route.Points.Count} points to {Path.GetFileName(outPath)} (NS {dNS:+0.0;-0.0}, EW {dEW:+0.0;-0.0}).");
}
private static bool TryParseLandblock(string s, out uint lb)
{
s = s.Trim();
if (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) s = s[2..];
bool ok = uint.TryParse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lb);
if (ok && lb > 0xFFFF) lb >>= 16; // accept a full cell id (0xXXYY0000)
return ok;
}
}

View file

@ -0,0 +1,128 @@
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// One bot per client under the Decal bridge: when VTank's macro starts, RynthAi's stops, and
/// it isn't started again while VTank runs. VTank stopping only allows it again; nothing is
/// restarted. The engine says whether VTank's macro runs (RynthCoreHost.TryGetVTankState, API
/// v74: VTank's documented /vt start and /vt stop through Decal's chat parser). Without Decal
/// the engine isn't watching and nothing here ever stops or refuses anything.
///
/// Pure decisions only (the plugin does the stopping and the chat), so the host tests drive it
/// with a fake VTank signal.
/// </summary>
internal sealed class VTankYield
{
public const string StoppedForStartLine = "[RynthAi] VTank started - RynthAi macro stopped (one bot per client).";
public const string StoppedWhileRunningLine = "[RynthAi] VTank is running - RynthAi macro stopped (one bot per client).";
public const string RefusedLine = "[RynthAi] VTank is running - RynthAi macro not started (one bot per client). Stop VTank first (/vt stop), or turn off Yield to VTank (/ra vtankyield off).";
/// <summary>Refusals the tick itself makes (a start that bypassed the checked paths) print at most this often.</summary>
public const long RefuseRepeatMs = 10_000;
public enum Verdict
{
/// <summary>Nothing to do.</summary>
None,
/// <summary>VTank just started and RynthAi's macro is on: stop it, print <see cref="StoppedForStartLine"/>.</summary>
StopForVTankStart,
/// <summary>VTank was already running and RynthAi's macro was running too (e.g. yield was just turned
/// back on): stop it, print <see cref="StoppedWhileRunningLine"/>.</summary>
StopWhileVTankRuns,
/// <summary>Something switched RynthAi's macro on while VTank runs: switch it back off before it acts,
/// print <see cref="RefusedLine"/> (throttled, see <see cref="ShouldPrintRefusal"/>).</summary>
RefuseStart,
}
private bool _vtankWasRunning;
private long _lastRefusalMs = long.MinValue / 2;
/// <summary>The engine watches VTank (Decal bridge mode), as of the last <see cref="Observe"/>.</summary>
public bool Watching { get; private set; }
/// <summary>VTank's macro runs, as of the last <see cref="Observe"/> (false whenever not watching).</summary>
public bool VTankRunning { get; private set; }
/// <summary>Asks the engine (API v74). An older engine, or no Decal bridge: not watching.</summary>
public void Poll(RynthCoreHost host)
{
if (host.TryGetVTankState(out bool watching, out bool running, out _))
Observe(watching, running);
else
Observe(false, false);
}
/// <summary>
/// The per-tick step the plugin runs before the macro acts: decides, switches the macro flag
/// off when it must (<paramref name="onStop"/> does the rest of a /ra stop: nav stop, pause
/// cancel), and prints the line. Returns what it decided.
/// </summary>
public Verdict Apply(LegacyUiSettings settings, bool macroWasRunning, Action? onStop, Action<string> chat, long nowMs)
{
Verdict v = Tick(settings.IsMacroRunning, macroWasRunning, settings.YieldToVTank);
if (v == Verdict.None)
return v;
settings.IsMacroRunning = false;
onStop?.Invoke();
if (v == Verdict.StopForVTankStart) chat(StoppedForStartLine);
else if (v == Verdict.StopWhileVTankRuns) chat(StoppedWhileRunningLine);
else if (ShouldPrintRefusal(nowMs)) chat(RefusedLine);
return v;
}
/// <summary>An explicit start: true = refused (the line is printed), the caller must not start.</summary>
public bool RefuseStart(LegacyUiSettings settings, Action<string> chat)
{
if (!BlocksStart(settings.YieldToVTank))
return false;
chat(RefusedLine);
return true;
}
/// <summary>Takes the engine's answer (call before deciding; cheap, any number of times).</summary>
public void Observe(bool watching, bool vtankRunning)
{
Watching = watching;
VTankRunning = watching && vtankRunning;
}
/// <summary>
/// Once per plugin tick, BEFORE the macro acts. <paramref name="macroOn"/> = the macro flag now;
/// <paramref name="macroWasRunning"/> = it was on at the end of the previous tick.
/// </summary>
public Verdict Tick(bool macroOn, bool macroWasRunning, bool yieldEnabled)
{
bool started = VTankRunning && !_vtankWasRunning;
_vtankWasRunning = VTankRunning;
if (!yieldEnabled || !VTankRunning || !macroOn)
return Verdict.None;
if (started)
return Verdict.StopForVTankStart;
return macroWasRunning ? Verdict.StopWhileVTankRuns : Verdict.RefuseStart;
}
/// <summary>An explicit start (button, /ra start, a meta, the phone, a script) must be refused.</summary>
public bool BlocksStart(bool yieldEnabled) => yieldEnabled && VTankRunning;
/// <summary>Throttle for <see cref="Verdict.RefuseStart"/> lines from the tick (explicit starts always print).</summary>
public bool ShouldPrintRefusal(long nowMs)
{
if (nowMs - _lastRefusalMs < RefuseRepeatMs)
return false;
_lastRefusalMs = nowMs;
return true;
}
public string Describe(bool yieldEnabled, bool engineHasIt)
{
if (!engineHasIt)
return "[RynthAi] Yield to VTank: " + (yieldEnabled ? "on" : "off") + " - this engine can't tell whether VTank runs (needs API v74), so it does nothing.";
if (!Watching)
return "[RynthAi] Yield to VTank: " + (yieldEnabled ? "on" : "off") + " - no Decal bridge in this client, so it does nothing.";
return "[RynthAi] Yield to VTank: " + (yieldEnabled ? "on" : "off") + ". VTank macro: " + (VTankRunning ? "RUNNING" : "not running") +
" (seen through /vt start and /vt stop; VTank's own Run Macro button isn't seen - /rc vtank clear if it was stopped that way).";
}
}

Some files were not shown because too many files have changed in this diff Show more