// ============================================================================ // RynthAi - UtilityBeltInventoryCommands.cs // UtilityBelt's /ub equip list|load|test|create and /ub autosalvage [force] // (2026-12-01 command audit). Both judge what the character carries by a loot // profile's rules, so they share one job: read the profile, identify the items // whose rule needs it, then act. // // /ub equip used to fall through to /mt equip, which looked for an item named // "load" and failed, so a meta's armor or weapon swap did nothing. /ub autosalvage // was accepted and ignored. // ============================================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using RynthCore.Loot; using RynthCore.Loot.Editing; using RynthCore.Loot.VTank; using RynthCore.Plugin.RynthAi.Loot; using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi; /// /// Which items of an equipment profile go on, one per slot (pure, so tests can run it). An item is /// placed in the order of its rule (then of the inventory); a slot can only take one item. Rings and /// bracelets fit either of their two slots; the weapon slots (melee, missile, wand, two-handed) are /// one hand, so one weapon. Items already worn keep their slots. /// internal static class UbEquipPlan { // AC's EquipMask bits (ValidLocations / CurrentWieldedLocation). internal const int MeleeWeapon = 0x00100000, MissileWeapon = 0x00400000, Held = 0x01000000, TwoHanded = 0x02000000; internal const int WeaponSlots = MeleeWeapon | MissileWeapon | Held | TwoHanded; internal const int WristPair = 0x00010000 | 0x00020000, FingerPair = 0x00040000 | 0x00080000; /// /// A carried item a Keep rule takes. is where it can go (ValidLocations), /// where it is worn now (0 when that isn't known); sorts them. /// public readonly record struct Item(int Id, string Name, int Slots, bool Worn, int WornSlots, int Order); public sealed class Result { public List Equip { get; } = new(); public List AlreadyWorn { get; } = new(); public List<(Item Item, string Why)> Skipped { get; } = new(); } public static Result Plan(IEnumerable matched) { var result = new Result(); var list = matched.OrderBy(i => i.Order).ToList(); int taken = 0; foreach (Item worn in list.Where(i => i.Worn)) { taken |= Expand(worn.WornSlots); result.AlreadyWorn.Add(worn); } foreach (Item item in list.Where(i => !i.Worn)) { if (item.Slots == 0) result.Skipped.Add((item, "it isn't something to wear or wield")); else if (TryClaim(item.Slots, ref taken)) result.Equip.Add(item); else result.Skipped.Add((item, "another item of the profile has its slot")); } return result; } private static int Expand(int slots) => (slots & WeaponSlots) != 0 ? slots | WeaponSlots : slots; private static bool TryClaim(int slots, ref int taken) { foreach (int pair in new[] { WristPair, FingerPair }) { if ((slots & ~pair) != 0 || (slots & pair) != pair) continue; int free = pair & ~taken; if (free == 0) return false; taken |= free & -free; // the lower free one of the two return true; } int need = Expand(slots); if ((need & taken) != 0) return false; taken |= need; return true; } } public sealed partial class RynthAiPlugin { /// Where /ub equip finds and makes its profiles: RynthAi's LootProfiles (tests point it elsewhere). internal static string UbEquipFolder { get; set; } = LootEditorBridge.LootFolder; internal const string UbEquipUsage = "/ub equip list | load | test | create "; internal const string UbAutoSalvageUsage = "/ub autosalvage [force]"; // Pacing: one identify every IdSpacingMs, a wait of IdWaitMs for the last one, the whole job at // most JobMaxMs; one wield every EquipSpacingMs, the check EquipSettleMs after the last. internal const long UbIdSpacingMs = 300, UbIdWaitMs = 3000, UbJobMaxMs = 60_000; internal const long UbEquipSpacingMs = 700, UbEquipSettleMs = 2000; internal const int UbMaxIds = 100; // STypeInts AutoSalvage reads (UtilityBelt leaves tinkered and imbued items alone). private const uint NumTimesTinkeredInt = 171, ImbuedEffectInt = 179; private enum UbInvKind { EquipLoad, EquipTest, Salvage, SalvageForce } private sealed class UbInvJob { public UbInvKind Kind; public InventoryRules Rules = null!; public bool FromMeta; public long StartedAt; public long NextIdAt; public long LastIdAt; public readonly Queue IdQueue = new(); public readonly List Asked = new(); } private UbInvJob? _ubInvJob; private readonly Queue<(uint Id, string Name)> _ubEquipSends = new(); private readonly List<(uint Id, string Name)> _ubEquipSent = new(); private long _ubEquipNextAt, _ubEquipLastAt; private bool _ubEquipFromMeta; private string _ubEquipProfile = string.Empty; /// Milliseconds for the job's pacing (tests move it on). internal Func UbInvClock { get; set; } = () => Environment.TickCount64; /// The profile a /ub equip or /ub autosalvage line names: a full path, else LootProfiles\name[.utl|.json]. internal static string ResolveUbEquipProfile(string name) { string n = name.Trim().Trim('"'); if (n.Length == 0) return string.Empty; if (Path.IsPathFullyQualified(n)) return File.Exists(n) ? n : string.Empty; foreach (string cand in new[] { n, n + ".utl", n + ".json" }) { string p = Path.Combine(UbEquipFolder, cand); if (File.Exists(p)) return p; } return string.Empty; } // ── /ub equip ───────────────────────────────────────────────────────── /// /// UtilityBelt's own /ub equip line (list, load, test, create, or nothing). Anything else is an item /// name, as metas wrote for the /mt equip this used to be: that still wields the item. /// internal static bool UbEquipOwns(string args) { string first = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries) is { Length: > 0 } w ? w[0].ToLowerInvariant() : ""; return first is "" or "list" or "load" or "test" or "create"; } private void UbEquip(string args) { string[] w = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries); string sub = w.Length > 0 ? w[0].ToLowerInvariant() : ""; string name = w.Length > 1 ? w[1].Trim() : ""; switch (sub) { case "list": UbEquipList(); return; case "load" or "test" when name.Length > 0: { string path = ResolveUbEquipProfile(name); if (path.Length == 0) { ReplyFail($"[RynthAi] /ub equip: no profile '{name}' in {UbEquipFolder}."); return; } InventoryRules? rules = InventoryRules.Load(path, out string why); if (rules == null) { ReplyFail($"[RynthAi] /ub equip: couldn't read {Path.GetFileName(path)}: {why}"); return; } StartUbInvJob(sub == "load" ? UbInvKind.EquipLoad : UbInvKind.EquipTest, rules); return; } case "create" when name.Length > 0: UbEquipCreate(name); return; } ReplyFail("[RynthAi] Usage: " + UbEquipUsage); } private void UbEquipList() { var names = new List(); try { if (Directory.Exists(UbEquipFolder)) foreach (string f in Directory.GetFiles(UbEquipFolder)) if (f.EndsWith(".utl", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) names.Add(Path.GetFileName(f)); } catch (IOException) { } catch (UnauthorizedAccessException) { } names.Sort(StringComparer.OrdinalIgnoreCase); ChatLine(names.Count == 0 ? $"[RynthAi] Equipment profiles: none in {UbEquipFolder}. /ub equip create makes one from what you wear." : $"[RynthAi] Equipment profiles ({names.Count}, the loot profiles in {UbEquipFolder}): {string.Join(", ", names)}"); } /// /// /ub equip create <name>: LootProfiles\<name>.utl with one Keep rule per worn item (its exact /// name and object class), so /ub equip load puts the same things on again. Never over an existing file: /// the folder holds the loot profiles too. /// private void UbEquipCreate(string raw) { if (_objectCache == null || _playerId == 0) { ReplyFail("[RynthAi] /ub equip create: not ready (log in first)."); return; } string? why = LegacyUi.ProfileFileOps.CleanName(raw, LegacyUi.LegacyDashboardRenderer.LootExtensions, out string name); if (why != null) { ReplyFail($"[RynthAi] /ub equip create: can't use '{name}': {why}."); return; } string path = Path.Combine(UbEquipFolder, name + ".utl"); if (File.Exists(path) || File.Exists(Path.Combine(UbEquipFolder, name + ".json"))) { ReplyFail($"[RynthAi] /ub equip create: {name} already exists in {UbEquipFolder}; pick another name."); return; } var profile = new VTankLootProfile(); var seen = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (WorldObject wo in _objectCache.GetDirectInventory(forceRefresh: true)) { if (!WorldObjectCache.IsWieldedByPlayer(Host, wo) || string.IsNullOrWhiteSpace(wo.Name)) continue; if (!seen.Add(wo.Name + "|" + (int)wo.ObjectClass)) continue; // two of the same ring: one rule takes both var rule = new VTankLootRule { Name = "Equip " + wo.Name.Trim(), Action = VTankLootAction.Keep, CustomExpression = string.Empty }; if (wo.ObjectClass != AcObjectClass.Unknown) rule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.ObjectClass, "0", new[] { ((int)wo.ObjectClass).ToString(System.Globalization.CultureInfo.InvariantCulture) })); rule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.StringValueMatch, "0", new[] { LootItemRules.ExactPattern(wo.Name.Trim()), "1" })); profile.Rules.Add(rule); } if (profile.Rules.Count == 0) { ReplyFail("[RynthAi] /ub equip create: you aren't wearing anything to put in it."); return; } if (!DataWriteGuard.TrySave("the equipment profile", path, () => { Directory.CreateDirectory(UbEquipFolder); VTankLootWriter.Save(profile, path); }, out string saveWhy, callerShows: true)) { ReplyFail($"[RynthAi] /ub equip create: couldn't write {Path.GetFileName(path)}: {saveWhy}"); return; } ReplyOk($"[RynthAi] Equipment profile {Path.GetFileName(path)}: {profile.Rules.Count} item(s) you wear. /ub equip load {name} puts them on."); } // ── /ub autosalvage ─────────────────────────────────────────────────── /// /// /ub autosalvage [force] (UtilityBelt): the carried items the loot profile in use says Salvage. /// As UtilityBelt, nothing is salvaged without "force" (UB only fills its salvage window then): /// here that lists them. With "force" they go to RynthAi's salvage queue, which skips what it /// always skips (worn, retained, the Items list, the UST, bags). Tinkered and imbued items are /// left out as UtilityBelt does; AutoSalvage.OnlyFromMainPack (a /ub opt) keeps to the main pack. /// private void UbAutoSalvage(string args) { string a = args.Trim().ToLowerInvariant(); if (a.Length > 0 && a != "force") { ReplyFail("[RynthAi] Usage: " + UbAutoSalvageUsage); return; } string path = (_dashboard?.Settings?.CurrentLootPath ?? string.Empty).Trim().Trim('"'); if (path.Length == 0) { ReplyFail("[RynthAi] /ub autosalvage: no loot profile in use (pick one under LOOT)."); return; } InventoryRules? rules = InventoryRules.Load(path, out string why); if (rules == null) { ReplyFail($"[RynthAi] /ub autosalvage: couldn't read {Path.GetFileName(path)}: {why}"); return; } if (a == "force" && _salvageManager == null) { ReplyFail("[RynthAi] /ub autosalvage: salvaging isn't ready (log in first)."); return; } StartUbInvJob(a == "force" ? UbInvKind.SalvageForce : UbInvKind.Salvage, rules); } // ── The job ─────────────────────────────────────────────────────────── private bool IsEquipJob(UbInvKind k) => k is UbInvKind.EquipLoad or UbInvKind.EquipTest; private string UbVerb(UbInvKind k) => k switch { UbInvKind.EquipLoad => "/ub equip load", UbInvKind.EquipTest => "/ub equip test", UbInvKind.Salvage => "/ub autosalvage", _ => "/ub autosalvage force", }; /// The items the job judges: wearables for equip (worn ones too), else what is in the packs. private List UbInvCandidates(UbInvKind kind) { var list = new List(); if (_objectCache == null) return list; foreach (WorldObject wo in _objectCache.GetDirectInventory(forceRefresh: true)) { if (IsEquipJob(kind)) { if (wo.Values(LongValueKey.Locations, 0) != 0 || WorldObjectCache.IsWieldedByPlayer(Host, wo)) list.Add(wo); } else if (wo.ObjectClass != AcObjectClass.Container && !WorldObjectCache.IsWieldedByPlayer(Host, wo)) list.Add(wo); } return list; } private bool HasIdData(uint id) => !Host.HasHasAppraisalData || Host.HasAppraisalData(id); private void StartUbInvJob(UbInvKind kind, InventoryRules rules) { if (_objectCache == null || _playerId == 0) { ReplyFail($"[RynthAi] {UbVerb(kind)}: not ready (log in first)."); return; } if (_ubInvJob != null) Log($"[RynthAi] {UbVerb(kind)}: replaces {UbVerb(_ubInvJob.Kind)} ({_ubInvJob.Rules.FileName}), which hadn't finished."); if (kind == UbInvKind.EquipLoad) { _ubEquipSends.Clear(); _ubEquipSent.Clear(); } var job = new UbInvJob { Kind = kind, Rules = rules, FromMeta = Reply.FromScript, StartedAt = UbInvClock() }; var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache }; bool salvage = !IsEquipJob(kind); foreach (WorldObject wo in UbInvCandidates(kind)) { uint id = unchecked((uint)wo.Id); if (HasIdData(id) || !Host.HasRequestId) continue; VTankLootVerdict v = rules.Decide(wo, ctx, _charSkills, hasIdData: false, out InventoryRuleKind k, out _); // Salvage also needs the ID to tell a tinkered or imbued item. if (v == VTankLootVerdict.NeedsId || (salvage && v == VTankLootVerdict.Match && k == InventoryRuleKind.Salvage)) if (job.IdQueue.Count < UbMaxIds) job.IdQueue.Enqueue(id); } _ubInvJob = job; if (job.IdQueue.Count == 0) { FinishUbInvJob(job); return; } Log($"[RynthAi] {UbVerb(kind)} {rules.FileName}: identifying {job.IdQueue.Count} item(s) first."); Reply.Ok($"[RynthAi] {UbVerb(kind)} {rules.FileName}: identifying {job.IdQueue.Count} item(s) first."); } /// Pump thread, every tick: the job's identifies, then its result; the wields of an equip load. private void TickUbInventoryJobs() { if (!_loginComplete) return; long now = UbInvClock(); UbInvJob? job = _ubInvJob; if (job != null) { if (job.IdQueue.Count > 0) { if (now >= job.NextIdAt) { uint id = job.IdQueue.Dequeue(); if (!HasIdData(id) && Host.RequestId(id)) job.Asked.Add(id); job.NextIdAt = now + UbIdSpacingMs; job.LastIdAt = now; } } else if (job.Asked.All(HasIdData) || now - job.LastIdAt >= UbIdWaitMs || now - job.StartedAt >= UbJobMaxMs) { FinishUbInvJob(job); } } TickUbEquipSends(now); } private void FinishUbInvJob(UbInvJob job) { if (ReferenceEquals(_ubInvJob, job)) _ubInvJob = null; if (IsEquipJob(job.Kind)) FinishUbEquip(job); else FinishUbAutoSalvage(job); } /// A job's answer: as its command would have said it (quiet in chat when a meta sent it, except Info). private void UbJobSay(UbInvJob job, string text, bool fail = false, bool info = false) { if (job.FromMeta) RunAsMeta(() => { Say(); return true; }); else Say(); void Say() { if (info) ChatLine(text); else if (fail) ReplyFail(text); else ReplyOk(text); } } private static string Names(IEnumerable names, int max = 12) { var l = names.ToList(); return l.Count <= max ? string.Join(", ", l) : string.Join(", ", l.Take(max)) + $" and {l.Count - max} more"; } private void FinishUbEquip(UbInvJob job) { var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache }; var matched = new List(); int order = 0, unidentified = 0; var ruleOrder = new Dictionary(StringComparer.Ordinal); foreach (WorldObject wo in UbInvCandidates(job.Kind)) { uint id = unchecked((uint)wo.Id); VTankLootVerdict v = job.Rules.Decide(wo, ctx, _charSkills, HasIdData(id), out InventoryRuleKind k, out string rule); if (v == VTankLootVerdict.NeedsId) { unidentified++; continue; } if (v != VTankLootVerdict.Match || k != InventoryRuleKind.Keep) continue; if (!ruleOrder.TryGetValue(rule, out int r)) ruleOrder[rule] = r = ruleOrder.Count; bool worn = WorldObjectCache.IsWieldedByPlayer(Host, wo); int slots = wo.Values(LongValueKey.Locations, 0); int wornAt = 0; if (worn) { wornAt = wo.Values(LongValueKey.CurrentWieldedLocation, 0); if (wornAt <= 0 && Host.HasGetObjectWielderInfo && Host.TryGetObjectWielderInfo(id, out _, out uint loc)) wornAt = unchecked((int)loc); if (wornAt < 0) wornAt = 0; } matched.Add(new UbEquipPlan.Item(wo.Id, wo.Name, slots, worn, wornAt, r * 10_000 + order++)); } UbEquipPlan.Result plan = UbEquipPlan.Plan(matched); string profile = job.Rules.FileName; string idNote = unidentified > 0 ? $" {unidentified} item(s) couldn't be identified in time and were left out." : ""; if (job.Kind == UbInvKind.EquipTest) { UbJobSay(job, $"[RynthAi] /ub equip test {profile}: " + (plan.Equip.Count > 0 ? $"would equip {Names(plan.Equip.Select(i => i.Name))}" : "nothing to equip") + (plan.AlreadyWorn.Count > 0 ? $"; already worn: {Names(plan.AlreadyWorn.Select(i => i.Name))}" : "") + (plan.Skipped.Count > 0 ? $"; left out: {Names(plan.Skipped.Select(s => $"{s.Item.Name} ({s.Why})"))}" : "") + "." + idNote, info: true); return; } if (plan.Equip.Count == 0) { UbJobSay(job, matched.Count == 0 ? $"[RynthAi] /ub equip load {profile}: nothing you carry matches its rules.{idNote}" : $"[RynthAi] /ub equip load {profile}: nothing to put on ({plan.AlreadyWorn.Count} already worn).{idNote}", fail: matched.Count == 0); return; } if (!Host.HasUseObject) { UbJobSay(job, "[RynthAi] /ub equip load: this RynthCore can't use items.", fail: true); return; } _ubEquipSends.Clear(); _ubEquipSent.Clear(); foreach (UbEquipPlan.Item i in plan.Equip) _ubEquipSends.Enqueue((unchecked((uint)i.Id), i.Name)); _ubEquipFromMeta = job.FromMeta; _ubEquipProfile = profile; _ubEquipNextAt = 0; Log($"[RynthAi] /ub equip load {profile}: equipping {Names(plan.Equip.Select(i => i.Name), 40)}" + (plan.Skipped.Count > 0 ? $"; left out: {Names(plan.Skipped.Select(s => $"{s.Item.Name} ({s.Why})"), 40)}" : "") + "." + idNote); UbJobSay(job, $"[RynthAi] /ub equip load {profile}: equipping {plan.Equip.Count} item(s).{idNote}"); TickUbEquipSends(UbInvClock()); } /// One wield per ; after the last, says how many went on. private void TickUbEquipSends(long now) { if (_ubEquipSends.Count > 0) { if (now < _ubEquipNextAt) return; var (id, name) = _ubEquipSends.Dequeue(); WorldObject? wo = _objectCache?[unchecked((int)id)]; // Already on (worn since the plan): using it again would take it off. if (wo != null && WorldObjectCache.IsWieldedByPlayer(Host, wo)) { _ubEquipSent.Add((id, name)); return; } Host.UseFor(id, "Command", "/ub equip load", UseKind.Asked); _ubEquipSent.Add((id, name)); _ubEquipNextAt = _ubEquipLastAt = now; _ubEquipNextAt += UbEquipSpacingMs; return; } if (_ubEquipSent.Count == 0 || now - _ubEquipLastAt < UbEquipSettleMs) return; var missing = new List(); foreach (var (id, name) in _ubEquipSent) { WorldObject? wo = _objectCache?[unchecked((int)id)]; if (wo == null || !WorldObjectCache.IsWieldedByPlayer(Host, wo)) missing.Add(name); } int on = _ubEquipSent.Count - missing.Count; string text = missing.Count == 0 ? $"[RynthAi] /ub equip load {_ubEquipProfile}: equipped {on} item(s)." : $"[RynthAi] /ub equip load {_ubEquipProfile}: equipped {on} of {_ubEquipSent.Count}; not on: {Names(missing)}."; _ubEquipSent.Clear(); var job = new UbInvJob { FromMeta = _ubEquipFromMeta }; UbJobSay(job, text, fail: missing.Count > 0); } private void FinishUbAutoSalvage(UbInvJob job) { var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache }; bool mainOnly = _metaManager?.Expressions is { } ex && ex.GetOption("AutoSalvage.OnlyFromMainPack") is string o && (o == "1" || o.Equals("true", StringComparison.OrdinalIgnoreCase)); var take = new List(); var left = new List(); int unidentified = 0; foreach (WorldObject wo in UbInvCandidates(job.Kind)) { uint id = unchecked((uint)wo.Id); bool hasId = HasIdData(id); VTankLootVerdict v = job.Rules.Decide(wo, ctx, _charSkills, hasId, out InventoryRuleKind k, out _); if (v == VTankLootVerdict.NeedsId) { unidentified++; continue; } if (v != VTankLootVerdict.Match || k != InventoryRuleKind.Salvage) continue; if (!hasId) { unidentified++; continue; } // tinkered or imbued can't be told without it if (wo.Values(unchecked((int)NumTimesTinkeredInt), 0) > 0) { left.Add(wo.Name + " (tinkered)"); continue; } if (wo.Values(unchecked((int)ImbuedEffectInt), 0) != 0) { left.Add(wo.Name + " (imbued)"); continue; } if (mainOnly && wo.Container != 0 && wo.Container != unchecked((int)_playerId)) continue; take.Add(wo); } string profile = job.Rules.FileName; string notes = (left.Count > 0 ? $" Left alone: {Names(left)}." : "") + (unidentified > 0 ? $" {unidentified} item(s) couldn't be identified in time and were left out." : ""); if (take.Count == 0) { UbJobSay(job, $"[RynthAi] /ub autosalvage ({profile}): nothing you carry is marked Salvage.{notes}", info: job.Kind == UbInvKind.Salvage); return; } if (job.Kind == UbInvKind.Salvage) { UbJobSay(job, $"[RynthAi] /ub autosalvage ({profile}): {take.Count} item(s) would be salvaged: {Names(take.Select(t => t.Name))}." + notes + " /ub autosalvage force salvages them.", info: true); return; } if (_salvageManager == null) { UbJobSay(job, "[RynthAi] /ub autosalvage: salvaging isn't ready.", fail: true); return; } foreach (WorldObject wo in take) _salvageManager.EnqueueItem(unchecked((uint)wo.Id)); Log($"[RynthAi] /ub autosalvage force ({profile}): queued {Names(take.Select(t => $"{t.Name} 0x{(uint)t.Id:X8}"), 60)}.{notes}"); UbJobSay(job, $"[RynthAi] /ub autosalvage force ({profile}): salvaging {take.Count} item(s): {Names(take.Select(t => t.Name))}.{notes}"); } /// At logout: nothing of a job carries into the next character's session. private void ResetUbInventoryJobs() { _ubInvJob = null; _ubEquipSends.Clear(); _ubEquipSent.Clear(); } }