From d55ffda4ed68abf80098b7f8c9aa7346f55043ad Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Sun, 27 Sep 2026 20:25:46 -0400 Subject: [PATCH] RynthSuite as of 2026-09-27 (internal 1816d05): AutoVendor (UtilityBelt port), missile/magic facing and arc line of sight, nav waypoint skipping, rebuff batch and item-enchant fixes, crafting fallback, Loot Editor AutoVendor folder and command-line open, release 2026.9.27.2 --- .github/workflows/release.yml | 7 + BUILD.md | 10 + .../Combat/AcStubs.cs | 53 +- .../Combat/BuffManager.cs | 39 +- .../Combat/CombatManager.cs | 192 ++- .../Combat/MissileCraftingManager.cs | 48 +- .../Combat/WorldObjectCache.cs | 8 +- .../CorpseOpenController.cs | 20 +- .../LegacyUi/LegacyAdvancedSettingsUi.cs | 86 +- .../LegacyUi/LegacyDashboardRenderer.cs | 75 +- .../LegacyUi/LegacyUiSettings.cs | 62 +- .../Loot/VTankLootEvaluator.cs | 8 + .../MagToolsCommands.cs | 10 + .../Meta/ExpressionEngine.cs | 19 + .../NavigationEngine.cs | 101 +- .../Raycasting/MissileBallistics.cs | 182 ++ .../Raycasting/RaycastEngine.cs | 83 + .../Raycasting/TargetingFSM.cs | 134 +- .../RynthAiCommands.cs | 67 +- .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 78 +- .../UtilityBeltCommands.cs | 4 + .../Vendor/AutoVendorCommands.cs | 94 ++ .../Vendor/AutoVendorManager.cs | 1470 +++++++++++++++++ .../Vendor/AutoVendorPlanner.cs | 497 ++++++ .../Vendor/AutoVendorRules.cs | 318 ++++ Tools/RynthCore.AutoVendorTests/Program.cs | 541 ++++++ .../RynthCore.AutoVendorTests.csproj | 26 + Tools/RynthCore.LootEditor/App.axaml.cs | 2 +- Tools/RynthCore.LootEditor/MainViewModel.cs | 85 +- Tools/RynthCore.LootEditor/MainWindow.axaml | 25 + .../RynthCore.LootEditor/MainWindow.axaml.cs | 7 +- Tools/RynthCore.MissileArcTests/Program.cs | 193 +++ .../RynthCore.MissileArcTests.csproj | 21 + 33 files changed, 4361 insertions(+), 204 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Raycasting/MissileBallistics.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorCommands.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorRules.cs create mode 100644 Tools/RynthCore.AutoVendorTests/Program.cs create mode 100644 Tools/RynthCore.AutoVendorTests/RynthCore.AutoVendorTests.csproj create mode 100644 Tools/RynthCore.MissileArcTests/Program.cs create mode 100644 Tools/RynthCore.MissileArcTests/RynthCore.MissileArcTests.csproj diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b7e665d..994ef11 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -85,6 +85,13 @@ jobs: dotnet run --project "$env:GITHUB_WORKSPACE\Tools\RynthCore.LootSdkTests\RynthCore.LootSdkTests.csproj" -c Release if ($LASTEXITCODE -ne 0) { throw "LootSdk golden tests FAILED" } + # AutoVendor pure-logic tests (rule judging, buy-up-to-N, batch planning, splits). + - name: Validation gate - AutoVendor tests + shell: pwsh + run: | + dotnet run --project "$env:GITHUB_WORKSPACE/Tools/RynthCore.AutoVendorTests/RynthCore.AutoVendorTests.csproj" -c Release + if ($LASTEXITCODE -ne 0) { throw "AutoVendor tests FAILED" } + # ── Build LootEditor ─────────────────────────────────────────────────────── - name: Build LootEditor shell: pwsh diff --git a/BUILD.md b/BUILD.md index 8d56ee1..6b0b0b9 100644 --- a/BUILD.md +++ b/BUILD.md @@ -52,6 +52,16 @@ dotnet build -c Release dotnet run -c Release ``` +```powershell +cd C:\Projects\RynthSuite\Tools\RynthCore.AutoVendorTests +dotnet run -c Release # RynthAi AutoVendor rule/planning tests +``` + +```powershell +cd C:\Projects\RynthSuite\Tools\RynthCore.MissileArcTests +dotnet run -c Release # RynthAi missile arc (LoS ballistics) tests +``` + These projects target `net10.0` (no `-windows` suffix) and use Avalonia 11.2.3, so they build and run identically on Windows, Linux, and macOS. ## Deploy — Plugin diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs index 05347ae..41f3a14 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/AcStubs.cs @@ -54,6 +54,7 @@ public enum DoubleValueKey DamageVariance = 22, CurrentPowerMod = 23, AccuracyMod = 24, + MaximumVelocity = 26, // missile launcher launch speed (m/s); known once appraised WeaponDefense = 29, UseRadius = 54, WeaponOffense = 61, @@ -106,17 +107,59 @@ public class WorldObject // Set by WorldObjectCache when it creates/updates this object internal WorldObjectCache? Cache { get; set; } - public int Values(LongValueKey key, int defaultValue) - => Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue; + /// + /// Values that answer Values() before any live read (AutoVendor: a vendor-list item + /// built from the engine's vendor snapshot, or an item's known name). Null = live only. + /// + internal ItemPropertyOverlay? Overlay { get; set; } + + public int Values(LongValueKey key, int defaultValue) => Values((int)key, defaultValue); public int Values(int key, int defaultValue) - => Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue; + { + var o = Overlay; + if (o != null) + { + if (o.Ints.TryGetValue(unchecked((uint)key), out int v)) return v; + if (!o.LiveFallback) return defaultValue; + } + return Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue; + } public string Values(StringValueKey key, string defaultValue) - => Cache?.GetStringProperty(Id, (uint)key, defaultValue) ?? defaultValue; + { + var o = Overlay; + if (o != null) + { + if (o.Strings.TryGetValue((uint)key, out string? v)) return v; + if (!o.LiveFallback) return defaultValue; + } + return Cache?.GetStringProperty(Id, (uint)key, defaultValue) ?? defaultValue; + } public double Values(DoubleValueKey key, double defaultValue) - => Cache?.GetDoubleProperty(Id, (uint)key, defaultValue) ?? defaultValue; + { + var o = Overlay; + if (o != null) + { + if (o.Doubles.TryGetValue((uint)key, out double v)) return v; + if (!o.LiveFallback) return defaultValue; + } + return Cache?.GetDoubleProperty(Id, (uint)key, defaultValue) ?? defaultValue; + } +} + +/// +/// Fixed property values for a . With LiveFallback off, a key +/// that isn't here reads as the caller's default instead of the client object's value +/// (a vendor-list item carries only what the vendor snapshot holds). +/// +internal sealed class ItemPropertyOverlay +{ + public Dictionary Ints { get; } = new(); + public Dictionary Strings { get; } = new(); + public Dictionary Doubles { get; } = new(); + public bool LiveFallback { get; init; } } // ── SpellInfo stub ──────────────────────────────────────────────────────── diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 87301b5..62d13a7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -36,6 +36,10 @@ public class BuffManager : IDisposable private DateTime _lastBuffStanceAttempt = DateTime.MinValue; private int _buffStanceConsecutiveFails = 0; private bool _isForceRebuffing = false; + // Set with _isForceRebuffing when the pass is the automatic batch (one buff fell + // under RebuffSecondsRemaining), not the Force Rebuff button. The batch only tops + // off buffs under RebuffTopOffSecondsRemaining; Force Rebuff recasts everything. + private bool _isAutoBatchRebuff = false; private int _pendingSpellId = 0; private Action? _onCastResolved; @@ -475,6 +479,7 @@ public class BuffManager : IDisposable public void ForceFullRebuff() { _isForceRebuffing = true; + _isAutoBatchRebuff = false; _forceRebuffCastFamilies.Clear(); _buffFailCooldownUntil.Clear(); // explicit recast-all must not be blocked by stale cooldowns _silentNoShowCounts.Clear(); // give parked families a fresh shot on FR too @@ -496,6 +501,7 @@ public class BuffManager : IDisposable public void CancelBuffing() { _isForceRebuffing = false; + _isAutoBatchRebuff = false; _isRechargingMana = false; _isRechargingStamina = false; _isHealingSelf = false; @@ -810,15 +816,17 @@ public class BuffManager : IDisposable if (_isForceRebuffing) { + bool wasAutoBatch = _isAutoBatchRebuff; _isForceRebuffing = false; - _host.Log($"[FR] complete — cast {_forceRebuffCastFamilies.Count} spell families"); + _isAutoBatchRebuff = false; + _host.Log($"[FR] complete — cast {_forceRebuffCastFamilies.Count} spell families{(wasAutoBatch ? " (auto batch)" : "")}"); // Order matters: the flag must already be false (IsBuffActive // short-circuits on _forceRebuffCastFamilies while it is set, so // every family would read "active"), and the set must still be // populated — it is what the audit iterates. AuditBatchSatisfied(); _forceRebuffCastFamilies.Clear(); - _host.WriteToChat("[RynthAi] Force Rebuff Complete.", 1); + _host.WriteToChat(wasAutoBatch ? "[RynthAi] Rebuff complete." : "[RynthAi] Force Rebuff Complete.", 1); } } } @@ -1066,6 +1074,7 @@ public class BuffManager : IDisposable // no-show → re-park → another auto-batch → loop. Hard-reject // cooldowns are short-lived (120s) so they expire on their own. _isForceRebuffing = true; + _isAutoBatchRebuff = true; _forceRebuffCastFamilies.Clear(); } @@ -1377,13 +1386,23 @@ public class BuffManager : IDisposable // Force Rebuff: ignore live timers entirely — only spells we've already // cast THIS rebuff cycle count as "active". The whole point of FR is to // recast every spell so all timers align to the same start time. + // The automatic batch shares FR's bookkeeping but must NOT recast + // everything: one buff under the threshold used to refresh every buff, + // even ones with 30+ minutes left (2026-09-27). It tops off only buffs + // under RebuffTopOffSecondsRemaining (never less than RebuffSecondsRemaining, + // so the buff that started the batch is always in it) and leaves the rest + // to their own timers. if (_isForceRebuffing) - return _forceRebuffCastFamilies.Contains(targetSpell.Family); + { + if (_forceRebuffCastFamilies.Contains(targetSpell.Family)) return true; + if (!_isAutoBatchRebuff) return false; + rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining); + } int targetLevel = GetSpellLevel(targetSpell); // Recast when remaining duration drops below this many seconds. // User-configurable via Advanced Settings → Buffing; overridden during - // batch-rebuff passes (CheckAndCastSelfBuffs) to 1200s (20 min). + // batch-rebuff passes (CheckAndCastSelfBuffs) by RebuffTopOffSecondsRemaining. int rebufferSec = Math.Max(0, rebufferSecOverride ?? _settings.RebuffSecondsRemaining); // Tier-upgrade rule (applies to both item enchantments and player buffs): @@ -1664,10 +1683,16 @@ public class BuffManager : IDisposable // Learn the real ceiling this family lands at (Incantations cap below // their nominal tier) so IsBuffActive stops chasing an unreachable tier. - // Recorded for EVERY entry read, including one the merge above + // Recorded for every timed entry read, including one the merge above // discarded — the ceiling is about what this character can land, not - // about which entry currently wins the family slot. - RecordAchievedTier(spellInfo.Family, level); + // about which entry currently wins the family slot. NOT for permanent + // entries: those are item-granted ("Willpower Other I" on gear), not + // something this character cast, and learning their tier as the + // ceiling made a permanent level-1 enchant satisfy the family forever + // (effective target 1, never expires): after a relog with the real + // buff gone, Lucy went 17 minutes without Willpower (2026-09-27). + if (!isPermanent) + RecordAchievedTier(spellInfo.Family, level); if (isPermanent && _loggedPermanentFamilies.Add(spellInfo.Family)) _host.Log($"[BuffDiag] permanent player enchant tracked: id={spellInfo.Id} '{spellInfo.Name}' (fam={spellInfo.Family}, lvl={level}) — presence-only, not persisted" + diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index a477960..09ad86e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -160,7 +160,7 @@ public class CombatManager : IDisposable // a perfectly good target in ~3 ticks (~1.2s at SpellCastIntervalMs=400). private bool _offensiveCastThisCycle; private DateTime _faceStartTime = DateTime.MinValue; - private const double FACE_TIMEOUT_MS = 1000.0; // give up waiting and fire anyway (MISSILE only) + private const double FACE_TIMEOUT_MS = 1000.0; // give up waiting and swing anyway (non-native MELEE only) private const double FACE_TOLERANCE_DEG = 15.0; // heading error threshold to fire // ── Magic targeted-cast settle gate (root-cause fix 2026-06-19) ────────── @@ -168,11 +168,11 @@ public class CombatManager : IDisposable // turn-to-face; a turn/stop MoveToState that lands during that deferred // windup ORPHANS the cast (DoSpellWords/CreatePlayerSpell never runs) → the // gesture animates but 0 damage / "You're too busy!" forever. Self-buffs are - // immune (untargeted → synchronous, no turn). Fix: for MAGIC, never cast - // mid-turn — keep turning until actually within angle, then release the turn - // motions and let the stop reach the server (settle tick) BEFORE the cast. + // immune (untargeted → synchronous, no turn). The 2026-06-19 fix turned the + // bot itself until within angle, then released and settled before the cast; + // since 2026-09-27 the bot doesn't turn for magic at all (the server's own + // Rotate does it), and this only settles after releasing a turn melee left held. private DateTime _faceSettledAt = DateTime.MinValue; - private const double FACE_MAX_WAIT_MS = 2500.0; // safety: heading never converges (jittery point-blank pose) → cast anyway rather than wedge private const double FACE_SETTLE_MS = 140.0; // let the turn-stop reach the server (≥ one 30Hz tick) before the cast packet // ── Magic cast cadence guard ──────────────────────────────────────────── @@ -665,7 +665,9 @@ public class CombatManager : IDisposable double maxDist = _settings.MonsterRange; TargetingFSM.AttackType attackType = TargetingFSM.AttackType.Linear; if (RaycastInitialized && _raycastSystem?.TargetingFSM != null) - attackType = _raycastSystem.GetAttackType(CurrentCombatMode, ""); + attackType = DetermineAttackTypeForLOS(); + bool losDebug = _settings.LosDebugLog; + if (losDebug) LogLosDebugWeapon(); foreach (var wo in _worldFilter.GetLandscape()) { @@ -721,14 +723,12 @@ public class CombatManager : IDisposable if (dist > (isEngaged ? Math.Max(maxDist, DisengageDistance) : maxDist)) continue; bool losBlocked = false; - if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem != null) + if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem?.TargetingFSM != null) { RaycastCheckCount++; - if (_raycastSystem.IsTargetBlocked(_host, (uint)wo.Id, attackType)) - { - RaycastBlockCount++; - losBlocked = true; - } + losBlocked = _raycastSystem.TargetingFSM.IsTargetBlocked(_host, (uint)wo.Id, attackType, out var losDetail); + if (losBlocked) RaycastBlockCount++; + if (losDebug) LogLosDebug(wo, losBlocked, losDetail); } // Don't blacklist from scan — just exclude from this result. @@ -1337,9 +1337,12 @@ public class CombatManager : IDisposable private void DropTarget(string reason) { if (activeTargetId != 0) - _host.Log($"[RynthAi] DropTarget 0x{activeTargetId:X8}: {reason}"); + _host.Log($"[RynthAi] DropTarget 0x{activeTargetId:X8}: {reason} [{DescribeTargetPos(activeTargetId)}]"); activeTargetId = 0; _lockedTargetId = 0; + // A turn held toward the dropped target must be let go, or the character keeps + // spinning until something else happens to release it. + if (_facingTarget) ClearCombatTurnMotions(); _facingTarget = false; _returnToPhysicalCombat = false; _targetLockedAt = DateTime.MinValue; @@ -1775,6 +1778,7 @@ public class CombatManager : IDisposable fsm.CrossbowArcVelocity = _settings.CrossbowArcVelocity; fsm.AtlatlArcVelocity = _settings.AtlatlArcVelocity; fsm.MagicArcVelocity = _settings.MagicArcVelocity; + fsm.MissileArcClearance = _settings.MissileArcClearance; } // Deferred predicted kill-shot swap: a cast that armed it is confirmed @@ -1990,39 +1994,19 @@ public class CombatManager : IDisposable return true; } - // MAGIC: settle-before-cast facing gate. Never cast mid-turn and - // never let a turn-stop ride alongside the cast packet — both orphan - // the ACE server's deferred targeted-cast windup (root cause of - // "animates but 0 damage / too busy"). Makes combat behave like the - // working self-buff path. Applies regardless of UseNativeAttack - // (native attack is a physical swing; in Magic mode the bot always - // casts, so the facing race is the same with or without it). - if (CurrentCombatMode == CombatMode.Magic) + // MAGIC and MISSILE: the server turns the player to the target itself, + // as retail did — ACE Rotate(target) before a targeted cast (and again + // after the windup if needed) and before the first missile shot and + // between repeat shots. So the bot doesn't turn at all. A client-side + // turn servo on top only fought that rotation: missile characters spun + // in circles between shots (2026-09-27, Lucy, Olthoi swarm at close + // range), and for magic the server waits while the client holds a turn + // (PendingTurnRelease), which is where the "animates but 0 damage / too + // busy" orphaned windups came from. Applies with or without + // UseNativeAttack. Only a turn another mode left held is released — with one + // settle tick before a cast, so the stop doesn't ride with the packet. + if (CurrentCombatMode == CombatMode.Magic || CurrentCombatMode == CombatMode.Missile) { - double facingError = GetFacingError(activeTargetId); - if (facingError > FACE_TOLERANCE_DEG) - { - FaceTarget(activeTargetId); - if (!_facingTarget) - { - _facingTarget = true; - _faceStartTime = DateTime.Now; - } - // Keep turning until actually within angle. Do NOT "fire - // anyway" while still turning (that was the bug). Only a long - // safety timeout falls through, so a jittery point-blank pose - // can't wedge combat forever. - if ((DateTime.Now - _faceStartTime).TotalMilliseconds < FACE_MAX_WAIT_MS) - { - LastCombatSkipReason = "facing-turning"; // D4 record-only - return true; - } - _host.Log($"[CombatCast] facing did not converge in {FACE_MAX_WAIT_MS:0}ms (err={facingError:0.0}°) — releasing turn + casting anyway"); - } - - // Within angle (or safety-timed-out). If we were turning, release - // the turn motions and give the stop ONE settle tick to reach the - // server BEFORE the cast packet. if (_facingTarget) { ClearCombatTurnMotions(); @@ -2031,7 +2015,8 @@ public class CombatManager : IDisposable LastCombatSkipReason = "face-settle-release"; // D4 record-only return true; // settle tick } - if ((DateTime.Now - _faceSettledAt).TotalMilliseconds < FACE_SETTLE_MS) + if (CurrentCombatMode == CombatMode.Magic + && (DateTime.Now - _faceSettledAt).TotalMilliseconds < FACE_SETTLE_MS) { LastCombatSkipReason = "face-settle-wait"; // D4 record-only return true; // let the turn-stop settle on the server first @@ -2282,11 +2267,20 @@ public class CombatManager : IDisposable double bestScore = double.MinValue; double heldScore = double.MinValue; // scored total for the incumbent, for the switch log bool incumbentSeen = false; + double acquireRange = Math.Max(1.0, _settings.MonsterRange); foreach (var c in _scannedTargets) { double s = ScoreCandidate(c); + // The incumbent keeps stickiness and commitment only inside MonsterRange. The + // scan holds a locked target out to DisengageDistance (MonsterRange+3 by default) + // so a lone mob at the edge doesn't flip engage/peace, not so it can out-score + // mobs inside the range the user set. Beyond MonsterRange it competes on its + // merits, and any reasonable in-range mob takes over. Before this a target at + // 5-8 m kept +45 and could hold off mobs at 3-5 m (2026-09-27, Olthoi swarm: + // Monster Range 5, one target kept for over a minute, never out of range). if (c.Id == _lockedTargetId) { + double meritScore = s; s += TARGET_SWITCH_STICKINESS; // Commitment: once we have COMMITTED to the locked target, // finishing it outranks any small positional edge a fresh mob @@ -2334,6 +2328,8 @@ public class CombatManager : IDisposable if (!undamaged || (withinFlightWindow && withinUndamagedGrace)) s += DAMAGE_COMMITMENT_BONUS; + if (c.Distance > acquireRange) + s = meritScore; // beyond MonsterRange: no stickiness, no commitment (see above) heldScore = s; incumbentSeen = true; _lockedLastScore = s; @@ -2365,8 +2361,10 @@ public class CombatManager : IDisposable // up) — if this floods the log, selection is thrashing again and the two // scores say by how much. if (_lockedTargetId != 0) - _host.Log($"[CombatTarget] switch 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' (score={(heldScore == double.MinValue ? "gone" : heldScore.ToString("0.0"))}) " + - $"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0})"); + _host.Log($"[CombatTarget] switch 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' (score={(heldScore == double.MinValue ? "gone" : heldScore.ToString("0.0"))}, {DescribeTargetPos(_lockedTargetId)}) " + + $"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0}, {DescribeTargetPos(bestId)})"); + else + _host.Log($"[CombatTarget] lock 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0}, {DescribeTargetPos(bestId)})"); activeTargetId = bestId; _lockedTargetId = bestId; @@ -2898,21 +2896,92 @@ public class CombatManager : IDisposable return lines; } + /// + /// Attack type for the scan's LOS test. Missile mode names the weapon in hand so the + /// bow/crossbow/atlatl arc and its velocity apply (the scan used to pass "", which made + /// every missile LOS test a straight line). Peace mode with a missile weapon picked counts + /// as missile, so a target acquired from peace is tested with the arc it will be shot on. + /// Magic stays a straight line, as before. + /// private TargetingFSM.AttackType DetermineAttackTypeForLOS() { - if (CurrentCombatMode == CombatMode.Magic) + if (_raycastSystem?.TargetingFSM == null) return TargetingFSM.AttackType.Linear; + + int mode = CurrentCombatMode; + WorldObject? weapon = _equippedWeaponId != 0 ? _worldFilter[_equippedWeaponId] : null; + bool missileWeapon = weapon != null && weapon.ObjectClass == AcObjectClass.MissileWeapon; + if (mode == CombatMode.NonCombat && missileWeapon) + mode = CombatMode.Missile; + + string weaponName = mode == CombatMode.Missile && missileWeapon ? weapon!.Name ?? "" : ""; + return _raycastSystem.GetAttackType(mode, weaponName); + } + + // ── LOS / target-distance diagnostics ──────────────────────────────────── + // "Far away" can't be judged from the log without positions, so target lock, switch and + // drop lines carry the 3D distance, its horizontal and vertical parts and both cells. + // With LosDebugLog on, the scan also logs each target's LOS verdict (line / arc, rise, + // hit point) when it changes and at most every LosDebugRepeatMs otherwise. + private readonly Dictionary _losDebugLast = new(); + private const double LosDebugRepeatMs = 5000; + private const double LosDebugMinGapMs = 1000; + private int _losDebugWeaponId; + + /// "d=6.2m (h=5.9 dz=+1.8) cell=0x61450123 me=0x61450119", or why it can't be measured. + private string DescribeTargetPos(int targetId) + { + uint pid = _host.GetPlayerId(); + if (pid == 0 || targetId == 0) return "pos=?"; + if (!_host.TryGetObjectPosition(pid, out uint pc, out float px, out float py, out float pz)) + return "pos=? (no player position)"; + if (!_host.TryGetObjectPosition((uint)targetId, out uint tc, out float tx, out float ty, out float tz)) + return "pos=? (no target position)"; + double dx = (((tc >> 24) & 0xFF) * 192.0 + tx) - (((pc >> 24) & 0xFF) * 192.0 + px); + double dy = (((tc >> 16) & 0xFF) * 192.0 + ty) - (((pc >> 16) & 0xFF) * 192.0 + py); + double dz = tz - pz; + double h = Math.Sqrt(dx * dx + dy * dy); + double d = Math.Sqrt(h * h + dz * dz); + return $"d={d:0.0}m (h={h:0.0} dz={dz:+0.0;-0.0;0.0}) cell=0x{tc:X8} me=0x{pc:X8}"; + } + + private void LogLosDebug(WorldObject wo, bool blocked, in TargetingFSM.LosDetail det) + { + DateTime now = DateTime.Now; + if (_losDebugLast.TryGetValue(wo.Id, out var last)) { - // Get rule from current target name if available - var targetObj = _worldFilter[activeTargetId]; - var rule = GetRuleForTarget(targetObj); - if (rule != null && rule.UseArc) return TargetingFSM.AttackType.MagicArc; - return TargetingFSM.AttackType.Linear; + double ms = (now - last.At).TotalMilliseconds; + bool changed = last.Blocked != blocked; + if (ms < LosDebugMinGapMs || (!changed && ms < LosDebugRepeatMs)) return; } + if (_losDebugLast.Count > 256) _losDebugLast.Clear(); + _losDebugLast[wo.Id] = (now, blocked); - if (_raycastSystem?.TargetingFSM != null) - return _raycastSystem.GetAttackType(CurrentCombatMode, ""); + string verdict; + if (!det.Checked) verdict = "clear (not tested: no geometry near the path)"; + else if (det.LineBlocked) verdict = "BLOCKED line"; + else if (det.ArcChecked && det.Arc.OutOfReach) verdict = "BLOCKED arc: out of reach at this velocity"; + else if (det.ArcChecked && det.Arc.Blocked) verdict = $"BLOCKED arc: hit {det.Arc.HitAlong:0.0}m out, {det.Arc.HitZ:+0.0;-0.0;0.0}m vs launch"; + else verdict = "clear"; - return TargetingFSM.AttackType.Linear; + string arcInfo = det.Velocity > 0 + ? $" v={det.Velocity:0.0} rise={det.Arc.Sag:0.00} apex={det.Arc.Apex:0.00} clr={_settings.MissileArcClearance:0.0}{(det.ArcChecked ? "" : " (flat: line only)")}" + : ""; + _host.Log($"[LOS] 0x{(uint)wo.Id:X8} '{wo.Name}' {verdict} | {det.Type}{(det.Dungeon ? " dungeon" : "")}{arcInfo} | {DescribeTargetPos(wo.Id)}"); + } + + /// LOS debug: once per missile weapon, what the client knows of its launch speed. + private void LogLosDebugWeapon() + { + int wid = _equippedWeaponId; + if (wid == 0 || wid == _losDebugWeaponId) return; + var weapon = _worldFilter[wid]; + if (weapon == null || weapon.ObjectClass != AcObjectClass.MissileWeapon) return; + _losDebugWeaponId = wid; + double maxVel = _worldFilter.GetDoubleProperty(wid, (uint)DoubleValueKey.MaximumVelocity, 0); + var type = DetermineAttackTypeForLOS(); + float setting = _raycastSystem?.TargetingFSM?.VelocityFor(type) ?? 0f; + _host.Log($"[LOS] missile weapon 0x{(uint)wid:X8} '{weapon.Name}': MaximumVelocity={(maxVel > 0 ? maxVel.ToString("0.0") : "unknown (not appraised)")}, " + + $"LOS uses {type} v={setting:0.0}"); } private void FaceTarget(int targetId) @@ -2961,6 +3030,15 @@ public class CombatManager : IDisposable _host.SetMotion(MotionTurnLeft, false); } + /// Let go of a turn the facing servo is holding. Called when combat stops + /// ticking (macro off), which would otherwise leave the turn held for good. + public void ReleaseHeldTurn() + { + if (!_facingTarget) return; + _facingTarget = false; + ClearCombatTurnMotions(); + } + /// /// True while a previously-issued combat cast is still resolving on the ACE /// server. Serializes magic casts so the next cast's turn/stop motion can't diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs index 363d0ea..a597156 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/MissileCraftingManager.cs @@ -45,6 +45,7 @@ public class MissileCraftingManager private const int APPLY_RETRY_MS = 2000; private const int CRAFT_TIMEOUT_MS = 15000; private const int EQUIP_DELAY_MS = 500; + private const int ERROR_BACKOFF_MS = 60000; private int _headBundleId = 0; private int _shaftBundleId = 0; @@ -69,15 +70,33 @@ public class MissileCraftingManager public void ProcessCrafting() { - if (!_settings.EnableMissileCrafting) return; + // While State isn't Idle the plugin holds combat, nav and looting, so turning + // crafting off mid-craft must let go too. + if (!_settings.EnableMissileCrafting) + { + if (State != CraftState.Idle) Reset("Missile crafting turned off"); + return; + } if (IsBusy) return; - switch (State) + // An exception here used to leave State where it was, and the bot stood still + // forever with nothing in chat: say what broke, let go, and try again later. + try { - case CraftState.Idle: ProcessIdle(); break; - case CraftState.Evaluating: ProcessEvaluating(); break; - case CraftState.Combining: ProcessCombining(); break; - case CraftState.EquippingAmmo: ProcessEquippingAmmo(); break; + switch (State) + { + case CraftState.Idle: ProcessIdle(); break; + case CraftState.Evaluating: ProcessEvaluating(); break; + case CraftState.Combining: ProcessCombining(); break; + case CraftState.EquippingAmmo: ProcessEquippingAmmo(); break; + } + } + catch (Exception ex) + { + string reason = $"Stopped by an error ({ex.GetType().Name}: {ex.Message}); trying again in a minute"; + if (State == CraftState.Idle) ChatLog(reason); // Reset only speaks for a craft in progress + Reset(reason); + _lastAmmoCheck = DateTime.Now.AddMilliseconds(ERROR_BACKOFF_MS - AMMO_CHECK_INTERVAL_MS); } } @@ -169,9 +188,22 @@ public class MissileCraftingManager if (bestCraftable != null) { StartCrafting(bestCraftable, inv); return; } + // No ammo at all and only bundles the skill check calls risky: a bow with nothing + // to shoot can't fight, so a combine that may fail beats standing there. if (tooHard != null) - Reset($"No ammo, and Fletching {fletching?.Buffed} is too low to make {tooHard.OutputName} reliably " + - $"(difficulty {tooHard.Difficulty}; a failed combine destroys both bundles)"); + { + int skill = fletching?.Buffed ?? 250; + ChatLog($"No ammo: making {tooHard.OutputName} anyway, about " + + $"{AmmoRecipes.SuccessChance(skill, tooHard.Difficulty):P0} with Fletching {skill} " + + "(a failed combine destroys both bundles)"); + StartCrafting(tooHard, inv); + return; + } + + if (fletching != null && fletching.Training < 2 + && AmmoRecipes.BestCraftable(inv.Select(i => i.Name), category, 0, out var carried) == null + && carried != null) + Reset($"No ammo, and Fletching is untrained, so the bundles for {carried.OutputName} can't be combined"); else Reset("No ammo and no bundles available"); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs index 0b2275f..85a3339 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs @@ -903,7 +903,11 @@ public class WorldObjectCache float dx = gx1 - gx2; float dy = gy1 - gy2; float dz = z1 - z2; - return Math.Sqrt(dx * dx + dy * dy + dz * dz); + double d = Math.Sqrt(dx * dx + dy * dy + dz * dz); + // A garbage position read (NaN/∞) must read as out of range. NaN fails every + // "dist > limit" test, so it passed both the scan's range gate and Think's + // disengage drop, and a target could be kept at any real distance. + return double.IsFinite(d) ? d : double.MaxValue; } /// Enumerate objects in player's inventory (no physics position). @@ -1547,7 +1551,7 @@ public class WorldObjectCache // ── Type-flag item classification ───────────────────────────────────── - private static AcObjectClass ClassifyByItemType(uint typeFlags) + internal static AcObjectClass ClassifyByItemType(uint typeFlags) { // Most specific / unambiguous types first if ((typeFlags & ItemTypePromissoryNote) != 0) return AcObjectClass.TradeNote; diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 490892d..688147b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -374,16 +374,32 @@ public sealed partial class RynthAiPlugin public override void OnVendorOpen(uint vendorId) { + _metaManager?.OnVendorOpen(vendorId); + + // AutoVendor prints the open line itself (UB's merchant-info line when it can read the + // vendor, once per open rather than on every list re-send) and may start a session. + var autoVendor = _autoVendor; + if (autoVendor != null) + { + autoVendor.OnVendorOpen(vendorId); + return; + } string label = Host.TryGetObjectName(vendorId, out string name) ? name : $"0x{vendorId:X8}"; Host.WriteToChat($"[RynthAi] Vendor open: {label}", 1); - _metaManager?.OnVendorOpen(vendorId); } public override void OnVendorClose(uint vendorId) { + _metaManager?.OnVendorClose(vendorId); + + var autoVendor = _autoVendor; + if (autoVendor != null) + { + autoVendor.OnVendorClose(vendorId); + return; + } string label = Host.TryGetObjectName(vendorId, out string name) ? name : $"0x{vendorId:X8}"; Host.WriteToChat($"[RynthAi] Vendor closed: {label}", 1); - _metaManager?.OnVendorClose(vendorId); } private void TickCorpseOpening() diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index 0ab2a56..280331e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -23,6 +23,9 @@ internal sealed class LegacyAdvancedSettingsUi public void SetMissileCraftingManager(MissileCraftingManager mgr) => _missileCraftingManager = mgr; + private Func? _autoVendorStatus; + public void SetAutoVendorStatusProvider(Func status) => _autoVendorStatus = status; + public string MissileCraftingState => _missileCraftingManager?.State.ToString() ?? string.Empty; public bool MissileCraftingActive => _missileCraftingManager?.IsCrafting ?? false; public string MissileCraftingStatus => _missileCraftingManager?.StatusMessage ?? string.Empty; @@ -60,6 +63,51 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.End(); } + private void RenderVendoring() + { + ImGui.Text("AutoVendor (UtilityBelt)"); + ImGui.Separator(); + ImGui.Spacing(); + + string status = _autoVendorStatus?.Invoke() ?? "Not logged in"; + ImGui.TextDisabled($"Status: {status}"); + ImGui.Spacing(); + + ImGui.Checkbox("Enabled##AV", ref _settings.AutoVendorEnabled); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\n" + + "Profiles: .utl or default.utl in your character's AutoVendor\n" + + "folder, the server folder, or " + Vendor.AutoVendorManager.MainProfileDir + "."); + ImGui.Checkbox("Test Mode (only print what it would do)##AV", ref _settings.AutoVendorTestMode); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Lists what would be bought and sold without trading. Leave this on until\n" + + "the list looks right: selling can't be undone."); + ImGui.Checkbox("Buy##AV", ref _settings.AutoVendorEnableBuying); + ImGui.SameLine(); + ImGui.Checkbox("Sell##AV", ref _settings.AutoVendorEnableSelling); + ImGui.Checkbox("Only Sell From Main Pack##AV", ref _settings.AutoVendorOnlyFromMainPack); + ImGui.Checkbox("Show Merchant Info##AV", ref _settings.AutoVendorShowMerchantInfo); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Print the vendor's buy/sell rates and max value when it opens."); + ImGui.Checkbox("Think When Finished##AV", ref _settings.AutoVendorThink); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Send 'AutoVendor finished: ' (and failures) as a /tell to yourself,\n" + + "so a meta's chat condition can wait for it."); + + ImGui.Spacing(); + ImGui.Text("/ub vendor open"); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Tries##AV", ref _settings.AutoVendorTries)) + _settings.AutoVendorTries = Math.Clamp(_settings.AutoVendorTries, 1, 20); + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Time Between Tries (ms)##AV", ref _settings.AutoVendorTriesTime, 250)) + _settings.AutoVendorTriesTime = Math.Clamp(_settings.AutoVendorTriesTime, 500, 30000); + + 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."); + } + private void RenderTabContent(int tabIndex) { if (tabIndex < 0 || tabIndex >= _settings.AdvancedTabs.Length) @@ -147,10 +195,15 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Spacing(); ImGui.Text("Missile Arc Velocities (m/s)"); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Per-weapon projectile speed used for line-of-sight arc checks.\nLower velocity = higher arc. Tune until LoS matches in-game hits.\nDungeons always use linear checks to avoid false ceiling blocks."); + ImGui.SetTooltip("Per-weapon launch speed used for line-of-sight arc checks.\n" + + "Lower velocity = higher arc. Tune until LoS matches in-game hits\n" + + "(/ra lostest bow on a selected mob shows the arc and where it hits).\n" + + "Indoors the arc is checked against ceilings too."); ImGui.Checkbox("Use Arcs for Missile LoS", ref _settings.UseArcs); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("When off, all missile LoS checks are linear (eye-to-eye)."); + ImGui.SetTooltip("On: a missile target must pass the straight line AND the arc the\n" + + "missile flies (checked against ceilings in dungeons).\n" + + "Off: all missile LoS checks are a straight line (eye-to-eye)."); if (_settings.UseArcs) { ImGui.Indent(); @@ -162,8 +215,18 @@ internal sealed class LegacyAdvancedSettingsUi 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" + + "still hit ceilings; lower it if mobs the arrows can reach are skipped.\n" + + "Default 0.5."); ImGui.Unindent(); } + 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" + + "how high the arc rises, where it hits, distance and cells). For tuning."); ImGui.Separator(); ImGui.Spacing(); @@ -490,6 +553,12 @@ 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()) @@ -541,6 +610,15 @@ internal sealed class LegacyAdvancedSettingsUi "values (<60s) risk a gap between the old buff dropping and the new one\n" + "landing."); + ImGui.SetNextItemWidth(180); + ImGui.SliderInt("Also Refresh Under (seconds left)", ref _settings.RebuffTopOffSecondsRemaining, 30, 3600); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip( + "When a buff is due, also recast every other buff with less than this\n" + + "much time left, so they land together. Buffs with more time are left\n" + + "alone. Default 1200 (20 minutes). At or below 'Rebuff With', only the\n" + + "expiring buff is recast."); + ImGui.Spacing(); ImGui.Separator(); ImGui.Text("Buff Difficulty (Min Buffed Skill)"); @@ -667,6 +745,10 @@ internal sealed class LegacyAdvancedSettingsUi } break; + case "Vendoring": + RenderVendoring(); + break; + default: ImGui.Text($"Settings for {tabName} are currently under development."); break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index ad74247..52f6092 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -280,6 +280,12 @@ internal sealed class LegacyDashboardRenderer public void SetWorldFilter(WorldObjectCache cache) => _weaponsUi.SetWorldFilter(cache); public void SetMissileCraftingManager(MissileCraftingManager mgr) => _advancedSettingsUi.SetMissileCraftingManager(mgr); + public void SetAutoVendorStatusProvider(Func status) => _advancedSettingsUi.SetAutoVendorStatusProvider(status); + + // The open vendor's AutoVendor profile path (null when no vendor is open), for the + // dashboard snapshot's vendorProfilePath. + private Func? _vendorProfilePath; + public void SetVendorProfilePathProvider(Func path) => _vendorProfilePath = path; public void SetRaycast(Raycasting.MainLogic raycast) { @@ -766,6 +772,8 @@ internal sealed class LegacyDashboardRenderer CrossbowArcVelocity = s.CrossbowArcVelocity, AtlatlArcVelocity = s.AtlatlArcVelocity, MagicArcVelocity = s.MagicArcVelocity, + MissileArcClearance = s.MissileArcClearance, + LosDebugLog = s.LosDebugLog, BlacklistAttempts = s.BlacklistAttempts, BlacklistTimeoutSec = s.BlacklistTimeoutSec, BlacklistCastSettleMs = s.BlacklistCastSettleMs, @@ -827,6 +835,7 @@ internal sealed class LegacyDashboardRenderer NavDeadZone = s.NavDeadZone, NavSweepMult = s.NavSweepMult, NavLookaheadYards = s.NavLookaheadYards, + NavShortcutYards = s.NavShortcutYards, NavTurnRateDegPerSec = s.NavTurnRateDegPerSec, NavTier1TurnSpeed = s.NavTier1TurnSpeed, PostPortalDelaySec = s.PostPortalDelaySec, @@ -840,6 +849,7 @@ internal sealed class LegacyDashboardRenderer EnableBuffing = s.EnableBuffing, RebuffWhenIdle = s.RebuffWhenIdle, RebuffSecondsRemaining = s.RebuffSecondsRemaining, + RebuffTopOffSecondsRemaining = s.RebuffTopOffSecondsRemaining, BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1, BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2, BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3, @@ -878,6 +888,16 @@ internal sealed class LegacyDashboardRenderer SalvageSalvageDelayMs = s.SalvageSalvageDelayMs, SalvageResultDelayFirstMs = s.SalvageResultDelayFirstMs, SalvageResultDelayFastMs = s.SalvageResultDelayFastMs, + // Vendoring (AutoVendor) + AutoVendorEnabled = s.AutoVendorEnabled, + AutoVendorEnableBuying = s.AutoVendorEnableBuying, + AutoVendorEnableSelling = s.AutoVendorEnableSelling, + AutoVendorTestMode = s.AutoVendorTestMode, + AutoVendorThink = s.AutoVendorThink, + AutoVendorShowMerchantInfo = s.AutoVendorShowMerchantInfo, + AutoVendorOnlyFromMainPack = s.AutoVendorOnlyFromMainPack, + AutoVendorTries = s.AutoVendorTries, + AutoVendorTriesTime = s.AutoVendorTriesTime, }; return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.SettingsBridgePayload); } @@ -892,7 +912,20 @@ internal sealed class LegacyDashboardRenderer if (string.IsNullOrWhiteSpace(json)) return; try { - var p = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.SettingsBridgePayload); + // Lay the sent fields over the current settings, so a field the sender leaves + // out keeps its value instead of deserializing to 0 and being applied. The + // overlay's Settings panel keeps its own copy of this payload; when that copy + // lacked BlacklistCastSettleMs/MonsterDisengageRange, every click zeroed them. + var merged = System.Text.Json.Nodes.JsonNode.Parse(BuildSettingsJson(), + new System.Text.Json.Nodes.JsonNodeOptions { PropertyNameCaseInsensitive = true })?.AsObject(); + if (merged == null) return; + using (var sent = JsonDocument.Parse(json)) + { + if (sent.RootElement.ValueKind != JsonValueKind.Object) return; + foreach (var prop in sent.RootElement.EnumerateObject()) + merged[prop.Name] = System.Text.Json.Nodes.JsonNode.Parse(prop.Value.GetRawText()); + } + var p = JsonSerializer.Deserialize(merged.ToJsonString(), RynthAiJsonContext.Default.SettingsBridgePayload); if (p == null) return; var s = _settings; // Display @@ -918,9 +951,13 @@ internal sealed class LegacyDashboardRenderer s.CrossbowArcVelocity = p.CrossbowArcVelocity; s.AtlatlArcVelocity = p.AtlatlArcVelocity; s.MagicArcVelocity = p.MagicArcVelocity; + if (p.MissileArcClearance >= 0f) s.MissileArcClearance = Math.Min(p.MissileArcClearance, 3f); + s.LosDebugLog = p.LosDebugLog; s.BlacklistAttempts = p.BlacklistAttempts; s.BlacklistTimeoutSec = p.BlacklistTimeoutSec; - s.BlacklistCastSettleMs = p.BlacklistCastSettleMs; + // -1 = not sent. 0 is never meant (it judges a cast before its damage can land) + // and is what the bug saved into profiles, so it keeps the default too. + if (p.BlacklistCastSettleMs > 0) s.BlacklistCastSettleMs = p.BlacklistCastSettleMs; s.TargetNoProgressTimeoutSec = p.TargetNoProgressTimeoutSec; s.GiveQueueIntervalMs = p.GiveQueueIntervalMs; // Recharge @@ -957,7 +994,7 @@ internal sealed class LegacyDashboardRenderer s.MinSkillLevelTier8 = p.MinSkillLevelTier8; // Ranges s.MonsterRange = p.MonsterRange; - s.MonsterDisengageRange = p.MonsterDisengageRange; + if (p.MonsterDisengageRange >= 0) s.MonsterDisengageRange = p.MonsterDisengageRange; // -1 = not sent s.RingRange = p.RingRange; s.ApproachRange = p.ApproachRange; s.CorpseApproachRangeMax = p.CorpseApproachRangeMax; @@ -979,6 +1016,7 @@ internal sealed class LegacyDashboardRenderer s.NavDeadZone = p.NavDeadZone; s.NavSweepMult = p.NavSweepMult; s.NavLookaheadYards = p.NavLookaheadYards; + s.NavShortcutYards = p.NavShortcutYards; s.NavTurnRateDegPerSec = p.NavTurnRateDegPerSec; s.NavTier1TurnSpeed = p.NavTier1TurnSpeed; s.PostPortalDelaySec = p.PostPortalDelaySec; @@ -992,6 +1030,7 @@ internal sealed class LegacyDashboardRenderer s.EnableBuffing = p.EnableBuffing; s.RebuffWhenIdle = p.RebuffWhenIdle; s.RebuffSecondsRemaining = p.RebuffSecondsRemaining; + if (p.RebuffTopOffSecondsRemaining > 0) s.RebuffTopOffSecondsRemaining = p.RebuffTopOffSecondsRemaining; s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1; s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2; s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3; @@ -1027,6 +1066,16 @@ internal sealed class LegacyDashboardRenderer s.SalvageSalvageDelayMs = p.SalvageSalvageDelayMs; s.SalvageResultDelayFirstMs = p.SalvageResultDelayFirstMs; s.SalvageResultDelayFastMs = p.SalvageResultDelayFastMs; + // Vendoring: only fields the sender actually included (older panels omit them) + if (p.AutoVendorEnabled is bool avOn) s.AutoVendorEnabled = avOn; + if (p.AutoVendorEnableBuying is bool avBuy) s.AutoVendorEnableBuying = avBuy; + if (p.AutoVendorEnableSelling is bool avSell) s.AutoVendorEnableSelling = avSell; + if (p.AutoVendorTestMode is bool avTest) s.AutoVendorTestMode = avTest; + if (p.AutoVendorThink is bool avThink) s.AutoVendorThink = avThink; + if (p.AutoVendorShowMerchantInfo is bool avInfo) s.AutoVendorShowMerchantInfo = avInfo; + if (p.AutoVendorOnlyFromMainPack is bool avMain) s.AutoVendorOnlyFromMainPack = avMain; + if (p.AutoVendorTries is int avTries) s.AutoVendorTries = Math.Clamp(avTries, 1, 20); + if (p.AutoVendorTriesTime is int avTime) s.AutoVendorTriesTime = Math.Clamp(avTime, 500, 30000); SaveSettings(); } catch { } @@ -1302,6 +1351,7 @@ internal sealed class LegacyDashboardRenderer dst.NavDeadZone = tmp.NavDeadZone; dst.NavSweepMult = tmp.NavSweepMult; dst.NavLookaheadYards = tmp.NavLookaheadYards; + dst.NavShortcutYards = tmp.NavShortcutYards; dst.NavTurnRateDegPerSec = tmp.NavTurnRateDegPerSec; dst.NavTier1TurnSpeed = tmp.NavTier1TurnSpeed; dst.PostPortalDelaySec = tmp.PostPortalDelaySec; @@ -1384,9 +1434,12 @@ internal sealed class LegacyDashboardRenderer dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle; dst.RebuffWhenIdle = tmp.RebuffWhenIdle; dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining; + dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining; dst.BlacklistAttempts = tmp.BlacklistAttempts; dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec; - dst.BlacklistCastSettleMs = tmp.BlacklistCastSettleMs; + // 0 is never meant (every UI floors it at 250+) and is what the Settings-panel bug + // saved into profiles: it judges each cast before its damage can land. + dst.BlacklistCastSettleMs = tmp.BlacklistCastSettleMs > 0 ? tmp.BlacklistCastSettleMs : 1500; dst.TargetNoProgressTimeoutSec = tmp.TargetNoProgressTimeoutSec; dst.MeleeAttackPower = tmp.MeleeAttackPower; dst.MissileAttackPower = tmp.MissileAttackPower; @@ -1399,6 +1452,8 @@ internal sealed class LegacyDashboardRenderer dst.CrossbowArcVelocity = tmp.CrossbowArcVelocity; dst.AtlatlArcVelocity = tmp.AtlatlArcVelocity; dst.MagicArcVelocity = tmp.MagicArcVelocity; + dst.MissileArcClearance = tmp.MissileArcClearance >= 0f ? Math.Min(tmp.MissileArcClearance, 3f) : 0.5f; + dst.LosDebugLog = tmp.LosDebugLog; dst.EnableFPSLimit = tmp.EnableFPSLimit; dst.TargetFPSFocused = tmp.TargetFPSFocused; dst.TargetFPSBackground = tmp.TargetFPSBackground; @@ -1453,6 +1508,15 @@ internal sealed class LegacyDashboardRenderer dst.EnableManaTapping = tmp.EnableManaTapping; dst.ManaTapMinMana = tmp.ManaTapMinMana; dst.ManaStoneKeepCount = tmp.ManaStoneKeepCount; + dst.AutoVendorEnabled = tmp.AutoVendorEnabled; + dst.AutoVendorEnableBuying = tmp.AutoVendorEnableBuying; + dst.AutoVendorEnableSelling = tmp.AutoVendorEnableSelling; + dst.AutoVendorTestMode = tmp.AutoVendorTestMode; + dst.AutoVendorThink = tmp.AutoVendorThink; + dst.AutoVendorShowMerchantInfo = tmp.AutoVendorShowMerchantInfo; + dst.AutoVendorOnlyFromMainPack = tmp.AutoVendorOnlyFromMainPack; + dst.AutoVendorTries = tmp.AutoVendorTries; + dst.AutoVendorTriesTime = tmp.AutoVendorTriesTime; dst.MetaDebug = tmp.MetaDebug; dst.StartMacroOnLogin = tmp.StartMacroOnLogin; dst.PatrolOnLogin = tmp.PatrolOnLogin; @@ -2542,6 +2606,9 @@ internal sealed class LegacyDashboardRenderer string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath)); sb.Append(','); AppendString(sb, "currentLootName", string.IsNullOrEmpty(_settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentLootPath)); sb.Append(','); + // Full paths for the dashboard's Edit (✎) button, which opens the Loot Editor. + AppendString(sb, "currentLootPath", _settings.CurrentLootPath ?? string.Empty); sb.Append(','); + AppendString(sb, "vendorProfilePath", _vendorProfilePath?.Invoke() ?? string.Empty); sb.Append(','); AppendString(sb, "currentMetaName", string.IsNullOrEmpty(_settings.CurrentMetaPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentMetaPath)); sb.Append(','); AppendInt(sb, "selectedNavIdx", _selectedNavIdx); sb.Append(','); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index 17dcf12..a15912c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -40,6 +40,7 @@ public sealed class LegacyUiSettings public float NavDeadZone = 4f; public float NavSweepMult = 2.5f; public float NavLookaheadYards = 4.0f; // distance to start blending the aim point toward the next waypoint (0 = off) + public float NavShortcutYards = 1.0f; // on arrival, skip waypoints only while the straight run to a later one stays within this of every skipped point (0 = visit every point) 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; @@ -149,6 +150,13 @@ public sealed class LegacyUiSettings /// landing. /// public int RebuffSecondsRemaining = 300; + /// + /// When a buff falls under RebuffSecondsRemaining, also refresh every other buff + /// with less than this many seconds left, so they land together instead of each + /// interrupting the fight on its own. Buffs with more time are left alone. At or + /// below RebuffSecondsRemaining only the expiring buff is recast. + /// + public int RebuffTopOffSecondsRemaining = 1200; public bool StartMacroOnLogin; public bool PatrolOnLogin; @@ -225,6 +233,20 @@ public sealed class LegacyUiSettings public float CrossbowArcVelocity = 40.0f; public float AtlatlArcVelocity = 22.0f; public float MagicArcVelocity = 25.0f; + /// + /// 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 + /// what the model can't know exactly: launch height, the real launch speed, the + /// projectile's size. Raise it if shots still hit ceilings, lower it if targets + /// under a ceiling the arrows clear are skipped. Only used with UseArcs. + /// + public float MissileArcClearance = 0.5f; + /// + /// Log each in-range target's LoS verdict (straight line / arc, how high the arc + /// rises, where it hits) and the missile weapon's known launch speed. For tuning + /// the arc settings; off by default (a few lines a second in a crowd). + /// + public bool LosDebugLog; public bool EnableFPSLimit = true; public int TargetFPSFocused = 60; @@ -256,6 +278,23 @@ public sealed class LegacyUiSettings public int ManaTapMinMana = 2500; public int ManaStoneKeepCount = 5; + // ── AutoVendor (UtilityBelt AutoVendor; /ub autovendor, /ub vendor) ──────── + /// Run AutoVendor when a vendor opens (and allow /ub autovendor). UB defaults this on; + /// RynthAi defaults it off because the plugin auto-updates and selling can't be undone. + public bool AutoVendorEnabled = false; + public bool AutoVendorEnableBuying = true; + public bool AutoVendorEnableSelling = true; + /// Only print what would be bought and sold. On by default in RynthAi (UB: off). + public bool AutoVendorTestMode = true; + /// Send "AutoVendor finished: ..." (and fatal/failed lines) as a /tell to yourself, for metas. + public bool AutoVendorThink = false; + public bool AutoVendorShowMerchantInfo = true; + public bool AutoVendorOnlyFromMainPack = false; + /// Attempts to open a vendor on /ub vendor open[p]. + public int AutoVendorTries = 4; + /// Milliseconds between /ub vendor open attempts. + public int AutoVendorTriesTime = 5000; + public List MonsterRules { get; set; } = new(); public List ItemRules { get; set; } = new(); public List ConsumableRules { get; set; } = new(); @@ -372,7 +411,7 @@ public sealed class LegacyUiSettings public readonly string[] AdvancedTabs = { "Display", "UI", "Misc", "Recharge", "Melee Combat", "Spell Combat", - "Ranges", "Navigation", "Buffing", "Crafting", "Looting" + "Ranges", "Navigation", "Buffing", "Crafting", "Looting", "Vendoring" }; [JsonIgnore] @@ -571,9 +610,13 @@ public sealed class SettingsBridgePayload public float CrossbowArcVelocity { get; set; } public float AtlatlArcVelocity { get; set; } public float MagicArcVelocity { get; set; } + public float MissileArcClearance { get; set; } = 0.5f; // absent in older payloads + public bool LosDebugLog { get; set; } public int BlacklistAttempts { get; set; } public int BlacklistTimeoutSec { get; set; } - public int BlacklistCastSettleMs { get; set; } + // -1 = absent from the payload: the overlay's Settings panel didn't send it, and + // applying the missing 0 made every panel click zero the setting (2026-09-27). + public int BlacklistCastSettleMs { get; set; } = -1; public int TargetNoProgressTimeoutSec { get; set; } public int GiveQueueIntervalMs { get; set; } @@ -614,7 +657,7 @@ public sealed class SettingsBridgePayload // Ranges public int MonsterRange { get; set; } - public int MonsterDisengageRange { get; set; } + public int MonsterDisengageRange { get; set; } = -1; // -1 = absent, see BlacklistCastSettleMs public int RingRange { get; set; } public int ApproachRange { get; set; } public double CorpseApproachRangeMax { get; set; } @@ -637,6 +680,7 @@ public sealed class SettingsBridgePayload public float NavDeadZone { get; set; } public float NavSweepMult { get; set; } public float NavLookaheadYards { get; set; } + public float NavShortcutYards { get; set; } public float NavTurnRateDegPerSec { get; set; } public float NavTier1TurnSpeed { get; set; } public float PostPortalDelaySec { get; set; } @@ -651,6 +695,7 @@ public sealed class SettingsBridgePayload public bool EnableBuffing { get; set; } public bool RebuffWhenIdle { get; set; } public int RebuffSecondsRemaining { get; set; } + public int RebuffTopOffSecondsRemaining { get; set; } = 1200; // absent in older files public int BuffMinSkillLevelTier1 { get; set; } public int BuffMinSkillLevelTier2 { get; set; } public int BuffMinSkillLevelTier3 { get; set; } @@ -691,6 +736,17 @@ public sealed class SettingsBridgePayload public int SalvageSalvageDelayMs { get; set; } public int SalvageResultDelayFirstMs { get; set; } public int SalvageResultDelayFastMs { get; set; } + // AutoVendor. Nullable so a settings panel that doesn't know these fields yet + // leaves the character's values alone instead of resetting them. + public bool? AutoVendorEnabled { get; set; } + public bool? AutoVendorEnableBuying { get; set; } + public bool? AutoVendorEnableSelling { get; set; } + public bool? AutoVendorTestMode { get; set; } + public bool? AutoVendorThink { get; set; } + public bool? AutoVendorShowMerchantInfo { get; set; } + public bool? AutoVendorOnlyFromMainPack { get; set; } + public int? AutoVendorTries { get; set; } + public int? AutoVendorTriesTime { get; set; } } public enum MetaConditionType diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs index 952268f..e51fc03 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs @@ -158,6 +158,14 @@ public static class VTankLootEvaluator } } + /// + /// One condition on its own, same semantics as inside . + /// AutoVendor judges conditions one at a time so it can tell "no" from "can't tell". + /// Throws on a malformed data line or an unsupported node type (the caller decides what that means). + /// + public static bool MatchCondition(VTankLootCondition cond, WorldObject item, VTankLootContext? ctx) + => Match(cond, item, unchecked((uint)item.Id), ctx); + private static bool Match(VTankLootCondition cond, WorldObject item, uint itemId, VTankLootContext? ctx) { var d = cond.DataLines; diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs index 66096c0..1274795 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs @@ -209,6 +209,16 @@ public sealed partial class RynthAiPlugin ["manastonelootcount"] = "ManaStoneKeepCount", ["rebuftimeremainingseconds"] = "RebuffSecondsRemaining", ["navclosestoprange"] = "NavCloseStopRange", + // UtilityBelt AutoVendor options (/ub opt set AutoVendor.TestMode true) + ["autovendor.enabled"] = "AutoVendorEnabled", + ["autovendor.enablebuying"] = "AutoVendorEnableBuying", + ["autovendor.enableselling"] = "AutoVendorEnableSelling", + ["autovendor.testmode"] = "AutoVendorTestMode", + ["autovendor.think"] = "AutoVendorThink", + ["autovendor.showmerchantinfo"] = "AutoVendorShowMerchantInfo", + ["autovendor.onlyfrommainpack"] = "AutoVendorOnlyFromMainPack", + ["autovendor.tries"] = "AutoVendorTries", + ["autovendor.triestime"] = "AutoVendorTriesTime", }; private string? GetOptionValue(string optName) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index ff9fc6a..12fd795 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -3204,6 +3204,13 @@ internal sealed class ExpressionEngine ["EnableLooting"] = (() => B(s.EnableLooting), v => s.EnableLooting = ToDouble(v) != 0), ["EnableMeta"] = (() => B(s.EnableMeta), v => s.EnableMeta = ToDouble(v) != 0), ["EnableRaycasting"] = (() => B(s.EnableRaycasting), v => s.EnableRaycasting = ToDouble(v) != 0), + ["UseArcs"] = (() => B(s.UseArcs), v => s.UseArcs = ToDouble(v) != 0), + ["LosDebugLog"] = (() => B(s.LosDebugLog), v => s.LosDebugLog = ToDouble(v) != 0), + ["BowArcVelocity"] = (() => F(s.BowArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.BowArcVelocity = Math.Clamp(f, 10f, 60f); }), + ["CrossbowArcVelocity"] = (() => F(s.CrossbowArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.CrossbowArcVelocity = Math.Clamp(f, 10f, 80f); }), + ["AtlatlArcVelocity"] = (() => F(s.AtlatlArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.AtlatlArcVelocity = Math.Clamp(f, 10f, 60f); }), + ["MagicArcVelocity"] = (() => F(s.MagicArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.MagicArcVelocity = Math.Clamp(f, 10f, 60f); }), + ["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), ["EnableCombineSalvage"]= (() => B(s.EnableCombineSalvage),v => s.EnableCombineSalvage= ToDouble(v) != 0), @@ -3236,7 +3243,19 @@ internal sealed class ExpressionEngine ["CorpseApproachRangeMin"] = (() => D(s.CorpseApproachRangeMin), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.CorpseApproachRangeMin = d; }), ["ManaStoneKeepCount"] = (() => I(s.ManaStoneKeepCount), v => { if (int.TryParse(v, out int i)) s.ManaStoneKeepCount = i; }), ["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }), + ["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }), + // AutoVendor (UB names map here through /ub opt: AutoVendor.Enabled -> AutoVendorEnabled, ...) + ["AutoVendorEnabled"] = (() => B(s.AutoVendorEnabled), v => s.AutoVendorEnabled = ToDouble(v) != 0), + ["AutoVendorEnableBuying"] = (() => B(s.AutoVendorEnableBuying), v => s.AutoVendorEnableBuying = ToDouble(v) != 0), + ["AutoVendorEnableSelling"] = (() => B(s.AutoVendorEnableSelling), v => s.AutoVendorEnableSelling = ToDouble(v) != 0), + ["AutoVendorTestMode"] = (() => B(s.AutoVendorTestMode), v => s.AutoVendorTestMode = ToDouble(v) != 0), + ["AutoVendorThink"] = (() => B(s.AutoVendorThink), v => s.AutoVendorThink = ToDouble(v) != 0), + ["AutoVendorShowMerchantInfo"] = (() => B(s.AutoVendorShowMerchantInfo), v => s.AutoVendorShowMerchantInfo = ToDouble(v) != 0), + ["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; }), + ["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; }), ["NavLineThickness"] = (() => F(s.NavLineThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavLineThickness = f; }), diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs index 8c62888..227a91e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs @@ -121,6 +121,11 @@ internal sealed class NavigationEngine // waypoint). Tunable in Advanced ▸ Navigation ▸ Steering. private double LookaheadYards => Math.Max(0.0, _settings.NavLookaheadYards); + // Straight-line shortcut on arrival: skip waypoints only while the straight run + // to a later one stays within this many yards of every waypoint skipped. + // 0 = off (visit every waypoint). Tunable in Advanced ▸ Navigation ▸ Steering. + private double ShortcutYards => Math.Max(0.0, _settings.NavShortcutYards); + // Mode 0 heading servo: cap the heading change we command per tick so the // turn is smooth and never overshoots (deadbeat). Floored at 10°/s so a // stray 0 from an old config can't freeze turning. @@ -423,7 +428,16 @@ internal sealed class NavigationEngine { _inPause = false; _inRecovery = false; - _linearDir = 1; + // _linearDir is NOT reset here. Stop() runs on every pause (combat, loot, + // buff, door), and resetting it turned a Linear route around after each + // fight on the way back: the bot re-walked the far leg to the end instead of + // finishing the return. A new route resets it (route swap / ResetRouteState). + // + // Combat, looting, buffing and doors stop nav and move the character. The + // closest-approach reading from before the pause says nothing about where we + // are now; kept, the first tick back reads the displacement as a sweep-pass + // and advances past a waypoint that was never reached. + _prevDist = double.MaxValue; _stopRequestedAt = long.MaxValue; ResetPortalState(); _host.SetAutoRun(false); @@ -436,6 +450,7 @@ internal sealed class NavigationEngine public void ResetRouteState() { Stop(); + _linearDir = 1; _stuckCount = 0; _recoveryKind = RecoveryKind.Jump; _prevDist = double.MaxValue; @@ -871,36 +886,59 @@ internal sealed class NavigationEngine if (skipped > 0) _host.Log($"Nav: skipped {skipped} dense waypoint(s) within {arrival:F1}yd → now on [{_settings.ActiveNavIndex}]"); - // Collinear-waypoint skip: if current target lies nearly on the straight - // line from the player to the waypoint after it, skip it. Handles straight - // dungeon corridors and outdoor paths with too many recorded points. - const double CollinearThreshYards = 2.0; - const int ColSkipBudget = 64; - int colSkipped = 0; - while (colSkipped < ColSkipBudget && IndexValid(_settings.ActiveNavIndex, route)) + // Straight-line shortcut: bypass waypoints that the straight run from here + // to a later waypoint already passes close to (straight corridors, recorded + // routes with many points on a line). EVERY bypassed waypoint must lie + // within ShortcutYards of the segment player→new target. + // + // This used to test each waypoint only against the line to its immediate + // successor. A point is never farther than one spacing from the line to the + // next point, so on a player-made route with 1-3yd spacing the test passed + // step after step around curves and corners: one arrival jumped up to 64 + // waypoints and aimed a straight line 15-50yd off the route, into walls, + // where the stuck ladder then skipped more (2026-09-27). Replaying every + // arrival of 518 real VTank routes: 5% cut a corner by >3yd, worst 49.6yd. + // The cumulative test caps the deviation at ShortcutYards by construction. + double tolerance = ShortcutYards; + if (tolerance > 0.0) { - var curr = route.Points[_settings.ActiveNavIndex]; - if (curr.Type != NavPointType.Point) break; + const int ShortcutBudget = 64; + Span bypassed = stackalloc int[ShortcutBudget]; + int count = 0; + double worst = 0.0; + while (count < ShortcutBudget && IndexValid(_settings.ActiveNavIndex, route)) + { + int ci = _settings.ActiveNavIndex; + var curr = route.Points[ci]; + if (curr.Type != NavPointType.Point) break; - int ni = PeekNext(_settings.ActiveNavIndex, route); - if (ni < 0 || ni == _settings.ActiveNavIndex) break; - var next = route.Points[ni]; - if (next.Type != NavPointType.Point) break; + int ni = PeekNext(ci, route); + if (ni < 0 || ni == ci) break; + var next = route.Points[ni]; + if (next.Type != NavPointType.Point) break; - // Only skip if next is farther from player than curr (don't skip past a turn) - double dCurrNS = curr.NS - curNs, dCurrEW = curr.EW - curEw; - double dNextNS = next.NS - curNs, dNextEW = next.EW - curEw; - if (dNextNS * dNextNS + dNextEW * dNextEW <= dCurrNS * dCurrNS + dCurrEW * dCurrEW) break; + // Only shortcut forward: the new target must be farther from the + // player than the one it replaces (don't skip past a turn back). + double dCurrNS = curr.NS - curNs, dCurrEW = curr.EW - curEw; + double dNextNS = next.NS - curNs, dNextEW = next.EW - curEw; + if (dNextNS * dNextNS + dNextEW * dNextEW <= dCurrNS * dCurrNS + dCurrEW * dCurrEW) break; - if (CrossDistYards(curNs, curEw, curr.NS, curr.EW, next.NS, next.EW) >= CollinearThreshYards) break; + double off = SegmentDistYards(curr.NS, curr.EW, curNs, curEw, next.NS, next.EW); + for (int b = 0; b < count && off < tolerance; b++) + { + var bp = route.Points[bypassed[b]]; + off = Math.Max(off, SegmentDistYards(bp.NS, bp.EW, curNs, curEw, next.NS, next.EW)); + } + if (off >= tolerance) break; - int beforeCol = _settings.ActiveNavIndex; - AdvanceOneIndex(route); - if (_settings.ActiveNavIndex == beforeCol) break; - colSkipped++; + AdvanceOneIndex(route); + if (_settings.ActiveNavIndex == ci) break; + bypassed[count++] = ci; + if (off > worst) worst = off; + } + if (count > 0) + _host.Log($"Nav: shortcut past {count} waypoint(s), ≤{worst:F1}yd off route → now on [{_settings.ActiveNavIndex}]"); } - if (colSkipped > 0) - _host.Log($"Nav: skipped {colSkipped} collinear waypoint(s) → now on [{_settings.ActiveNavIndex}]"); } if (_settings.ActiveNavIndex != oldIdx && IndexValid(_settings.ActiveNavIndex, route)) @@ -1734,13 +1772,14 @@ internal sealed class NavigationEngine private static double Lerp(double a, double b, double t) => a + (b - a) * t; - // Perpendicular distance (yards) from point B to the infinite line through A and C. - private static double CrossDistYards(double aNS, double aEW, double bNS, double bEW, double cNS, double cEW) + // Distance (yards) from point P to the segment A→B. + private static double SegmentDistYards(double pNS, double pEW, double aNS, double aEW, double bNS, double bEW) { - double acNS = cNS - aNS, acEW = cEW - aEW; - double acLen = Math.Sqrt(acNS * acNS + acEW * acEW); - if (acLen < 1e-9) return 0.0; double abNS = bNS - aNS, abEW = bEW - aEW; - return Math.Abs(abNS * acEW - abEW * acNS) / acLen * 240.0; + double len2 = abNS * abNS + abEW * abEW; + double t = len2 < 1e-18 ? 0.0 + : Math.Clamp(((pNS - aNS) * abNS + (pEW - aEW) * abEW) / len2, 0.0, 1.0); + double dNS = pNS - (aNS + t * abNS), dEW = pEW - (aEW + t * abEW); + return Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/MissileBallistics.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/MissileBallistics.cs new file mode 100644 index 0000000..29f1e5e --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/MissileBallistics.cs @@ -0,0 +1,182 @@ +using System; + +namespace RynthCore.Plugin.RynthAi.Raycasting +{ + /// + /// The flight path of an AC missile (arrow, bolt, dart), as pure math: no host, no + /// geometry, no allocation. Kept dependency-free so Tools/RynthCore.MissileArcTests + /// compiles it directly. + /// + /// The server launches every missile at the weapon's fixed speed on the LOW solution of + /// the ballistic arc to the aim point, under gravity (ACE GetProjectileVelocity → + /// Trajectory.solve_ballistic_arc, first solution; PhysicsGlobals.Gravity = 9.8). So the + /// arc height is not a constant: it grows with distance and shrinks with launch speed. + /// At 5 m a bow shot is a straight line; at 40 m with 25 m/s it rises about 3.5 m above + /// the launch point, which is enough to hit a dungeon ceiling the straight line clears. + /// + /// Units are meters, Z up. "t" is the horizontal fraction of the shot, 0 at the launch + /// point and 1 at the aim point. + /// + public readonly struct MissileArc + { + /// Launch point. + public readonly float OX, OY, OZ; + /// Unit horizontal direction from launch point to aim point. + public readonly float DirX, DirY; + /// Horizontal distance from launch point to aim point. + public readonly float HorizDist; + /// Aim point Z minus launch point Z. + public readonly float Rise; + /// Tangent of the launch elevation (low solution). + public readonly float TanTheta; + /// Curvature: height(x) = x·TanTheta − K·x², K = g(1+tan²θ)/(2v²). + public readonly float K; + /// False when the aim point is out of reach at this launch speed. + public readonly bool Valid; + /// True for a (near) vertical shot, flown as a straight line. + public readonly bool Vertical; + + internal MissileArc(float ox, float oy, float oz, float dirX, float dirY, float horizDist, + float rise, float tanTheta, float k, bool valid, bool vertical) + { + OX = ox; OY = oy; OZ = oz; + DirX = dirX; DirY = dirY; + HorizDist = horizDist; Rise = rise; + TanTheta = tanTheta; K = k; + Valid = valid; Vertical = vertical; + } + + /// Height above the launch point at horizontal fraction t (no clearance). + public float HeightAt(float t) + { + if (!Valid) return 0f; + if (Vertical) return Rise * t; + float x = t * HorizDist; + return x * TanTheta - K * x * x; + } + + /// + /// The point at horizontal fraction t, raised by at + /// mid-flight (see ). The ends never + /// move: t=0 is the launch point and t=1 the aim point. + /// + public void PointAt(float t, float clearance, out float x, out float y, out float z) + { + float h = t * HorizDist; + x = OX + DirX * h; + y = OY + DirY * h; + z = OZ + HeightAt(t) + MissileBallistics.ClearanceBump(t, clearance); + } + + /// + /// How far the arc rises above the straight line from launch point to aim point, at + /// its highest. This is the part a straight line-of-sight check never sees. + /// + public float MaxRiseAboveChord + { + get + { + if (!Valid || Vertical || HorizDist <= 0f || K <= 0f) return 0f; + // height(x) − Rise·x/d = x·(tanθ − Rise/d) − K·x². Its maximum is at + // x* = a/(2K), value a²/(4K), where a = tanθ − Rise/d. + float a = TanTheta - Rise / HorizDist; + if (a <= 0f) return 0f; + float xStar = a / (2f * K); + if (xStar >= HorizDist) xStar = HorizDist; + return a * xStar - K * xStar * xStar; + } + } + + /// Highest point of the flight above the launch point (never below the ends). + public float ApexAboveLaunch + { + get + { + if (!Valid) return 0f; + if (Vertical) return Math.Max(0f, Rise); + if (K <= 0f) return Math.Max(0f, Rise); + float xApex = TanTheta / (2f * K); + float apex = xApex > 0f && xApex < HorizDist + ? TanTheta * xApex - K * xApex * xApex + : 0f; + return Math.Max(apex, Math.Max(0f, Rise)); + } + } + } + + public static class MissileBallistics + { + /// AC's gravity (PhysicsGlobals.Gravity = -9.8). + public const float AcGravity = 9.8f; + + /// Below this horizontal distance a shot is treated as vertical. + private const float VerticalEpsilon = 0.05f; + + /// + /// Solves the low ballistic arc from the launch point to the aim point at a fixed launch + /// speed. Out of reach (the speed can't carry that far or that high) gives Valid=false. + /// + public static MissileArc Solve(float ox, float oy, float oz, + float tx, float ty, float tz, + float speed, 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) || speed <= 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); + + // Low-angle solution of rise = d·tanθ − g·d²·(1+tan²θ)/(2v²): + // tanθ = (v² − √(v⁴ − g(g·d² + 2·rise·v²))) / (g·d) + double v2 = (double)speed * speed; + double disc = v2 * v2 - gravity * (gravity * (double)d * d + 2.0 * rise * v2); + if (disc < 0.0) + return new MissileArc(ox, oy, oz, dx / d, dy / d, d, rise, 0f, 0f, valid: false, vertical: false); + + double tan = (v2 - Math.Sqrt(disc)) / (gravity * (double)d); + double k = gravity * (1.0 + tan * tan) / (2.0 * v2); + return new MissileArc(ox, oy, oz, dx / d, dy / d, d, rise, (float)tan, (float)k, valid: true, vertical: false); + } + + /// + /// Extra height added to the tested path: at mid-flight, + /// tapering to zero at both ends (4t(1−t)), so the launch and aim points stay put. It + /// covers what the model can't know exactly: launch height, the real launch speed, the + /// projectile's own size. + /// + public static float ClearanceBump(float t, float clearance) + { + if (clearance <= 0f || t <= 0f || t >= 1f) return 0f; + return clearance * 4f * t * (1f - t); + } + + /// Number of straight segments used to test an arc: about one per 2.5 m, 6 to 24. + public static int SegmentCount(float horizDist) + { + if (float.IsNaN(horizDist) || horizDist <= 0f) return 6; + int n = (int)Math.Ceiling(horizDist / 2.5f); + return Math.Clamp(n, 6, 24); + } + + /// + /// Highest Z the tested path reaches (arc plus clearance), sampled like the geometry + /// test samples it. Lets a caller compare the path against a known ceiling height. + /// + public static float MaxPathZ(in MissileArc arc, float clearance) + { + if (!arc.Valid) return float.NaN; + int n = SegmentCount(arc.HorizDist) * 4; + float best = Math.Max(arc.OZ, arc.OZ + arc.Rise); + for (int i = 1; i < n; i++) + { + arc.PointAt((float)i / n, clearance, out _, out _, out float z); + if (z > best) best = z; + } + return best; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/RaycastEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/RaycastEngine.cs index 4b27c32..6d91154 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/RaycastEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/RaycastEngine.cs @@ -224,6 +224,89 @@ namespace RynthCore.Plugin.RynthAi.Raycasting return false; // Arc clears all obstacles } + /// What found, for the LOS debug log and /ra lostest. + public struct ArcLosResult + { + public bool Blocked; + public bool OutOfReach; // the launch speed can't carry the shot that far / that high + public float Sag; // how far the arc rises above the straight line, at most (m) + public float Apex; // highest point of the flight above the launch point (m) + public float HitAlong; // horizontal distance from the shooter to the hit (m) + public float HitZ; // height of the hit above the launch point (m) + } + + /// + /// Tests the path a missile really flies: the low ballistic arc at the weapon's launch + /// speed (see ), raised by + /// at mid-flight. Unlike (the old flat-ground + /// approximation, kept for magic arcs), 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 + /// straight-line test. + /// + public static bool IsBallisticArcBlocked(Vector3 origin, Vector3 target, float speed, float clearance, + List 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; + + var arc = MissileBallistics.Solve(origin.X, origin.Y, origin.Z, target.X, target.Y, target.Z, speed); + result.Sag = arc.MaxRiseAboveChord; + result.Apex = arc.ApexAboveLaunch; + if (!arc.Valid) + { + result.OutOfReach = true; + result.Blocked = true; + return true; + } + if (geometry == null || geometry.Count == 0) + return false; + + clearance = Math.Max(0f, clearance); + int n = MissileBallistics.SegmentCount(arc.HorizDist); + Vector3 prev = origin; + float travelled = 0f; + + for (int i = 1; i <= n; i++) + { + float t = (float)i / n; + Vector3 cur; + if (i == n) cur = target; + else + { + arc.PointAt(t, clearance, out float px, out float py, out float pz); + cur = new Vector3(px, py, pz); + } + + Vector3 seg = cur - prev; + float len = seg.Length(); + if (len > 1e-4f) + { + Vector3 dir = seg / len; + foreach (var volume in geometry) + { + if (volume.IsDoor) 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 + if (i == n && hd > len - 0.3f) continue; // at the target + Vector3 hit = prev + dir * hd; + float hx = hit.X - origin.X, hy = hit.Y - origin.Y; + result.Blocked = true; + result.HitAlong = (float)Math.Sqrt(hx * hx + hy * hy); + result.HitZ = hit.Z - origin.Z; + return true; + } + } + travelled += len; + prev = cur; + } + return false; + } + /// /// Tests if a line segment between two points intersects any geometry. /// Used internally for arc sampling. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/TargetingFSM.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/TargetingFSM.cs index c31b819..0f80086 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/TargetingFSM.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/TargetingFSM.cs @@ -45,6 +45,41 @@ namespace RynthCore.Plugin.RynthAi.Raycasting // If true, use arc checks for missile weapons. If false, treat all as linear. public bool UseArcs { get; set; } = true; + // Extra headroom (m) the missile arc must have at mid-flight, on top of the modelled + // flight path. Covers launch height, the real launch speed and the projectile's size. + // CombatManager overrides it from LegacyUiSettings.MissileArcClearance each tick. + public float MissileArcClearance { get; set; } = 0.5f; + + // An arc that rises less than this above the straight line is flown as that line: + // the straight-line test (multi-ray in dungeons, ±0.3 m) already covers it, and the + // clearance bump is not applied to short, flat shots. + private const float ArcSagIgnoreMeters = 0.15f; + + /// How a LOS verdict was reached, for the LOS debug log. + public struct LosDetail + { + public AttackType Type; + public bool Dungeon; + public bool Checked; // false = no verdict computed (no geometry near, too far, no position) + public float Velocity; // launch speed used for a missile arc (0 = straight line) + public bool LineBlocked; + public bool ArcChecked; + public RaycastEngine.ArcLosResult Arc; + } + + private static bool IsMissileArc(AttackType t) => + t == AttackType.BowArc || t == AttackType.CrossbowArc || t == AttackType.AtlatlArc; + + /// Launch speed configured for a missile attack type. + public float VelocityFor(AttackType t) => t switch + { + AttackType.BowArc => BowArcVelocity, + AttackType.CrossbowArc => CrossbowArcVelocity, + AttackType.AtlatlArc => AtlatlArcVelocity, + AttackType.MagicArc => MagicArcVelocity, + _ => 0f, + }; + // Max scan distance in meters. Only check LOS for targets within this range. // Set from CombatManager based on MonsterRange + buffer. public float MaxScanDistanceMeters { get; set; } = 120.0f; @@ -62,7 +97,23 @@ namespace RynthCore.Plugin.RynthAi.Raycasting /// Returns false if the target is clear to attack. /// public bool IsTargetBlocked(RynthCoreHost host, uint targetId, AttackType attackType) + => IsTargetBlocked(host, targetId, attackType, out _); + + /// + /// As , and reports how the + /// verdict was reached. + /// + /// Missile weapons (bow, crossbow, atlatl) with UseArcs on: the target must pass the + /// straight line (walls, corner seams) AND the arc the missile really flies, low + /// ballistic solution at the weapon's launch speed plus MissileArcClearance headroom. + /// Indoors this is what catches ceilings: the old code forced a straight-line test in + /// dungeons, so a target 20-50 m down a corridor passed LOS while the arrow, rising + /// 2-6 m on its way there, hit the ceiling (2026-09-27, Longbow, Olthoi swarm). + /// + public bool IsTargetBlocked(RynthCoreHost host, uint targetId, AttackType attackType, out LosDetail detail) { + detail = default; + detail.Type = attackType; if (!_geoLoader.IsInitialized) return false; @@ -90,55 +141,72 @@ namespace RynthCore.Plugin.RynthAi.Raycasting uint landcell = GetPlayerLandcell(host); uint cellPart = landcell & 0xFFFF; bool isDungeon = cellPart >= 0x0100; + detail.Dungeon = isDungeon; - // Force linear checks indoors — arc trajectories hit ceilings - if (isDungeon) + bool missileArc = UseArcs && IsMissileArc(attackType); + + // Magic arcs keep the old rule: straight line indoors. + if (isDungeon && !missileArc) attackType = AttackType.Linear; + detail.Type = attackType; var geometry = _geoLoader.GetLandblockGeometry(landcell); if (geometry == null || geometry.Count == 0) return false; + // The missile's real path: solved up front so the pre-filter box covers its apex. + MissileArc arc = default; + float arcHeadroom = 0f; + if (missileArc) + { + detail.Velocity = VelocityFor(attackType); + arc = 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; + } + // Pre-filter: skip full ray test if no geometry near the path float margin = Math.Min(flatDist * 0.3f, 15.0f); margin = Math.Max(margin, 3.0f); + margin = Math.Max(margin, arcHeadroom); if (!RaycastEngine.HasNearbyGeometry(origin, targetPos, geometry, margin)) return false; + detail.Checked = true; + + if (missileArc) + { + // Walls first (cheap, and most blocked targets stop here). In dungeons use + // multi-ray: 5 rays covering the player silhouette catch thin corner + // geometry that a single center ray slips through. + detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon); + if (detail.LineBlocked) + return true; + + // A short, flat shot is the straight line just tested. + if (arc.Valid && arc.MaxRiseAboveChord < ArcSagIgnoreMeters) + { + detail.Arc.Sag = arc.MaxRiseAboveChord; + detail.Arc.Apex = arc.ApexAboveLaunch; + return false; + } + + detail.ArcChecked = true; + return RaycastEngine.IsBallisticArcBlocked(origin, targetPos, detail.Velocity, + MissileArcClearance, geometry, out detail.Arc); + } + // In dungeons use multi-ray checks — 5 rays covering the player silhouette // catch thin corner geometry that a single center ray slips through. switch (attackType) { case AttackType.Linear: - return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon); - - case AttackType.BowArc: - if (UseArcs) - { - if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, BowArcVelocity, geometry)) - return false; - return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon); - } - return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon); - + case AttackType.BowArc: // arcs off (UseArcs=false) → straight line case AttackType.CrossbowArc: - if (UseArcs) - { - if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, CrossbowArcVelocity, geometry)) - return false; - return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon); - } - return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon); - case AttackType.AtlatlArc: - if (UseArcs) - { - if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, AtlatlArcVelocity, geometry)) - return false; - return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon); - } - return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon); + detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon); + return detail.LineBlocked; case AttackType.MagicArc: if (UseArcs && !isDungeon) @@ -289,8 +357,14 @@ namespace RynthCore.Plugin.RynthAi.Raycasting if (currentCombatMode == 2) return AttackType.Linear; - // MISSILE MODE: Check the weapon name for bow vs crossbow vs thrown - if (currentCombatMode == 4 && !string.IsNullOrEmpty(wieldedWeaponName)) + // 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 + // combat scan used to pass "" here, which fell through to Linear, so no missile + // LOS check ever used an arc or the per-weapon velocities. + if (currentCombatMode == 4 && string.IsNullOrEmpty(wieldedWeaponName)) + return UseArcs ? AttackType.BowArc : AttackType.Linear; + + if (currentCombatMode == 4) { string name = wieldedWeaponName.ToLower(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index e412749..53f4777 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -80,6 +80,8 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra bufftest — one-shot: snapshot enchant registries pre/post next item-spell cast (logs to RynthCore.log)"); ChatLine("[RynthAi] /ra settings savechar — save current settings to named profile (create if new)"); ChatLine("[RynthAi] /ra settings loadchar — load named settings profile (create from current if new)"); + ChatLine("[RynthAi] /ub autovendor [profile.utl|cancel] — run AutoVendor at the open vendor (TestMode on by default)"); + ChatLine("[RynthAi] /ub vendor open[p] | opencancel | addbuy[p]/addsell[p] [n] | buyall | sellall | clearbuy | clearsell"); } private void HandlePowerCommand(string[] parts) @@ -324,8 +326,20 @@ public sealed partial class RynthAiPlugin if (geometry != null && geometry.Count > 0) { - staticBlocked = RaycastEngine.IsArcPathBlocked(origin, targetPos, arcVelocity, geometry); - ChatLine($"[RynthAi LOS] IsArcPathBlocked: {staticBlocked}{(isDungeon && staticBlocked ? " (likely ceiling — combat LoS forces Linear in dungeons)" : "")}"); + // Same test combat runs for missile targets: straight line (walls), then the + // 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); + 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"); + if (arc.OutOfReach) + ChatLine($"[RynthAi LOS] Arc: OUT OF REACH at v={arcVelocity:F1} (raise the velocity or get closer)"); + else if (arcBlocked) + ChatLine($"[RynthAi LOS] Arc: BLOCKED {arc.HitAlong:F1}m out, {arc.HitZ:+0.0;-0.0;0.0}m vs launch{(isDungeon && arc.HitZ > 0.5f ? " (ceiling)" : "")}"); + else + ChatLine("[RynthAi LOS] Arc: clear"); } } else @@ -392,63 +406,30 @@ public sealed partial class RynthAiPlugin ChatLine($"[RynthAi LOS] Combined LoS ({modeLabel}): {verdict}"); } - // Samples a parabolic arc from origin→target at the given launch velocity, - // returns true if any sample point dips below terrain Z. Mirrors the math - // in RaycastEngine.IsArcPathBlocked so the terrain check tracks the same - // trajectory the static-geometry check uses. + // Samples the missile's arc from origin→target at the given launch speed and returns + // true if any sample point dips below terrain Z. Same flight path as combat's missile + // LOS (MissileBallistics: low ballistic solution, AC gravity), without the clearance. private static bool TerrainBlockedAlongArc(Raycasting.Vector3 origin, Raycasting.Vector3 target, float velocity, Raycasting.GeometryLoader geo, out float hitDist, out Raycasting.Vector3 hitPoint) { hitDist = 0f; hitPoint = origin; - const float GRAVITY = 9.81f; - const int SAMPLES = 20; + const int SAMPLES = 20; - var delta = target - origin; - float horiz = delta.Length2D(); - if (horiz < 0.1f) return false; - - float maxRange = (velocity * velocity) / GRAVITY; - if (horiz > maxRange) return false; // out-of-range is the shooter's problem, not terrain's - - float sinArg = (GRAVITY * horiz) / (velocity * velocity); - if (sinArg > 1.0f) sinArg = 1.0f; - float launchAngle = (float)(0.5 * Math.Asin(sinArg)); - if (launchAngle < 0.1f) launchAngle = (float)(Math.PI / 4); - - float cosA = (float)Math.Cos(launchAngle); - float sinA = (float)Math.Sin(launchAngle); - float vH = velocity * cosA; - float vV = velocity * sinA; - if (vH < 0.01f) return false; - - float totalTime = horiz / vH; - float hdx = delta.X / horiz; - float hdy = delta.Y / horiz; + var arc = Raycasting.MissileBallistics.Solve(origin.X, origin.Y, origin.Z, target.X, target.Y, target.Z, velocity); + if (!arc.Valid || arc.Vertical) return false; // out of reach is the shooter's problem, not terrain's for (int i = 1; i <= SAMPLES; i++) { float t = (float)i / SAMPLES; - float time = t * totalTime; - float hDistAlong = vH * time; - // Deep-audit finding #31 (2026-06-18) — mirrors the fix in - // RaycastEngine.IsArcPathBlocked: the flat-range parabolic sag - // (vV*time - 0.5g*time²) is exactly 0 at t=0 AND t=1 by - // construction (totalTime is the equal-height time-of-flight), - // so adding it to a straight lerp(origin.Z, target.Z) anchors - // both endpoints exactly instead of double-applying the - // elevation difference via a separate (1-t) blend. - float z = origin.Z + delta.Z * t + (vV * time - 0.5f * GRAVITY * time * time); - - float wx = origin.X + hdx * hDistAlong; - float wy = origin.Y + hdy * hDistAlong; + arc.PointAt(t, 0f, out float wx, out float wy, out float z); float groundZ = geo.GetTerrainZWorld(wx, wy); if (float.IsNaN(groundZ)) continue; if (z < groundZ) { - hitDist = hDistAlong; + hitDist = t * arc.HorizDist; hitPoint = new Raycasting.Vector3(wx, wy, z); return true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 4838f8a..938408c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -11,6 +11,7 @@ using RynthCore.Plugin.RynthAi.LegacyUi; using RynthCore.Plugin.RynthAi.Loot; using RynthCore.Plugin.RynthAi.Meta; using RynthCore.Plugin.RynthAi.Raycasting; +using RynthCore.Plugin.RynthAi.Vendor; using RynthCore.PluginCore; using RynthCore.Loot; using RynthCore.Loot.VTank; @@ -64,6 +65,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthAi"); internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.5.0-legacy-ui"); + /// + /// Oldest engine RynthAi runs on. Players get plugin updates automatically but engine + /// updates only when they click, so this stays at 66 while newer calls are feature- + /// detected (Host.HasVendorTrade for API v67 vendor trading: AutoVendor reports "needs a + /// RynthCore update" without it). The SDK default is CurrentApiVersion, which would make + /// every SDK bump refuse older engines. Raise it only for a call RynthAi can't run without. + /// + public override uint MinimumApiVersion => 66; + private LegacyDashboardRenderer? _dashboard; /// Snapshot bridge accessor for engine-side panels. @@ -245,6 +255,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _missileCraftingManager = null; _jumper?.Cancel(); _jumper = null; + _autoVendor?.Reset(); + _autoVendor = null; _playerId = 0; _loginComplete = false; _windowVisible = false; @@ -425,6 +437,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _jumper = new Jumper(Host, _dashboard.Settings, s => Host.WriteToChat(s, 1)); + if (_objectCache != null) + { + var dashForAv = _dashboard; + _autoVendor = new AutoVendorManager(Host, _dashboard.Settings, _objectCache, _playerId, + () => dashForAv?.CharFolder ?? string.Empty); + var avForUi = _autoVendor; + _dashboard.SetAutoVendorStatusProvider(() => avForUi.Status); + _dashboard.SetVendorProfilePathProvider(() => avForUi.OpenVendorProfilePath); + } + Log("RynthAi: login complete, legacy ImGui dashboard ready."); } @@ -436,6 +458,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // away from Navigating, and the arbiter's decision is the only thing that // decides whether nav runs at all. One edge-detect replaces the cascade. private BotActivity _activity = BotActivity.Idle; // last arbiter decision + private bool _macroWasRunning; // edge: release held turns when the macro stops private BotActivity _navStoppedFor = BotActivity.Idle; // activity we last issued a nav Stop() for private bool _navStopIssued; // Buffing-coma watchdog (see the Priority-1 block): how long BotAction has @@ -554,7 +577,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase ["TargetFPSFocused"] = (10, 240), ["TargetFPSBackground"] = (5, 60), ["BlacklistAttempts"] = (1, 20), ["BlacklistTimeoutSec"] = (5, 120), ["BlacklistCastSettleMs"] = (500, 5000), ["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (50, 2000), - ["BowArcVelocity"] = (10, 60), ["CrossbowArcVelocity"] = (10, 80), ["AtlatlArcVelocity"] = (10, 60), ["MagicArcVelocity"] = (10, 60), + ["BowArcVelocity"] = (10, 60), ["CrossbowArcVelocity"] = (10, 80), ["AtlatlArcVelocity"] = (10, 60), ["MagicArcVelocity"] = (10, 60), ["MissileArcClearance"] = (0, 3), ["HealAt"] = (0, 100), ["RestamAt"] = (0, 100), ["GetManaAt"] = (0, 100), ["TopOffHP"] = (0, 100), ["TopOffStam"] = (0, 100), ["TopOffMana"] = (0, 100), ["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100), @@ -569,10 +592,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase ["FollowNavMin"] = (0.5, 20), ["NavRingThickness"] = (1, 16), ["NavLineThickness"] = (1, 16), ["NavHeightOffset"] = (-5, 5), ["NavSlopeSink"] = (0, 8), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 2), ["NavStopTurnAngle"] = (1, 90), ["NavResumeTurnAngle"] = (1, 45), ["NavDeadZone"] = (0.5, 20), ["NavSweepMult"] = (0.5, 10), - ["NavLookaheadYards"] = (0, 30), ["NavTurnRateDegPerSec"] = (30, 720), ["NavTier1TurnSpeed"] = (0.5, 15), ["PostPortalDelaySec"] = (0, 30), + ["NavLookaheadYards"] = (0, 30), ["NavShortcutYards"] = (0, 10), ["NavTurnRateDegPerSec"] = (30, 720), ["NavTier1TurnSpeed"] = (0.5, 15), ["PostPortalDelaySec"] = (0, 30), ["T2Speed"] = (0.1, 5), ["T2WalkWithinYd"] = (1, 50), ["T2DistanceTo"] = (0.1, 10), ["T2ReissueMs"] = (100, 10000), ["T2MaxRangeYd"] = (50, 2000), ["T2MaxLandblocks"] = (1, 20), - ["RebuffSecondsRemaining"] = (30, 1800), + ["RebuffSecondsRemaining"] = (30, 1800), ["RebuffTopOffSecondsRemaining"] = (30, 3600), + ["AutoVendorTries"] = (1, 20), ["AutoVendorTriesTime"] = (500, 30000), ["BuffMinSkillLevelTier1"] = (1, 500), ["BuffMinSkillLevelTier2"] = (1, 500), ["BuffMinSkillLevelTier3"] = (1, 500), ["BuffMinSkillLevelTier4"] = (1, 500), ["BuffMinSkillLevelTier5"] = (1, 500), ["BuffMinSkillLevelTier6"] = (1, 500), ["BuffMinSkillLevelTier7"] = (1, 500), ["BuffMinSkillLevelTier8"] = (1, 500), ["LootJumpHeight"] = (1, 100), ["LootOwnership"] = (0, 2), @@ -1116,6 +1140,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase return; if (diag) Host.Log($"[RynthAi] OnTick: settings ok, macro={settings.IsMacroRunning} action={settings.BotAction}"); + // Macro switched off: combat stops ticking, so a turn it was holding would + // stay held and the character spun on its own (2026-09-27). Let go once. + if (_macroWasRunning && !settings.IsMacroRunning) + _combatManager?.ReleaseHeldTurn(); + _macroWasRunning = settings.IsMacroRunning; + if (_patrolOnLoginPending && _raycast?.GeometryLoader?.CellDat?.IsLoaded == true) { _patrolOnLoginPending = false; @@ -1232,6 +1262,25 @@ public sealed partial class RynthAiPlugin : RynthPluginBase } catch { /* arbiter must never throw out of the live tick */ } + // ── AutoVendor (UtilityBelt-style) ─────────────────────────────── + // Runs whether or not the macro is on: it starts when a vendor opens. + // While it holds the bot (a vendoring session, or /ub vendor open + // trying to reach a vendor) nothing else moves the character or the + // inventory — UB takes VTank's Navigation + ItemUse locks the same way. + // Bounded by AutoVendor's own 60 s bail timer. + var autoVendor = _autoVendor; + if (autoVendor != null) + { + autoVendor.Tick(_busyCount); + if (autoVendor.HoldsBot) + { + if (settings.IsMacroRunning) + StopNavFor(BotActivity.Idle); + _metaManager?.Think(); + return; + } + } + // ── Priority 1: Buffing ─────────────────────────────────────────── // Blocks combat, looting, and navigation entirely. The coma // watchdog that used to live here now runs ahead of the decision @@ -1543,6 +1592,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) { + float prevRatio = _objectCache?.GetHealthRatio(unchecked((int)targetId)) ?? -1f; _objectCache?.OnUpdateHealth(targetId, healthRatio); _dashboard?.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth); if (_loginComplete && targetId == _playerId && maxHealth > 0) @@ -1551,9 +1601,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _vitals.MaxHealth = maxHealth; } - // When a creature's health changes, something hit it — reset its miss counter - // so the blacklist doesn't trigger on valid in-combat targets. - if (targetId != _playerId) + // When a creature's health DROPS, something hit it — reset its miss counter so the + // blacklist doesn't trigger on valid in-combat targets. Only a drop counts: the + // client also gets health for a mob the player merely selects (QueryHealth reply), + // for the fight target combat queries at lock, and on regen, all at unchanged or + // higher health. Counting those as hits reset the no-damage miss streak, + // un-blacklisted the mob and gave it the damage-commitment bonus, so selecting a + // mob could steer combat and a target the arrows weren't hurting could be held far + // past BlacklistAttempts misses (2026-09-27, Olthoi swarm). + if (targetId != _playerId && IsHealthDrop(prevRatio, healthRatio)) _combatManager?.ReportDamageOnTarget((int)targetId); // Capture observed creature data into the persistent store. maxHealth>0 means @@ -1563,6 +1619,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase CaptureCreatureSample(targetId, maxHealth); } + /// + /// True when a health update means the creature lost health: lower than the last ratio + /// we knew, or, for the first report of a creature, below full. + /// + private static bool IsHealthDrop(float prevRatio, float newRatio) + { + if (float.IsNaN(newRatio)) return false; + return prevRatio < 0f ? newRatio < 0.999f : newRatio < prevRatio - 0.0005f; + } + /// /// Something you can fight — what the Damage tab and creatures.json should learn from. /// Appraising an NPC, a vendor, another player or your own pet also returns health, and diff --git a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs index 7899b1f..7aa3075 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs @@ -25,6 +25,10 @@ public sealed partial class RynthAiPlugin return true; } + // /ub autovendor ... and /ub vendor ... (UtilityBelt AutoVendor) — Vendor/AutoVendorCommands.cs + if (TryHandleAutoVendorCommand(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 / diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorCommands.cs new file mode 100644 index 0000000..0bbc4c7 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorCommands.cs @@ -0,0 +1,94 @@ +using System; +using RynthCore.Plugin.RynthAi.Vendor; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// UtilityBelt's /ub autovendor and /ub vendor commands. Parsed here (chat thread), +/// run by AutoVendorManager on the plugin tick thread. +/// +public sealed partial class RynthAiPlugin +{ + private AutoVendorManager? _autoVendor; + + /// + /// /ub autovendor [cancel|stop|quit|profile] + /// /ub vendor {open[p] [name|id|hex|selected] | opencancel | buy[all] | sell[all] | + /// clearbuy | clearsell | addbuy[p] [count] item | addsell[p] [count] item} + /// Returns false when the verb isn't an AutoVendor verb. + /// + private bool TryHandleAutoVendorCommand(string cmd, string fullCommand) + { + if (cmd != "autovendor" && cmd != "vendor") + return false; + + var av = _autoVendor; + if (av == null) + { + ChatLine("[RynthAi] AutoVendor isn't ready yet (log in first)."); + return true; + } + + string rest = AfterWords(fullCommand, 2); // everything after "/ub " + + if (cmd == "autovendor") + { + av.Enqueue(() => av.CommandAutoVendor(rest)); + return true; + } + + string action = rest; + string args = string.Empty; + int asp = rest.IndexOf(' '); + if (asp >= 0) + { + action = rest.Substring(0, asp); + args = rest.Substring(asp + 1).Trim(); + } + action = action.ToLowerInvariant(); + + switch (action) + { + case "buy": + case "buyall": av.Enqueue(av.CommandBuyAll); break; + case "sell": + case "sellall": av.Enqueue(av.CommandSellAll); break; + case "clearbuy": av.Enqueue(av.CommandClearBuy); break; + case "clearsell": av.Enqueue(av.CommandClearSell); break; + // UB: "open" with no name picks the nearest vendor, like openp. + case "open": av.Enqueue(() => av.CommandOpen(args, partial: args.Length == 0)); break; + case "openp": av.Enqueue(() => av.CommandOpen(args, partial: true)); break; + case "opencancel": av.Enqueue(av.CommandOpenCancel); break; + case "addbuy": + case "addbuyp": + if (args.Length == 0) { VendorUsage(); break; } + av.Enqueue(() => av.CommandAddBuy(args, partial: action == "addbuyp")); + break; + case "addsell": + case "addsellp": + if (args.Length == 0) { VendorUsage(); break; } + av.Enqueue(() => av.CommandAddSell(args, partial: action == "addsellp")); + break; + default: + VendorUsage(); + break; + } + return true; + } + + /// The text after the first space-separated words, trimmed. + private static string AfterWords(string text, int words) + { + int i = 0; + string s = text ?? string.Empty; + for (int w = 0; w < words; w++) + { + while (i < s.Length && char.IsWhiteSpace(s[i])) i++; + while (i < s.Length && !char.IsWhiteSpace(s[i])) i++; + } + return i < s.Length ? s.Substring(i).Trim() : string.Empty; + } + + private void VendorUsage() + => ChatLine("[RynthAi] Usage: /ub vendor {open[p] | buyall | sellall | clearbuy | clearsell | opencancel | addbuy[p] [count] | addsell[p] [count] }"); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs new file mode 100644 index 0000000..8665415 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs @@ -0,0 +1,1470 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using RynthCore.Loot.VTank; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi.Vendor; + +/// +/// UtilityBelt's AutoVendor on RynthCore's vendor trading calls (plugin API v67). +/// +/// When a vendor opens (or on /ub autovendor) it loads a VTank .utl named for the vendor +/// (or default.utl), identifies inventory items a rule could want, then repeats one +/// transaction at a time until there's nothing left: buy what Keep / Keep # rules want, +/// else sell what Sell rules match, splitting stacks when needed. Each transaction waits +/// for the server (engine trade status) and for the inventory to show the result. +/// +/// Threading: everything here runs on the plugin tick thread (Tick, OnVendorOpen/Close, +/// which the engine dispatches from the same pump). Chat commands arrive on AC's main +/// thread and are queued with . The engine's vendor calls are safe +/// from any thread; they read a snapshot and queue sends for AC's main thread. +/// +/// On an engine older than API v67 the vendor calls are absent (Host.HasVendorTrade is +/// false): AutoVendor says it needs a RynthCore update and does nothing else. Opening a +/// vendor (/ub vendor open) only needs UseObject and works on any engine. +/// +internal sealed class AutoVendorManager +{ + public const string MainProfileDir = @"C:\Games\RynthSuite\RynthAi\AutoVendor"; + public const string ProfileSubfolder = "AutoVendor"; + + private const long BailMs = 60_000; // UB bailTimer + private const long ConfirmTimeoutMs = 15_000; // UB lastEvent timeout + private const long TradeWaitMs = 15_000; // engine answers or times out in 10 s + private const long SplitWaitMs = 10_000; + private const long RetryDelayMs = 1_500; + private const int MaxFailures = 3; + private const int IdMaxInFlight = 4; // UB Assessor pacing + private const long IdSpacingMs = 75; + private const long IdResendMs = 1_500; + private const int IdMaxAttempts = 3; + private const long PollMs = 300; + + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings; + private readonly WorldObjectCache _cache; + private readonly Func _charFolder; + private readonly ConcurrentQueue _commands = new(); + private readonly VendorCart _cart = new(); + private uint _playerId; + + // ── Vendor tracking ── + private uint _openVendorId; // open right now (events) + private uint _vendorId; // last approached (UB vendorId) + private string _vendorName = string.Empty; + private volatile string? _openVendorProfilePath; + /// The open vendor's AutoVendor profile (existing, or where it would be created); null when none is open. + public string? OpenVendorProfilePath => _openVendorProfilePath; + private bool _needsUpdateSaid; + + // ── Session ── + private enum Phase { Idle, Identifying, Ready, WaitTrade, WaitConfirm, WaitSplit } + private Phase _phase = Phase.Idle; + private VTankLootProfile? _profile; + private string _profilePath = string.Empty; + private long _bailAt; + private long _nextActionAt; + private long _nextPollAt; + private int _failures; + private readonly HashSet _sessionSkip = new(); // items the engine refused to sell + + private readonly List _idQueue = new(); + private readonly Dictionary _idState = new(); + private long _lastIdSentAt; + + private uint _requestId; + private bool _tradeIsBuy; + private long _tradeSentAt; + private readonly List _lastSellIds = new(); + private readonly List<(string Name, int Target)> _expectBought = new(); + private readonly HashSet _expectSold = new(); + private long _confirmDeadline; + + private string _splitName = string.Empty; + private int _splitAmount; + private HashSet _splitBefore = new(); + private long _splitDeadline; + + private int _pyrealStackSize; + + // ── /ub vendor open ── + private bool _opening; + private uint _openTarget; + private string _openTargetName = string.Empty; + private int _openAttempts; + private long _openNextAt; + private long _openHoldUntil; // UB's nav lock outlives the open by 500 ms + TriesTime + + // ── /ub vendor addsell ── + private sealed class AddSellJob + { + public string Name = string.Empty; + public int Count; + public bool Partial; + public int Stage; // 0 = identifying, 1 = plan, 2 = waiting for split + public long Deadline; + public string SplitName = string.Empty; + public int Missing; + public string FirstName = string.Empty; + public HashSet Before = new(); + } + private AddSellJob? _addSell; + + private volatile string _status = "Idle"; + + public AutoVendorManager(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache cache, uint playerId, Func charFolder) + { + _host = host; + _settings = settings; + _cache = cache; + _playerId = playerId; + _charFolder = charFolder; + try { Directory.CreateDirectory(MainProfileDir); } catch { } + } + + /// A session or a vendor-open attempt is running: nav, looting and inventory moves wait. + public bool HoldsBot => _phase != Phase.Idle || _opening || Now() < _openHoldUntil; + + /// One line for the settings UI (any thread). + public string Status => _status; + + public bool VendorApiAvailable => _host.HasVendorTrade; + + /// Queue work from another thread (chat commands); runs on the next Tick. + public void Enqueue(Action action) + { + if (action != null) _commands.Enqueue(action); + } + + public void SetPlayerId(uint id) { if (id != 0) _playerId = id; } + + // ════════════════════════════════════════════════════════════════════════ + // Vendor events (tick thread) + // ════════════════════════════════════════════════════════════════════════ + + /// UB WorldFilter_ApproachVendor. Also fires on every vendor-list re-send. + public void OnVendorOpen(uint vendorId) + { + if (vendorId == 0) return; + bool fresh = vendorId != _openVendorId; + _openVendorId = vendorId; + + if (_opening && vendorId == _openTarget) + { + _opening = false; + _host.Log($"[RynthAi] AutoVendor: vendor {_openTargetName} opened successfully"); + } + + if (fresh) + { + PrintVendorOpened(vendorId); + EnsureProfileFolders(); + // For the dashboard's Edit button: the profile this vendor uses, or where its + // own would be created. Resolved once per open (it checks files on disk). + try { _openVendorProfilePath = ResolveProfilePath(VendorName(vendorId) + ".utl", false); } + catch { _openVendorProfilePath = null; } + } + + if (_phase != Phase.Idle) + return; // our own trade's list re-send, or a restart mid-run + + if (vendorId != _vendorId) + { + _vendorId = vendorId; + _vendorName = VendorName(vendorId); + } + + if (!_settings.AutoVendorEnabled) + return; + + if (!_host.HasVendorTrade) + { + if (!_needsUpdateSaid) { _needsUpdateSaid = true; SayNeedsUpdate(); } + return; + } + + Start(vendorId, string.Empty, explicitCommand: false); + } + + public void OnVendorClose(uint vendorId) + { + if (vendorId == 0) return; + if (vendorId == _openVendorId) + { + _openVendorId = 0; + _openVendorProfilePath = null; + Chat($"Vendor closed: {VendorName(vendorId)}"); + _cart.ClearBuy(); + _cart.ClearSell(); + } + if (_phase != Phase.Idle) + Stop(false); + } + + private void PrintVendorOpened(uint vendorId) + { + string name = VendorName(vendorId); + if (_settings.AutoVendorShowMerchantInfo && _host.HasVendorTrade + && _host.TryGetVendorInfo(out VendorInfo vi) && vi.VendorId == vendorId) + { + bool on = _settings.AutoVendorEnabled; + string line = string.Format(CultureInfo.InvariantCulture, + "{0}[0x{1:X8}]: BuyRate: {2:n0}% SellRate: {3:n0}% MaxValue: {4:n0} Buy: {5} Sell: {6}", + name, vendorId, vi.BuyRate * 100, vi.SellRate * 100, vi.MaxValue, + on && _settings.AutoVendorEnableBuying ? "Enabled" : "Disabled", + on && _settings.AutoVendorEnableSelling ? "Enabled" : "Disabled"); + if (vi.UsesAltCurrency) + line += $" Currency: {(string.IsNullOrEmpty(vi.AltCurrencyName) ? $"wcid {vi.AltCurrencyWcid}" : vi.AltCurrencyName)}"; + Chat(line); + } + else + { + Chat($"Vendor open: {name}"); + } + } + + // ════════════════════════════════════════════════════════════════════════ + // Commands (queued from chat; run on the tick thread) + // ════════════════════════════════════════════════════════════════════════ + + /// /ub autovendor [cancel|stop|quit|profile] + public void CommandAutoVendor(string arg) + { + string a = (arg ?? string.Empty).Trim(); + if (a.Equals("cancel", StringComparison.OrdinalIgnoreCase) + || a.Equals("stop", StringComparison.OrdinalIgnoreCase) + || a.Equals("quit", StringComparison.OrdinalIgnoreCase)) + { + Stop(false); + return; + } + if (!_host.HasVendorTrade) { SayNeedsUpdate(); return; } + Start(0, a, explicitCommand: true); + } + + public void CommandBuyAll() + { + if (!_host.HasVendorTrade) { SayNeedsUpdate(); return; } + if (_cart.BuyList.Count == 0) { Tool("buy list is empty"); return; } + if (_cart.BuyAll(_host, _openVendorId) == 0) + Error($"buy refused: {TradeMessage()}"); + } + + public void CommandSellAll() + { + if (!_host.HasVendorTrade) { SayNeedsUpdate(); return; } + if (_cart.SellList.Count == 0) { Tool("sell list is empty"); return; } + if (_cart.SellAll(_host, _openVendorId) == 0) + Error($"sell refused: {TradeMessage()}"); + } + + public void CommandClearBuy() => _cart.ClearBuy(); + public void CommandClearSell() => _cart.ClearSell(); + + /// /ub vendor addbuy[p] [count] name + public void CommandAddBuy(string args, bool partial) + { + if (!_host.HasVendorTrade) { SayNeedsUpdate(); return; } + var (count, name) = AutoVendorPlanner.ParseCountAndName(args); + if (_openVendorId == 0 || !_host.TryGetVendorInfo(out _)) + { + Error("addbuy: No vendor open"); + return; + } + string want = name.ToLowerInvariant(); + foreach (VendorItem it in _host.GetVendorItems()) + { + string n = it.Name.ToLowerInvariant(); + if (partial ? n.Contains(want) : n == want) + { + _cart.AddBuy(it.ObjectId, count); + Chat($"Added item to buy list: {it.Name} * {count}"); + return; + } + } + Error($"addbuy: Unable to find item {(partial ? "partially " : string.Empty)}named '{name}' in vendor sell list"); + } + + /// /ub vendor addsell[p] [count] name (splits a stack when no whole stacks add up). + public void CommandAddSell(string args, bool partial) + { + if (!_host.HasVendorTrade) { SayNeedsUpdate(); return; } + var (count, name) = AutoVendorPlanner.ParseCountAndName(args); + if (_openVendorId == 0 || !_host.TryGetVendorInfo(out _)) + { + Error("addsell: No vendor open"); + return; + } + if (_addSell != null) { Error("addsell: still working on the last addsell"); return; } + + var job = new AddSellJob { Name = name, Count = Math.Max(1, count), Partial = partial, Deadline = Now() + 5_000 }; + // Identify matches first: the safety checks read appraisal data. + int asked = 0; + foreach (var wo in Inventory()) + { + if (!NameMatches(wo.Name, name, partial)) continue; + uint id = unchecked((uint)wo.Id); + if (!Appraised(id) && _host.HasRequestId && asked < 20) + { + _host.RequestId(id); + asked++; + } + } + job.Stage = asked > 0 ? 0 : 1; + _addSell = job; + } + + /// /ub vendor open[p] [name|id|hex|selected] + public void CommandOpen(string target, bool partial) + { + WorldObject? vendor = FindVendor(target ?? string.Empty, partial); + if (vendor == null) + { + ThinkOrWrite("AutoVendor failed to open vendor"); + return; + } + _openTarget = unchecked((uint)vendor.Id); + _openTargetName = vendor.Name; + _openAttempts = 1; + _openNextAt = Now() + 250; // UB fudges the first attempt to ~250 ms after the command + _opening = true; + if (_host.HasSetAutoRun) _host.SetAutoRun(false); + _host.Log($"[RynthAi] AutoVendor: attempting to open vendor {vendor.Name}"); + } + + /// /ub vendor opencancel + public void CommandOpenCancel() + { + if (_opening) CancelUse(); + _opening = false; + _openHoldUntil = 0; + } + + // ════════════════════════════════════════════════════════════════════════ + // Tick + // ════════════════════════════════════════════════════════════════════════ + + public void Tick(int busyCount) + { + while (_commands.TryDequeue(out Action? cmd)) + { + try { cmd(); } + catch (Exception ex) { _host.Log($"[RynthAi] AutoVendor command failed: {ex.GetType().Name}: {ex.Message}"); } + } + + long now = Now(); + TickOpener(now); + TickAddSell(now, busyCount); + + if (_phase == Phase.Idle) + { + UpdateStatus(); + return; + } + + if (now - _bailAt > BailMs) + { + Tool("bail, Timeout expired"); + Stop(false); + return; + } + if (!_settings.AutoVendorEnabled) + { + Stop(false); + return; + } + + switch (_phase) + { + case Phase.Identifying: TickIdentify(now); break; + case Phase.Ready: TickReady(now, busyCount); break; + case Phase.WaitTrade: TickWaitTrade(now); break; + case Phase.WaitConfirm: TickWaitConfirm(now); break; + case Phase.WaitSplit: TickWaitSplit(now); break; + } + UpdateStatus(); + } + + /// Logout / teardown: drop everything without chat. + public void Reset() + { + _phase = Phase.Idle; + _opening = false; + _openHoldUntil = 0; + _addSell = null; + _profile = null; + _openVendorId = 0; + _cart.ClearBuy(); + _cart.ClearSell(); + while (_commands.TryDequeue(out _)) { } + _status = "Idle"; + } + + // ── Session start / stop (UB Start / Stop) ── + + private void Start(uint merchantId, string profileArg, bool explicitCommand) + { + if (merchantId == 0) merchantId = _vendorId; + if (!string.IsNullOrEmpty(profileArg) && merchantId == 0) merchantId = _openVendorId; + if (merchantId == 0) + { + ThinkOrWrite("AutoVendor Fatal - no vendor, cannot start"); + return; + } + + if (_phase != Phase.Idle) + Stop(true); + + _vendorId = merchantId; + _vendorName = VendorName(merchantId); + + if (explicitCommand && !_settings.AutoVendorEnabled) + { + Tool("AutoVendor is disabled (/ub opt set AutoVendor.Enabled true)"); + Stop(false); + return; + } + + bool fromArg = !string.IsNullOrEmpty(profileArg); + string path = ResolveProfilePath(fromArg ? profileArg : _vendorName + ".utl", fromArg); + if (!File.Exists(path)) + { + Error($"No vendor profile exists: {path}"); + Stop(false); + return; + } + + try + { + _profile = VTankLootParser.Load(path); + } + catch (Exception ex) + { + Error($"Unable to load loot profile {path}: {ex.Message}"); + Stop(false); + return; + } + + _profilePath = path; + _failures = 0; + _sessionSkip.Clear(); + _bailAt = Now(); + _nextActionAt = 0; + _host.Log($"[RynthAi] AutoVendor: {_vendorName} [0x{merchantId:X8}] profile '{path}' ({_profile.Rules.Count} rules)"); + + BuildIdQueue(); + _phase = Phase.Identifying; + } + + private void Stop(bool silent) + { + if (!silent) + ThinkOrWrite($"AutoVendor finished: {_vendorName}"); + _phase = Phase.Idle; + _profile = null; + _requestId = 0; + _idQueue.Clear(); + _idState.Clear(); + _expectBought.Clear(); + _expectSold.Clear(); + _lastSellIds.Clear(); + } + + // ── Identify (UB Assessor job) ── + + private void BuildIdQueue() + { + _idQueue.Clear(); + _idState.Clear(); + if (_profile == null || !_settings.AutoVendorEnableSelling || !_host.HasRequestId || !_host.HasHasAppraisalData) + return; + if (!TryGetVendor(out VendorView v, out _)) + return; + + var ctx = NewContext(); + uint player = PlayerId(); + foreach (var wo in Inventory()) + { + uint id = unchecked((uint)wo.Id); + if (IsEquipped(wo)) continue; + if (_settings.AutoVendorOnlyFromMainPack && !InMainPack(wo, player)) continue; + if (wo.ObjectClass is AcObjectClass.Container or AcObjectClass.Foci or AcObjectClass.Money) continue; + if (Appraised(id)) continue; + uint type = ItemType(wo); + if (type == 0 || !v.Buys(type)) continue; + + // Only ID what a Sell rule might still take: skip items no rule can match, and items + // a Keep (or other non-Sell) rule already decides without ID data. + ItemFacts f = InventoryFacts(wo, appraised: false); + ProfileVerdict verdict = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), f, ctx)); + if (verdict.Rule == null) continue; + if (verdict.Certain && verdict.Rule.Action != VTankLootAction.Sell) continue; + + _idQueue.Add(id); + } + if (_idQueue.Count > 0) + Tool($"identifying {_idQueue.Count} item(s)..."); + } + + private void TickIdentify(long now) + { + if (now < _nextPollAt) return; + _nextPollAt = now + 100; + + int inFlight = 0; + for (int i = _idQueue.Count - 1; i >= 0; i--) + { + uint id = _idQueue[i]; + if (Appraised(id)) + { + _idQueue.RemoveAt(i); + _idState.Remove(id); + _bailAt = now; + continue; + } + if (_idState.TryGetValue(id, out var st)) + { + bool waiting = now - st.LastAt < IdResendMs; + if (!waiting && st.Attempts >= IdMaxAttempts) + { + _idQueue.RemoveAt(i); // give up; it stays unsellable + _idState.Remove(id); + continue; + } + if (waiting) inFlight++; + } + } + + if (_idQueue.Count == 0) + { + if (_settings.AutoVendorTestMode) + { + DoTestMode(); + Stop(false); + return; + } + _phase = Phase.Ready; + return; + } + + if (inFlight >= IdMaxInFlight || now - _lastIdSentAt < IdSpacingMs) + return; + foreach (uint id in _idQueue) + { + _idState.TryGetValue(id, out var st); + if (st.Attempts > 0 && now - st.LastAt < IdResendMs) continue; + _host.RequestId(id); + _idState[id] = (st.Attempts + 1, now); + _lastIdSentAt = now; + break; + } + } + + // ── Plan and act (UB Core_RenderFrame + DoVendoring) ── + + private void TickReady(long now, int busyCount) + { + if (!TryGetVendor(out VendorView v, out VendorInfo vi) || v.Id != _vendorId) + { + if (now - _bailAt > 500) + { + _host.Log("[RynthAi] AutoVendor: stop because no vendor"); + Stop(false); + } + return; + } + if (now < _nextActionAt || busyCount != 0 || vi.TradeInFlight) + return; + if (!vi.TradingAvailable) + { + ThinkOrWrite("AutoVendor Fatal - the engine can't trade with this vendor (see RynthCore.log)"); + Stop(false); + return; + } + + var inv = Inventory(); + var ctx = NewContext(); + List wants = CollectWants(v, inv, ctx); + List sells = AutoVendorPlanner.SortSells(v, CollectSells(v, inv, ctx, null)); + PackState pack = ReadPack(v, vi, inv); + VendorPlan plan = AutoVendorPlanner.PlanNext(v, wants, sells, pack); + + switch (plan.Kind) + { + case PlanKind.Done: + Stop(false); + break; + + case PlanKind.Fatal: + ThinkOrWrite(plan.Message); + Stop(false); + break; + + case PlanKind.Buy: + SendBuy(v, plan, pack, inv, now); + break; + + case PlanKind.Sell: + SendSell(v, plan, now); + break; + + case PlanKind.Split: + DoSplit(plan.SplitItem!, plan.SplitAmount, plan.Message, inv, now); + break; + } + } + + private void SendBuy(VendorView v, VendorPlan plan, PackState pack, List inv, long now) + { + var entries = new List(plan.Buys.Count); + var sb = new StringBuilder(); + _expectBought.Clear(); + foreach (var line in plan.Buys) + { + entries.Add(new VendorTradeEntryNative(line.Item.Id, line.Amount)); + if (sb.Length > 0) sb.Append(", "); + sb.Append(line.Amount.ToString("n0", CultureInfo.InvariantCulture)).Append("x ").Append(line.Item.Name); + int have = CountByName(inv, line.Item.Name); + int prev = _expectBought.FindIndex(e => e.Name == line.Item.Name); + if (prev >= 0) _expectBought[prev] = (line.Item.Name, _expectBought[prev].Target + line.Amount); + else _expectBought.Add((line.Item.Name, have + line.Amount)); + } + _host.Log($"[RynthAi] AutoVendor Buy List: {sb} - {plan.Total}/{pack.Funds}"); + + uint id = _host.VendorBuy(v.Id, entries); + if (id == 0) + { + TradeFailed(isBuy: true, TradeMessage(), now); + return; + } + Tool(string.Format(CultureInfo.InvariantCulture, "buying {0} (~{1:n0} {2})", sb, plan.Total, v.UsesAltCurrency ? "currency" : "pyreals")); + _requestId = id; + _tradeIsBuy = true; + _tradeSentAt = now; + _bailAt = now; + _phase = Phase.WaitTrade; + } + + private void SendSell(VendorView v, VendorPlan plan, long now) + { + var ids = plan.Sells.Select(s => s.Id).ToList(); + _expectSold.Clear(); + _lastSellIds.Clear(); + foreach (uint i in ids) { _expectSold.Add(i); _lastSellIds.Add(i); } + string names = string.Join(", ", plan.Sells.Select(s => s.StackSize > 1 ? $"{s.Name} x{s.StackSize}" : s.Name)); + _host.Log($"[RynthAi] AutoVendor Sell List: {names} - {plan.Total}"); + + uint id = _host.VendorSell(v.Id, ids); + if (id == 0) + { + TradeFailed(isBuy: false, TradeMessage(), now); + return; + } + Tool(string.Format(CultureInfo.InvariantCulture, "selling {0} item(s) (~{1:n0} pyreals)", ids.Count, plan.Total)); + _requestId = id; + _tradeIsBuy = false; + _tradeSentAt = now; + _bailAt = now; + _phase = Phase.WaitTrade; + } + + private static readonly Regex HexId = new(@"0x([0-9A-Fa-f]{8})", RegexOptions.CultureInvariant); + + private void TradeFailed(bool isBuy, string message, long now) + { + Error($"vendor {(isBuy ? "buy" : "sell")} refused: {message}"); + + // An item the engine won't sell (e.g. "0x80001234 is not in your packs") is dropped for + // this session rather than blocking every later batch; that doesn't count as a failure. + if (!isBuy) + { + Match m = HexId.Match(message ?? string.Empty); + if (m.Success && uint.TryParse(m.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint bad) + && _lastSellIds.Contains(bad) && _sessionSkip.Add(bad)) + { + _phase = Phase.Ready; + _nextActionAt = now + RetryDelayMs; + return; + } + } + + if (++_failures >= MaxFailures) + { + ThinkOrWrite($"AutoVendor Fatal - {message}"); + Stop(false); + return; + } + _phase = Phase.Ready; + _nextActionAt = now + RetryDelayMs; + } + + private void TickWaitTrade(long now) + { + bool mine = _host.TryGetVendorTradeStatus(out VendorTradeStatus st) && st.RequestId == _requestId; + if (!mine || !st.IsFinished) + { + if (now - _tradeSentAt > TradeWaitMs) + { + _host.Log("[RynthAi] AutoVendor: no trade status in time; checking the inventory"); + EnterConfirm(now); + } + return; + } + + if (st.State == VendorTradeState.Refused) + { + TradeFailed(_tradeIsBuy, st.Message, now); + return; + } + switch (st.Result) + { + case VendorTradeResult.Accepted: + _failures = 0; + EnterConfirm(now); + break; + case VendorTradeResult.AnsweredNoRefresh: + TradeFailed(_tradeIsBuy, string.IsNullOrEmpty(st.Message) ? "the server refused" : st.Message, now); + break; + default: // timed out: it may still have gone through, so look before planning again + if (++_failures >= MaxFailures) + { + ThinkOrWrite($"AutoVendor Fatal - {st.Message}"); + Stop(false); + return; + } + EnterConfirm(now); + break; + } + } + + private void EnterConfirm(long now) + { + _phase = Phase.WaitConfirm; + _confirmDeadline = now + ConfirmTimeoutMs; + _nextPollAt = now + PollMs; + _bailAt = now; + } + + /// UB pendingBuy / pendingSell: wait for the inventory to show the trade. + private void TickWaitConfirm(long now) + { + if (now < _nextPollAt) return; + _nextPollAt = now + PollMs; + + var inv = Inventory(); + int sellLeft = 0; + if (_expectSold.Count > 0) + { + var have = new HashSet(inv.Select(w => unchecked((uint)w.Id))); + foreach (uint id in _expectSold) + if (have.Contains(id)) sellLeft++; + } + int buyLeft = 0; + foreach (var (name, target) in _expectBought) + if (CountByName(inv, name) < target) buyLeft++; + + if (sellLeft == 0 && buyLeft == 0) + { + _expectSold.Clear(); + _expectBought.Clear(); + _phase = Phase.Ready; + return; + } + if (now > _confirmDeadline) + { + _host.Log($"[RynthAi] AutoVendor: event timeout. Sell list: {sellLeft}, buy list: {buyLeft}"); + _expectSold.Clear(); + _expectBought.Clear(); + _phase = Phase.Ready; + } + } + + private void DoSplit(SellItem item, int amount, string why, List inv, long now) + { + if (!_host.HasSplitStackInternal) + { + ThinkOrWrite("AutoVendor Fatal - this engine can't split stacks"); + Stop(false); + return; + } + uint player = PlayerId(); + _splitBefore = new HashSet(inv.Select(w => unchecked((uint)w.Id))); + _splitName = item.Name; + _splitAmount = amount; + _host.Log($"[RynthAi] AutoVendor DoSplit {item.Name}:{item.Id:X8} old: {item.StackSize} new: {amount} ({why})"); + if (player == 0 || !_host.SplitStackInternal(item.Id, player, 0, amount)) + { + TradeFailed(isBuy: false, $"could not split {item.Name}", now); + return; + } + Tool($"splitting {amount} off {item.Name} ({why})"); + _splitDeadline = now + SplitWaitMs; + _nextPollAt = now + PollMs; + _bailAt = now; + _phase = Phase.WaitSplit; + } + + private void TickWaitSplit(long now) + { + if (now < _nextPollAt) return; + _nextPollAt = now + PollMs; + if (FindNewStack(Inventory(), _splitBefore, _splitName, _splitAmount) != 0 || now > _splitDeadline) + _phase = Phase.Ready; + } + + // ── Collect (UB GetBuyItems / GetSellItems) ── + + private List CollectWants(VendorView v, List inv, VTankLootContext ctx) + { + if (!_settings.AutoVendorEnableBuying || _profile == null) + return new List(); + var judged = new List<(Listing, BuyDecision)>(); + foreach (Listing l in Listings(v)) + { + ItemFacts f = ListingFacts(l); + judged.Add((l, AutoVendorRules.DecideBuy(_profile.Rules, Judge(ListingObject(l), f, ctx)))); + } + return AutoVendorPlanner.BuildBuyWants(v, judged, n => CountByName(inv, n), c => CountByClass(inv, c)); + } + + /// Test mode: items a Sell rule points at that are held back, with why. + private List CollectSells(VendorView v, List inv, VTankLootContext ctx, List? heldBack) + { + var result = new List(); + if (!_settings.AutoVendorEnableSelling || _profile == null) + return result; + + uint player = PlayerId(); + var packOrder = PackOrder(inv, player); + foreach (var wo in inv) + { + uint id = unchecked((uint)wo.Id); + if (_sessionSkip.Contains(id)) continue; + + SafetyFacts safety = ReadSafety(wo, player); + string? unsafeWhy = AutoVendorPlanner.UnsafeReason(safety, _settings.AutoVendorOnlyFromMainPack); + if (unsafeWhy != null && heldBack == null) + continue; + + uint type = ItemType(wo); + int stack = StackOf(wo); + bool isNote = wo.ObjectClass == AcObjectClass.TradeNote || (type & AutoVendorPlanner.ItemTypePromissoryNote) != 0; + int unitValue = stack > 1 ? safety.Value / stack : safety.Value; + if (unsafeWhy == null && !AutoVendorPlanner.VendorWillBuy(v, type, isNote, unitValue)) + continue; + + ItemFacts f = InventoryFacts(wo, safety.Appraised); + ProfileVerdict verdict = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), f, ctx)); + SellDecision sd = AutoVendorRules.JudgeSell(verdict); + + if (unsafeWhy != null) + { + if (verdict.Rule?.Action == VTankLootAction.Sell) + heldBack!.Add($"{wo.Name} - {unsafeWhy}"); + continue; + } + if (!sd.Sell) + { + if (heldBack != null && verdict.Rule?.Action == VTankLootAction.Sell) + heldBack.Add($"{wo.Name} - {sd.Reason}"); + continue; + } + + bool main = InMainPack(wo, player); + int packIdx = main ? 0 : (packOrder.TryGetValue(wo.DirectContainerId, out int pi) ? pi : 99); + string packName = main ? "Main Pack" : (_cache[wo.DirectContainerId]?.Name ?? "Pack"); + result.Add(new SellItem + { + Id = id, + Name = wo.Name, + Class = wo.ObjectClass, + ItemType = type, + StackSize = stack, + Value = safety.Value, + RuleName = sd.RuleName, + Location = main ? "Main Pack" : $"{packName} #{packIdx}", + SortSlot = main ? Math.Max(0, wo.DirectSlot) : 1000 + 100 * packIdx + Math.Max(0, wo.DirectSlot), + }); + } + return result; + } + + // ── Test mode (UB DoTestMode) ── + + private void DoTestMode() + { + Chat("AutoVendor TEST MODE"); + if (!TryGetVendor(out VendorView v, out _)) + { + Chat(" (no vendor open)"); + return; + } + var inv = Inventory(); + var ctx = NewContext(); + + Chat("Buy Items:"); + var wants = CollectWants(v, inv, ctx); + foreach (var w in wants) + Chat($" {AutoVendorPlanner.CategoryName(w.Item.ItemType)} -> {w.Item.Name} * {(w.Amount == int.MaxValue ? "max" : w.Amount.ToString("n0", CultureInfo.InvariantCulture))} - {w.RuleName}"); + if (wants.Count == 0) Chat(" (Nothing)"); + + Chat("Sell Items:"); + var held = new List(); + var sells = CollectSells(v, inv, ctx, held).OrderBy(s => s.SortSlot).ToList(); + foreach (var s in sells) + Chat($" {s.Location}: {s.Name}{(s.StackSize > 1 ? $" x{s.StackSize}" : string.Empty)} - {s.RuleName}"); + if (sells.Count == 0) Chat(" (Nothing)"); + + if (held.Count > 0) + { + Chat("Held back (never sold):"); + foreach (string h in held.Take(10)) Chat($" {h}"); + if (held.Count > 10) Chat($" ...and {held.Count - 10} more"); + } + Chat("TestMode is on: nothing was bought or sold (/ub opt set AutoVendor.TestMode false)."); + } + + // ── /ub vendor open attempts ── + + private void TickOpener(long now) + { + if (!_opening || now < _openNextAt) return; + int tries = Math.Clamp(_settings.AutoVendorTries, 1, 20); + if (_openAttempts <= tries) + { + if (_openAttempts > 1) + _host.Log("[RynthAi] AutoVendor: vendor open timed out, trying again"); + _openAttempts++; + _openNextAt = now + Math.Clamp(_settings.AutoVendorTriesTime, 500, 30_000); + if (_host.HasUseObject) _host.UseObject(_openTarget); + _openHoldUntil = now + 500 + Math.Clamp(_settings.AutoVendorTriesTime, 500, 30_000); + return; + } + CancelUse(); + _opening = false; + _openHoldUntil = 0; + ThinkOrWrite("AutoVendor failed to open vendor"); + } + + /// UB cancels a pending use by facing one degree away. + private void CancelUse() + { + if (_host.HasTurnToHeading && _host.TryGetPlayerHeading(out float h)) + _host.TurnToHeading((h + 359f) % 360f); + else if (_host.HasStopCompletely) + _host.StopCompletely(); + } + + private WorldObject? FindVendor(string target, bool partial) + { + string t = target.Trim(); + if (t.Length > 0) + { + if (uint.TryParse(t, NumberStyles.Integer, CultureInfo.InvariantCulture, out uint dec) && IsVendor(dec, out var byDec)) + return byDec; + string hex = t.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? t.Substring(2) : t; + if (uint.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint hx) && IsVendor(hx, out var byHex)) + return byHex; + if (t.Equals("selected", StringComparison.OrdinalIgnoreCase) && _host.HasGetSelectedItemId + && IsVendor(_host.GetSelectedItemId(), out var bySel)) + return bySel; + } + + int player = unchecked((int)PlayerId()); + string lower = t.ToLowerInvariant(); + WorldObject? best = null; + double bestDist = double.MaxValue; + foreach (var wo in _cache.GetLandscapeObjects()) + { + if (wo.ObjectClass != AcObjectClass.Vendor || wo.Id == player) continue; + string n = (wo.Name ?? string.Empty).ToLowerInvariant(); + bool match = lower.Length == 0 || (partial ? n.Contains(lower) : n == lower); + if (!match) continue; + double d = _cache.Distance(player, wo.Id); + if (best == null || d < bestDist) { best = wo; bestDist = d; } + } + return best; + } + + private bool IsVendor(uint id, out WorldObject? wo) + { + wo = id != 0 ? _cache[unchecked((int)id)] : null; + return wo != null && wo.ObjectClass == AcObjectClass.Vendor; + } + + // ── /ub vendor addsell ── + + private void TickAddSell(long now, int busyCount) + { + var job = _addSell; + if (job == null) return; + + if (job.Stage == 0) + { + bool allIded = Inventory().Where(w => NameMatches(w.Name, job.Name, job.Partial)) + .All(w => Appraised(unchecked((uint)w.Id))); + if (allIded || now > job.Deadline) job.Stage = 1; + return; + } + + if (job.Stage == 1) + { + if (busyCount != 0 && now < job.Deadline + 5_000) return; + var inv = Inventory(); + uint player = PlayerId(); + var matches = new List(); + foreach (var wo in inv) + { + if (!NameMatches(wo.Name, job.Name, job.Partial)) continue; + SafetyFacts safety = ReadSafety(wo, player); + if (AutoVendorPlanner.UnsafeReason(safety, _settings.AutoVendorOnlyFromMainPack) != null) continue; + matches.Add(new SellItem { Id = unchecked((uint)wo.Id), Name = wo.Name, Class = wo.ObjectClass, StackSize = StackOf(wo), Value = safety.Value }); + } + if (matches.Count == 0) + { + Error($"addsell: Unable to find item {(job.Partial ? "partially " : string.Empty)}named '{job.Name}' in inventory"); + _addSell = null; + return; + } + + var (whole, missing, splitFrom) = AutoVendorPlanner.PlanAddSell(matches, job.Count); + foreach (var w in whole) _cart.AddSell(w.Id); + job.FirstName = matches[0].Name; + if (missing == 0) + { + Chat($"Added item to sell list: {job.FirstName} * {job.Count}"); + _addSell = null; + return; + } + if (splitFrom == null || !_host.HasSplitStackInternal || player == 0) + { + Chat($"Added item to sell list: {job.FirstName} * {job.Count}, but was missing {missing} items"); + _addSell = null; + return; + } + job.Before = new HashSet(inv.Select(w => unchecked((uint)w.Id))); + job.SplitName = splitFrom.Name; + job.Missing = missing; + if (!_host.SplitStackInternal(splitFrom.Id, player, 0, missing)) + { + Chat($"Added item to sell list: {job.FirstName} * {job.Count - missing}, but was missing {missing} items"); + _addSell = null; + return; + } + job.Deadline = now + SplitWaitMs; + job.Stage = 2; + return; + } + + // Stage 2: wait for the split-off stack, then add it. + uint found = FindNewStack(Inventory(), job.Before, job.SplitName, job.Missing); + if (found != 0) + { + _cart.AddSell(found); + Chat($"Added item to sell list: {job.FirstName} * {job.Count}"); + _addSell = null; + } + else if (now > job.Deadline) + { + Chat($"Added item to sell list: {job.FirstName} * {job.Count - job.Missing}, but was missing {job.Missing} items"); + _addSell = null; + } + } + + // ════════════════════════════════════════════════════════════════════════ + // Reads + // ════════════════════════════════════════════════════════════════════════ + + private bool TryGetVendor(out VendorView v, out VendorInfo vi) + { + v = null!; + vi = null!; + if (!_host.HasVendorTrade || !_host.TryGetVendorInfo(out vi) || vi.VendorId == 0) + return false; + v = new VendorView + { + Id = vi.VendorId, + Name = string.IsNullOrEmpty(vi.Name) ? VendorName(vi.VendorId) : vi.Name, + BuyRate = vi.BuyRate, + SellRate = vi.SellRate, + ItemTypes = vi.ItemTypes, + MaxValue = vi.MaxValue, + UsesAltCurrency = vi.UsesAltCurrency, + }; + return true; + } + + private List Listings(VendorView v) + { + var list = new List(); + foreach (VendorItem it in _host.GetVendorItems()) + { + if (it.ObjectId == 0) continue; + if (!it.Unlimited && it.Amount <= 0) continue; + AcObjectClass cls = WorldObjectCache.ClassifyByItemType(it.ItemType); + list.Add(new Listing + { + Id = it.ObjectId, + Name = it.Name, + Class = cls, + ItemType = it.ItemType, + Amount = it.Unlimited ? -1 : it.Amount, + StackSize = Math.Max(1, it.StackSize), + MaxStackSize = it.Stackable ? Math.Max(1, it.MaxStackSize) : 1, + Value = it.Value, + UnitPrice = it.UnitPrice, + Burden = it.Burden, + NeedsContainerSlot = it.NeedsContainerSlot, + }); + } + return list; + } + + private PackState ReadPack(VendorView v, VendorInfo vi, List inv) + { + uint player = PlayerId(); + long funds; + if (v.UsesAltCurrency) + { + funds = vi.AltCurrencyHave >= 0 ? vi.AltCurrencyHave + : vi.AltCurrencyServerCount >= 0 ? vi.AltCurrencyServerCount : 0; + } + else + { + funds = vi.PlayerCoins >= 0 ? vi.PlayerCoins : CountPyreals(inv); + } + + int mainCap = ReadPlayerInt(player, 6, 102); + int mainCount = _host.HasGetNumContainedItems ? _host.GetNumContainedItems(player) : -1; + if (mainCount < 0) + mainCount = inv.Count(w => InMainPack(w, player) && !IsEquipped(w) + && w.ObjectClass is not (AcObjectClass.Container or AcObjectClass.Foci)); + int contCap = ReadPlayerInt(player, 7, 7); + int contCount = _host.HasGetNumContainedContainers ? _host.GetNumContainedContainers(player) : -1; + if (contCount < 0) + contCount = inv.Count(w => InMainPack(w, player) && w.ObjectClass is AcObjectClass.Container or AcObjectClass.Foci); + + return new PackState + { + Funds = Math.Max(0, funds), + FreeMainSlots = Math.Max(0, mainCap - mainCount), + FreeContainerSlots = Math.Max(0, contCap - contCount), + PyrealStackSize = PyrealStack(inv), + }; + } + + private int ReadPlayerInt(uint player, uint stype, int fallback) + { + if (player != 0 && _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(player, stype, out int v) && v > 0) + return v; + return fallback; + } + + private int PyrealStack(List inv) + { + if (_pyrealStackSize > 0) return _pyrealStackSize; + foreach (var wo in inv) + { + if (!IsPyreal(wo)) continue; + int max = wo.Values(LongValueKey.MaxStackSize, 0); + if (max > 0) { _pyrealStackSize = max; return max; } + } + return AutoVendorPlanner.DefaultPyrealStackSize; + } + + private long CountPyreals(List inv) + { + long total = 0; + foreach (var wo in inv) + if (IsPyreal(wo)) total += StackOf(wo); + return total; + } + + private bool IsPyreal(WorldObject wo) + => _host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)wo.Id), out uint wcid) && wcid == AutoVendorPlanner.PyrealWcid; + + private SafetyFacts ReadSafety(WorldObject wo, uint player) + { + uint id = unchecked((uint)wo.Id); + bool appraised = Appraised(id); + bool? canBeSold = _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(id, 69 /* IsSellable */, out bool sellable) + ? sellable : null; + bool retained = false; + if (_host.HasGetObjectBitfield && _host.TryGetObjectBitfield(id, out uint bf) && (bf & 0x01000000u) != 0) + retained = true; // BF_RETAINED + if (!retained && _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(id, 91 /* Retained */, out bool ret) && ret) + retained = true; + bool rare = wo.Values(17 /* RareId */, 0) > 0; + if (!rare && _host.HasGetObjectDataIdProperty && _host.TryGetObjectDataIdProperty(id, 52 /* IconUnderlay */, out uint underlay) + && (underlay & 0x00FFFFFFu) == 23308u) + rare = true; // UB: IconUnderlay 23308 = rare + + return new SafetyFacts + { + Appraised = appraised, + Class = wo.ObjectClass, + Value = wo.Values(19 /* Value */, 0), + CanBeSold = canBeSold, + IsRare = rare, + InMainPack = InMainPack(wo, player), + Equipped = IsEquipped(wo), + Attuned = wo.Values(114 /* Attuned */, 0), + Bonded = wo.Values(33 /* Bonded */, 0), + Retained = retained, + TimesTinkered = wo.Values(171 /* NumTimesTinkered */, 0), + Imbued = wo.Values(179 /* ImbuedEffect */, 0), + Inscription = wo.Values((StringValueKey)7 /* Inscription */, string.Empty), + HoldsItems = wo.Values(LongValueKey.ItemsCapacity, 0) > 0, + }; + } + + private ItemFacts InventoryFacts(WorldObject wo, bool appraised) => new() + { + IsVendorListing = false, + Appraised = appraised, + ObjectClass = wo.ObjectClass, + HasSpellData = appraised && _host.HasGetObjectSpellIds, + HasPalettes = _host.HasGetObjectPalettes, + HasCharacterSkills = _host.HasGetObjectSkill, + HasCharacterLevel = _host.HasGetObjectIntProperty, + }; + + private ItemFacts ListingFacts(Listing l) => new() + { + IsVendorListing = true, + Appraised = false, + ObjectClass = l.Class, + HasCharacterSkills = _host.HasGetObjectSkill, + HasCharacterLevel = _host.HasGetObjectIntProperty, + }; + + /// The inventory item as the evaluator sees it: live reads, with the name we already have. + private WorldObject EvalObject(WorldObject wo) + { + var overlay = new ItemPropertyOverlay { LiveFallback = true }; + overlay.Strings[(uint)StringValueKey.Name] = wo.Name; + return new WorldObject(wo.Id, wo.Name, wo.ObjectClass) { Cache = _cache, Overlay = overlay }; + } + + /// A vendor listing as the evaluator sees it: only what the vendor snapshot holds. + private static WorldObject ListingObject(Listing l) + { + var overlay = new ItemPropertyOverlay { LiveFallback = false }; + overlay.Ints[1] = unchecked((int)l.ItemType); + overlay.Ints[5] = l.Burden; + overlay.Ints[11] = l.MaxStackSize; + overlay.Ints[12] = l.StackSize; + overlay.Ints[19] = l.Value; + overlay.Strings[(uint)StringValueKey.Name] = l.Name; + return new WorldObject(unchecked((int)l.Id), l.Name, l.Class) { Overlay = overlay }; + } + + private static Func Judge(WorldObject evalObj, ItemFacts facts, VTankLootContext ctx) + => c => AutoVendorRules.JudgeCondition(c, facts, cc => VTankLootEvaluator.MatchCondition(cc, evalObj, ctx)); + + private VTankLootContext NewContext() => new(_host, PlayerId()) { Cache = _cache }; + + private List Inventory() + { + try { return _cache.GetDirectInventory(forceRefresh: true).Where(w => w != null && w.Id != 0).ToList(); } + catch { return new List(); } + } + + private static int StackOf(WorldObject wo) + { + int s = wo.Values(LongValueKey.StackCount, 0); + return s > 0 ? s : 1; + } + + /// UB GetItemCountInInventoryByName: exact name, stack sizes summed. + private static int CountByName(List inv, string name) + { + int count = 0; + foreach (var wo in inv) + if (string.Equals(wo.Name, name, StringComparison.Ordinal)) + count += StackOf(wo); + return count; + } + + private static int CountByClass(List inv, AcObjectClass cls) + { + int count = 0; + foreach (var wo in inv) + if (wo.ObjectClass == cls) + count += StackOf(wo); + return count; + } + + private uint FindNewStack(List inv, HashSet before, string name, int amount) + { + foreach (var wo in inv) + { + uint id = unchecked((uint)wo.Id); + if (before.Contains(id)) continue; + if (string.Equals(wo.Name, name, StringComparison.OrdinalIgnoreCase) && StackOf(wo) == amount) + return id; + } + return 0; + } + + private static Dictionary PackOrder(List inv, uint player) + { + var order = new Dictionary(); + int n = 0; + foreach (var wo in inv.Where(w => w.DirectContainerId == unchecked((int)player) + && w.ObjectClass is AcObjectClass.Container or AcObjectClass.Foci) + .OrderBy(w => w.DirectSlot)) + order[wo.Id] = ++n; + return order; + } + + private static bool InMainPack(WorldObject wo, uint player) + { + int p = unchecked((int)player); + int container = wo.DirectContainerId != 0 ? wo.DirectContainerId : wo.Container; + return player != 0 && container == p; + } + + private static bool IsEquipped(WorldObject wo) + => wo.WieldedLocation > 0 || wo.Values(LongValueKey.EquippedSlots, 0) > 0; + + private uint ItemType(WorldObject wo) + => _host.TryGetItemType(unchecked((uint)wo.Id), out uint t) ? t : 0u; + + private bool Appraised(uint id) => _host.HasHasAppraisalData && _host.HasAppraisalData(id); + + private static bool NameMatches(string itemName, string want, bool partial) + { + string n = (itemName ?? string.Empty).ToLowerInvariant(); + string w = (want ?? string.Empty).ToLowerInvariant(); + return partial ? n.Contains(w) : n == w; + } + + private uint PlayerId() + { + if (_playerId == 0) _playerId = _host.GetPlayerId(); + return _playerId; + } + + private string VendorName(uint id) + { + if (id != 0 && _host.HasVendorTrade && _host.TryGetVendorInfo(out VendorInfo vi) && vi.VendorId == id && !string.IsNullOrEmpty(vi.Name)) + return vi.Name; + return _host.TryGetObjectName(id, out string n) && !string.IsNullOrWhiteSpace(n) ? n : $"0x{id:X8}"; + } + + private string TradeMessage() + => _host.TryGetVendorTradeStatus(out VendorTradeStatus st) && !string.IsNullOrEmpty(st.Message) ? st.Message : "no reason given"; + + // ── Profiles (UB GetProfilePath) ── + + /// + /// First existing file of: character folder, server folder, main folder (the named + /// profile), then default.utl in the same three; else the main-folder path (missing). + /// A name typed on /ub autovendor also tries name + ".utl". + /// + public string ResolveProfilePath(string profileName, bool addUtlGuess) + { + var dirs = ProfileDirs(); + var names = new List { profileName }; + if (addUtlGuess && string.IsNullOrEmpty(Path.GetExtension(profileName))) + names.Add(profileName + ".utl"); + + foreach (string dir in dirs) + foreach (string n in names) + { + string p = SafeCombine(dir, n); + if (p.Length > 0 && File.Exists(p)) return p; + } + foreach (string dir in dirs) + { + string p = SafeCombine(dir, "default.utl"); + if (p.Length > 0 && File.Exists(p)) return p; + } + string fallback = SafeCombine(MainProfileDir, profileName); + return fallback.Length > 0 ? fallback : Path.Combine(MainProfileDir, "default.utl"); + } + + /// Character, server, main - UB's order. + public List ProfileDirs() + { + var dirs = new List(); + string charFolder = _charFolder() ?? string.Empty; + if (!string.IsNullOrEmpty(charFolder)) + dirs.Add(Path.Combine(charFolder, ProfileSubfolder)); + if (_host.HasGetWorldName && _host.TryGetWorldName(out string world) && !string.IsNullOrWhiteSpace(world)) + dirs.Add(Path.Combine(MainProfileDir, Sanitize(world))); + dirs.Add(MainProfileDir); + return dirs; + } + + /// Create the per-character and per-server folders so players can see where profiles go (UB Init). + public void EnsureProfileFolders() + { + foreach (string dir in ProfileDirs()) + try { Directory.CreateDirectory(dir); } catch { } + } + + private static string SafeCombine(string dir, string name) + { + try { return Path.Combine(dir, name); } catch { return string.Empty; } + } + + private static string Sanitize(string s) + { + foreach (char c in Path.GetInvalidFileNameChars()) + s = s.Replace(c, '_'); + return s.Trim(); + } + + // ── Chat ── + + private void Chat(string msg) => _host.WriteToChat($"[RynthAi] {msg}", 1); + private void Tool(string msg) => _host.WriteToChat($"[RynthAi] AutoVendor: {msg}", 1); + private void Error(string msg) => _host.WriteToChat($"[RynthAi] AutoVendor: {msg}", 2); + + /// UB Util.ThinkOrWrite: a /tell to yourself when Think is on (metas watch for it). + private void ThinkOrWrite(string msg) + { + uint player = PlayerId(); + if (_settings.AutoVendorThink && _host.HasInvokeChatParser && player != 0 + && _host.TryGetObjectName(player, out string me) && !string.IsNullOrWhiteSpace(me)) + { + _host.InvokeChatParser($"/tell {me}, {msg}"); + return; + } + Chat(msg); + } + + private void SayNeedsUpdate() + => Error($"needs a RynthCore update: vendor trading is plugin API v67, this engine is v{_host.Version}."); + + private void UpdateStatus() + { + string s; + if (_opening) + s = $"Opening {_openTargetName} (attempt {Math.Max(1, _openAttempts - 1)}/{Math.Clamp(_settings.AutoVendorTries, 1, 20)})"; + else + s = _phase switch + { + Phase.Idle => _host.HasVendorTrade ? "Idle" : $"Needs RynthCore update (engine API v{_host.Version}, needs v67)", + Phase.Identifying => $"Identifying {_idQueue.Count} item(s) - {_vendorName}", + Phase.WaitTrade => $"Waiting for the server - {_vendorName}", + Phase.WaitConfirm => $"Confirming trade - {_vendorName}", + Phase.WaitSplit => $"Splitting {_splitName} - {_vendorName}", + _ => $"Vendoring {_vendorName} ({Path.GetFileName(_profilePath)})", + }; + if (_settings.AutoVendorTestMode && _phase != Phase.Idle) s += " [test mode]"; + _status = s; + } + + private static long Now() => Environment.TickCount64; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs new file mode 100644 index 0000000..737eda2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs @@ -0,0 +1,497 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using RynthCore.Loot; + +namespace RynthCore.Plugin.RynthAi.Vendor; + +// Pure planning for AutoVendor, a port of UtilityBelt's AutoVendor.DoVendoring / +// GetBuyItems / GetSellItems / ItemIsSafeToGetRidOf / AddItemToSellList. No host calls: +// the manager fills these views from the engine's vendor snapshot and the inventory, +// executes the plan, waits for the server, and plans again. One transaction per plan, +// buying before selling, exactly as UB does. + +/// The open vendor (engine VendorInfo). +internal sealed class VendorView +{ + public uint Id { get; init; } + public string Name { get; init; } = string.Empty; + /// Vendor pays value x BuyRate when you sell. + public float BuyRate { get; init; } = 1f; + /// Vendor charges value x SellRate when you buy. + public float SellRate { get; init; } = 1f; + public uint ItemTypes { get; init; } + public int MaxValue { get; init; } + public bool UsesAltCurrency { get; init; } + + public bool Buys(uint itemType) => (ItemTypes & itemType) != 0; +} + +/// One item on the vendor's list (engine VendorItem). +internal sealed class Listing +{ + public uint Id { get; init; } + public string Name { get; init; } = string.Empty; + public AcObjectClass Class { get; init; } + public uint ItemType { get; init; } + /// How many the vendor has; negative = unlimited. + public int Amount { get; init; } = -1; + public int StackSize { get; init; } = 1; + public int MaxStackSize { get; init; } = 1; + /// Value of the listed stack. + public int Value { get; init; } + /// Engine's per-unit price at this vendor (0 = unknown). + public int UnitPrice { get; init; } + /// Burden of the listed stack. + public int Burden { get; init; } + public bool NeedsContainerSlot { get; init; } + + public bool Unlimited => Amount < 0; + public bool IsNote => Class == AcObjectClass.TradeNote || (ItemType & AutoVendorPlanner.ItemTypePromissoryNote) != 0; + public int UnitValue => StackSize > 1 ? Value / StackSize : Value; +} + +/// A vendor item the profile wants, with how many (int.MaxValue = all you can afford). +internal sealed class BuyWant +{ + public Listing Item { get; init; } = null!; + public int Amount { get; init; } + public string RuleName { get; init; } = string.Empty; +} + +/// An inventory item that passed the safety checks and a Sell rule. +internal sealed class SellItem +{ + public uint Id { get; init; } + public string Name { get; init; } = string.Empty; + public AcObjectClass Class { get; init; } + public uint ItemType { get; init; } + public int StackSize { get; init; } = 1; + /// Value of the whole stack. + public int Value { get; init; } + public string RuleName { get; init; } = string.Empty; + public string Location { get; init; } = string.Empty; + public int SortSlot { get; init; } + + public bool IsNote => Class == AcObjectClass.TradeNote || (ItemType & AutoVendorPlanner.ItemTypePromissoryNote) != 0; + public int UnitValue => StackSize > 1 ? Value / StackSize : Value; +} + +/// Money and room, read fresh before each plan. +internal sealed class PackState +{ + /// Pyreals, or the vendor's alt currency. + public long Funds { get; init; } + /// Free item slots in the MAIN pack (UB: Weenie(player).FreeSpace). + public int FreeMainSlots { get; init; } + public int FreeContainerSlots { get; init; } + public int PyrealStackSize { get; init; } = AutoVendorPlanner.DefaultPyrealStackSize; +} + +internal enum PlanKind : byte +{ + Done = 0, + Buy = 1, + Sell = 2, + Split = 3, + Fatal = 4, +} + +internal readonly record struct BuyLine(Listing Item, int Amount); + +internal sealed class VendorPlan +{ + public PlanKind Kind { get; init; } + public List Buys { get; init; } = new(); + public List Sells { get; init; } = new(); + /// Buy: estimated cost. Sell: estimated payout. + public long Total { get; init; } + public SellItem? SplitItem { get; init; } + public int SplitAmount { get; init; } + public string Message { get; init; } = string.Empty; + + public static VendorPlan Done() => new() { Kind = PlanKind.Done }; + public static VendorPlan Fatal(string msg) => new() { Kind = PlanKind.Fatal, Message = msg }; + public static VendorPlan Split(SellItem item, int amount, string why) => + new() { Kind = PlanKind.Split, SplitItem = item, SplitAmount = amount, Message = why }; +} + +/// What the manager read about an inventory item for UB's "safe to get rid of" checks. +internal sealed class SafetyFacts +{ + /// Has appraisal data: without it the checks below can't be trusted, so never sell. + public bool Appraised { get; init; } + public AcObjectClass Class { get; init; } + public int Value { get; init; } + /// ACE IsSellable (69); null = unknown (treated as sellable, like UB's default). + public bool? CanBeSold { get; init; } + public bool IsRare { get; init; } + public bool InMainPack { get; init; } + public bool Equipped { get; init; } + public int Attuned { get; init; } + public int Bonded { get; init; } + public bool Retained { get; init; } + public int TimesTinkered { get; init; } + public int Imbued { get; init; } + public string Inscription { get; init; } = string.Empty; + /// A pack or focus (holds items). + public bool HoldsItems { get; init; } +} + +internal static class AutoVendorPlanner +{ + public const int MaxVendorBuyCount = 5000; // UB MAX_VENDOR_BUY_COUNT + public const int MaxSellLines = 99; // UB: GDLE rejects 100+ items per transaction + public const int DefaultPyrealStackSize = 25000; + public const uint PyrealWcid = 273; + public const uint ItemTypePromissoryNote = 0x00040000; + + // UB ShopItemListTypes: shop category names for the test-mode report. + private static readonly (uint Bit, string Name)[] ShopCategories = + { + (0x00000001, "Weapons"), (0x00000002, "Armor"), (0x00000004, "Clothing"), (0x00000008, "Jewelry"), + (0x00000010, "Miscellaneous"), (0x00000020, "Food"), (0x00000080, "Miscellaneous"), (0x00000100, "Weapons"), + (0x00000200, "Containers"), (0x00000400, "Miscellaneous"), (0x00000800, "Gems"), (0x00001000, "Spell Components"), + (0x00002000, "Books, Paper"), (0x00004000, "Keys, Tools"), (0x00008000, "Magic Items"), (0x00040000, "Trade Notes"), + (0x00080000, "Mana Stones"), (0x00100000, "Services"), (0x00400000, "Cooking Items"), (0x00800000, "Alchemical Items"), + (0x01000000, "Fletching Items"), (0x04000000, "Alchemical Items"), (0x08000000, "Fletching Items"), (0x20000000, "Keys, Tools"), + }; + + public static string CategoryName(uint itemType) + { + foreach (var (bit, name) in ShopCategories) + if ((itemType & bit) != 0) return name; + return $"Unknown Category 0x{itemType:X8}"; + } + + // ── Prices (ACE Vendor.GetSellCost / GetBuyCost, as the engine checks them) ────────── + + /// What you pay for one created stack worth . + public static long PlayerPays(VendorView v, bool isNote, long stackValue) + { + float rate = isNote ? 1.15f : v.SellRate; + float product = rate * stackValue; + return Math.Max(1L, (long)Math.Ceiling(product - 0.1)); + } + + /// What the vendor pays for one item (whole stack) worth . + public static long VendorPays(VendorView v, bool isNote, long value) + { + float rate = isNote ? 1.0f : v.BuyRate; + float product = rate * value; + return Math.Max(1L, (long)Math.Floor(product + 0.1)); + } + + /// Per-unit price: the engine's figure, else UB's (int)(Value/Stack) x rate rounded like ACE. + public static long UnitPrice(VendorView v, Listing item) + { + if (item.UnitPrice > 0) return item.UnitPrice; + if (item.UnitValue <= 0) return 0; + return PlayerPays(v, item.IsNote, item.UnitValue); + } + + /// The engine's EstimateBuy: stackables in full stacks, limited listings at least the whole listing. + public static long EstimateCost(VendorView v, Listing item, int amount) + { + if (amount <= 0) return 0; + long unitValue = Math.Max(0, item.UnitValue); + long cost; + if (item.MaxStackSize > 1) + { + long max = item.MaxStackSize; + long full = amount / max; + long rem = amount % max; + cost = full * PlayerPays(v, item.IsNote, unitValue * max) + (rem > 0 ? PlayerPays(v, item.IsNote, unitValue * rem) : 0); + } + else + { + cost = amount * PlayerPays(v, item.IsNote, unitValue); + } + if (!item.Unlimited) + cost = Math.Max(cost, PlayerPays(v, item.IsNote, Math.Max(0, item.Value))); + return cost; + } + + /// Largest amount in [0, max] whose EstimateCost fits (cost only grows with amount). + public static int MostAffordable(VendorView v, Listing item, int max, long money) + { + int lo = 0, hi = Math.Max(0, max); + while (lo < hi) + { + int mid = lo + (hi - lo + 1) / 2; + if (EstimateCost(v, item, mid) <= money) lo = mid; + else hi = mid - 1; + } + return lo; + } + + public static int SlotsFor(Listing item, int amount) + { + int max = Math.Max(1, item.MaxStackSize); + return (int)((amount + (long)max - 1) / max); + } + + /// UB PyrealsWillFitInMainPack: always leaves one main-pack slot free. + public static bool PyrealsFit(PackState p, double amount) + { + int stack = Math.Max(1, p.PyrealStackSize); + return p.FreeMainSlots - Math.Ceiling(amount / stack) > 0; + } + + // ── Safety (UB ItemIsSafeToGetRidOf + Util.IsItemSafeToGetRidOf, stricter) ────────── + + /// Null when the item may be sold; otherwise the reason it never will be. + public static string? UnsafeReason(SafetyFacts f, bool onlyFromMainPack) + { + if (!f.Appraised) return "not identified"; + if (f.Equipped) return "equipped"; + if (f.Class == AcObjectClass.Money) return "money"; + if (f.Class == AcObjectClass.Container || f.HoldsItems) return "container"; + if (f.Class == AcObjectClass.Foci) return "focus"; + if (f.Value <= 0) return "no value"; + if (f.CanBeSold == false) return "not sellable"; + if (f.IsRare) return "rare"; + if (onlyFromMainPack && !f.InMainPack) return "not in main pack"; + if (f.Attuned != 0) return "attuned"; + if (f.Bonded != 0) return "bonded"; + if (f.Retained) return "retained"; + if (f.TimesTinkered > 0) return "tinkered"; + if (f.Imbued != 0) return "imbued"; + if (!string.IsNullOrEmpty(f.Inscription)) return "inscribed"; + return null; + } + + /// + /// UB VendorInfo.WillBuyItem. Trade notes skip the value cap like UB, but the vendor must + /// still list the note item type: the engine refuses anything outside the vendor's types. + /// + public static bool VendorWillBuy(VendorView v, uint itemType, bool isNote, int unitValue) + { + if (!v.Buys(itemType)) return false; + if (isNote) return true; + return v.MaxValue > 0 && unitValue <= v.MaxValue; + } + + // ── Buy list (UB GetBuyItems) ──────────────────────────────────────────── + + /// + /// Keep # buys (count - have), where have is the inventory count by exact name (containers: + /// by object class, and only the first container rule). Keep buys int.MaxValue. Sorted + /// trade notes last, then cheapest unit price first. + /// + public static List BuildBuyWants( + VendorView v, + IEnumerable<(Listing Item, BuyDecision Decision)> judged, + Func countByName, + Func countByClass) + { + var list = judged.ToList(); + var wants = new List(); + bool buyingContainers = false; + + foreach (var (item, d) in list) + { + if (d.Kind != BuyKind.KeepUpTo) continue; + if (item.Class == AcObjectClass.Container) + { + int have = countByClass(AcObjectClass.Container); + if (!buyingContainers && d.KeepCount > have) + { + buyingContainers = true; + wants.Add(new BuyWant { Item = item, Amount = d.KeepCount - have, RuleName = d.RuleName }); + } + } + else + { + int have = countByName(item.Name); + if (d.KeepCount > have) + wants.Add(new BuyWant { Item = item, Amount = d.KeepCount - have, RuleName = d.RuleName }); + } + } + + foreach (var (item, d) in list) + if (d.Kind == BuyKind.Keep) + wants.Add(new BuyWant { Item = item, Amount = int.MaxValue, RuleName = d.RuleName }); + + return wants + .OrderBy(w => w.Item.IsNote ? 1 : 0) + .ThenBy(w => UnitPrice(v, w.Item)) + .ToList(); + } + + /// UB GetSellItems sort: trade notes last, then cheapest stack payout first. + public static List SortSells(VendorView v, IEnumerable items) => + items.OrderBy(s => s.IsNote ? 1 : 0) + .ThenBy(s => VendorPays(v, s.IsNote, s.Value)) + .ToList(); + + // ── One transaction (UB DoVendoring) ───────────────────────────────────── + + /// From BuildBuyWants (already sorted). + /// From SortSells. + public static VendorPlan PlanNext(VendorView v, IReadOnlyList wants, IReadOnlyList sells, PackState p) + { + // ── Buy first ── + var buys = new List(); + long totalCost = 0; + int totalSlots = 0, totalContainerSlots = 0; + + // UB re-orders by the listing's raw Value here (a stable sort over the price order). + foreach (var want in wants.OrderBy(w => w.Item.Value)) + { + Listing item = want.Item; + long price = UnitPrice(v, item); + if (price <= 0) + return VendorPlan.Fatal(string.Format(CultureInfo.InvariantCulture, + "AutoVendor Fatal - No vendor price found while adding {0:n0}x {1}[0x{2:X8}] Value: {3:n}", + want.Amount, item.Name, item.Id, (double)price)); + + bool fits; + if (item.NeedsContainerSlot) + fits = p.FreeContainerSlots - totalContainerSlots > 0; + else + fits = p.FreeMainSlots - totalSlots > (item.IsNote ? 0 : 1); + + if (totalCost + price <= p.Funds && fits) + { + long affordable = (p.Funds - totalCost) / price; + long count = Math.Min(affordable, want.Amount); + count = Math.Min(count, MaxVendorBuyCount); + if (!item.Unlimited) count = Math.Min(count, item.Amount); + + if (item.NeedsContainerSlot) + { + count = Math.Min(count, p.FreeContainerSlots - totalContainerSlots); + } + else if (p.FreeMainSlots < SlotsFor(item, (int)count) + totalSlots) + { + // UB: limit to what fits, keeping two slots spare (never below zero). + long fit = (long)Math.Max(1, item.MaxStackSize) * Math.Max(0, (p.FreeMainSlots - 2) - totalSlots); + count = Math.Min(count, fit); + } + + // The engine's exact cost can exceed the per-unit estimate (a limited listing + // costs at least the whole listing): take the most that still fits the money. + if (count > 0 && totalCost + EstimateCost(v, item, (int)count) > p.Funds) + count = MostAffordable(v, item, (int)count, p.Funds - totalCost); + if (count <= 0) + break; + + int n = (int)count; + buys.Add(new BuyLine(item, n)); + if (item.NeedsContainerSlot) totalContainerSlots += n; + else totalSlots += SlotsFor(item, n); + totalCost += EstimateCost(v, item, n); + + if (want.Amount > n) + break; // couldn't take all of it: don't reach for the next item + } + else if (buys.Count > 0) + { + break; + } + } + + if (buys.Count > 0) + return new VendorPlan { Kind = PlanKind.Buy, Buys = buys, Total = totalCost }; + + // ── Then sell ── + // nextBuy: the item we want but couldn't afford (notes are sold only to pay for it). + // An alt-currency vendor isn't paid in pyreals, so selling can't fund its items. + Listing? nextBuy = !v.UsesAltCurrency && wants.Count > 0 ? wants[0].Item : null; + + var chosen = new List(); + long totalValue = 0; + for (int i = 0; i < sells.Count && chosen.Count < MaxSellLines; i++) + { + SellItem item = sells[i]; + int stack = Math.Max(1, item.StackSize); + long stackPayout = VendorPays(v, item.IsNote, item.Value); + double unit = (double)stackPayout / stack; + + // Never sell notes to buy notes, and never sell notes when there's nothing to buy. + if (item.IsNote && (nextBuy == null || nextBuy.IsNote)) + break; + + // Selling notes to afford something: one note at a time, and only on its own. + if (nextBuy != null && item.IsNote) + { + if (chosen.Count > 0) break; + if (!PyrealsFit(p, unit)) + return VendorPlan.Fatal($"AutoVendor Fatal - No inventory room to sell {item.Name}"); + + SellItem? single = null; + foreach (var s in sells) + if (s.IsNote && s.StackSize <= 1 && string.Equals(s.Name, item.Name, StringComparison.Ordinal)) + { single = s; break; } + if (single != null) + return new VendorPlan { Kind = PlanKind.Sell, Sells = new List { single }, Total = VendorPays(v, true, single.Value) }; + + return VendorPlan.Split(item, 1, $"one {item.Name} to afford {nextBuy.Name}"); + } + + // Can't sell the whole stack? Split off what the pyreals will fit. + if (!PyrealsFit(p, totalValue + stackPayout)) + { + if (chosen.Count < 1) + { + int newStack = unit > 0 ? (int)Math.Floor((p.FreeMainSlots - 2) * (double)Math.Max(1, p.PyrealStackSize) / unit) : 0; + newStack = Math.Min(newStack, stack - 1); + if (newStack > 0) + return VendorPlan.Split(item, newStack, "the pyreals for the whole stack won't fit"); + return VendorPlan.Fatal($"AutoVendor Fatal - No inventory room to sell {item.Name}"); + } + break; + } + + chosen.Add(item); + totalValue += stackPayout; + } + + if (chosen.Count > 0) + return new VendorPlan { Kind = PlanKind.Sell, Sells = chosen, Total = totalValue }; + + return VendorPlan.Done(); + } + + // ── /ub vendor addsell (UB AddItemToSellList) ──────────────────────────── + + /// + /// Whole stacks that fit in the remaining count are taken; if units are still missing, + /// the smallest stack bigger than what's missing is returned to be split. + /// + public static (List Whole, int Missing, SellItem? SplitFrom) PlanAddSell(IReadOnlyList matches, int count) + { + var whole = new List(); + int needed = Math.Max(0, count); + SellItem? oversized = null; + foreach (var m in matches) + { + if (needed == 0) break; + int stack = Math.Max(1, m.StackSize); + if (stack <= needed) + { + whole.Add(m); + needed -= stack; + } + else if (oversized == null || oversized.StackSize > stack) + { + oversized = m; + } + } + return (whole, needed, needed > 0 ? oversized : null); + } + + // ── Shared parsing ─────────────────────────────────────────────────────── + + /// "[count] name" as UB's addbuy/addsell read it; count defaults to 1. + public static (int Count, string Name) ParseCountAndName(string args) + { + string s = (args ?? string.Empty).Trim(); + int sp = s.IndexOf(' '); + if (sp > 0 && int.TryParse(s.Substring(0, sp), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) + return (n, s.Substring(sp + 1).Trim()); + return (1, s); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorRules.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorRules.cs new file mode 100644 index 0000000..ecee31c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorRules.cs @@ -0,0 +1,318 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using RynthCore.Loot; +using RynthCore.Loot.VTank; + +namespace RynthCore.Plugin.RynthAi.Vendor; + +// Pure rule judging for AutoVendor: no host, no WorldObject. The manager hands in a +// per-condition matcher (VTankLootEvaluator.MatchCondition) and the facts it has about +// the item; this file decides which conditions can be answered with that data and turns +// the answers into a profile verdict. Kept dependency-free so the test project can link it. +// +// Selling is destructive, so every answer is three-valued: Yes, No, or Unknown ("we don't +// have the data VTank would use"). A rule with an Unknown condition never counts as a +// match. UB leans on VTank's own evaluator; ours has approximations (buffed damage, colour +// similarity, base skill), and those node types always read Unknown here. + +internal enum Tri : byte +{ + No = 0, + Yes = 1, + Unknown = 2, +} + +/// What the manager knows about an item before judging it. +internal readonly struct ItemFacts +{ + /// An item on the vendor's list: only the engine's vendor snapshot is known. + public bool IsVendorListing { get; init; } + /// Inventory item with appraisal (ID) data. + public bool Appraised { get; init; } + public AcObjectClass ObjectClass { get; init; } + /// The item's spell list can be read (appraised and the host exposes spell ids). + public bool HasSpellData { get; init; } + public bool HasPalettes { get; init; } + public bool HasCharacterSkills { get; init; } + public bool HasCharacterLevel { get; init; } +} + +/// The profile's answer for one item. +internal sealed class ProfileVerdict +{ + /// First rule that matched (Certain) or might match (!Certain); null = no rule can match. + public VTankLootRule? Rule { get; init; } + public int RuleIndex { get; init; } = -1; + /// True when Rule definitely matched, or when no rule can match at all. + public bool Certain { get; init; } + /// Some Keep / Keep # rule anywhere in the profile matches or might match. + public bool KeepPossible { get; init; } + /// Name of a Keep / Keep # rule that matches or might match (for messages). + public string KeepRuleName { get; init; } = string.Empty; + /// Why the deciding rule could not be judged (node type name), when !Certain. + public string UnknownReason { get; init; } = string.Empty; + + public string RuleName => Rule == null ? string.Empty : AutoVendorRules.RuleLabel(Rule, RuleIndex); +} + +internal enum BuyKind : byte +{ + None = 0, + /// Keep: buy as many as you can afford. + Keep = 1, + /// Keep #: buy up to the rule's count. + KeepUpTo = 2, +} + +internal readonly record struct BuyDecision(BuyKind Kind, int KeepCount, string RuleName); + +internal readonly record struct SellDecision(bool Sell, string RuleName, string Reason); + +internal static class AutoVendorRules +{ + // STypeInt keys a vendor listing carries (engine VendorItem: ItemType, Burden, + // MaxStackSize, StackSize, Value). Anything else on a listing is unknown. + internal static readonly HashSet ListingIntKeys = new() { 1, 5, 11, 12, 19 }; + + // Keys the client keeps in PublicWeenieDesc, readable without appraisal + // (items/containers capacity, locations, wielded location, stack sizes, material). + internal static readonly HashSet PwdIntKeys = new() { 6, 7, 9, 10, 11, 12, 131 }; + + // Decal's synthetic LongValueKey ids start at 0x0D000000; RynthAi reads STypes only. + internal const int MaxStandardKey = 0xFFFF; + + // RynthAi derives ObjectClass from ITEM_TYPE alone. Decal splits these further + // (Misc -> HealingKit/Lockpick, Book -> Scroll/Journal/Sign, Container -> Foci, + // Key -> Lockpick, Food -> Plant), so an ObjectClass test on them is unknown. + internal static readonly HashSet CoarseClasses = new() + { + AcObjectClass.Unknown, AcObjectClass.Misc, AcObjectClass.Book, + AcObjectClass.Container, AcObjectClass.Food, AcObjectClass.Key, + }; + + public static string RuleLabel(VTankLootRule rule, int index) + => string.IsNullOrWhiteSpace(rule.Name) ? $"#{index}" : rule.Name.Trim(); + + /// Can this condition be answered for an item with these facts? + public static bool CanJudge(VTankLootCondition cond, in ItemFacts f) + { + var d = cond.DataLines; + switch (cond.NodeType) + { + case VTankNodeTypes.DisabledRule: + case VTankNodeTypes.DamagePercentGE: // VTank itself always answers "no" + case VTankNodeTypes.ObjectClass: // coarse classes handled in JudgeObjectClass + return true; + + case VTankNodeTypes.CharacterMainPackEmptySlotsGE: + return true; + case VTankNodeTypes.CharacterSkillGE: + return f.HasCharacterSkills; + case VTankNodeTypes.CharacterLevelGE: + case VTankNodeTypes.CharacterLevelLE: + return f.HasCharacterLevel; + + case VTankNodeTypes.StringValueMatch: + { + if (!TryKey(d, 1, out int key)) return false; + if (key == 1) return true; // Name + return !f.IsVendorListing && f.Appraised && key <= MaxStandardKey; + } + + case VTankNodeTypes.LongValKeyLE: + case VTankNodeTypes.LongValKeyGE: + case VTankNodeTypes.LongValKeyE: + case VTankNodeTypes.LongValKeyNE: + case VTankNodeTypes.LongValKeyFlagExists: + { + if (!TryKey(d, 1, out int key) || key < 0 || key > MaxStandardKey) return false; + if (f.IsVendorListing) return ListingIntKeys.Contains(key); + return f.Appraised || PwdIntKeys.Contains(key); + } + + case VTankNodeTypes.DoubleValKeyLE: + case VTankNodeTypes.DoubleValKeyGE: + { + if (!TryKey(d, 1, out int key) || key < 0 || key > MaxStandardKey) return false; + return !f.IsVendorListing && f.Appraised; + } + + case VTankNodeTypes.SpellNameMatch: + case VTankNodeTypes.SpellMatch: + case VTankNodeTypes.SpellCountGE: + return !f.IsVendorListing && f.HasSpellData; + + case VTankNodeTypes.SlotExactPalette: + return !f.IsVendorListing && f.HasPalettes; + + case VTankNodeTypes.TotalRatingsGE: + return !f.IsVendorListing && f.Appraised; + + // Approximated or not implemented by RynthAi's evaluator: never trusted. + case VTankNodeTypes.AnySimilarColor: + case VTankNodeTypes.SimilarColorArmorType: + case VTankNodeTypes.SlotSimilarColor: + case VTankNodeTypes.CharacterBaseSkill: + case VTankNodeTypes.MinDamageGE: + case VTankNodeTypes.BuffedMedianDamageGE: + case VTankNodeTypes.BuffedMissileDamageGE: + case VTankNodeTypes.BuffedLongValKeyGE: + case VTankNodeTypes.BuffedDoubleValKeyGE: + case VTankNodeTypes.CalcdBuffedTinkedDamageGE: + case VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE: + default: + return false; + } + } + + /// ObjectClass test without the evaluator: unknown for classes Decal splits further. + public static Tri JudgeObjectClass(VTankLootCondition cond, AcObjectClass itemClass) + { + if (!TryKey(cond.DataLines, 0, out int target)) return Tri.Unknown; + if (CoarseClasses.Contains(itemClass)) return Tri.Unknown; + return (int)itemClass == target ? Tri.Yes : Tri.No; + } + + /// + /// Judge one condition. is only called for conditions that + /// CanJudge says are answerable; if it throws (malformed data line) the answer is Unknown. + /// + public static Tri JudgeCondition(VTankLootCondition cond, in ItemFacts f, Func match) + { + if (!CanJudge(cond, f)) return Tri.Unknown; + if (cond.NodeType == VTankNodeTypes.ObjectClass) return JudgeObjectClass(cond, f.ObjectClass); + try { return match(cond) ? Tri.Yes : Tri.No; } + catch { return Tri.Unknown; } + } + + /// All conditions must hold: any No -> No, else any Unknown -> Unknown, else Yes. + public static Tri JudgeRule(VTankLootRule rule, Func cond, out string unknownReason) + { + unknownReason = string.Empty; + if (rule.Conditions.Count == 0) return Tri.Yes; + bool unknown = false; + foreach (var c in rule.Conditions) + { + Tri t = cond(c); + if (t == Tri.No) { unknownReason = string.Empty; return Tri.No; } + if (t == Tri.Unknown && !unknown) + { + unknown = true; + unknownReason = VTankNodeTypes.DisplayName(c.NodeType); + } + } + return unknown ? Tri.Unknown : Tri.Yes; + } + + /// + /// VTank order: the first rule that matches decides. A rule that might match stops the + /// scan too (we can't know whether it or a later rule applies). Also records whether + /// any Keep / Keep # rule anywhere could match, which AutoVendor treats as "never sell". + /// + public static ProfileVerdict Decide(IReadOnlyList rules, Func cond) + { + VTankLootRule? decided = null; + int decidedIdx = -1; + bool certain = true; + string reason = string.Empty; + bool keepPossible = false; + string keepName = string.Empty; + + for (int i = 0; i < rules.Count; i++) + { + var rule = rules[i]; + bool isKeep = rule.Action is VTankLootAction.Keep or VTankLootAction.KeepUpTo; + if (decided != null && (!isKeep || keepPossible)) + continue; // only still scanning for keep rules + + Tri t = JudgeRule(rule, cond, out string why); + if (t == Tri.No) continue; + + if (isKeep && !keepPossible) + { + keepPossible = true; + keepName = RuleLabel(rule, i); + } + if (decided == null) + { + decided = rule; + decidedIdx = i; + certain = t == Tri.Yes; + reason = why; + } + } + + return new ProfileVerdict + { + Rule = decided, + RuleIndex = decidedIdx, + Certain = decided == null || certain, + UnknownReason = reason, + KeepPossible = keepPossible, + KeepRuleName = keepName, + }; + } + + /// + /// UB GetBuyItems for one vendor listing: Keep # buys up to the count, Keep buys all it + /// can afford. First match decides, as in VTank. A rule we can't judge (a listing carries + /// only name, type, value, stack and burden) is handled so we never buy more than VTank would: + /// an unjudgeable non-buy rule ends the scan with no purchase (it might be the one that + /// matches); an unjudgeable Keep / Keep # rule lets the scan go on, since either way the + /// item gets bought, and the smallest count seen is used. + /// + public static BuyDecision DecideBuy(IReadOnlyList rules, Func cond) + { + long cap = long.MaxValue; + for (int i = 0; i < rules.Count; i++) + { + var rule = rules[i]; + Tri t = JudgeRule(rule, cond, out _); + if (t == Tri.No) continue; + + long count = rule.Action switch + { + VTankLootAction.KeepUpTo => Math.Max(0, rule.KeepCount ?? 0), + VTankLootAction.Keep => int.MaxValue, + _ => -1, + }; + if (count < 0) + return new BuyDecision(BuyKind.None, 0, RuleLabel(rule, i)); // a non-buy rule matches or might + + cap = Math.Min(cap, count); + if (t == Tri.Yes) + { + int n = (int)Math.Min(cap, int.MaxValue); + return n == int.MaxValue + ? new BuyDecision(BuyKind.Keep, int.MaxValue, RuleLabel(rule, i)) + : new BuyDecision(BuyKind.KeepUpTo, n, RuleLabel(rule, i)); + } + } + return new BuyDecision(BuyKind.None, 0, string.Empty); + } + + /// + /// UB GetSellItems (result.IsSell), stricter: the deciding rule must be a Sell rule that + /// definitely matched, and no Keep / Keep # rule anywhere in the profile may match or + /// possibly match the item. + /// + public static SellDecision JudgeSell(ProfileVerdict v) + { + if (v.Rule == null) return new SellDecision(false, string.Empty, "no rule matches"); + if (v.Rule.Action != VTankLootAction.Sell) + return new SellDecision(false, v.RuleName, $"first rule is {v.Rule.Action}"); + if (!v.Certain) + return new SellDecision(false, v.RuleName, $"rule '{v.RuleName}' needs {v.UnknownReason} data we don't have"); + if (v.KeepPossible) + return new SellDecision(false, v.RuleName, $"also matches keep rule '{v.KeepRuleName}'"); + return new SellDecision(true, v.RuleName, string.Empty); + } + + private static bool TryKey(IList d, int idx, out int value) + { + value = 0; + return d != null && idx < d.Count + && int.TryParse(d[idx].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out value); + } +} diff --git a/Tools/RynthCore.AutoVendorTests/Program.cs b/Tools/RynthCore.AutoVendorTests/Program.cs new file mode 100644 index 0000000..f572224 --- /dev/null +++ b/Tools/RynthCore.AutoVendorTests/Program.cs @@ -0,0 +1,541 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; +using RynthCore.Loot; +using RynthCore.Loot.VTank; +using RynthCore.Plugin.RynthAi.Vendor; + +namespace RynthCore.AutoVendorTests; + +// Tests for AutoVendor's pure logic: three-valued rule judging, UB's buy-up-to-N math, +// one-transaction planning (buy first, sell second, notes, pyreal room, splits) and the +// "never sell" checks. Self-contained fixtures only; fails on zero assertions. +// +// Run: dotnet run -c Release (exit 0 = pass, 1 = fail) +internal static class Program +{ + private static int _asserts; + private static int _fails; + + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + + private static void Eq(T actual, T expected, string msg) + { + _asserts++; + if (!EqualityComparer.Default.Equals(actual, expected)) + { _fails++; Console.WriteLine($" [FAIL] {msg}: expected <{expected}>, got <{actual}>"); } + } + + private static int Main() + { + Console.WriteLine("=== AutoVendor tests ==="); + TestJudgeRule(); + TestCanJudge(); + TestObjectClass(); + TestDecideAndSell(); + TestDecideFromUtl(); + TestJudgeBuy(); + TestBuildBuyWants(); + TestPlanBuy(); + TestPlanSell(); + TestPlanNotes(); + TestPrices(); + TestSafety(); + TestVendorWillBuy(); + TestAddSell(); + TestParse(); + + Console.WriteLine($"\n{_asserts} assertions, {_fails} failed."); + if (_asserts == 0) { Console.WriteLine("ABORT: zero assertions ran."); return 1; } + Console.WriteLine(_fails == 0 ? "ALL AUTOVENDOR TESTS PASSED." : $"{_fails} FAILURE(S)."); + return _fails == 0 ? 0 : 1; + } + + // ── helpers ──────────────────────────────────────────────────────────── + + private static VTankLootCondition Cond(int type, params string[] data) => new(type, "0", data); + + private static VTankLootRule Rule(string name, VTankLootAction action, int? keep, params VTankLootCondition[] conds) + => new() { Name = name, Action = action, KeepCount = keep, Conditions = conds.ToList() }; + + private static Func Fixed(params Tri[] answers) + { + int i = 0; + return _ => answers[i++ % answers.Length]; + } + + /// A stand-in for VTankLootEvaluator: name regex (key 1), long equality, disabled flag. + private static bool FakeMatch(VTankLootCondition c, string name, Dictionary ints) + { + var d = c.DataLines; + return c.NodeType switch + { + VTankNodeTypes.StringValueMatch => Regex.IsMatch(name, d[0], RegexOptions.IgnoreCase), + VTankNodeTypes.LongValKeyE => ints.TryGetValue(int.Parse(d[1], CultureInfo.InvariantCulture), out int v) + && v == int.Parse(d[0], CultureInfo.InvariantCulture), + VTankNodeTypes.DisabledRule => !string.Equals(d[0].Trim(), "true", StringComparison.OrdinalIgnoreCase), + _ => throw new InvalidOperationException("fake matcher: unsupported node"), + }; + } + + private static Func JudgeFake(ItemFacts f, string name, Dictionary? ints = null) + { + ints ??= new Dictionary(); + return c => AutoVendorRules.JudgeCondition(c, f, cc => FakeMatch(cc, name, ints)); + } + + private static readonly ItemFacts AppraisedSalvage = new() { Appraised = true, ObjectClass = AcObjectClass.Salvage, HasCharacterSkills = true, HasCharacterLevel = true }; + private static readonly ItemFacts ListingComp = new() { IsVendorListing = true, ObjectClass = AcObjectClass.SpellComponent, HasCharacterSkills = true, HasCharacterLevel = true }; + + private static VendorView Vendor(float buy = 0.5f, float sell = 1.5f, uint types = 0xFFFFFFFF, int maxValue = 50000, bool alt = false) + => new() { Id = 1, Name = "Test Vendor", BuyRate = buy, SellRate = sell, ItemTypes = types, MaxValue = maxValue, UsesAltCurrency = alt }; + + private static Listing L(uint id, string name, int unitPrice, int value = 10, int maxStack = 1, int amount = -1, + AcObjectClass cls = AcObjectClass.SpellComponent, uint type = 0x1000, bool packSlot = false) + => new() { Id = id, Name = name, UnitPrice = unitPrice, Value = value, MaxStackSize = maxStack, Amount = amount, Class = cls, ItemType = type, NeedsContainerSlot = packSlot }; + + private static SellItem S(uint id, string name, int value, int stack = 1, AcObjectClass cls = AcObjectClass.Salvage, uint type = 0x40000000) + => new() { Id = id, Name = name, Value = value, StackSize = stack, Class = cls, ItemType = type, RuleName = "S" }; + + private static PackState Pack(long funds, int free = 50, int freePacks = 2, int pyrealStack = 25000) + => new() { Funds = funds, FreeMainSlots = free, FreeContainerSlots = freePacks, PyrealStackSize = pyrealStack }; + + // ── rules ────────────────────────────────────────────────────────────── + + private static void TestJudgeRule() + { + Console.WriteLine("\n-- JudgeRule --"); + var r2 = Rule("r", VTankLootAction.Sell, null, Cond(1, "x", "1"), Cond(1, "y", "1")); + Eq(AutoVendorRules.JudgeRule(r2, Fixed(Tri.Yes, Tri.Yes), out _), Tri.Yes, "yes+yes"); + Eq(AutoVendorRules.JudgeRule(r2, Fixed(Tri.Yes, Tri.Unknown), out string why), Tri.Unknown, "yes+unknown"); + Eq(why, VTankNodeTypes.DisplayName(1), "unknown reason names the node type"); + Eq(AutoVendorRules.JudgeRule(r2, Fixed(Tri.Unknown, Tri.No), out _), Tri.No, "unknown+no = no (AND)"); + Eq(AutoVendorRules.JudgeRule(Rule("empty", VTankLootAction.Sell, null), Fixed(Tri.No), out _), Tri.Yes, "no conditions = unconditional"); + } + + private static void TestCanJudge() + { + Console.WriteLine("\n-- CanJudge --"); + Check(AutoVendorRules.CanJudge(Cond(1, "Taper", "1"), ListingComp), "listing: name match"); + Check(!AutoVendorRules.CanJudge(Cond(1, "x", "16"), ListingComp), "listing: other string key unknown"); + Check(AutoVendorRules.CanJudge(Cond(12, "250000", "19"), ListingComp), "listing: Value"); + Check(AutoVendorRules.CanJudge(Cond(3, "5", "12"), ListingComp), "listing: StackSize"); + Check(!AutoVendorRules.CanJudge(Cond(12, "6", "131"), ListingComp), "listing: Material unknown"); + Check(!AutoVendorRules.CanJudge(Cond(0, "Blood"), ListingComp), "listing: spell name unknown"); + Check(!AutoVendorRules.CanJudge(Cond(5, "0.5", "22"), ListingComp), "listing: double unknown"); + + Check(AutoVendorRules.CanJudge(Cond(12, "6", "131"), AppraisedSalvage), "appraised: Material"); + Check(!AutoVendorRules.CanJudge(Cond(12, "6", "218103842"), AppraisedSalvage), "Decal synthetic key unknown"); + Check(!AutoVendorRules.CanJudge(Cond(0, "Blood"), AppraisedSalvage), "spells need spell data"); + Check(AutoVendorRules.CanJudge(Cond(0, "Blood"), AppraisedSalvage with { HasSpellData = true }), "spells with data"); + + var unappraised = AppraisedSalvage with { Appraised = false }; + Check(!AutoVendorRules.CanJudge(Cond(12, "250", "19"), unappraised), "unappraised: Value unknown"); + Check(AutoVendorRules.CanJudge(Cond(12, "6", "131"), unappraised), "unappraised: Material is in PWD"); + Check(AutoVendorRules.CanJudge(Cond(1, "x", "1"), unappraised), "unappraised: name"); + + foreach (int t in new[] { 10, 14, 15, 16, 1004, 2000, 2001, 2003, 2005, 2006, 2008, 424242 }) + Check(!AutoVendorRules.CanJudge(Cond(t, "0", "0", "0", "0", "0", "0"), AppraisedSalvage with { HasSpellData = true, HasPalettes = true }), $"approximated/unknown node {t} never judged"); + + Check(!AutoVendorRules.CanJudge(Cond(1000, "200", "39"), AppraisedSalvage with { HasCharacterSkills = false }), "skill needs skill reads"); + Check(AutoVendorRules.CanJudge(Cond(9999, "false"), ListingComp), "disabled flag"); + + // A matcher that throws (malformed line) reads as Unknown, not No. + Eq(AutoVendorRules.JudgeCondition(Cond(1, "x", "1"), ListingComp, _ => throw new FormatException()), Tri.Unknown, "throwing matcher = unknown"); + Eq(AutoVendorRules.JudgeCondition(Cond(12, "abc", "notakey"), AppraisedSalvage, _ => true), Tri.Unknown, "unparseable key = unknown"); + } + + private static void TestObjectClass() + { + Console.WriteLine("\n-- ObjectClass --"); + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "39"), AcObjectClass.Salvage), Tri.Yes, "salvage = salvage"); + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "12"), AcObjectClass.Salvage), Tri.No, "salvage != comps"); + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "29"), AcObjectClass.Misc), Tri.Unknown, "Misc may be a healing kit"); + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "8"), AcObjectClass.Misc), Tri.Unknown, "Misc vs Misc still unknown"); + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "42"), AcObjectClass.Book), Tri.Unknown, "Book may be a scroll"); + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "38"), AcObjectClass.Container), Tri.Unknown, "Container may be a focus"); + Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "15"), AcObjectClass.TradeNote), Tri.Yes, "trade note"); + } + + private static void TestDecideAndSell() + { + Console.WriteLine("\n-- Decide / JudgeSell --"); + var keepGranite = Rule("K: Granite", VTankLootAction.Keep, null, Cond(12, "67", "131")); + var sellSalvage = Rule("S: Salvage", VTankLootAction.Sell, null, Cond(1, "Salvage", "1")); + var rules = new List { keepGranite, sellSalvage }; + + var granite = new Dictionary { [131] = 67 }; + var steel = new Dictionary { [131] = 64 }; + + var v1 = AutoVendorRules.Decide(rules, JudgeFake(AppraisedSalvage, "Salvage (100)", granite)); + Eq(v1.Rule?.Name, "K: Granite", "granite: keep rule decides"); + Check(!AutoVendorRules.JudgeSell(v1).Sell, "granite not sold"); + + var v2 = AutoVendorRules.Decide(rules, JudgeFake(AppraisedSalvage, "Salvage (100)", steel)); + Eq(v2.Rule?.Name, "S: Salvage", "steel: sell rule decides"); + Check(v2.Certain && !v2.KeepPossible, "steel: certain, no keep"); + Check(AutoVendorRules.JudgeSell(v2).Sell, "steel sold"); + + // Sell rule first, keep rule later: UB (first match) would sell; we don't. + var sellFirst = new List { sellSalvage, keepGranite }; + var v3 = AutoVendorRules.Decide(sellFirst, JudgeFake(AppraisedSalvage, "Salvage (100)", granite)); + Eq(v3.Rule?.Name, "S: Salvage", "sell-first: sell rule decides"); + Check(v3.KeepPossible, "sell-first: later keep rule noticed"); + var sd3 = AutoVendorRules.JudgeSell(v3); + Check(!sd3.Sell && sd3.Reason.Contains("K: Granite"), "sell-first: held back by keep rule"); + + // A keep rule we can't judge also blocks selling. + var keepBuffed = Rule("K: Good weapons", VTankLootAction.Keep, null, Cond(2003, "50", "160")); + var v4 = AutoVendorRules.Decide(new List { keepBuffed, sellSalvage }, JudgeFake(AppraisedSalvage, "Salvage (100)", steel)); + Check(v4.Rule == keepBuffed && !v4.Certain, "unjudgeable keep rule stops the scan"); + Check(!AutoVendorRules.JudgeSell(v4).Sell, "not sold behind an unjudgeable keep rule"); + + // A sell rule we can't judge never sells. + var sellBuffed = Rule("S: Weak weapons", VTankLootAction.Sell, null, Cond(2003, "10", "160")); + var v5 = AutoVendorRules.Decide(new List { sellBuffed }, JudgeFake(AppraisedSalvage, "Sword", steel)); + Check(!v5.Certain && !AutoVendorRules.JudgeSell(v5).Sell, "unjudgeable sell rule never sells"); + + // Disabled rules are skipped. + var disabledKeep = Rule("K: off", VTankLootAction.Keep, null, Cond(1, "Salvage", "1"), Cond(9999, "true")); + var v6 = AutoVendorRules.Decide(new List { disabledKeep, sellSalvage }, JudgeFake(AppraisedSalvage, "Salvage (100)", steel)); + Check(AutoVendorRules.JudgeSell(v6).Sell, "disabled keep rule doesn't protect"); + + var none = AutoVendorRules.Decide(rules, JudgeFake(AppraisedSalvage, "Sword", steel)); + Check(none.Rule == null && none.Certain, "no rule matches"); + Check(!AutoVendorRules.JudgeSell(none).Sell, "unmatched not sold"); + } + + private const string FixtureUtl = + "UTL\n1\n5\n" + + "K: Granite\n\n0;1;12\n9\n67\n131\n" + + "Taper stock\n\n0;10;7;1\n100\n4\n12\n20\nPrismatic Taper\n1\n" + + "S: Salvage\n\n0;3;7\n4\n39\n" + + "S: Peas\n\n0;3;1\n19\nLead Pea|Copper Pea\n1\n" + + "S: Buffed\n\n0;3;2003\n3\n50\n160\n"; + + private static void TestDecideFromUtl() + { + Console.WriteLine("\n-- Decide from a parsed .utl --"); + var profile = VTankLootParser.LoadFromText(FixtureUtl); + Eq(profile.Rules.Count, 5, "rule count"); + Eq(profile.Rules[1].Action, VTankLootAction.KeepUpTo, "keep # action"); + Eq(profile.Rules[1].KeepCount, 100, "keep # count"); + + // "K: Granite" (Material) can't be judged on a listing, but it's a keep rule: either + // way the taper is bought, at the taper rule's count. + var buy = AutoVendorRules.DecideBuy(profile.Rules, JudgeFake(ListingComp, "Prismatic Taper")); + Eq(buy.Kind, BuyKind.KeepUpTo, "taper listing: keep #"); + Eq(buy.KeepCount, 100, "taper listing: count"); + Eq(buy.RuleName, "Taper stock", "taper listing: rule"); + var peaListing = AutoVendorRules.DecideBuy(profile.Rules, JudgeFake(ListingComp, "Lead Pea")); + Eq(peaListing.Kind, BuyKind.None, "pea listing: a sell rule, not bought"); + + var pea = AutoVendorRules.Decide(profile.Rules, JudgeFake(ListingComp with { IsVendorListing = false, Appraised = true }, "Copper Pea")); + Check(AutoVendorRules.JudgeSell(pea).Sell, "copper pea sold"); + + var sword = AutoVendorRules.Decide(profile.Rules, JudgeFake(AppraisedSalvage with { ObjectClass = AcObjectClass.MeleeWeapon }, "Sword")); + Eq(sword.Rule?.Name, "S: Buffed", "sword falls to the buffed rule"); + Check(!sword.Certain && !AutoVendorRules.JudgeSell(sword).Sell, "buffed rule unjudged: sword kept"); + } + + private static void TestJudgeBuy() + { + Console.WriteLine("\n-- JudgeBuy --"); + var keepAll = Rule("B: notes", VTankLootAction.Keep, null); + var all = AutoVendorRules.DecideBuy(new List { keepAll }, Fixed(Tri.Yes)); + Eq(all.Kind, BuyKind.Keep, "keep = buy all"); + Eq(all.KeepCount, int.MaxValue, "keep amount"); + + var keep5 = Rule("u", VTankLootAction.KeepUpTo, 5, Cond(0, "x")); + Eq(AutoVendorRules.DecideBuy(new List { keep5 }, Fixed(Tri.Unknown)).Kind, BuyKind.None, "only an unjudgeable rule: not bought"); + + var sell = Rule("s", VTankLootAction.Sell, null, Cond(0, "x")); + Eq(AutoVendorRules.DecideBuy(new List { sell }, Fixed(Tri.Yes)).Kind, BuyKind.None, "sell rule never buys"); + + // An unjudgeable SELL rule ahead of a keep rule might be the match: don't buy. + var keep100 = Rule("k100", VTankLootAction.KeepUpTo, 100, Cond(1, "x", "1")); + Eq(AutoVendorRules.DecideBuy(new List { sell, keep100 }, Fixed(Tri.Unknown, Tri.Yes)).Kind, BuyKind.None, "unjudgeable sell rule first: no buy"); + + // Unjudgeable keep rules ahead: buy, at the smallest count seen. + var r = AutoVendorRules.DecideBuy(new List { keep5, keep100 }, Fixed(Tri.Unknown, Tri.Yes)); + Eq(r.Kind, BuyKind.KeepUpTo, "unjudgeable keep # then keep #"); + Eq(r.KeepCount, 5, "smallest count"); + var keepAllIf = Rule("all?", VTankLootAction.Keep, null, Cond(0, "x")); + var r2 = AutoVendorRules.DecideBuy(new List { keepAllIf, keep100 }, Fixed(Tri.Unknown, Tri.Yes)); + Eq(r2.Kind, BuyKind.KeepUpTo, "unjudgeable keep-all then keep #: capped"); + Eq(r2.KeepCount, 100, "keep # count"); + } + + // ── buy-up-to-N ──────────────────────────────────────────────────────── + + private static void TestBuildBuyWants() + { + Console.WriteLine("\n-- BuildBuyWants --"); + var v = Vendor(); + var taper = L(10, "Prismatic Taper", 5); + var scarab = L(11, "Mana Scarab", 40); + var note = L(12, "Trade Note (250,000)", 287500, 250000, cls: AcObjectClass.TradeNote, type: 0x40000); + var packA = L(13, "Pack", 100, cls: AcObjectClass.Container, type: 0x200, packSlot: true); + var packB = L(14, "Bag", 50, cls: AcObjectClass.Container, type: 0x200, packSlot: true); + + var have = new Dictionary { ["Prismatic Taper"] = 250, ["Mana Scarab"] = 60 }; + var judged = new List<(Listing, BuyDecision)> + { + (note, new BuyDecision(BuyKind.Keep, int.MaxValue, "B: notes")), + (taper, new BuyDecision(BuyKind.KeepUpTo, 1000, "B: tapers")), + (scarab, new BuyDecision(BuyKind.KeepUpTo, 50, "B: scarabs")), // have 60 >= 50 + (packA, new BuyDecision(BuyKind.KeepUpTo, 3, "B: packs")), + (packB, new BuyDecision(BuyKind.KeepUpTo, 5, "B: bags")), // second container rule ignored + }; + var wants = AutoVendorPlanner.BuildBuyWants(v, judged, n => have.TryGetValue(n, out int c) ? c : 0, c => c == AcObjectClass.Container ? 2 : 0); + + Eq(wants.Count, 3, "tapers + one pack rule + notes"); + Eq(wants[0].Item.Name, "Prismatic Taper", "cheapest first"); + Eq(wants[0].Amount, 750, "keep # 1000 with 250 held = 750"); + Eq(wants[1].Item.Name, "Pack", "first container rule"); + Eq(wants[1].Amount, 1, "packs: 3 wanted, 2 containers held"); + Eq(wants[2].Item.Name, "Trade Note (250,000)", "notes last"); + Eq(wants[2].Amount, int.MaxValue, "keep = all"); + Check(!wants.Any(w => w.Item.Name == "Mana Scarab"), "scarabs already stocked"); + } + + private static void TestPlanBuy() + { + Console.WriteLine("\n-- PlanNext (buy) --"); + var v = Vendor(sell: 1.0f); + var taper = L(10, "Prismatic Taper", 10, value: 10, maxStack: 5000); + var want = new List { new() { Item = taper, Amount = 750, RuleName = "t" } }; + + var p1 = AutoVendorPlanner.PlanNext(v, want, new List(), Pack(100_000)); + Eq(p1.Kind, PlanKind.Buy, "buys"); + Eq(p1.Buys.Single().Amount, 750, "all 750 affordable"); + + var p2 = AutoVendorPlanner.PlanNext(v, want, new List(), Pack(1_005)); + Eq(p2.Buys.Single().Amount, 100, "funds limit: 1005 / 10 = 100"); + Check(p2.Total <= 1_005, "estimated cost within funds"); + + var big = new List { new() { Item = taper, Amount = int.MaxValue } }; + var p3 = AutoVendorPlanner.PlanNext(v, big, new List(), Pack(10_000_000)); + Eq(p3.Buys.Single().Amount, AutoVendorPlanner.MaxVendorBuyCount, "5000 per transaction"); + + var limited = L(20, "Rare Thing", 10, value: 10, amount: 3); + var p4 = AutoVendorPlanner.PlanNext(v, new List { new() { Item = limited, Amount = 10 } }, new List(), Pack(1_000)); + Eq(p4.Buys.Single().Amount, 3, "limited listing: only what the vendor has"); + + // Slots: 500 units, stacks of 100, 3 free main slots -> 100 * (3 - 2) = 100. + var arrows = L(30, "Arrow", 1, value: 1, maxStack: 100); + var p5 = AutoVendorPlanner.PlanNext(v, new List { new() { Item = arrows, Amount = 500 } }, new List(), Pack(1_000_000, free: 3)); + Eq(p5.Buys.Single().Amount, 100, "slot limit keeps two free"); + + var p6 = AutoVendorPlanner.PlanNext(v, new List { new() { Item = arrows, Amount = 5 } }, new List(), Pack(1_000_000, free: 1)); + Eq(p6.Kind, PlanKind.Done, "one free slot: nothing bought (UB keeps one free)"); + + // Partial buy stops the batch: the second item waits for the next transaction. + var a = L(40, "A", 10, value: 1); + var b = L(41, "B", 10, value: 2); + var p7 = AutoVendorPlanner.PlanNext(v, new List { new() { Item = a, Amount = 50 }, new() { Item = b, Amount = 5 } }, new List(), Pack(300)); + Eq(p7.Buys.Count, 1, "partial A ends the batch"); + Eq(p7.Buys[0].Amount, 30, "A limited by funds"); + + // An unaffordable first item is skipped while nothing is on the list. + var dear = L(50, "Dear", 1_000, value: 1); + var cheap = L(51, "Cheap", 10, value: 5); + var p8 = AutoVendorPlanner.PlanNext(v, new List { new() { Item = dear, Amount = 1 }, new() { Item = cheap, Amount = 2 } }, new List(), Pack(100)); + Eq(p8.Buys.Single().Item.Name, "Cheap", "skips the unaffordable item"); + + // Packs need a container slot, not a main-pack slot. + var pack = L(60, "Pack", 100, value: 50, cls: AcObjectClass.Container, type: 0x200, packSlot: true); + var p9 = AutoVendorPlanner.PlanNext(v, new List { new() { Item = pack, Amount = 5 } }, new List(), Pack(10_000, free: 0, freePacks: 2)); + Eq(p9.Buys.Single().Amount, 2, "packs limited by container slots"); + + var zero = L(70, "Broken", 0, value: 0); + var p10 = AutoVendorPlanner.PlanNext(v, new List { new() { Item = zero, Amount = 1 } }, new List(), Pack(100)); + Eq(p10.Kind, PlanKind.Fatal, "no price is fatal (UB)"); + Check(p10.Message.StartsWith("AutoVendor Fatal - No vendor price found", StringComparison.Ordinal), "UB fatal text"); + + // Buying comes before selling. + var p11 = AutoVendorPlanner.PlanNext(v, want, new List { S(1, "Salvage", 100) }, Pack(100_000)); + Eq(p11.Kind, PlanKind.Buy, "buy first"); + } + + private static void TestPlanSell() + { + Console.WriteLine("\n-- PlanNext (sell) --"); + var v = Vendor(buy: 1.0f); + var none = new List(); + + var sells = Enumerable.Range(1, 120).Select(i => S((uint)i, "Salvage", 100)).ToList(); + var p1 = AutoVendorPlanner.PlanNext(v, none, sells, Pack(0, free: 50)); + Eq(p1.Kind, PlanKind.Sell, "sells"); + Eq(p1.Sells.Count, AutoVendorPlanner.MaxSellLines, "99 items per transaction"); + + // Pyreal room: 3 free slots, 25000 per stack; a 100-unit stack worth 1000 each won't fit. + var p2 = AutoVendorPlanner.PlanNext(v, none, new List { S(1, "Gem", 100_000, stack: 100) }, Pack(0, free: 3)); + Eq(p2.Kind, PlanKind.Split, "split when the pyreals won't fit"); + Eq(p2.SplitAmount, 25, "(3 - 2) * 25000 / 1000 = 25"); + + var p3 = AutoVendorPlanner.PlanNext(v, none, new List { S(1, "Gem", 100_000, stack: 100) }, Pack(0, free: 2)); + Eq(p3.Kind, PlanKind.Fatal, "no room at all is fatal"); + Check(p3.Message.Contains("No inventory room to sell Gem"), "UB fatal text"); + + // Later items that won't fit wait for the next batch. + var p4 = AutoVendorPlanner.PlanNext(v, none, new List { S(1, "A", 20_000), S(2, "B", 20_000), S(3, "C", 20_000) }, Pack(0, free: 3)); + Eq(p4.Sells.Count, 2, "stop adding when the payout stops fitting"); + + var p5 = AutoVendorPlanner.PlanNext(v, none, new List(), Pack(0)); + Eq(p5.Kind, PlanKind.Done, "nothing to do"); + + // Payout estimate uses the vendor's buy rate (ACE floor(value * rate + 0.1)). + var half = Vendor(buy: 0.5f); + var p6 = AutoVendorPlanner.PlanNext(half, none, new List { S(1, "Salvage", 101) }, Pack(0)); + Eq(p6.Total, 50L, "floor(101 * 0.5 + 0.1)"); + } + + private static void TestPlanNotes() + { + Console.WriteLine("\n-- PlanNext (trade notes) --"); + var v = Vendor(buy: 0.5f); + SellItem Note(uint id, int stack) => S(id, "Trade Note (100)", 100 * stack, stack, AcObjectClass.TradeNote, 0x40000); + + var sorted = AutoVendorPlanner.SortSells(v, new[] { Note(1, 3), S(2, "Salvage", 5000) }); + Eq(sorted[0].Name, "Salvage", "notes sort last"); + + // Nothing to buy: notes are never sold. + var p1 = AutoVendorPlanner.PlanNext(v, new List(), new List { Note(1, 3) }, Pack(0)); + Eq(p1.Kind, PlanKind.Done, "notes kept when nothing to buy"); + + var dear = new List { new() { Item = L(10, "Pack", 500, value: 400), Amount = 1 } }; + // Want something unaffordable: split one note off a stack... + var p2 = AutoVendorPlanner.PlanNext(v, dear, new List { Note(1, 3) }, Pack(0)); + Eq(p2.Kind, PlanKind.Split, "split one note"); + Eq(p2.SplitAmount, 1, "one note"); + // ...or sell a single note already on its own. + var p3 = AutoVendorPlanner.PlanNext(v, dear, new List { Note(1, 3), Note(2, 1) }, Pack(0)); + Eq(p3.Kind, PlanKind.Sell, "sell the single note"); + Eq(p3.Sells.Single().Id, 2u, "the single one"); + Eq(p3.Total, 100L, "notes sell at face value"); + + // Other items go first; the note waits. + var p4 = AutoVendorPlanner.PlanNext(v, dear, new List { S(5, "Salvage", 100), Note(2, 1) }, Pack(0)); + Eq(p4.Sells.Single().Id, 5u, "regular items before notes"); + + // Never sell notes to buy notes. + var noteWant = new List { new() { Item = L(11, "Trade Note (250,000)", 287500, 250000, cls: AcObjectClass.TradeNote, type: 0x40000), Amount = int.MaxValue } }; + var p5 = AutoVendorPlanner.PlanNext(v, noteWant, new List { Note(2, 1) }, Pack(0)); + Eq(p5.Kind, PlanKind.Done, "no notes for notes"); + + // An alt-currency vendor isn't paid in pyreals: selling notes can't help. + var alt = Vendor(buy: 0.5f, alt: true); + var p6 = AutoVendorPlanner.PlanNext(alt, dear, new List { Note(2, 1) }, Pack(0)); + Eq(p6.Kind, PlanKind.Done, "alt currency: notes kept"); + } + + private static void TestPrices() + { + Console.WriteLine("\n-- prices --"); + var v = Vendor(buy: 0.5f, sell: 1.5f); + Eq(AutoVendorPlanner.PlayerPays(v, false, 10), 15L, "ceil(10 * 1.5 - 0.1)"); + Eq(AutoVendorPlanner.PlayerPays(v, true, 100), 115L, "notes cost 1.15x"); + Eq(AutoVendorPlanner.PlayerPays(v, false, 0), 1L, "at least 1"); + Eq(AutoVendorPlanner.VendorPays(v, false, 101), 50L, "floor(101 * 0.5 + 0.1)"); + Eq(AutoVendorPlanner.VendorPays(v, true, 250000), 250000L, "notes pay face value"); + + var one = Vendor(sell: 1.0f); + var stackable = L(1, "Arrow", 0, value: 10, maxStack: 100); + Eq(AutoVendorPlanner.EstimateCost(one, stackable, 250), 2500L, "2 full stacks + a partial"); + var limited = L(2, "Whole Lot", 0, value: 500, amount: 5); + Eq(AutoVendorPlanner.EstimateCost(one, limited, 1), 500L, "limited listing costs at least the listing"); + Eq(AutoVendorPlanner.MostAffordable(one, limited, 5, 1200), 2, "most that fits 1200 at 500 each"); + Eq(AutoVendorPlanner.MostAffordable(one, limited, 5, 499), 0, "can't afford one"); + var lot = new Listing { Id = 9, Name = "Lot of 10", UnitPrice = 1, Value = 1000, StackSize = 10, MaxStackSize = 10, Amount = 10 }; + // The per-unit price says 3 units cost 3, but ACE charges the whole listing (1000). + var p = AutoVendorPlanner.PlanNext(one, new List { new() { Item = lot, Amount = 3 } }, new List(), Pack(500)); + Eq(p.Kind, PlanKind.Done, "limited listing: whole-listing price over funds, nothing bought"); + Eq(AutoVendorPlanner.UnitPrice(v, L(3, "X", 0, value: 10)), 15L, "unit price falls back to the rate"); + Eq(AutoVendorPlanner.UnitPrice(v, L(4, "Y", 7, value: 10)), 7L, "engine unit price wins"); + + Check(AutoVendorPlanner.PyrealsFit(Pack(0, free: 2), 25_000), "one stack, two free slots"); + Check(!AutoVendorPlanner.PyrealsFit(Pack(0, free: 1), 1), "one free slot is kept"); + Eq(AutoVendorPlanner.SlotsFor(stackable, 250), 3, "250 arrows = 3 slots"); + Eq(AutoVendorPlanner.CategoryName(0x1000), "Spell Components", "category"); + } + + private static void TestSafety() + { + Console.WriteLine("\n-- never-sell checks --"); + var ok = new SafetyFacts { Appraised = true, Class = AcObjectClass.Salvage, Value = 100, InMainPack = true }; + Eq(AutoVendorPlanner.UnsafeReason(ok, false), null, "plain item is sellable"); + + (SafetyFacts, string)[] cases = + { + (new SafetyFacts { Appraised = false, Value = 100 }, "not identified"), + (new SafetyFacts { Appraised = true, Value = 100, Equipped = true }, "equipped"), + (new SafetyFacts { Appraised = true, Value = 0 }, "no value"), + (new SafetyFacts { Appraised = true, Value = 100, CanBeSold = false }, "not sellable"), + (new SafetyFacts { Appraised = true, Value = 100, IsRare = true }, "rare"), + (new SafetyFacts { Appraised = true, Value = 100, Attuned = 1 }, "attuned"), + (new SafetyFacts { Appraised = true, Value = 100, Bonded = 1 }, "bonded"), + (new SafetyFacts { Appraised = true, Value = 100, Retained = true }, "retained"), + (new SafetyFacts { Appraised = true, Value = 100, TimesTinkered = 1 }, "tinkered"), + (new SafetyFacts { Appraised = true, Value = 100, Imbued = 1 }, "imbued"), + (new SafetyFacts { Appraised = true, Value = 100, Inscription = "mine" }, "inscribed"), + (new SafetyFacts { Appraised = true, Value = 100, Class = AcObjectClass.Container }, "container"), + (new SafetyFacts { Appraised = true, Value = 100, HoldsItems = true }, "container"), + (new SafetyFacts { Appraised = true, Value = 100, Class = AcObjectClass.Foci }, "focus"), + (new SafetyFacts { Appraised = true, Value = 100, Class = AcObjectClass.Money }, "money"), + }; + foreach (var (f, why) in cases) + Eq(AutoVendorPlanner.UnsafeReason(f, false), why, $"never sell: {why}"); + + var side = new SafetyFacts { Appraised = true, Class = AcObjectClass.Salvage, Value = 100, InMainPack = false }; + Eq(AutoVendorPlanner.UnsafeReason(side, false), null, "side pack ok by default"); + Eq(AutoVendorPlanner.UnsafeReason(side, true), "not in main pack", "OnlyFromMainPack"); + } + + private static void TestVendorWillBuy() + { + Console.WriteLine("\n-- VendorWillBuy --"); + var v = Vendor(types: 0x40000000 | 0x40000, maxValue: 1000); + Check(AutoVendorPlanner.VendorWillBuy(v, 0x40000000, false, 500), "salvage under the cap"); + Check(!AutoVendorPlanner.VendorWillBuy(v, 0x40000000, false, 1500), "over MaxValue"); + Check(!AutoVendorPlanner.VendorWillBuy(v, 0x1, false, 10), "type the vendor doesn't buy"); + Check(AutoVendorPlanner.VendorWillBuy(v, 0x40000, true, 250000), "notes skip the cap"); + Check(!AutoVendorPlanner.VendorWillBuy(Vendor(types: 0x40000000), 0x40000, true, 100), "notes still need the vendor's type (engine rule)"); + Check(!AutoVendorPlanner.VendorWillBuy(Vendor(maxValue: 0), 0x1000, false, 1), "unknown MaxValue: don't sell"); + } + + private static void TestAddSell() + { + Console.WriteLine("\n-- addsell split planning --"); + var stacks = new List { S(1, "Pea", 5, 5), S(2, "Pea", 3, 3), S(3, "Pea", 10, 10) }; + + var (w1, m1, s1) = AutoVendorPlanner.PlanAddSell(stacks, 8); + Eq(string.Join(",", w1.Select(x => x.Id)), "1,2", "5 + 3 = 8"); + Eq(m1, 0, "nothing missing"); + Check(s1 == null, "no split"); + + var (w2, m2, s2) = AutoVendorPlanner.PlanAddSell(stacks, 7); + Eq(string.Join(",", w2.Select(x => x.Id)), "1", "take 5"); + Eq(m2, 2, "2 missing"); + Eq(s2?.Id, 2u, "split the smallest bigger stack (3)"); + + var (w3, m3, s3) = AutoVendorPlanner.PlanAddSell(stacks, 30); + Eq(w3.Count, 3, "all stacks"); + Eq(m3, 12, "12 missing"); + Check(s3 == null, "nothing big enough to split"); + } + + private static void TestParse() + { + Console.WriteLine("\n-- parsing --"); + Eq(AutoVendorPlanner.ParseCountAndName("10 Mana Scarab"), (10, "Mana Scarab"), "count + name"); + Eq(AutoVendorPlanner.ParseCountAndName("Mana Scarab"), (1, "Mana Scarab"), "name only"); + Eq(AutoVendorPlanner.ParseCountAndName(" 3 Lead Pea "), (3, "Lead Pea"), "extra spaces"); + } +} diff --git a/Tools/RynthCore.AutoVendorTests/RynthCore.AutoVendorTests.csproj b/Tools/RynthCore.AutoVendorTests/RynthCore.AutoVendorTests.csproj new file mode 100644 index 0000000..2a65bf4 --- /dev/null +++ b/Tools/RynthCore.AutoVendorTests/RynthCore.AutoVendorTests.csproj @@ -0,0 +1,26 @@ + + + + + Exe + net10.0 + enable + RynthCore.AutoVendorTests + + + + + + + + + + + + diff --git a/Tools/RynthCore.LootEditor/App.axaml.cs b/Tools/RynthCore.LootEditor/App.axaml.cs index 9df5c65..3384c0f 100644 --- a/Tools/RynthCore.LootEditor/App.axaml.cs +++ b/Tools/RynthCore.LootEditor/App.axaml.cs @@ -18,7 +18,7 @@ public partial class App : Application }; if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) - desktop.MainWindow = new MainWindow(); + desktop.MainWindow = new MainWindow(desktop.Args is { Length: > 0 } a ? a[0] : null); base.OnFrameworkInitializationCompleted(); } } diff --git a/Tools/RynthCore.LootEditor/MainViewModel.cs b/Tools/RynthCore.LootEditor/MainViewModel.cs index 1a18d22..843b2ca 100644 --- a/Tools/RynthCore.LootEditor/MainViewModel.cs +++ b/Tools/RynthCore.LootEditor/MainViewModel.cs @@ -15,6 +15,9 @@ namespace RynthCore.LootEditor; public class MainViewModel : INotifyPropertyChanged { private const string DefaultFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles"; + // RynthAi's AutoVendor reads .utl / default.utl from here (and from + // AutoVendor folders per server and per character, which IsAutoVendorPath also covers). + private const string AutoVendorFolder = @"C:\Games\RynthSuite\RynthAi\AutoVendor"; public event PropertyChangedEventHandler? PropertyChanged; private void Set(ref T field, T value, [CallerMemberName] string? name = null) @@ -172,6 +175,42 @@ public class MainViewModel : INotifyPropertyChanged { string baseName = string.IsNullOrEmpty(_filePath) ? "untitled.utl" : Path.GetFileName(_filePath); WindowTitle = $"RynthCore Loot Editor — {baseName}{(_dirty ? "*" : "")}"; + + // The folder switch follows the open file, so Save As lands next to it. + if (!string.IsNullOrEmpty(_filePath)) + UseAutoVendorFolder = IsAutoVendorPath(_filePath); + Notify(nameof(IsAutoVendorProfile)); + } + + // ── Profile folder (Loot / AutoVendor) ─────────────────────────────────── + + private bool _useAutoVendorFolder; + /// Open / Save start in the AutoVendor folder instead of LootProfiles. + public bool UseAutoVendorFolder + { + get => _useAutoVendorFolder; + set + { + Set(ref _useAutoVendorFolder, value); + Notify(nameof(UseLootFolder)); + Notify(nameof(ProfileFolderHint)); + Notify(nameof(IsAutoVendorProfile)); + } + } + public bool UseLootFolder => !_useAutoVendorFolder; + public string ProfileFolderHint => $"Open and Save start in {(_useAutoVendorFolder ? AutoVendorFolder : DefaultFolder)}"; + + /// An AutoVendor profile is open (or, for an unsaved one, the AutoVendor folder is picked). + public bool IsAutoVendorProfile => + string.IsNullOrEmpty(_filePath) ? _useAutoVendorFolder : IsAutoVendorPath(_filePath); + + private static bool IsAutoVendorPath(string path) + { + string? dir = Path.GetDirectoryName(Path.GetFullPath(path)); + for (; !string.IsNullOrEmpty(dir); dir = Path.GetDirectoryName(dir)) + if (string.Equals(Path.GetFileName(dir), "AutoVendor", StringComparison.OrdinalIgnoreCase)) + return true; + return false; } // ── Picker option lists ────────────────────────────────────────────────── @@ -207,6 +246,7 @@ public class MainViewModel : INotifyPropertyChanged public RelayCommand RuleMoveUp { get; } public RelayCommand RuleMoveDown { get; } public RelayCommand SetActionFilter { get; } + public RelayCommand SetProfileFolder { get; } public RelayCommand CondAdd { get; } public RelayCommand CondDelete { get; } public RelayCommand CondMoveUp { get; } @@ -239,6 +279,8 @@ public class MainViewModel : INotifyPropertyChanged _ => null, }; }); + SetProfileFolder = new RelayCommand(arg => + UseAutoVendorFolder = string.Equals(arg as string, "AutoVendor", StringComparison.OrdinalIgnoreCase)); CondAdd = new RelayCommand(_ => DoCondAdd()); CondDelete = new RelayCommand(_ => DoCondDelete(), _ => _selectedCondition != null); CondMoveUp = new RelayCommand(_ => DoCondMove(-1), _ => CanMoveCond(-1)); @@ -273,6 +315,40 @@ public class MainViewModel : INotifyPropertyChanged LoadProfile(new VTankLootProfile()); } + /// + /// Opens the profile named on the command line (RynthAi's dashboard Edit button passes + /// the loot profile in use, or the open vendor's AutoVendor profile). A path that doesn't + /// exist yet starts an empty profile that saves there - how a vendor gets its first one. + /// + public void OpenFromCommandLine(string path) + { + try + { + path = Path.GetFullPath(path); + if (File.Exists(path)) + { + VTankLootProfile loaded = path.EndsWith(".json", StringComparison.OrdinalIgnoreCase) + ? ConvertFromJson(path) + : VTankLootParser.Load(path); + _filePath = path; + SearchText = ""; + LoadProfile(loaded); + Status($"Opened {Path.GetFileName(path)} ({loaded.Rules.Count} rules)"); + } + else + { + _filePath = path; + SearchText = ""; + LoadProfile(new VTankLootProfile()); + Status($"New profile - Save writes {path}"); + } + } + catch (Exception ex) + { + Status($"Could not open {path}: {ex.Message}"); + } + } + private async Task DoOpenAsync() { if (!ConfirmDiscard()) return; @@ -685,8 +761,13 @@ public class MainViewModel : INotifyPropertyChanged private async Task GetFolderAsync() { - if (Directory.Exists(DefaultFolder)) - return await _window.StorageProvider.TryGetFolderFromPathAsync(DefaultFolder); + string folder = _useAutoVendorFolder ? AutoVendorFolder : DefaultFolder; + if (_useAutoVendorFolder && !Directory.Exists(folder)) + { + try { Directory.CreateDirectory(folder); } catch { } + } + if (Directory.Exists(folder)) + return await _window.StorageProvider.TryGetFolderFromPathAsync(folder); return null; } diff --git a/Tools/RynthCore.LootEditor/MainWindow.axaml b/Tools/RynthCore.LootEditor/MainWindow.axaml index 6dbb057..09997a6 100644 --- a/Tools/RynthCore.LootEditor/MainWindow.axaml +++ b/Tools/RynthCore.LootEditor/MainWindow.axaml @@ -29,6 +29,31 @@ + + + + + + + + + + + + + + + diff --git a/Tools/RynthCore.LootEditor/MainWindow.axaml.cs b/Tools/RynthCore.LootEditor/MainWindow.axaml.cs index 0966311..7a13c14 100644 --- a/Tools/RynthCore.LootEditor/MainWindow.axaml.cs +++ b/Tools/RynthCore.LootEditor/MainWindow.axaml.cs @@ -8,11 +8,16 @@ public partial class MainWindow : Window private readonly MainViewModel _vm; private bool _forceClose; - public MainWindow() + public MainWindow() : this(null) { } + + /// A profile to open at startup (from the command line), or null. + public MainWindow(string? openPath) { InitializeComponent(); _vm = new MainViewModel(this); DataContext = _vm; + if (!string.IsNullOrWhiteSpace(openPath)) + _vm.OpenFromCommandLine(openPath); // (Confirm-on-close was disabled when the dirty-flag was made private during // the VTank model migration. Re-add via a public IsDirty later if desired.) diff --git a/Tools/RynthCore.MissileArcTests/Program.cs b/Tools/RynthCore.MissileArcTests/Program.cs new file mode 100644 index 0000000..f16208c --- /dev/null +++ b/Tools/RynthCore.MissileArcTests/Program.cs @@ -0,0 +1,193 @@ +using System; +using RynthCore.Plugin.RynthAi.Raycasting; + +namespace RynthCore.MissileArcTests; + +// Tests for the missile arc math combat's LOS uses (MissileBallistics): the low ballistic +// solution passes through the aim point, rises with distance and falls with launch speed, +// goes out of reach past v²/g, and the clearance bump leaves both ends in place. +// Self-contained; fails on zero assertions. +// +// Run: dotnet run -c Release (exit 0 = pass, 1 = fail) +internal static class Program +{ + private static int _asserts; + private static int _fails; + + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + + private static void Near(double actual, double expected, double tol, string msg) + { + _asserts++; + if (double.IsNaN(actual) || Math.Abs(actual - expected) > tol) + { _fails++; Console.WriteLine($" [FAIL] {msg}: expected {expected:0.####} ±{tol}, got {actual:0.####}"); } + } + + private static int Main() + { + Console.WriteLine("=== Missile arc tests ==="); + TestFlatShot(); + TestPassesThroughAimPoint(); + TestRiseGrowsWithDistance(); + TestFasterIsFlatter(); + TestOutOfReach(); + TestUphillAndDownhill(); + TestShortShotIsALine(); + TestVerticalShot(); + TestClearanceBump(); + TestDungeonCeiling(); + TestSegmentCount(); + TestBadInput(); + + Console.WriteLine($"\n{_asserts} assertions, {_fails} failed."); + if (_asserts == 0) { Console.WriteLine("ABORT: zero assertions ran."); return 1; } + Console.WriteLine(_fails == 0 ? "ALL MISSILE ARC TESTS PASSED." : $"{_fails} FAILURE(S)."); + return _fails == 0 ? 0 : 1; + } + + private static MissileArc Flat(float d, float v) => MissileBallistics.Solve(0, 0, 1, d, 0, 1, v); + + // 40 m on the level at 25 m/s: low solution tanθ = (v² − √(v⁴ − g²d²))/(g·d) ≈ 0.3526 + // (19.4°), apex at mid-flight, d·tanθ/4 ≈ 3.53 m above the launch point. + private static void TestFlatShot() + { + var a = Flat(40, 25); + Check(a.Valid, "40 m at 25 m/s is in reach"); + Near(a.TanTheta, 0.35259, 0.0005, "tanθ, 40 m at 25 m/s"); + Check(a.TanTheta < 1f, "the LOW solution is used (under 45°)"); + Near(a.ApexAboveLaunch, 40 * a.TanTheta / 4, 0.01, "flat apex = d·tanθ/4"); + Near(a.ApexAboveLaunch, 3.526, 0.01, "apex, 40 m at 25 m/s"); + Near(a.MaxRiseAboveChord, a.ApexAboveLaunch, 0.01, "on the level the rise above the line is the apex"); + Near(a.HeightAt(0.5f), a.ApexAboveLaunch, 0.01, "apex at mid-flight"); + Near(a.HeightAt(0.25f), a.HeightAt(0.75f), 0.001, "symmetric on the level"); + } + + private static void TestPassesThroughAimPoint() + { + var a = MissileBallistics.Solve(10, 20, 5, 40, -10, 7.5f, 30); + Check(a.Valid, "diagonal shot in reach"); + a.PointAt(1f, 0f, out float x, out float y, out float z); + Near(x, 40, 0.001, "end x"); + Near(y, -10, 0.001, "end y"); + Near(z, 7.5, 0.01, "end z (aim point)"); + a.PointAt(0f, 0f, out x, out y, out z); + Near(x, 10, 0.001, "start x"); + Near(y, 20, 0.001, "start y"); + Near(z, 5, 0.001, "start z (launch point)"); + a.PointAt(0.5f, 0f, out x, out y, out _); + Near(x, 25, 0.001, "mid x on the horizontal line"); + Near(y, 5, 0.001, "mid y on the horizontal line"); + } + + private static void TestRiseGrowsWithDistance() + { + float r10 = Flat(10, 25).MaxRiseAboveChord; + float r20 = Flat(20, 25).MaxRiseAboveChord; + float r40 = Flat(40, 25).MaxRiseAboveChord; + float r55 = Flat(55, 25).MaxRiseAboveChord; + Check(r10 < r20 && r20 < r40 && r40 < r55, $"rise grows with distance ({r10:0.00} < {r20:0.00} < {r40:0.00} < {r55:0.00})"); + Check(r10 < 0.25f, $"10 m is nearly flat ({r10:0.000} m)"); + Check(r55 > 5f, $"55 m rises past 5 m at 25 m/s ({r55:0.00} m)"); + } + + private static void TestFasterIsFlatter() + { + float slow = Flat(40, 22).MaxRiseAboveChord; + float mid = Flat(40, 25).MaxRiseAboveChord; + float fast = Flat(40, 40).MaxRiseAboveChord; + Check(slow > mid && mid > fast, $"faster launch = flatter arc ({slow:0.00} > {mid:0.00} > {fast:0.00})"); + } + + private static void TestOutOfReach() + { + float v = 25f, g = MissileBallistics.AcGravity; + float maxRange = v * v / g; // 63.8 m on the level, at 45° + Check(Flat(maxRange - 0.5f, v).Valid, "just inside v²/g is in reach"); + Check(!Flat(maxRange + 0.5f, v).Valid, "past v²/g is out of reach"); + var edge = Flat(maxRange * 0.9999f, v); + Check(edge.Valid && Math.Abs(edge.TanTheta - 1f) < 0.05f, "maximum range is flown at 45°"); + Check(!MissileBallistics.Solve(0, 0, 0, 5, 0, 40, 20).Valid, "40 m straight up a 5 m slope at 20 m/s is out of reach"); + } + + private static void TestUphillAndDownhill() + { + var up = MissileBallistics.Solve(0, 0, 1, 30, 0, 9, 25); + var down = MissileBallistics.Solve(0, 0, 9, 30, 0, 1, 25); + Check(up.Valid && down.Valid, "8 m up / down over 30 m in reach"); + Near(up.HeightAt(1f), 8, 0.01, "uphill arc ends at the aim point"); + Near(down.HeightAt(1f), -8, 0.01, "downhill arc ends at the aim point"); + Check(up.TanTheta > Flat(30, 25).TanTheta, "uphill launches steeper than level"); + Check(down.TanTheta < Flat(30, 25).TanTheta, "downhill launches flatter than level"); + Check(up.MaxRiseAboveChord > 0f && down.MaxRiseAboveChord > 0f, "both still bow above the straight line"); + Check(up.ApexAboveLaunch >= 8f, "uphill apex is at least the aim point"); + } + + private static void TestShortShotIsALine() + { + var a = Flat(5, 25); + Check(a.Valid, "5 m in reach"); + Check(a.MaxRiseAboveChord < 0.06f, $"5 m at 25 m/s rises under 6 cm ({a.MaxRiseAboveChord:0.000})"); + } + + private static void TestVerticalShot() + { + var a = MissileBallistics.Solve(3, 3, 0, 3.01f, 3, 6, 25); + Check(a.Valid && a.Vertical, "near-vertical shot is flown as a line"); + Near(a.HeightAt(0.5f), 3, 0.001, "vertical shot mid height"); + Near(a.MaxRiseAboveChord, 0, 0.0001, "vertical shot has no rise above the line"); + } + + private static void TestClearanceBump() + { + Near(MissileBallistics.ClearanceBump(0f, 0.5f), 0, 1e-6, "bump 0 at launch"); + Near(MissileBallistics.ClearanceBump(1f, 0.5f), 0, 1e-6, "bump 0 at the aim point"); + Near(MissileBallistics.ClearanceBump(0.5f, 0.5f), 0.5, 1e-6, "bump = clearance at mid-flight"); + Near(MissileBallistics.ClearanceBump(0.5f, 0f), 0, 1e-6, "no clearance, no bump"); + Near(MissileBallistics.ClearanceBump(0.5f, -1f), 0, 1e-6, "negative clearance ignored"); + var a = Flat(40, 25); + a.PointAt(0.5f, 0.5f, out _, out _, out float zWith); + a.PointAt(0.5f, 0f, out _, out _, out float zWithout); + Near(zWith - zWithout, 0.5, 1e-4, "PointAt applies the bump"); + a.PointAt(1f, 2f, out _, out _, out float zEnd); + Near(zEnd, 1, 1e-3, "the bump never moves the aim point"); + } + + // A 4 m high corridor, launching from chest height (1 m above the floor): the straight + // line to a target 40 m away clears, the 25 m/s arrow (apex ≈ 4.5 m) doesn't. + private static void TestDungeonCeiling() + { + const float ceiling = 4f; + var far = Flat(40, 25); + var near = Flat(15, 25); + float farTop = MissileBallistics.MaxPathZ(far, 0f); + float nearTop = MissileBallistics.MaxPathZ(near, 0.5f); + Check(farTop > ceiling, $"40 m shot hits a 4 m ceiling (top {farTop:0.00} m)"); + Check(nearTop < ceiling, $"15 m shot clears it even with 0.5 m clearance (top {nearTop:0.00} m)"); + Check(MissileBallistics.MaxPathZ(near, 3f) > MissileBallistics.MaxPathZ(near, 0f) + 2.9f, "clearance raises the tested top"); + Check(float.IsNaN(MissileBallistics.MaxPathZ(Flat(100, 25), 0f)), "out of reach has no path"); + } + + private static void TestSegmentCount() + { + Check(MissileBallistics.SegmentCount(0f) == 6, "minimum 6 segments"); + Check(MissileBallistics.SegmentCount(5f) == 6, "5 m → 6 segments"); + Check(MissileBallistics.SegmentCount(25f) == 10, "25 m → 10 segments"); + Check(MissileBallistics.SegmentCount(50f) == 20, "50 m → 20 segments"); + Check(MissileBallistics.SegmentCount(500f) == 24, "capped at 24 segments"); + Check(MissileBallistics.SegmentCount(float.NaN) == 6, "NaN → minimum"); + } + + private static void TestBadInput() + { + Check(!MissileBallistics.Solve(0, 0, 0, 10, 0, 0, 0f).Valid, "zero speed is out of reach"); + Check(!MissileBallistics.Solve(0, 0, 0, 10, 0, 0, -5f).Valid, "negative speed is out of reach"); + Check(!MissileBallistics.Solve(0, 0, 0, float.NaN, 0, 0, 25f).Valid, "NaN position is not a shot"); + var bad = MissileBallistics.Solve(0, 0, 0, 10, 0, 0, 0f); + Near(bad.MaxRiseAboveChord, 0, 0, "invalid arc has no rise"); + Near(bad.ApexAboveLaunch, 0, 0, "invalid arc has no apex"); + } +} diff --git a/Tools/RynthCore.MissileArcTests/RynthCore.MissileArcTests.csproj b/Tools/RynthCore.MissileArcTests/RynthCore.MissileArcTests.csproj new file mode 100644 index 0000000..0e91195 --- /dev/null +++ b/Tools/RynthCore.MissileArcTests/RynthCore.MissileArcTests.csproj @@ -0,0 +1,21 @@ + + + + + Exe + net10.0 + enable + RynthCore.MissileArcTests + + + + + + +